version 0.2.1
[fms.git] / libs / sqlite3 / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.5.7.  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 ** 5413 lines past this header comment.)  Additional code files may be
15 ** needed if you want a wrapper to interface SQLite with your choice of
16 ** programming language.  The code for the "sqlite3" command-line shell
17 ** is also in a separate file.  This file contains only code for the core
18 ** SQLite library.
19 **
20 ** This amalgamation was generated on 2008-03-17 18:47:08 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.673 2008/03/14 13:02:08 mlcreech Exp $
45 */
46 #ifndef _SQLITEINT_H_
47 #define _SQLITEINT_H_
48
49 /*
50 ** Include the configuration header output by 'configure' if it was run
51 ** (otherwise we get an empty default).
52 */
53 /************** Include config.h in the middle of sqliteInt.h ****************/
54 /************** Begin file config.h ******************************************/
55 /*
56 ** 2008 March 6
57 **
58 ** The author disclaims copyright to this source code.  In place of
59 ** a legal notice, here is a blessing:
60 **
61 **    May you do good and not evil.
62 **    May you find forgiveness for yourself and forgive others.
63 **    May you share freely, never taking more than you give.
64 **
65 *************************************************************************
66 ** Default configuration header in case the 'configure' script is not used
67 **
68 ** @(#) $Id: config.h,v 1.1 2008/03/06 07:36:18 mlcreech Exp $
69 */
70 #ifndef _CONFIG_H_
71 #define _CONFIG_H_
72
73 /* We do nothing here, since no assumptions are made by default */
74
75 #endif
76
77 /************** End of config.h **********************************************/
78 /************** Continuing where we left off in sqliteInt.h ******************/
79
80 /* Needed for various definitions... */
81 #define _GNU_SOURCE
82
83 /*
84 ** Include standard header files as necessary
85 */
86 #ifdef HAVE_STDINT_H
87 #include <stdint.h>
88 #endif
89 #ifdef HAVE_INTTYPES_H
90 #include <inttypes.h>
91 #endif
92
93 /*
94 ** If possible, use the C99 intptr_t type to define an integral type of
95 ** equivalent size to a pointer.  (Technically it's >= sizeof(void *), but
96 ** practically it's == sizeof(void *)).  We fall back to an int if this type
97 ** isn't defined.
98 */
99 #ifdef HAVE_INTPTR_T
100   typedef intptr_t sqlite3_intptr_t;
101 #else
102   typedef int sqlite3_intptr_t;
103 #endif
104
105
106 /*
107 ** The macro unlikely() is a hint that surrounds a boolean
108 ** expression that is usually false.  Macro likely() surrounds
109 ** a boolean expression that is usually true.  GCC is able to
110 ** use these hints to generate better code, sometimes.
111 */
112 #if defined(__GNUC__) && 0
113 # define likely(X)    __builtin_expect((X),1)
114 # define unlikely(X)  __builtin_expect((X),0)
115 #else
116 # define likely(X)    !!(X)
117 # define unlikely(X)  !!(X)
118 #endif
119
120
121 /*
122 ** These #defines should enable >2GB file support on Posix if the
123 ** underlying operating system supports it.  If the OS lacks
124 ** large file support, or if the OS is windows, these should be no-ops.
125 **
126 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
127 ** system #includes.  Hence, this block of code must be the very first
128 ** code in all source files.
129 **
130 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
131 ** on the compiler command line.  This is necessary if you are compiling
132 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
133 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
134 ** without this option, LFS is enable.  But LFS does not exist in the kernel
135 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
136 ** portability you should omit LFS.
137 **
138 ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
139 */
140 #ifndef SQLITE_DISABLE_LFS
141 # define _LARGE_FILE       1
142 # ifndef _FILE_OFFSET_BITS
143 #   define _FILE_OFFSET_BITS 64
144 # endif
145 # define _LARGEFILE_SOURCE 1
146 #endif
147
148
149 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
150 /************** Begin file sqliteLimit.h *************************************/
151 /*
152 ** 2007 May 7
153 **
154 ** The author disclaims copyright to this source code.  In place of
155 ** a legal notice, here is a blessing:
156 **
157 **    May you do good and not evil.
158 **    May you find forgiveness for yourself and forgive others.
159 **    May you share freely, never taking more than you give.
160 **
161 *************************************************************************
162 ** 
163 ** This file defines various limits of what SQLite can process.
164 **
165 ** @(#) $Id: sqliteLimit.h,v 1.6 2007/12/17 16:20:07 drh Exp $
166 */
167
168 /*
169 ** The maximum length of a TEXT or BLOB in bytes.   This also
170 ** limits the size of a row in a table or index.
171 **
172 ** The hard limit is the ability of a 32-bit signed integer
173 ** to count the size: 2^31-1 or 2147483647.
174 */
175 #ifndef SQLITE_MAX_LENGTH
176 # define SQLITE_MAX_LENGTH 1000000000
177 #endif
178
179 /*
180 ** This is the maximum number of
181 **
182 **    * Columns in a table
183 **    * Columns in an index
184 **    * Columns in a view
185 **    * Terms in the SET clause of an UPDATE statement
186 **    * Terms in the result set of a SELECT statement
187 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
188 **    * Terms in the VALUES clause of an INSERT statement
189 **
190 ** The hard upper limit here is 32676.  Most database people will
191 ** tell you that in a well-normalized database, you usually should
192 ** not have more than a dozen or so columns in any table.  And if
193 ** that is the case, there is no point in having more than a few
194 ** dozen values in any of the other situations described above.
195 */
196 #ifndef SQLITE_MAX_COLUMN
197 # define SQLITE_MAX_COLUMN 2000
198 #endif
199
200 /*
201 ** The maximum length of a single SQL statement in bytes.
202 ** A value of zero means there is no limit.
203 */
204 #ifndef SQLITE_MAX_SQL_LENGTH
205 # define SQLITE_MAX_SQL_LENGTH 0
206 #endif
207
208 /*
209 ** The maximum depth of an expression tree. This is limited to 
210 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
211 ** want to place more severe limits on the complexity of an 
212 ** expression. A value of 0 (the default) means do not enforce
213 ** any limitation on expression tree depth.
214 */
215 #ifndef SQLITE_MAX_EXPR_DEPTH
216 # define SQLITE_MAX_EXPR_DEPTH 1000
217 #endif
218
219 /*
220 ** The maximum number of terms in a compound SELECT statement.
221 ** The code generator for compound SELECT statements does one
222 ** level of recursion for each term.  A stack overflow can result
223 ** if the number of terms is too large.  In practice, most SQL
224 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
225 ** any limit on the number of terms in a compount SELECT.
226 */
227 #ifndef SQLITE_MAX_COMPOUND_SELECT
228 # define SQLITE_MAX_COMPOUND_SELECT 500
229 #endif
230
231 /*
232 ** The maximum number of opcodes in a VDBE program.
233 ** Not currently enforced.
234 */
235 #ifndef SQLITE_MAX_VDBE_OP
236 # define SQLITE_MAX_VDBE_OP 25000
237 #endif
238
239 /*
240 ** The maximum number of arguments to an SQL function.
241 */
242 #ifndef SQLITE_MAX_FUNCTION_ARG
243 # define SQLITE_MAX_FUNCTION_ARG 100
244 #endif
245
246 /*
247 ** The maximum number of in-memory pages to use for the main database
248 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
249 */
250 #ifndef SQLITE_DEFAULT_CACHE_SIZE
251 # define SQLITE_DEFAULT_CACHE_SIZE  2000
252 #endif
253 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
254 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
255 #endif
256
257 /*
258 ** The maximum number of attached databases.  This must be at least 2
259 ** in order to support the main database file (0) and the file used to
260 ** hold temporary tables (1).  And it must be less than 32 because
261 ** we use a bitmask of databases with a u32 in places (for example
262 ** the Parse.cookieMask field).
263 */
264 #ifndef SQLITE_MAX_ATTACHED
265 # define SQLITE_MAX_ATTACHED 10
266 #endif
267
268
269 /*
270 ** The maximum value of a ?nnn wildcard that the parser will accept.
271 */
272 #ifndef SQLITE_MAX_VARIABLE_NUMBER
273 # define SQLITE_MAX_VARIABLE_NUMBER 999
274 #endif
275
276 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
277 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
278 ** and the fact that the page size must be a power of 2.
279 */
280 #ifndef SQLITE_MAX_PAGE_SIZE
281 # define SQLITE_MAX_PAGE_SIZE 32768
282 #endif
283
284
285 /*
286 ** The default size of a database page.
287 */
288 #ifndef SQLITE_DEFAULT_PAGE_SIZE
289 # define SQLITE_DEFAULT_PAGE_SIZE 1024
290 #endif
291 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
292 # undef SQLITE_DEFAULT_PAGE_SIZE
293 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
294 #endif
295
296 /*
297 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
298 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
299 ** device characteristics (sector-size and atomic write() support),
300 ** SQLite may choose a larger value. This constant is the maximum value
301 ** SQLite will choose on its own.
302 */
303 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
304 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
305 #endif
306 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
307 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
308 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
309 #endif
310
311
312 /*
313 ** Maximum number of pages in one database file.
314 **
315 ** This is really just the default value for the max_page_count pragma.
316 ** This value can be lowered (or raised) at run-time using that the
317 ** max_page_count macro.
318 */
319 #ifndef SQLITE_MAX_PAGE_COUNT
320 # define SQLITE_MAX_PAGE_COUNT 1073741823
321 #endif
322
323 /*
324 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
325 ** operator.
326 */
327 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
328 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
329 #endif
330
331 /************** End of sqliteLimit.h *****************************************/
332 /************** Continuing where we left off in sqliteInt.h ******************/
333
334 /*
335 ** For testing purposes, the various size limit constants are really
336 ** variables that we can modify in the testfixture.
337 */
338 #ifdef SQLITE_TEST
339   #undef SQLITE_MAX_LENGTH
340   #undef SQLITE_MAX_COLUMN
341   #undef SQLITE_MAX_SQL_LENGTH
342   #undef SQLITE_MAX_EXPR_DEPTH
343   #undef SQLITE_MAX_COMPOUND_SELECT
344   #undef SQLITE_MAX_VDBE_OP
345   #undef SQLITE_MAX_FUNCTION_ARG
346   #undef SQLITE_MAX_VARIABLE_NUMBER
347   #undef SQLITE_MAX_PAGE_SIZE
348   #undef SQLITE_MAX_PAGE_COUNT
349   #undef SQLITE_MAX_LIKE_PATTERN_LENGTH
350
351   #define SQLITE_MAX_LENGTH              sqlite3MAX_LENGTH
352   #define SQLITE_MAX_COLUMN              sqlite3MAX_COLUMN
353   #define SQLITE_MAX_SQL_LENGTH          sqlite3MAX_SQL_LENGTH
354   #define SQLITE_MAX_EXPR_DEPTH          sqlite3MAX_EXPR_DEPTH
355   #define SQLITE_MAX_COMPOUND_SELECT     sqlite3MAX_COMPOUND_SELECT
356   #define SQLITE_MAX_VDBE_OP             sqlite3MAX_VDBE_OP
357   #define SQLITE_MAX_FUNCTION_ARG        sqlite3MAX_FUNCTION_ARG
358   #define SQLITE_MAX_VARIABLE_NUMBER     sqlite3MAX_VARIABLE_NUMBER
359   #define SQLITE_MAX_PAGE_SIZE           sqlite3MAX_PAGE_SIZE
360   #define SQLITE_MAX_PAGE_COUNT          sqlite3MAX_PAGE_COUNT
361   #define SQLITE_MAX_LIKE_PATTERN_LENGTH sqlite3MAX_LIKE_PATTERN_LENGTH
362
363   extern int sqlite3MAX_LENGTH;
364   extern int sqlite3MAX_COLUMN;
365   extern int sqlite3MAX_SQL_LENGTH;
366   extern int sqlite3MAX_EXPR_DEPTH;
367   extern int sqlite3MAX_COMPOUND_SELECT;
368   extern int sqlite3MAX_VDBE_OP;
369   extern int sqlite3MAX_FUNCTION_ARG;
370   extern int sqlite3MAX_VARIABLE_NUMBER;
371   extern int sqlite3MAX_PAGE_SIZE;
372   extern int sqlite3MAX_PAGE_COUNT;
373   extern int sqlite3MAX_LIKE_PATTERN_LENGTH;
374 #endif
375
376
377 /*
378 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
379 ** Older versions of SQLite used an optional THREADSAFE macro.
380 ** We support that for legacy
381 */
382 #if !defined(SQLITE_THREADSAFE)
383 #if defined(THREADSAFE)
384 # define SQLITE_THREADSAFE THREADSAFE
385 #else
386 # define SQLITE_THREADSAFE 1
387 #endif
388 #endif
389
390 /*
391 ** Exactly one of the following macros must be defined in order to
392 ** specify which memory allocation subsystem to use.
393 **
394 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
395 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
396 **     SQLITE_MEMORY_SIZE            // internal allocator #1
397 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
398 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
399 **
400 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
401 ** the default.
402 */
403 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
404     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
405     defined(SQLITE_POW2_MEMORY_SIZE)>1
406 # error "At most one of the following compile-time configuration options\
407  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
408  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
409 #endif
410 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
411     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
412     defined(SQLITE_POW2_MEMORY_SIZE)==0
413 # define SQLITE_SYSTEM_MALLOC 1
414 #endif
415
416 /*
417 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
418 ** sizes of memory allocations below this value where possible.
419 */
420 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
421 # define SQLITE_MALLOC_SOFT_LIMIT 1024
422 #endif
423
424 /*
425 ** We need to define _XOPEN_SOURCE as follows in order to enable
426 ** recursive mutexes on most unix systems.  But Mac OS X is different.
427 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
428 ** so it is omitted there.  See ticket #2673.
429 **
430 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
431 ** implemented on some systems.  So we avoid defining it at all
432 ** if it is already defined or if it is unneeded because we are
433 ** not doing a threadsafe build.  Ticket #2681.
434 **
435 ** See also ticket #2741.
436 */
437 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
438 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
439 #endif
440
441 #if defined(SQLITE_TCL) || defined(TCLSH)
442 # include <tcl.h>
443 #endif
444
445 /*
446 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
447 ** Setting NDEBUG makes the code smaller and run faster.  So the following
448 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
449 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
450 ** feature.
451 */
452 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
453 # define NDEBUG 1
454 #endif
455
456 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
457 /************** Begin file sqlite3.h *****************************************/
458 /*
459 ** 2001 September 15
460 **
461 ** The author disclaims copyright to this source code.  In place of
462 ** a legal notice, here is a blessing:
463 **
464 **    May you do good and not evil.
465 **    May you find forgiveness for yourself and forgive others.
466 **    May you share freely, never taking more than you give.
467 **
468 *************************************************************************
469 ** This header file defines the interface that the SQLite library
470 ** presents to client programs.  If a C-function, structure, datatype,
471 ** or constant definition does not appear in this file, then it is
472 ** not a published API of SQLite, is subject to change without
473 ** notice, and should not be referenced by programs that use SQLite.
474 **
475 ** Some of the definitions that are in this file are marked as
476 ** "experimental".  Experimental interfaces are normally new
477 ** features recently added to SQLite.  We do not anticipate changes 
478 ** to experimental interfaces but reserve to make minor changes if
479 ** experience from use "in the wild" suggest such changes are prudent.
480 **
481 ** The official C-language API documentation for SQLite is derived
482 ** from comments in this file.  This file is the authoritative source
483 ** on how SQLite interfaces are suppose to operate.
484 **
485 ** The name of this file under configuration management is "sqlite.h.in".
486 ** The makefile makes some minor changes to this file (such as inserting
487 ** the version number) and changes its name to "sqlite3.h" as
488 ** part of the build process.
489 **
490 ** @(#) $Id: sqlite.h.in,v 1.291 2008/03/08 12:37:31 drh Exp $
491 */
492 #ifndef _SQLITE3_H_
493 #define _SQLITE3_H_
494 #include <stdarg.h>     /* Needed for the definition of va_list */
495
496 /*
497 ** Make sure we can call this stuff from C++.
498 */
499 #if 0
500 extern "C" {
501 #endif
502
503
504 /*
505 ** Add the ability to override 'extern'
506 */
507 #ifndef SQLITE_EXTERN
508 # define SQLITE_EXTERN extern
509 #endif
510
511 /*
512 ** Make sure these symbols where not defined by some previous header
513 ** file.
514 */
515 #ifdef SQLITE_VERSION
516 # undef SQLITE_VERSION
517 #endif
518 #ifdef SQLITE_VERSION_NUMBER
519 # undef SQLITE_VERSION_NUMBER
520 #endif
521
522 /*
523 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
524 **
525 ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
526 ** the sqlite3.h file specify the version of SQLite with which
527 ** that header file is associated.
528 **
529 ** The "version" of SQLite is a string of the form "X.Y.Z".
530 ** The phrase "alpha" or "beta" might be appended after the Z.
531 ** The X value is major version number always 3 in SQLite3.
532 ** The X value only changes when  backwards compatibility is
533 ** broken and we intend to never break
534 ** backwards compatibility.  The Y value is the minor version
535 ** number and only changes when
536 ** there are major feature enhancements that are forwards compatible
537 ** but not backwards compatible.  The Z value is release number
538 ** and is incremented with
539 ** each release but resets back to 0 when Y is incremented.
540 **
541 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
542 **
543 ** INVARIANTS:
544 **
545 ** {F10011} The SQLITE_VERSION #define in the sqlite3.h header file
546 **          evaluates to a string literal that is the SQLite version
547 **          with which the header file is associated.
548 **
549 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
550 **          with the value  (X*1000000 + Y*1000 + Z) where X, Y, and
551 **          Z are the major version, minor version, and release number.
552 */
553 #define SQLITE_VERSION         "3.5.7"
554 #define SQLITE_VERSION_NUMBER  3005007
555
556 /*
557 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
558 ** KEYWORDS: sqlite3_version
559 **
560 ** These features provide the same information as the [SQLITE_VERSION]
561 ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated
562 ** with the library instead of the header file.  Cautious programmers might
563 ** include a check in their application to verify that 
564 ** sqlite3_libversion_number() always returns the value 
565 ** [SQLITE_VERSION_NUMBER].
566 **
567 ** The sqlite3_libversion() function returns the same information as is
568 ** in the sqlite3_version[] string constant.  The function is provided
569 ** for use in DLLs since DLL users usually do not have direct access to string
570 ** constants within the DLL.
571 **
572 ** INVARIANTS:
573 **
574 ** {F10021} The [sqlite3_libversion_number()] interface returns an integer
575 **          equal to [SQLITE_VERSION_NUMBER]. 
576 **
577 ** {F10022} The [sqlite3_version] string constant contains the text of the
578 **          [SQLITE_VERSION] string. 
579 **
580 ** {F10023} The [sqlite3_libversion()] function returns
581 **          a pointer to the [sqlite3_version] string constant.
582 */
583 SQLITE_API const char sqlite3_version[];
584 SQLITE_API const char *sqlite3_libversion(void);
585 SQLITE_API int sqlite3_libversion_number(void);
586
587 /*
588 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
589 **
590 ** SQLite can be compiled with or without mutexes.  When
591 ** the SQLITE_THREADSAFE C preprocessor macro is true, mutexes
592 ** are enabled and SQLite is threadsafe.  When that macro is false,
593 ** the mutexes are omitted.  Without the mutexes, it is not safe
594 ** to use SQLite from more than one thread.
595 **
596 ** There is a measurable performance penalty for enabling mutexes.
597 ** So if speed is of utmost importance, it makes sense to disable
598 ** the mutexes.  But for maximum safety, mutexes should be enabled.
599 ** The default behavior is for mutexes to be enabled.
600 **
601 ** This interface can be used by a program to make sure that the
602 ** version of SQLite that it is linking against was compiled with
603 ** the desired setting of the SQLITE_THREADSAFE macro.
604 **
605 ** INVARIANTS:
606 **
607 ** {F10101} The [sqlite3_threadsafe()] function returns nonzero if
608 **          SQLite was compiled with its mutexes enabled or zero
609 **          if SQLite was compiled with mutexes disabled.
610 */
611 SQLITE_API int sqlite3_threadsafe(void);
612
613 /*
614 ** CAPI3REF: Database Connection Handle {F12000}
615 ** KEYWORDS: {database connection}
616 **
617 ** Each open SQLite database is represented by pointer to an instance of the
618 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
619 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
620 ** [sqlite3_open_v2()] interfaces are its constructors
621 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
622 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
623 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
624 ** object.
625 */
626 typedef struct sqlite3 sqlite3;
627
628
629 /*
630 ** CAPI3REF: 64-Bit Integer Types {F10200}
631 ** KEYWORDS: sqlite_int64 sqlite_uint64
632 **
633 ** Because there is no cross-platform way to specify 64-bit integer types
634 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
635 **
636 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
637 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
638 ** supported for backwards compatibility only.
639 **
640 ** INVARIANTS:
641 **
642 ** {F10201} The [sqlite_int64] and [sqlite3_int64] types specify a
643 **          64-bit signed integer.
644 **
645 ** {F10202} The [sqlite_uint64] and [sqlite3_uint64] types specify
646 **          a 64-bit unsigned integer.
647 */
648 #ifdef SQLITE_INT64_TYPE
649   typedef SQLITE_INT64_TYPE sqlite_int64;
650   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
651 #elif defined(_MSC_VER) || defined(__BORLANDC__)
652   typedef __int64 sqlite_int64;
653   typedef unsigned __int64 sqlite_uint64;
654 #else
655   typedef long long int sqlite_int64;
656   typedef unsigned long long int sqlite_uint64;
657 #endif
658 typedef sqlite_int64 sqlite3_int64;
659 typedef sqlite_uint64 sqlite3_uint64;
660
661 /*
662 ** If compiling for a processor that lacks floating point support,
663 ** substitute integer for floating-point
664 */
665 #ifdef SQLITE_OMIT_FLOATING_POINT
666 # define double sqlite3_int64
667 #endif
668
669 /*
670 ** CAPI3REF: Closing A Database Connection {F12010}
671 **
672 ** This routine is the destructor for the [sqlite3] object.  
673 **
674 ** Applications should [sqlite3_finalize | finalize] all
675 ** [prepared statements] and
676 ** [sqlite3_blob_close | close] all [sqlite3_blob | BLOBs] 
677 ** associated with the [sqlite3] object prior
678 ** to attempting to close the [sqlite3] object.
679 **
680 ** <todo>What happens to pending transactions?  Are they
681 ** rolled back, or abandoned?</todo>
682 **
683 ** INVARIANTS:
684 **
685 ** {F12011} The [sqlite3_close()] interface destroys an [sqlite3] object
686 **          allocated by a prior call to [sqlite3_open()],
687 **          [sqlite3_open16()], or [sqlite3_open_v2()].
688 **
689 ** {F12012} The [sqlite3_close()] function releases all memory used by the
690 **          connection and closes all open files.
691 **
692 ** {F12013} If the database connection contains
693 **          [prepared statements] that have not been
694 **          finalized by [sqlite3_finalize()], then [sqlite3_close()]
695 **          returns [SQLITE_BUSY] and leaves the connection open.
696 **
697 ** {F12014} Giving sqlite3_close() a NULL pointer is a harmless no-op.
698 **
699 ** LIMITATIONS:
700 **
701 ** {U12015} The parameter to [sqlite3_close()] must be an [sqlite3] object
702 **          pointer previously obtained from [sqlite3_open()] or the 
703 **          equivalent, or NULL.
704 **
705 ** {U12016} The parameter to [sqlite3_close()] must not have been previously
706 **          closed.
707 */
708 SQLITE_API int sqlite3_close(sqlite3 *);
709
710 /*
711 ** The type for a callback function.
712 ** This is legacy and deprecated.  It is included for historical
713 ** compatibility and is not documented.
714 */
715 typedef int (*sqlite3_callback)(void*,int,char**, char**);
716
717 /*
718 ** CAPI3REF: One-Step Query Execution Interface {F12100}
719 **
720 ** The sqlite3_exec() interface is a convenient way of running
721 ** one or more SQL statements without a lot of C code.  The
722 ** SQL statements are passed in as the second parameter to
723 ** sqlite3_exec().  The statements are evaluated one by one
724 ** until either an error or an interrupt is encountered or
725 ** until they are all done.  The 3rd parameter is an optional
726 ** callback that is invoked once for each row of any query results
727 ** produced by the SQL statements.  The 5th parameter tells where
728 ** to write any error messages.
729 **
730 ** The sqlite3_exec() interface is implemented in terms of
731 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
732 ** The sqlite3_exec() routine does nothing that cannot be done
733 ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
734 ** The sqlite3_exec() is just a convenient wrapper.
735 **
736 ** INVARIANTS:
737 ** 
738 ** {F12101} The [sqlite3_exec()] interface evaluates zero or more UTF-8
739 **          encoded, semicolon-separated, SQL statements in the
740 **          zero-terminated string of its 2nd parameter within the
741 **          context of the [sqlite3] object given in the 1st parameter.
742 **
743 ** {F12104} The return value of [sqlite3_exec()] is SQLITE_OK if all
744 **          SQL statements run successfully.
745 **
746 ** {F12105} The return value of [sqlite3_exec()] is an appropriate 
747 **          non-zero error code if any SQL statement fails.
748 **
749 ** {F12107} If one or more of the SQL statements handed to [sqlite3_exec()]
750 **          return results and the 3rd parameter is not NULL, then
751 **          the callback function specified by the 3rd parameter is
752 **          invoked once for each row of result.
753 **
754 ** {F12110} If the callback returns a non-zero value then [sqlite3_exec()]
755 **          will aborted the SQL statement it is currently evaluating,
756 **          skip all subsequent SQL statements, and return [SQLITE_ABORT].
757 **          <todo>What happens to *errmsg here?  Does the result code for
758 **          sqlite3_errcode() get set?</todo>
759 **
760 ** {F12113} The [sqlite3_exec()] routine will pass its 4th parameter through
761 **          as the 1st parameter of the callback.
762 **
763 ** {F12116} The [sqlite3_exec()] routine sets the 2nd parameter of its
764 **          callback to be the number of columns in the current row of
765 **          result.
766 **
767 ** {F12119} The [sqlite3_exec()] routine sets the 3rd parameter of its 
768 **          callback to be an array of pointers to strings holding the
769 **          values for each column in the current result set row as
770 **          obtained from [sqlite3_column_text()].
771 **
772 ** {F12122} The [sqlite3_exec()] routine sets the 4th parameter of its
773 **          callback to be an array of pointers to strings holding the
774 **          names of result columns as obtained from [sqlite3_column_name()].
775 **
776 ** {F12125} If the 3rd parameter to [sqlite3_exec()] is NULL then
777 **          [sqlite3_exec()] never invokes a callback.  All query
778 **          results are silently discarded.
779 **
780 ** {F12128} If an error occurs while parsing or evaluating any of the SQL
781 **          statements handed to [sqlite3_exec()] then [sqlite3_exec()] will
782 **          return an [error code] other than [SQLITE_OK].
783 **
784 ** {F12131} If an error occurs while parsing or evaluating any of the SQL
785 **          handed to [sqlite3_exec()] and if the 5th parameter (errmsg)
786 **          to [sqlite3_exec()] is not NULL, then an error message is
787 **          allocated using the equivalent of [sqlite3_mprintf()] and
788 **          *errmsg is made to point to that message.
789 **
790 ** {F12134} The [sqlite3_exec()] routine does not change the value of
791 **          *errmsg if errmsg is NULL or if there are no errors.
792 **
793 ** {F12137} The [sqlite3_exec()] function sets the error code and message
794 **          accessible via [sqlite3_errcode()], [sqlite3_errmsg()], and
795 **          [sqlite3_errmsg16()].
796 **
797 ** LIMITATIONS:
798 **
799 ** {U12141} The first parameter to [sqlite3_exec()] must be an valid and open
800 **          [database connection].
801 **
802 ** {U12142} The database connection must not be closed while
803 **          [sqlite3_exec()] is running.
804 ** 
805 ** {U12143} The calling function is should use [sqlite3_free()] to free
806 **          the memory that *errmsg is left pointing at once the error
807 **          message is no longer needed.
808 **
809 ** {U12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()]
810 **          must remain unchanged while [sqlite3_exec()] is running.
811 */
812 SQLITE_API int sqlite3_exec(
813   sqlite3*,                                  /* An open database */
814   const char *sql,                           /* SQL to be evaluted */
815   int (*callback)(void*,int,char**,char**),  /* Callback function */
816   void *,                                    /* 1st argument to callback */
817   char **errmsg                              /* Error msg written here */
818 );
819
820 /*
821 ** CAPI3REF: Result Codes {F10210}
822 ** KEYWORDS: SQLITE_OK {error code} {error codes}
823 **
824 ** Many SQLite functions return an integer result code from the set shown
825 ** here in order to indicates success or failure.
826 **
827 ** See also: [SQLITE_IOERR_READ | extended result codes]
828 */
829 #define SQLITE_OK           0   /* Successful result */
830 /* beginning-of-error-codes */
831 #define SQLITE_ERROR        1   /* SQL error or missing database */
832 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
833 #define SQLITE_PERM         3   /* Access permission denied */
834 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
835 #define SQLITE_BUSY         5   /* The database file is locked */
836 #define SQLITE_LOCKED       6   /* A table in the database is locked */
837 #define SQLITE_NOMEM        7   /* A malloc() failed */
838 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
839 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
840 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
841 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
842 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
843 #define SQLITE_FULL        13   /* Insertion failed because database is full */
844 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
845 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
846 #define SQLITE_EMPTY       16   /* Database is empty */
847 #define SQLITE_SCHEMA      17   /* The database schema changed */
848 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
849 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
850 #define SQLITE_MISMATCH    20   /* Data type mismatch */
851 #define SQLITE_MISUSE      21   /* Library used incorrectly */
852 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
853 #define SQLITE_AUTH        23   /* Authorization denied */
854 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
855 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
856 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
857 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
858 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
859 /* end-of-error-codes */
860
861 /*
862 ** CAPI3REF: Extended Result Codes {F10220}
863 ** KEYWORDS: {extended error code} {extended error codes}
864 ** KEYWORDS: {extended result codes}
865 **
866 ** In its default configuration, SQLite API routines return one of 26 integer
867 ** [SQLITE_OK | result codes].  However, experience has shown that
868 ** many of these result codes are too course-grained.  They do not provide as
869 ** much information about problems as programmers might like.  In an effort to
870 ** address this, newer versions of SQLite (version 3.3.8 and later) include
871 ** support for additional result codes that provide more detailed information
872 ** about errors. The extended result codes are enabled or disabled
873 ** for each database connection using the [sqlite3_extended_result_codes()]
874 ** API.
875 ** 
876 ** Some of the available extended result codes are listed here.
877 ** One may expect the number of extended result codes will be expand
878 ** over time.  Software that uses extended result codes should expect
879 ** to see new result codes in future releases of SQLite.
880 **
881 ** The SQLITE_OK result code will never be extended.  It will always
882 ** be exactly zero.
883 ** 
884 ** INVARIANTS:
885 **
886 ** {F10223} The symbolic name for an extended result code always contains
887 **          a related primary result code as a prefix.
888 **
889 ** {F10224} Primary result code names contain a single "_" character.
890 **
891 ** {F10225} Extended result code names contain two or more "_" characters.
892 **
893 ** {F10226} The numeric value of an extended result code contains the
894 **          numeric value of its corresponding primary result code in
895 **          its least significant 8 bits.
896 */
897 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
898 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
899 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
900 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
901 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
902 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
903 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
904 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
905 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
906 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
907 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
908 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
909
910 /*
911 ** CAPI3REF: Flags For File Open Operations {F10230}
912 **
913 ** These bit values are intended for use in the
914 ** 3rd parameter to the [sqlite3_open_v2()] interface and
915 ** in the 4th parameter to the xOpen method of the
916 ** [sqlite3_vfs] object.
917 */
918 #define SQLITE_OPEN_READONLY         0x00000001
919 #define SQLITE_OPEN_READWRITE        0x00000002
920 #define SQLITE_OPEN_CREATE           0x00000004
921 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
922 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
923 #define SQLITE_OPEN_MAIN_DB          0x00000100
924 #define SQLITE_OPEN_TEMP_DB          0x00000200
925 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
926 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
927 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
928 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
929 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
930
931 /*
932 ** CAPI3REF: Device Characteristics {F10240}
933 **
934 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
935 ** object returns an integer which is a vector of the these
936 ** bit values expressing I/O characteristics of the mass storage
937 ** device that holds the file that the [sqlite3_io_methods]
938 ** refers to.
939 **
940 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
941 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
942 ** mean that writes of blocks that are nnn bytes in size and
943 ** are aligned to an address which is an integer multiple of
944 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
945 ** that when data is appended to a file, the data is appended
946 ** first then the size of the file is extended, never the other
947 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
948 ** information is written to disk in the same order as calls
949 ** to xWrite().
950 */
951 #define SQLITE_IOCAP_ATOMIC          0x00000001
952 #define SQLITE_IOCAP_ATOMIC512       0x00000002
953 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
954 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
955 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
956 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
957 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
958 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
959 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
960 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
961 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
962
963 /*
964 ** CAPI3REF: File Locking Levels {F10250}
965 **
966 ** SQLite uses one of these integer values as the second
967 ** argument to calls it makes to the xLock() and xUnlock() methods
968 ** of an [sqlite3_io_methods] object.
969 */
970 #define SQLITE_LOCK_NONE          0
971 #define SQLITE_LOCK_SHARED        1
972 #define SQLITE_LOCK_RESERVED      2
973 #define SQLITE_LOCK_PENDING       3
974 #define SQLITE_LOCK_EXCLUSIVE     4
975
976 /*
977 ** CAPI3REF: Synchronization Type Flags {F10260}
978 **
979 ** When SQLite invokes the xSync() method of an
980 ** [sqlite3_io_methods] object it uses a combination of
981 ** these integer values as the second argument.
982 **
983 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
984 ** sync operation only needs to flush data to mass storage.  Inode
985 ** information need not be flushed. The SQLITE_SYNC_NORMAL flag means 
986 ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means 
987 ** to use Mac OS-X style fullsync instead of fsync().
988 */
989 #define SQLITE_SYNC_NORMAL        0x00002
990 #define SQLITE_SYNC_FULL          0x00003
991 #define SQLITE_SYNC_DATAONLY      0x00010
992
993
994 /*
995 ** CAPI3REF: OS Interface Open File Handle {F11110}
996 **
997 ** An [sqlite3_file] object represents an open file in the OS
998 ** interface layer.  Individual OS interface implementations will
999 ** want to subclass this object by appending additional fields
1000 ** for their own use.  The pMethods entry is a pointer to an
1001 ** [sqlite3_io_methods] object that defines methods for performing
1002 ** I/O operations on the open file.
1003 */
1004 typedef struct sqlite3_file sqlite3_file;
1005 struct sqlite3_file {
1006   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1007 };
1008
1009 /*
1010 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
1011 **
1012 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
1013 ** an instance of this object.  This object defines the
1014 ** methods used to perform various operations against the open file.
1015 **
1016 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1017 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1018 *  The second choice is an
1019 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
1020 ** indicate that only the data of the file and not its inode needs to be
1021 ** synced.
1022 ** 
1023 ** The integer values to xLock() and xUnlock() are one of
1024 ** <ul>
1025 ** <li> [SQLITE_LOCK_NONE],
1026 ** <li> [SQLITE_LOCK_SHARED],
1027 ** <li> [SQLITE_LOCK_RESERVED],
1028 ** <li> [SQLITE_LOCK_PENDING], or
1029 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1030 ** </ul>
1031 ** xLock() increases the lock. xUnlock() decreases the lock.  
1032 ** The xCheckReservedLock() method looks
1033 ** to see if any database connection, either in this
1034 ** process or in some other process, is holding an RESERVED,
1035 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1036 ** if such a lock exists and false if not.
1037 ** 
1038 ** The xFileControl() method is a generic interface that allows custom
1039 ** VFS implementations to directly control an open file using the
1040 ** [sqlite3_file_control()] interface.  The second "op" argument
1041 ** is an integer opcode.   The third
1042 ** argument is a generic pointer which is intended to be a pointer
1043 ** to a structure that may contain arguments or space in which to
1044 ** write return values.  Potential uses for xFileControl() might be
1045 ** functions to enable blocking locks with timeouts, to change the
1046 ** locking strategy (for example to use dot-file locks), to inquire
1047 ** about the status of a lock, or to break stale locks.  The SQLite
1048 ** core reserves opcodes less than 100 for its own use. 
1049 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1050 ** Applications that define a custom xFileControl method should use opcodes 
1051 ** greater than 100 to avoid conflicts.
1052 **
1053 ** The xSectorSize() method returns the sector size of the
1054 ** device that underlies the file.  The sector size is the
1055 ** minimum write that can be performed without disturbing
1056 ** other bytes in the file.  The xDeviceCharacteristics()
1057 ** method returns a bit vector describing behaviors of the
1058 ** underlying device:
1059 **
1060 ** <ul>
1061 ** <li> [SQLITE_IOCAP_ATOMIC]
1062 ** <li> [SQLITE_IOCAP_ATOMIC512]
1063 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1064 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1065 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1066 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1067 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1068 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1069 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1070 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1071 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1072 ** </ul>
1073 **
1074 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1075 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1076 ** mean that writes of blocks that are nnn bytes in size and
1077 ** are aligned to an address which is an integer multiple of
1078 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1079 ** that when data is appended to a file, the data is appended
1080 ** first then the size of the file is extended, never the other
1081 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1082 ** information is written to disk in the same order as calls
1083 ** to xWrite().
1084 */
1085 typedef struct sqlite3_io_methods sqlite3_io_methods;
1086 struct sqlite3_io_methods {
1087   int iVersion;
1088   int (*xClose)(sqlite3_file*);
1089   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1090   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1091   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1092   int (*xSync)(sqlite3_file*, int flags);
1093   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1094   int (*xLock)(sqlite3_file*, int);
1095   int (*xUnlock)(sqlite3_file*, int);
1096   int (*xCheckReservedLock)(sqlite3_file*);
1097   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1098   int (*xSectorSize)(sqlite3_file*);
1099   int (*xDeviceCharacteristics)(sqlite3_file*);
1100   /* Additional methods may be added in future releases */
1101 };
1102
1103 /*
1104 ** CAPI3REF: Standard File Control Opcodes {F11310}
1105 **
1106 ** These integer constants are opcodes for the xFileControl method
1107 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
1108 ** interface.
1109 **
1110 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1111 ** opcode causes the xFileControl method to write the current state of
1112 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1113 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1114 ** into an integer that the pArg argument points to. This capability
1115 ** is used during testing and only needs to be supported when SQLITE_TEST
1116 ** is defined.
1117 */
1118 #define SQLITE_FCNTL_LOCKSTATE        1
1119
1120 /*
1121 ** CAPI3REF: Mutex Handle {F17110}
1122 **
1123 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1124 ** abstract type for a mutex object.  The SQLite core never looks
1125 ** at the internal representation of an [sqlite3_mutex].  It only
1126 ** deals with pointers to the [sqlite3_mutex] object.
1127 **
1128 ** Mutexes are created using [sqlite3_mutex_alloc()].
1129 */
1130 typedef struct sqlite3_mutex sqlite3_mutex;
1131
1132 /*
1133 ** CAPI3REF: OS Interface Object {F11140}
1134 **
1135 ** An instance of this object defines the interface between the
1136 ** SQLite core and the underlying operating system.  The "vfs"
1137 ** in the name of the object stands for "virtual file system".
1138 **
1139 ** The iVersion field is initially 1 but may be larger for future
1140 ** versions of SQLite.  Additional fields may be appended to this
1141 ** object when the iVersion value is increased.
1142 **
1143 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1144 ** structure used by this VFS.  mxPathname is the maximum length of
1145 ** a pathname in this VFS.
1146 **
1147 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1148 ** the pNext pointer.  The [sqlite3_vfs_register()]
1149 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1150 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1151 ** searches the list.
1152 **
1153 ** The pNext field is the only field in the sqlite3_vfs 
1154 ** structure that SQLite will ever modify.  SQLite will only access
1155 ** or modify this field while holding a particular static mutex.
1156 ** The application should never modify anything within the sqlite3_vfs
1157 ** object once the object has been registered.
1158 **
1159 ** The zName field holds the name of the VFS module.  The name must
1160 ** be unique across all VFS modules.
1161 **
1162 ** {F11141} SQLite will guarantee that the zFilename string passed to
1163 ** xOpen() is a full pathname as generated by xFullPathname() and
1164 ** that the string will be valid and unchanged until xClose() is
1165 ** called.  {END} So the [sqlite3_file] can store a pointer to the
1166 ** filename if it needs to remember the filename for some reason.
1167 **
1168 ** {F11142} The flags argument to xOpen() includes all bits set in
1169 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1170 ** or [sqlite3_open16()] is used, then flags includes at least
1171 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
1172 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1173 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
1174 ** set.
1175 ** 
1176 ** {F11143} SQLite will also add one of the following flags to the xOpen()
1177 ** call, depending on the object being opened:
1178 ** 
1179 ** <ul>
1180 ** <li>  [SQLITE_OPEN_MAIN_DB]
1181 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1182 ** <li>  [SQLITE_OPEN_TEMP_DB]
1183 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1184 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1185 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1186 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1187 ** </ul> {END}
1188 **
1189 ** The file I/O implementation can use the object type flags to
1190 ** changes the way it deals with files.  For example, an application
1191 ** that does not care about crash recovery or rollback might make
1192 ** the open of a journal file a no-op.  Writes to this journal would
1193 ** also be no-ops, and any attempt to read the journal would return 
1194 ** SQLITE_IOERR.  Or the implementation might recognize that a database 
1195 ** file will be doing page-aligned sector reads and writes in a random 
1196 ** order and set up its I/O subsystem accordingly.
1197 ** 
1198 ** SQLite might also add one of the following flags to the xOpen
1199 ** method:
1200 ** 
1201 ** <ul>
1202 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1203 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1204 ** </ul>
1205 ** 
1206 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1207 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
1208 ** will be set for TEMP  databases, journals and for subjournals. 
1209 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
1210 ** for exclusive access.  This flag is set for all files except
1211 ** for the main database file. {END}
1212 ** 
1213 ** {F11148} At least szOsFile bytes of memory are allocated by SQLite 
1214 ** to hold the  [sqlite3_file] structure passed as the third 
1215 ** argument to xOpen.  {END}  The xOpen method does not have to
1216 ** allocate the structure; it should just fill it in.
1217 ** 
1218 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
1219 ** to test for the existance of a file,
1220 ** or [SQLITE_ACCESS_READWRITE] to test to see
1221 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
1222 ** to test to see if a file is at least readable.  {END} The file can be a 
1223 ** directory.
1224 ** 
1225 ** {F11150} SQLite will always allocate at least mxPathname+1 bytes for
1226 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
1227 ** size of the output buffer is also passed as a parameter to both 
1228 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
1229 ** should be returned. As this is handled as a fatal error by SQLite,
1230 ** vfs implementations should endeavor to prevent this by setting 
1231 ** mxPathname to a sufficiently large value.
1232 ** 
1233 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1234 ** are not strictly a part of the filesystem, but they are
1235 ** included in the VFS structure for completeness.
1236 ** The xRandomness() function attempts to return nBytes bytes
1237 ** of good-quality randomness into zOut.  The return value is
1238 ** the actual number of bytes of randomness obtained.  The
1239 ** xSleep() method causes the calling thread to sleep for at
1240 ** least the number of microseconds given.  The xCurrentTime()
1241 ** method returns a Julian Day Number for the current date and
1242 ** time.
1243 */
1244 typedef struct sqlite3_vfs sqlite3_vfs;
1245 struct sqlite3_vfs {
1246   int iVersion;            /* Structure version number */
1247   int szOsFile;            /* Size of subclassed sqlite3_file */
1248   int mxPathname;          /* Maximum file pathname length */
1249   sqlite3_vfs *pNext;      /* Next registered VFS */
1250   const char *zName;       /* Name of this virtual file system */
1251   void *pAppData;          /* Pointer to application-specific data */
1252   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1253                int flags, int *pOutFlags);
1254   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1255   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
1256   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
1257   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1258   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1259   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1260   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
1261   void (*xDlClose)(sqlite3_vfs*, void*);
1262   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1263   int (*xSleep)(sqlite3_vfs*, int microseconds);
1264   int (*xCurrentTime)(sqlite3_vfs*, double*);
1265   /* New fields may be appended in figure versions.  The iVersion
1266   ** value will increment whenever this happens. */
1267 };
1268
1269 /*
1270 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
1271 **
1272 ** {F11191} These integer constants can be used as the third parameter to
1273 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
1274 ** what kind of permissions the xAccess method is
1275 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
1276 ** simply checks to see if the file exists. {F11193} With
1277 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
1278 ** if the file is both readable and writable.  {F11194} With
1279 ** SQLITE_ACCESS_READ the xAccess method
1280 ** checks to see if the file is readable.
1281 */
1282 #define SQLITE_ACCESS_EXISTS    0
1283 #define SQLITE_ACCESS_READWRITE 1
1284 #define SQLITE_ACCESS_READ      2
1285
1286 /*
1287 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
1288 **
1289 ** The sqlite3_extended_result_codes() routine enables or disables the
1290 ** [SQLITE_IOERR_READ | extended result codes] feature of SQLite.
1291 ** The extended result codes are disabled by default for historical
1292 ** compatibility.
1293 **
1294 ** INVARIANTS:
1295 **
1296 ** {F12201} Each new [database connection] has the 
1297 **          [extended result codes] feature
1298 **          disabled by default.
1299 **
1300 ** {F12202} The [sqlite3_extended_result_codes(D,F)] interface will enable
1301 **          [extended result codes] for the 
1302 **          [database connection] D if the F parameter
1303 **          is true, or disable them if F is false.
1304 */
1305 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1306
1307 /*
1308 ** CAPI3REF: Last Insert Rowid {F12220}
1309 **
1310 ** Each entry in an SQLite table has a unique 64-bit signed
1311 ** integer key called the "rowid". The rowid is always available
1312 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1313 ** names are not also used by explicitly declared columns. If
1314 ** the table has a column of type INTEGER PRIMARY KEY then that column
1315 ** is another alias for the rowid.
1316 **
1317 ** This routine returns the rowid of the most recent
1318 ** successful INSERT into the database from the database connection
1319 ** shown in the first argument.  If no successful inserts
1320 ** have ever occurred on this database connection, zero is returned.
1321 **
1322 ** If an INSERT occurs within a trigger, then the rowid of the
1323 ** inserted row is returned by this routine as long as the trigger
1324 ** is running.  But once the trigger terminates, the value returned
1325 ** by this routine reverts to the last value inserted before the
1326 ** trigger fired.
1327 **
1328 ** An INSERT that fails due to a constraint violation is not a
1329 ** successful insert and does not change the value returned by this
1330 ** routine.  Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1331 ** and INSERT OR ABORT make no changes to the return value of this
1332 ** routine when their insertion fails.  When INSERT OR REPLACE 
1333 ** encounters a constraint violation, it does not fail.  The
1334 ** INSERT continues to completion after deleting rows that caused
1335 ** the constraint problem so INSERT OR REPLACE will always change
1336 ** the return value of this interface. 
1337 **
1338 ** For the purposes of this routine, an insert is considered to
1339 ** be successful even if it is subsequently rolled back.
1340 **
1341 ** INVARIANTS:
1342 **
1343 ** {F12221} The [sqlite3_last_insert_rowid()] function returns the
1344 **          rowid of the most recent successful insert done
1345 **          on the same database connection and within the same
1346 **          trigger context, or zero if there have
1347 **          been no qualifying inserts on that connection.
1348 **
1349 ** {F12223} The [sqlite3_last_insert_rowid()] function returns
1350 **          same value when called from the same trigger context
1351 **          immediately before and after a ROLLBACK.
1352 **
1353 ** LIMITATIONS:
1354 **
1355 ** {U12232} If a separate thread does a new insert on the same
1356 **          database connection while the [sqlite3_last_insert_rowid()]
1357 **          function is running and thus changes the last insert rowid,
1358 **          then the value returned by [sqlite3_last_insert_rowid()] is
1359 **          unpredictable and might not equal either the old or the new
1360 **          last insert rowid.
1361 */
1362 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1363
1364 /*
1365 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
1366 **
1367 ** This function returns the number of database rows that were changed
1368 ** or inserted or deleted by the most recently completed SQL statement
1369 ** on the connection specified by the first parameter.  Only
1370 ** changes that are directly specified by the INSERT, UPDATE, or
1371 ** DELETE statement are counted.  Auxiliary changes caused by
1372 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1373 ** to find the total number of changes including changes caused by triggers.
1374 **
1375 ** A "row change" is a change to a single row of a single table
1376 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1377 ** are changed as side effects of REPLACE constraint resolution,
1378 ** rollback, ABORT processing, DROP TABLE, or by any other
1379 ** mechanisms do not count as direct row changes.
1380 **
1381 ** A "trigger context" is a scope of execution that begins and
1382 ** ends with the script of a trigger.  Most SQL statements are
1383 ** evaluated outside of any trigger.  This is the "top level"
1384 ** trigger context.  If a trigger fires from the top level, a
1385 ** new trigger context is entered for the duration of that one
1386 ** trigger.  Subtriggers create subcontexts for their duration.
1387 **
1388 ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1389 ** not create a new trigger context.
1390 **
1391 ** This function returns the number of direct row changes in the
1392 ** most recent INSERT, UPDATE, or DELETE statement within the same
1393 ** trigger context.
1394 **
1395 ** So when called from the top level, this function returns the
1396 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1397 ** that also occurred at the top level.
1398 ** Within the body of a trigger, the sqlite3_changes() interface
1399 ** can be called to find the number of
1400 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1401 ** statement within the body of the same trigger.
1402 ** However, the number returned does not include in changes
1403 ** caused by subtriggers since they have their own context.
1404 **
1405 ** SQLite implements the command "DELETE FROM table" without
1406 ** a WHERE clause by dropping and recreating the table.  (This is much
1407 ** faster than going through and deleting individual elements from the
1408 ** table.)  Because of this optimization, the deletions in
1409 ** "DELETE FROM table" are not row changes and will not be counted
1410 ** by the sqlite3_changes() or [sqlite3_total_changes()] functions.
1411 ** To get an accurate count of the number of rows deleted, use
1412 ** "DELETE FROM table WHERE 1" instead.
1413 **
1414 ** INVARIANTS:
1415 **
1416 ** {F12241} The [sqlite3_changes()] function returns the number of
1417 **          row changes caused by the most recent INSERT, UPDATE,
1418 **          or DELETE statement on the same database connection and
1419 **          within the same trigger context, or zero if there have
1420 **          not been any qualifying row changes.
1421 **
1422 ** LIMITATIONS:
1423 **
1424 ** {U12252} If a separate thread makes changes on the same database connection
1425 **          while [sqlite3_changes()] is running then the value returned
1426 **          is unpredictable and unmeaningful.
1427 */
1428 SQLITE_API int sqlite3_changes(sqlite3*);
1429
1430 /*
1431 ** CAPI3REF: Total Number Of Rows Modified {F12260}
1432 ***
1433 ** This function returns the number of row changes caused
1434 ** by INSERT, UPDATE or DELETE statements since the database handle
1435 ** was opened.  The count includes all changes from all trigger
1436 ** contexts.  But the count does not include changes used to
1437 ** implement REPLACE constraints, do rollbacks or ABORT processing,
1438 ** or DROP table processing.
1439 ** The changes
1440 ** are counted as soon as the statement that makes them is completed 
1441 ** (when the statement handle is passed to [sqlite3_reset()] or 
1442 ** [sqlite3_finalize()]).
1443 **
1444 ** SQLite implements the command "DELETE FROM table" without
1445 ** a WHERE clause by dropping and recreating the table.  (This is much
1446 ** faster than going
1447 ** through and deleting individual elements from the table.)  Because of
1448 ** this optimization, the change count for "DELETE FROM table" will be
1449 ** zero regardless of the number of elements that were originally in the
1450 ** table. To get an accurate count of the number of rows deleted, use
1451 ** "DELETE FROM table WHERE 1" instead.
1452 **
1453 ** See also the [sqlite3_changes()] interface.
1454 **
1455 ** INVARIANTS:
1456 ** 
1457 ** {F12261} The [sqlite3_total_changes()] returns the total number
1458 **          of row changes caused by INSERT, UPDATE, and/or DELETE
1459 **          statements on the same [database connection], in any
1460 **          trigger context, since the database connection was
1461 **          created.
1462 **
1463 ** LIMITATIONS:
1464 **
1465 ** {U12264} If a separate thread makes changes on the same database connection
1466 **          while [sqlite3_total_changes()] is running then the value 
1467 **          returned is unpredictable and unmeaningful.
1468 */
1469 SQLITE_API int sqlite3_total_changes(sqlite3*);
1470
1471 /*
1472 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
1473 **
1474 ** This function causes any pending database operation to abort and
1475 ** return at its earliest opportunity. This routine is typically
1476 ** called in response to a user action such as pressing "Cancel"
1477 ** or Ctrl-C where the user wants a long query operation to halt
1478 ** immediately.
1479 **
1480 ** It is safe to call this routine from a thread different from the
1481 ** thread that is currently running the database operation.  But it
1482 ** is not safe to call this routine with a database connection that
1483 ** is closed or might close before sqlite3_interrupt() returns.
1484 **
1485 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
1486 ** is called, then it might not have an opportunity to be interrupted.
1487 ** It might continue to completion.
1488 ** An SQL operation that is interrupted will return
1489 ** [SQLITE_INTERRUPT].  If the interrupted SQL operation is an
1490 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
1491 ** then the entire transaction will be rolled back automatically.
1492 ** A call to sqlite3_interrupt() has no effect on SQL statements
1493 ** that are started after sqlite3_interrupt() returns.
1494 **
1495 ** INVARIANTS:
1496 **
1497 ** {F12271} The [sqlite3_interrupt()] interface will force all running
1498 **          SQL statements associated with the same database connection
1499 **          to halt after processing at most one additional row of
1500 **          data.
1501 **
1502 ** {F12272} Any SQL statement that is interrupted by [sqlite3_interrupt()]
1503 **          will return [SQLITE_INTERRUPT].
1504 **
1505 ** LIMITATIONS:
1506 **
1507 ** {U12279} If the database connection closes while [sqlite3_interrupt()]
1508 **          is running then bad things will likely happen.
1509 */
1510 SQLITE_API void sqlite3_interrupt(sqlite3*);
1511
1512 /*
1513 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
1514 **
1515 ** These routines are useful for command-line input to determine if the
1516 ** currently entered text seems to form complete a SQL statement or
1517 ** if additional input is needed before sending the text into
1518 ** SQLite for parsing.  These routines return true if the input string
1519 ** appears to be a complete SQL statement.  A statement is judged to be
1520 ** complete if it ends with a semicolon token and is not a fragment of a
1521 ** CREATE TRIGGER statement.  Semicolons that are embedded within
1522 ** string literals or quoted identifier names or comments are not
1523 ** independent tokens (they are part of the token in which they are
1524 ** embedded) and thus do not count as a statement terminator.
1525 **
1526 ** These routines do not parse the SQL and
1527 ** so will not detect syntactically incorrect SQL.
1528 **
1529 ** INVARIANTS:
1530 **
1531 ** {F10511} The sqlite3_complete() and sqlite3_complete16() functions
1532 **          return true (non-zero) if and only if the last
1533 **          non-whitespace token in their input is a semicolon that
1534 **          is not in between the BEGIN and END of a CREATE TRIGGER
1535 **          statement.
1536 **
1537 ** LIMITATIONS:
1538 **
1539 ** {U10512} The input to sqlite3_complete() must be a zero-terminated
1540 **          UTF-8 string.
1541 **
1542 ** {U10513} The input to sqlite3_complete16() must be a zero-terminated
1543 **          UTF-16 string in native byte order.
1544 */
1545 SQLITE_API int sqlite3_complete(const char *sql);
1546 SQLITE_API int sqlite3_complete16(const void *sql);
1547
1548 /*
1549 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
1550 **
1551 ** This routine identifies a callback function that might be
1552 ** invoked whenever an attempt is made to open a database table 
1553 ** that another thread or process has locked.
1554 ** If the busy callback is NULL, then [SQLITE_BUSY]
1555 ** or [SQLITE_IOERR_BLOCKED]
1556 ** is returned immediately upon encountering the lock.
1557 ** If the busy callback is not NULL, then the
1558 ** callback will be invoked with two arguments.  The
1559 ** first argument to the handler is a copy of the void* pointer which
1560 ** is the third argument to this routine.  The second argument to
1561 ** the handler is the number of times that the busy handler has
1562 ** been invoked for this locking event.   If the
1563 ** busy callback returns 0, then no additional attempts are made to
1564 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
1565 ** If the callback returns non-zero, then another attempt
1566 ** is made to open the database for reading and the cycle repeats.
1567 **
1568 ** The presence of a busy handler does not guarantee that
1569 ** it will be invoked when there is lock contention.
1570 ** If SQLite determines that invoking the busy handler could result in
1571 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
1572 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
1573 ** busy handler.
1574 ** Consider a scenario where one process is holding a read lock that
1575 ** it is trying to promote to a reserved lock and
1576 ** a second process is holding a reserved lock that it is trying
1577 ** to promote to an exclusive lock.  The first process cannot proceed
1578 ** because it is blocked by the second and the second process cannot
1579 ** proceed because it is blocked by the first.  If both processes
1580 ** invoke the busy handlers, neither will make any progress.  Therefore,
1581 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
1582 ** will induce the first process to release its read lock and allow
1583 ** the second process to proceed.
1584 **
1585 ** The default busy callback is NULL.
1586 **
1587 ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
1588 ** when SQLite is in the middle of a large transaction where all the
1589 ** changes will not fit into the in-memory cache.  SQLite will
1590 ** already hold a RESERVED lock on the database file, but it needs
1591 ** to promote this lock to EXCLUSIVE so that it can spill cache
1592 ** pages into the database file without harm to concurrent
1593 ** readers.  If it is unable to promote the lock, then the in-memory
1594 ** cache will be left in an inconsistent state and so the error
1595 ** code is promoted from the relatively benign [SQLITE_BUSY] to
1596 ** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
1597 ** forces an automatic rollback of the changes.  See the
1598 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
1599 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
1600 ** this is important.
1601 **      
1602 ** There can only be a single busy handler defined for each database
1603 ** connection.  Setting a new busy handler clears any previous one. 
1604 ** Note that calling [sqlite3_busy_timeout()] will also set or clear
1605 ** the busy handler.
1606 **
1607 ** INVARIANTS:
1608 **
1609 ** {F12311} The [sqlite3_busy_handler()] function replaces the busy handler
1610 **          callback in the database connection identified by the 1st
1611 **          parameter with a new busy handler identified by the 2nd and 3rd
1612 **          parameters.
1613 **
1614 ** {F12312} The default busy handler for new database connections is NULL.
1615 **
1616 ** {F12314} When two or more database connection share a common cache,
1617 **          the busy handler for the database connection currently using
1618 **          the cache is invoked when the cache encounters a lock.
1619 **
1620 ** {F12316} If a busy handler callback returns zero, then the SQLite
1621 **          interface that provoked the locking event will return
1622 **          [SQLITE_BUSY].
1623 **
1624 ** {F12318} SQLite will invokes the busy handler with two argument which
1625 **          are a copy of the pointer supplied by the 3rd parameter to
1626 **          [sqlite3_busy_handler()] and a count of the number of prior
1627 **          invocations of the busy handler for the same locking event.
1628 **
1629 ** LIMITATIONS:
1630 **
1631 ** {U12319} A busy handler should not call close the database connection
1632 **          or prepared statement that invoked the busy handler.
1633 */
1634 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
1635
1636 /*
1637 ** CAPI3REF: Set A Busy Timeout {F12340}
1638 **
1639 ** This routine sets a [sqlite3_busy_handler | busy handler]
1640 ** that sleeps for a while when a
1641 ** table is locked.  The handler will sleep multiple times until 
1642 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
1643 ** "ms" milliseconds of sleeping, the handler returns 0 which
1644 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
1645 **
1646 ** Calling this routine with an argument less than or equal to zero
1647 ** turns off all busy handlers.
1648 **
1649 ** There can only be a single busy handler for a particular database
1650 ** connection.  If another busy handler was defined  
1651 ** (using [sqlite3_busy_handler()]) prior to calling
1652 ** this routine, that other busy handler is cleared.
1653 **
1654 ** INVARIANTS:
1655 **
1656 ** {F12341} The [sqlite3_busy_timeout()] function overrides any prior
1657 **          [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting
1658 **          on the same database connection.
1659 **
1660 ** {F12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than
1661 **          or equal to zero, then the busy handler is cleared so that
1662 **          all subsequent locking events immediately return [SQLITE_BUSY].
1663 **
1664 ** {F12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive
1665 **          number N, then a busy handler is set that repeatedly calls
1666 **          the xSleep() method in the VFS interface until either the
1667 **          lock clears or until the cumulative sleep time reported back
1668 **          by xSleep() exceeds N milliseconds.
1669 */
1670 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
1671
1672 /*
1673 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
1674 **
1675 ** Definition: A <b>result table</b> is memory data structure created by the
1676 ** [sqlite3_get_table()] interface.  A result table records the
1677 ** complete query results from one or more queries.
1678 **
1679 ** The table conceptually has a number of rows and columns.  But
1680 ** these numbers are not part of the result table itself.  These
1681 ** numbers are obtained separately.  Let N be the number of rows
1682 ** and M be the number of columns.
1683 **
1684 ** A result table is an array of pointers to zero-terminated
1685 ** UTF-8 strings.  There are (N+1)*M elements in the array.  
1686 ** The first M pointers point to zero-terminated strings that 
1687 ** contain the names of the columns.
1688 ** The remaining entries all point to query results.  NULL
1689 ** values are give a NULL pointer.  All other values are in
1690 ** their UTF-8 zero-terminated string representation as returned by
1691 ** [sqlite3_column_text()].
1692 **
1693 ** A result table might consists of one or more memory allocations.
1694 ** It is not safe to pass a result table directly to [sqlite3_free()].
1695 ** A result table should be deallocated using [sqlite3_free_table()].
1696 **
1697 ** As an example of the result table format, suppose a query result
1698 ** is as follows:
1699 **
1700 ** <blockquote><pre>
1701 **        Name        | Age
1702 **        -----------------------
1703 **        Alice       | 43
1704 **        Bob         | 28
1705 **        Cindy       | 21
1706 ** </pre></blockquote>
1707 **
1708 ** There are two column (M==2) and three rows (N==3).  Thus the
1709 ** result table has 8 entries.  Suppose the result table is stored
1710 ** in an array names azResult.  Then azResult holds this content:
1711 **
1712 ** <blockquote><pre>
1713 **        azResult&#91;0] = "Name";
1714 **        azResult&#91;1] = "Age";
1715 **        azResult&#91;2] = "Alice";
1716 **        azResult&#91;3] = "43";
1717 **        azResult&#91;4] = "Bob";
1718 **        azResult&#91;5] = "28";
1719 **        azResult&#91;6] = "Cindy";
1720 **        azResult&#91;7] = "21";
1721 ** </pre></blockquote>
1722 **
1723 ** The sqlite3_get_table() function evaluates one or more
1724 ** semicolon-separated SQL statements in the zero-terminated UTF-8
1725 ** string of its 2nd parameter.  It returns a result table to the
1726 ** pointer given in its 3rd parameter.
1727 **
1728 ** After the calling function has finished using the result, it should 
1729 ** pass the pointer to the result table to sqlite3_free_table() in order to 
1730 ** release the memory that was malloc-ed.  Because of the way the 
1731 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
1732 ** function must not try to call [sqlite3_free()] directly.  Only 
1733 ** [sqlite3_free_table()] is able to release the memory properly and safely.
1734 **
1735 ** The sqlite3_get_table() interface is implemented as a wrapper around
1736 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
1737 ** to any internal data structures of SQLite.  It uses only the public
1738 ** interface defined here.  As a consequence, errors that occur in the
1739 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
1740 ** reflected in subsequent calls to [sqlite3_errcode()] or
1741 ** [sqlite3_errmsg()].
1742 **
1743 ** INVARIANTS:
1744 **
1745 ** {F12371} If a [sqlite3_get_table()] fails a memory allocation, then
1746 **          it frees the result table under construction, aborts the
1747 **          query in process, skips any subsequent queries, sets the
1748 **          *resultp output pointer to NULL and returns [SQLITE_NOMEM].
1749 **
1750 ** {F12373} If the ncolumn parameter to [sqlite3_get_table()] is not NULL
1751 **          then [sqlite3_get_table()] write the number of columns in the
1752 **          result set of the query into *ncolumn if the query is
1753 **          successful (if the function returns SQLITE_OK).
1754 **
1755 ** {F12374} If the nrow parameter to [sqlite3_get_table()] is not NULL
1756 **          then [sqlite3_get_table()] write the number of rows in the
1757 **          result set of the query into *nrow if the query is
1758 **          successful (if the function returns SQLITE_OK).
1759 **
1760 ** {F12376} The [sqlite3_get_table()] function sets its *ncolumn value
1761 **          to the number of columns in the result set of the query in the
1762 **          sql parameter, or to zero if the query in sql has an empty
1763 **          result set.
1764 */
1765 SQLITE_API int sqlite3_get_table(
1766   sqlite3*,             /* An open database */
1767   const char *sql,      /* SQL to be evaluated */
1768   char ***pResult,      /* Results of the query */
1769   int *nrow,            /* Number of result rows written here */
1770   int *ncolumn,         /* Number of result columns written here */
1771   char **errmsg         /* Error msg written here */
1772 );
1773 SQLITE_API void sqlite3_free_table(char **result);
1774
1775 /*
1776 ** CAPI3REF: Formatted String Printing Functions {F17400}
1777 **
1778 ** These routines are workalikes of the "printf()" family of functions
1779 ** from the standard C library.
1780 **
1781 ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
1782 ** results into memory obtained from [sqlite3_malloc()].
1783 ** The strings returned by these two routines should be
1784 ** released by [sqlite3_free()].   Both routines return a
1785 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
1786 ** memory to hold the resulting string.
1787 **
1788 ** In sqlite3_snprintf() routine is similar to "snprintf()" from
1789 ** the standard C library.  The result is written into the
1790 ** buffer supplied as the second parameter whose size is given by
1791 ** the first parameter. Note that the order of the
1792 ** first two parameters is reversed from snprintf().  This is an
1793 ** historical accident that cannot be fixed without breaking
1794 ** backwards compatibility.  Note also that sqlite3_snprintf()
1795 ** returns a pointer to its buffer instead of the number of
1796 ** characters actually written into the buffer.  We admit that
1797 ** the number of characters written would be a more useful return
1798 ** value but we cannot change the implementation of sqlite3_snprintf()
1799 ** now without breaking compatibility.
1800 **
1801 ** As long as the buffer size is greater than zero, sqlite3_snprintf()
1802 ** guarantees that the buffer is always zero-terminated.  The first
1803 ** parameter "n" is the total size of the buffer, including space for
1804 ** the zero terminator.  So the longest string that can be completely
1805 ** written will be n-1 characters.
1806 **
1807 ** These routines all implement some additional formatting
1808 ** options that are useful for constructing SQL statements.
1809 ** All of the usual printf formatting options apply.  In addition, there
1810 ** is are "%q", "%Q", and "%z" options.
1811 **
1812 ** The %q option works like %s in that it substitutes a null-terminated
1813 ** string from the argument list.  But %q also doubles every '\'' character.
1814 ** %q is designed for use inside a string literal.  By doubling each '\''
1815 ** character it escapes that character and allows it to be inserted into
1816 ** the string.
1817 **
1818 ** For example, so some string variable contains text as follows:
1819 **
1820 ** <blockquote><pre>
1821 **  char *zText = "It's a happy day!";
1822 ** </pre></blockquote>
1823 **
1824 ** One can use this text in an SQL statement as follows:
1825 **
1826 ** <blockquote><pre>
1827 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
1828 **  sqlite3_exec(db, zSQL, 0, 0, 0);
1829 **  sqlite3_free(zSQL);
1830 ** </pre></blockquote>
1831 **
1832 ** Because the %q format string is used, the '\'' character in zText
1833 ** is escaped and the SQL generated is as follows:
1834 **
1835 ** <blockquote><pre>
1836 **  INSERT INTO table1 VALUES('It''s a happy day!')
1837 ** </pre></blockquote>
1838 **
1839 ** This is correct.  Had we used %s instead of %q, the generated SQL
1840 ** would have looked like this:
1841 **
1842 ** <blockquote><pre>
1843 **  INSERT INTO table1 VALUES('It's a happy day!');
1844 ** </pre></blockquote>
1845 **
1846 ** This second example is an SQL syntax error.  As a general rule you
1847 ** should always use %q instead of %s when inserting text into a string 
1848 ** literal.
1849 **
1850 ** The %Q option works like %q except it also adds single quotes around
1851 ** the outside of the total string.  Or if the parameter in the argument
1852 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
1853 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
1854 **
1855 ** <blockquote><pre>
1856 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
1857 **  sqlite3_exec(db, zSQL, 0, 0, 0);
1858 **  sqlite3_free(zSQL);
1859 ** </pre></blockquote>
1860 **
1861 ** The code above will render a correct SQL statement in the zSQL
1862 ** variable even if the zText variable is a NULL pointer.
1863 **
1864 ** The "%z" formatting option works exactly like "%s" with the
1865 ** addition that after the string has been read and copied into
1866 ** the result, [sqlite3_free()] is called on the input string. {END}
1867 **
1868 ** INVARIANTS:
1869 **
1870 ** {F17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
1871 **           return either pointers to zero-terminated UTF-8 strings held in
1872 **           memory obtained from [sqlite3_malloc()] or NULL pointers if
1873 **           a call to [sqlite3_malloc()] fails.
1874 **
1875 ** {F17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
1876 **           UTF-8 string into the buffer pointed to by the second parameter
1877 **           provided that the first parameter is greater than zero.
1878 **
1879 ** {F17407}  The [sqlite3_snprintf()] interface does not writes slots of
1880 **           its output buffer (the second parameter) outside the range
1881 **           of 0 through N-1 (where N is the first parameter)
1882 **           regardless of the length of the string
1883 **           requested by the format specification.
1884 **   
1885 */
1886 SQLITE_API char *sqlite3_mprintf(const char*,...);
1887 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
1888 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
1889
1890 /*
1891 ** CAPI3REF: Memory Allocation Subsystem {F17300}
1892 **
1893 ** The SQLite core  uses these three routines for all of its own
1894 ** internal memory allocation needs. "Core" in the previous sentence
1895 ** does not include operating-system specific VFS implementation.  The
1896 ** windows VFS uses native malloc and free for some operations.
1897 **
1898 ** The sqlite3_malloc() routine returns a pointer to a block
1899 ** of memory at least N bytes in length, where N is the parameter.
1900 ** If sqlite3_malloc() is unable to obtain sufficient free
1901 ** memory, it returns a NULL pointer.  If the parameter N to
1902 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
1903 ** a NULL pointer.
1904 **
1905 ** Calling sqlite3_free() with a pointer previously returned
1906 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
1907 ** that it might be reused.  The sqlite3_free() routine is
1908 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
1909 ** to sqlite3_free() is harmless.  After being freed, memory
1910 ** should neither be read nor written.  Even reading previously freed
1911 ** memory might result in a segmentation fault or other severe error.
1912 ** Memory corruption, a segmentation fault, or other severe error
1913 ** might result if sqlite3_free() is called with a non-NULL pointer that
1914 ** was not obtained from sqlite3_malloc() or sqlite3_free().
1915 **
1916 ** The sqlite3_realloc() interface attempts to resize a
1917 ** prior memory allocation to be at least N bytes, where N is the
1918 ** second parameter.  The memory allocation to be resized is the first
1919 ** parameter.  If the first parameter to sqlite3_realloc()
1920 ** is a NULL pointer then its behavior is identical to calling
1921 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
1922 ** If the second parameter to sqlite3_realloc() is zero or
1923 ** negative then the behavior is exactly the same as calling
1924 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
1925 ** Sqlite3_realloc() returns a pointer to a memory allocation
1926 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
1927 ** If M is the size of the prior allocation, then min(N,M) bytes
1928 ** of the prior allocation are copied into the beginning of buffer returned
1929 ** by sqlite3_realloc() and the prior allocation is freed.
1930 ** If sqlite3_realloc() returns NULL, then the prior allocation
1931 ** is not freed.
1932 **
1933 ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
1934 ** is always aligned to at least an 8 byte boundary. {END}
1935 **
1936 ** The default implementation
1937 ** of the memory allocation subsystem uses the malloc(), realloc()
1938 ** and free() provided by the standard C library. {F17382} However, if 
1939 ** SQLite is compiled with the following C preprocessor macro
1940 **
1941 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
1942 **
1943 ** where <i>NNN</i> is an integer, then SQLite create a static
1944 ** array of at least <i>NNN</i> bytes in size and use that array
1945 ** for all of its dynamic memory allocation needs. {END}  Additional
1946 ** memory allocator options may be added in future releases.
1947 **
1948 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
1949 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
1950 ** implementation of these routines to be omitted.  That capability
1951 ** is no longer provided.  Only built-in memory allocators can be
1952 ** used.
1953 **
1954 ** The windows OS interface layer calls
1955 ** the system malloc() and free() directly when converting
1956 ** filenames between the UTF-8 encoding used by SQLite
1957 ** and whatever filename encoding is used by the particular windows
1958 ** installation.  Memory allocation errors are detected, but
1959 ** they are reported back as [SQLITE_CANTOPEN] or
1960 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
1961 **
1962 ** INVARIANTS:
1963 **
1964 ** {F17303}  The [sqlite3_malloc(N)] interface returns either a pointer to 
1965 **           newly checked-out block of at least N bytes of memory
1966 **           that is 8-byte aligned, 
1967 **           or it returns NULL if it is unable to fulfill the request.
1968 **
1969 ** {F17304}  The [sqlite3_malloc(N)] interface returns a NULL pointer if
1970 **           N is less than or equal to zero.
1971 **
1972 ** {F17305}  The [sqlite3_free(P)] interface releases memory previously
1973 **           returned from [sqlite3_malloc()] or [sqlite3_realloc()],
1974 **           making it available for reuse.
1975 **
1976 ** {F17306}  A call to [sqlite3_free(NULL)] is a harmless no-op.
1977 **
1978 ** {F17310}  A call to [sqlite3_realloc(0,N)] is equivalent to a call
1979 **           to [sqlite3_malloc(N)].
1980 **
1981 ** {F17312}  A call to [sqlite3_realloc(P,0)] is equivalent to a call
1982 **           to [sqlite3_free(P)].
1983 **
1984 ** {F17315}  The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()],
1985 **           and [sqlite3_free()] for all of its memory allocation and
1986 **           deallocation needs.
1987 **
1988 ** {F17318}  The [sqlite3_realloc(P,N)] interface returns either a pointer
1989 **           to a block of checked-out memory of at least N bytes in size
1990 **           that is 8-byte aligned, or a NULL pointer.
1991 **
1992 ** {F17321}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
1993 **           copies the first K bytes of content from P into the newly allocated
1994 **           where K is the lessor of N and the size of the buffer P.
1995 **
1996 ** {F17322}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
1997 **           releases the buffer P.
1998 **
1999 ** {F17323}  When [sqlite3_realloc(P,N)] returns NULL, the buffer P is
2000 **           not modified or released.
2001 **
2002 ** LIMITATIONS:
2003 **
2004 ** {U17350}  The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2005 **           must be either NULL or else a pointer obtained from a prior
2006 **           invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that has
2007 **           not been released.
2008 **
2009 ** {U17351}  The application must not read or write any part of 
2010 **           a block of memory after it has been released using
2011 **           [sqlite3_free()] or [sqlite3_realloc()].
2012 **
2013 */
2014 SQLITE_API void *sqlite3_malloc(int);
2015 SQLITE_API void *sqlite3_realloc(void*, int);
2016 SQLITE_API void sqlite3_free(void*);
2017
2018 /*
2019 ** CAPI3REF: Memory Allocator Statistics {F17370}
2020 **
2021 ** SQLite provides these two interfaces for reporting on the status
2022 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2023 ** the memory allocation subsystem included within the SQLite.
2024 **
2025 ** INVARIANTS:
2026 **
2027 ** {F17371} The [sqlite3_memory_used()] routine returns the
2028 **          number of bytes of memory currently outstanding 
2029 **          (malloced but not freed).
2030 **
2031 ** {F17373} The [sqlite3_memory_highwater()] routine returns the maximum
2032 **          value of [sqlite3_memory_used()] 
2033 **          since the highwater mark was last reset.
2034 **
2035 ** {F17374} The values returned by [sqlite3_memory_used()] and
2036 **          [sqlite3_memory_highwater()] include any overhead
2037 **          added by SQLite in its implementation of [sqlite3_malloc()],
2038 **          but not overhead added by the any underlying system library
2039 **          routines that [sqlite3_malloc()] may call.
2040 ** 
2041 ** {F17375} The memory highwater mark is reset to the current value of
2042 **          [sqlite3_memory_used()] if and only if the parameter to
2043 **          [sqlite3_memory_highwater()] is true.  The value returned
2044 **          by [sqlite3_memory_highwater(1)] is the highwater mark
2045 **          prior to the reset.
2046 */
2047 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2048 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2049
2050 /*
2051 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
2052 **
2053 ** This routine registers a authorizer callback with a particular
2054 ** database connection, supplied in the first argument.
2055 ** The authorizer callback is invoked as SQL statements are being compiled
2056 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2057 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
2058 ** points during the compilation process, as logic is being created
2059 ** to perform various actions, the authorizer callback is invoked to
2060 ** see if those actions are allowed.  The authorizer callback should
2061 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
2062 ** specific action but allow the SQL statement to continue to be
2063 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2064 ** rejected with an error.   If the authorizer callback returns
2065 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2066 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
2067 ** the authorizer will fail with an error message.
2068 **
2069 ** When the callback returns [SQLITE_OK], that means the operation
2070 ** requested is ok.  When the callback returns [SQLITE_DENY], the
2071 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2072 ** authorizer will fail with an error message explaining that
2073 ** access is denied.  If the authorizer code is [SQLITE_READ]
2074 ** and the callback returns [SQLITE_IGNORE] then the prepared
2075 ** statement is constructed to insert a NULL value in place of
2076 ** the table column that would have
2077 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2078 ** return can be used to deny an untrusted user access to individual
2079 ** columns of a table.
2080 **
2081 ** The first parameter to the authorizer callback is a copy of
2082 ** the third parameter to the sqlite3_set_authorizer() interface.
2083 ** The second parameter to the callback is an integer 
2084 ** [SQLITE_COPY | action code] that specifies the particular action
2085 ** to be authorized. The third through sixth
2086 ** parameters to the callback are zero-terminated strings that contain 
2087 ** additional details about the action to be authorized.
2088 **
2089 ** An authorizer is used when preparing SQL statements from an untrusted
2090 ** source, to ensure that the SQL statements do not try to access data
2091 ** that they are not allowed to see, or that they do not try to
2092 ** execute malicious statements that damage the database.  For
2093 ** example, an application may allow a user to enter arbitrary
2094 ** SQL queries for evaluation by a database.  But the application does
2095 ** not want the user to be able to make arbitrary changes to the
2096 ** database.  An authorizer could then be put in place while the
2097 ** user-entered SQL is being prepared that disallows everything
2098 ** except SELECT statements.  
2099 **
2100 ** Only a single authorizer can be in place on a database connection
2101 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2102 ** previous call.  Disable the authorizer by installing a NULL callback.
2103 ** The authorizer is disabled by default.
2104 **
2105 ** Note that the authorizer callback is invoked only during 
2106 ** [sqlite3_prepare()] or its variants.  Authorization is not
2107 ** performed during statement evaluation in [sqlite3_step()].
2108 **
2109 ** INVARIANTS:
2110 **
2111 ** {F12501} The [sqlite3_set_authorizer(D,...)] interface registers a
2112 **          authorizer callback with database connection D.
2113 **
2114 ** {F12502} The authorizer callback is invoked as SQL statements are
2115 **          being compiled
2116 **
2117 ** {F12503} If the authorizer callback returns any value other than
2118 **          [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] then
2119 **          the [sqlite3_prepare_v2()] or equivalent call that caused
2120 **          the authorizer callback to run shall fail with an
2121 **          [SQLITE_ERROR] error code and an appropriate error message.
2122 **
2123 ** {F12504} When the authorizer callback returns [SQLITE_OK], the operation
2124 **          described is coded normally.
2125 **
2126 ** {F12505} When the authorizer callback returns [SQLITE_DENY], the
2127 **          [sqlite3_prepare_v2()] or equivalent call that caused the
2128 **          authorizer callback to run shall fail
2129 **          with an [SQLITE_ERROR] error code and an error message
2130 **          explaining that access is denied.
2131 **
2132 ** {F12506} If the authorizer code (the 2nd parameter to the authorizer
2133 **          callback) is [SQLITE_READ] and the authorizer callback returns
2134 **          [SQLITE_IGNORE] then the prepared statement is constructed to
2135 **          insert a NULL value in place of the table column that would have
2136 **          been read if [SQLITE_OK] had been returned.
2137 **
2138 ** {F12507} If the authorizer code (the 2nd parameter to the authorizer
2139 **          callback) is anything other than [SQLITE_READ], then
2140 **          a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
2141 **
2142 ** {F12510} The first parameter to the authorizer callback is a copy of
2143 **          the third parameter to the [sqlite3_set_authorizer()] interface.
2144 **
2145 ** {F12511} The second parameter to the callback is an integer 
2146 **          [SQLITE_COPY | action code] that specifies the particular action
2147 **          to be authorized.
2148 **
2149 ** {F12512} The third through sixth parameters to the callback are
2150 **          zero-terminated strings that contain 
2151 **          additional details about the action to be authorized.
2152 **
2153 ** {F12520} Each call to [sqlite3_set_authorizer()] overrides the
2154 **          any previously installed authorizer.
2155 **
2156 ** {F12521} A NULL authorizer means that no authorization
2157 **          callback is invoked.
2158 **
2159 ** {F12522} The default authorizer is NULL.
2160 */
2161 SQLITE_API int sqlite3_set_authorizer(
2162   sqlite3*,
2163   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2164   void *pUserData
2165 );
2166
2167 /*
2168 ** CAPI3REF: Authorizer Return Codes {F12590}
2169 **
2170 ** The [sqlite3_set_authorizer | authorizer callback function] must
2171 ** return either [SQLITE_OK] or one of these two constants in order
2172 ** to signal SQLite whether or not the action is permitted.  See the
2173 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2174 ** information.
2175 */
2176 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2177 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2178
2179 /*
2180 ** CAPI3REF: Authorizer Action Codes {F12550}
2181 **
2182 ** The [sqlite3_set_authorizer()] interface registers a callback function
2183 ** that is invoked to authorizer certain SQL statement actions.  The
2184 ** second parameter to the callback is an integer code that specifies
2185 ** what action is being authorized.  These are the integer action codes that
2186 ** the authorizer callback may be passed.
2187 **
2188 ** These action code values signify what kind of operation is to be 
2189 ** authorized.  The 3rd and 4th parameters to the authorization
2190 ** callback function will be parameters or NULL depending on which of these
2191 ** codes is used as the second parameter.  The 5th parameter to the
2192 ** authorizer callback is the name of the database ("main", "temp", 
2193 ** etc.) if applicable.  The 6th parameter to the authorizer callback
2194 ** is the name of the inner-most trigger or view that is responsible for
2195 ** the access attempt or NULL if this access attempt is directly from 
2196 ** top-level SQL code.
2197 **
2198 ** INVARIANTS:
2199 **
2200 ** {F12551} The second parameter to an 
2201 **          [sqlite3_set_authorizer | authorizer callback is always an integer
2202 **          [SQLITE_COPY | authorizer code] that specifies what action
2203 **          is being authorized.
2204 **
2205 ** {F12552} The 3rd and 4th parameters to the 
2206 **          [sqlite3_set_authorizer | authorization callback function]
2207 **          will be parameters or NULL depending on which 
2208 **          [SQLITE_COPY | authorizer code] is used as the second parameter.
2209 **
2210 ** {F12553} The 5th parameter to the
2211 **          [sqlite3_set_authorizer | authorizer callback] is the name
2212 **          of the database (example: "main", "temp", etc.) if applicable.
2213 **
2214 ** {F12554} The 6th parameter to the
2215 **          [sqlite3_set_authorizer | authorizer callback] is the name
2216 **          of the inner-most trigger or view that is responsible for
2217 **          the access attempt or NULL if this access attempt is directly from 
2218 **          top-level SQL code.
2219 */
2220 /******************************************* 3rd ************ 4th ***********/
2221 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2222 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2223 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2224 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2225 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2226 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2227 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2228 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2229 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2230 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2231 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2232 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2233 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2234 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2235 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2236 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2237 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2238 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2239 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2240 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2241 #define SQLITE_SELECT               21   /* NULL            NULL            */
2242 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
2243 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2244 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2245 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2246 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2247 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2248 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2249 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2250 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2251 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
2252 #define SQLITE_COPY                  0   /* No longer used */
2253
2254 /*
2255 ** CAPI3REF: Tracing And Profiling Functions {F12280}
2256 **
2257 ** These routines register callback functions that can be used for
2258 ** tracing and profiling the execution of SQL statements.
2259 **
2260 ** The callback function registered by sqlite3_trace() is invoked at
2261 ** various times when an SQL statement is being run by [sqlite3_step()].
2262 ** The callback returns a UTF-8 rendering of the SQL statement text
2263 ** as the statement first begins executing.  Additional callbacks occur
2264 ** as each triggersubprogram is entered.  The callbacks for triggers
2265 ** contain a UTF-8 SQL comment that identifies the trigger.
2266 ** 
2267 ** The callback function registered by sqlite3_profile() is invoked
2268 ** as each SQL statement finishes.  The profile callback contains
2269 ** the original statement text and an estimate of wall-clock time
2270 ** of how long that statement took to run.
2271 **
2272 ** The sqlite3_profile() API is currently considered experimental and
2273 ** is subject to change or removal in a future release.
2274 **
2275 ** The trigger reporting feature of the trace callback is considered
2276 ** experimental and is subject to change or removal in future releases.
2277 ** Future versions of SQLite might also add new trace callback 
2278 ** invocations.
2279 **
2280 ** INVARIANTS:
2281 **
2282 ** {F12281} The callback function registered by [sqlite3_trace()] is
2283 **          whenever an SQL statement first begins to execute and
2284 **          whenever a trigger subprogram first begins to run.
2285 **
2286 ** {F12282} Each call to [sqlite3_trace()] overrides the previously
2287 **          registered trace callback.
2288 **
2289 ** {F12283} A NULL trace callback disables tracing.
2290 **
2291 ** {F12284} The first argument to the trace callback is a copy of
2292 **          the pointer which was the 3rd argument to [sqlite3_trace()].
2293 **
2294 ** {F12285} The second argument to the trace callback is a
2295 **          zero-terminated UTF8 string containing the original text
2296 **          of the SQL statement as it was passed into [sqlite3_prepare_v2()]
2297 **          or the equivalent, or an SQL comment indicating the beginning
2298 **          of a trigger subprogram.
2299 **
2300 ** {F12287} The callback function registered by [sqlite3_profile()] is invoked
2301 **          as each SQL statement finishes.
2302 **
2303 ** {F12288} The first parameter to the profile callback is a copy of
2304 **          the 3rd parameter to [sqlite3_profile()].
2305 **
2306 ** {F12289} The second parameter to the profile callback is a
2307 **          zero-terminated UTF-8 string that contains the complete text of
2308 **          the SQL statement as it was processed by [sqlite3_prepare_v2()]
2309 **          or the equivalent.
2310 **
2311 ** {F12290} The third parameter to the profile  callback is an estimate
2312 **          of the number of nanoseconds of wall-clock time required to
2313 **          run the SQL statement from start to finish.
2314 */
2315 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2316 SQLITE_API void *sqlite3_profile(sqlite3*,
2317    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2318
2319 /*
2320 ** CAPI3REF: Query Progress Callbacks {F12910}
2321 **
2322 ** This routine configures a callback function - the
2323 ** progress callback - that is invoked periodically during long
2324 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2325 ** [sqlite3_get_table()].   An example use for this 
2326 ** interface is to keep a GUI updated during a large query.
2327 **
2328 ** If the progress callback returns non-zero, the opertion is
2329 ** interrupted.  This feature can be used to implement a
2330 ** "Cancel" button on a GUI dialog box.
2331 **
2332 ** INVARIANTS:
2333 **
2334 ** {F12911} The callback function registered by [sqlite3_progress_handler()]
2335 **          is invoked periodically during long running calls to
2336 **          [sqlite3_step()].
2337 **
2338 ** {F12912} The progress callback is invoked once for every N virtual
2339 **          machine opcodes, where N is the second argument to 
2340 **          the [sqlite3_progress_handler()] call that registered
2341 **          the callback.  <todo>What if N is less than 1?</todo>
2342 **
2343 ** {F12913} The progress callback itself is identified by the third
2344 **          argument to [sqlite3_progress_handler()].
2345 **
2346 ** {F12914} The fourth argument [sqlite3_progress_handler()] is a
2347 ***         void pointer passed to the progress callback
2348 **          function each time it is invoked.
2349 **
2350 ** {F12915} If a call to [sqlite3_step()] results in fewer than
2351 **          N opcodes being executed,
2352 **          then the progress callback is never invoked. {END}
2353 ** 
2354 ** {F12916} Every call to [sqlite3_progress_handler()]
2355 **          overwrites any previously registere progress handler.
2356 **
2357 ** {F12917} If the progress handler callback is NULL then no progress
2358 **          handler is invoked.
2359 **
2360 ** {F12918} If the progress callback returns a result other than 0, then
2361 **          the behavior is a if [sqlite3_interrupt()] had been called.
2362 */
2363 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2364
2365 /*
2366 ** CAPI3REF: Opening A New Database Connection {F12700}
2367 **
2368 ** These routines open an SQLite database file whose name
2369 ** is given by the filename argument.
2370 ** The filename argument is interpreted as UTF-8
2371 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
2372 ** in the native byte order for [sqlite3_open16()].
2373 ** An [sqlite3*] handle is usually returned in *ppDb, even
2374 ** if an error occurs.  The only exception is if SQLite is unable
2375 ** to allocate memory to hold the [sqlite3] object, a NULL will
2376 ** be written into *ppDb instead of a pointer to the [sqlite3] object.
2377 ** If the database is opened (and/or created)
2378 ** successfully, then [SQLITE_OK] is returned.  Otherwise an
2379 ** error code is returned.  The
2380 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
2381 ** an English language description of the error.
2382 **
2383 ** The default encoding for the database will be UTF-8 if
2384 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
2385 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
2386 **
2387 ** Whether or not an error occurs when it is opened, resources
2388 ** associated with the [sqlite3*] handle should be released by passing it
2389 ** to [sqlite3_close()] when it is no longer required.
2390 **
2391 ** The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
2392 ** except that it acccepts two additional parameters for additional control
2393 ** over the new database connection.  The flags parameter can be
2394 ** one of:
2395 **
2396 ** <ol>
2397 ** <li>  [SQLITE_OPEN_READONLY]
2398 ** <li>  [SQLITE_OPEN_READWRITE]
2399 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
2400 ** </ol>
2401 **
2402 ** The first value opens the database read-only. 
2403 ** If the database does not previously exist, an error is returned.
2404 ** The second option opens
2405 ** the database for reading and writing if possible, or reading only if
2406 ** if the file is write protected.  In either case the database
2407 ** must already exist or an error is returned.  The third option
2408 ** opens the database for reading and writing and creates it if it does
2409 ** not already exist.
2410 ** The third options is behavior that is always used for [sqlite3_open()]
2411 ** and [sqlite3_open16()].
2412 **
2413 ** If the filename is ":memory:", then an private
2414 ** in-memory database is created for the connection.  This in-memory
2415 ** database will vanish when the database connection is closed.  Future
2416 ** version of SQLite might make use of additional special filenames
2417 ** that begin with the ":" character.  It is recommended that 
2418 ** when a database filename really does begin with
2419 ** ":" that you prefix the filename with a pathname like "./" to
2420 ** avoid ambiguity.
2421 **
2422 ** If the filename is an empty string, then a private temporary
2423 ** on-disk database will be created.  This private database will be
2424 ** automatically deleted as soon as the database connection is closed.
2425 **
2426 ** The fourth parameter to sqlite3_open_v2() is the name of the
2427 ** [sqlite3_vfs] object that defines the operating system 
2428 ** interface that the new database connection should use.  If the
2429 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
2430 ** object is used.
2431 **
2432 ** <b>Note to windows users:</b>  The encoding used for the filename argument
2433 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
2434 ** codepage is currently defined.  Filenames containing international
2435 ** characters must be converted to UTF-8 prior to passing them into
2436 ** [sqlite3_open()] or [sqlite3_open_v2()].
2437 **
2438 ** INVARIANTS:
2439 **
2440 ** {F12701} The [sqlite3_open()], [sqlite3_open16()], and
2441 **          [sqlite3_open_v2()] interfaces create a new
2442 **          [database connection] associated with
2443 **          the database file given in their first parameter.
2444 **
2445 ** {F12702} The filename argument is interpreted as UTF-8
2446 **          for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
2447 **          in the native byte order for [sqlite3_open16()].
2448 **
2449 ** {F12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()], 
2450 **          or [sqlite3_open_v2()] writes a pointer to a new
2451 **          [database connection] into *ppDb.
2452 **
2453 ** {F12704} The [sqlite3_open()], [sqlite3_open16()], and
2454 **          [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success,
2455 **          or an appropriate [error code] on failure.
2456 **
2457 ** {F12706} The default text encoding for a new database created using
2458 **          [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8.
2459 **
2460 ** {F12707} The default text encoding for a new database created using
2461 **          [sqlite3_open16()] will be UTF-16.
2462 **
2463 ** {F12709} The [sqlite3_open(F,D)] interface is equivalent to
2464 **          [sqlite3_open_v2(F,D,G,0)] where the G parameter is
2465 **          [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE].
2466 **
2467 ** {F12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2468 **          bit value [SQLITE_OPEN_READONLY] then the database is opened
2469 **          for reading only.
2470 **
2471 ** {F12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2472 **          bit value [SQLITE_OPEN_READWRITE] then the database is opened
2473 **          reading and writing if possible, or for reading only if the
2474 **          file is write protected by the operating system.
2475 **
2476 ** {F12713} If the G parameter to [sqlite3_open(v2(F,D,G,V)] omits the
2477 **          bit value [SQLITE_OPEN_CREATE] and the database does not
2478 **          previously exist, an error is returned.
2479 **
2480 ** {F12714} If the G parameter to [sqlite3_open(v2(F,D,G,V)] contains the
2481 **          bit value [SQLITE_OPEN_CREATE] and the database does not
2482 **          previously exist, then an attempt is made to create and
2483 **          initialize the database.
2484 **
2485 ** {F12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()],
2486 **          or [sqlite3_open_v2()] is ":memory:", then an private,
2487 **          ephemeral, in-memory database is created for the connection.
2488 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
2489 **          in sqlite3_open_v2()?</todo>
2490 **
2491 ** {F12719} If the filename is NULL or an empty string, then a private,
2492 **          ephermeral on-disk database will be created.
2493 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
2494 **          in sqlite3_open_v2()?</todo>
2495 **
2496 ** {F12721} The [database connection] created by 
2497 **          [sqlite3_open_v2(F,D,G,V)] will use the
2498 **          [sqlite3_vfs] object identified by the V parameter, or
2499 **          the default [sqlite3_vfs] object is V is a NULL pointer.
2500 */
2501 SQLITE_API int sqlite3_open(
2502   const char *filename,   /* Database filename (UTF-8) */
2503   sqlite3 **ppDb          /* OUT: SQLite db handle */
2504 );
2505 SQLITE_API int sqlite3_open16(
2506   const void *filename,   /* Database filename (UTF-16) */
2507   sqlite3 **ppDb          /* OUT: SQLite db handle */
2508 );
2509 SQLITE_API int sqlite3_open_v2(
2510   const char *filename,   /* Database filename (UTF-8) */
2511   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2512   int flags,              /* Flags */
2513   const char *zVfs        /* Name of VFS module to use */
2514 );
2515
2516 /*
2517 ** CAPI3REF: Error Codes And Messages {F12800}
2518 **
2519 ** The sqlite3_errcode() interface returns the numeric
2520 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
2521 ** for the most recent failed sqlite3_* API call associated
2522 ** with [sqlite3] handle 'db'. If a prior API call failed but the
2523 ** most recent API call succeeded, the return value from sqlite3_errcode()
2524 ** is undefined.
2525 **
2526 ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2527 ** text that describes the error, as either UTF8 or UTF16 respectively.
2528 ** Memory to hold the error message string is managed internally.
2529 ** The application does not need to worry with freeing the result.
2530 ** However, the error string might be overwritten or deallocated by
2531 ** subsequent calls to other SQLite interface functions.
2532 **
2533 ** INVARIANTS:
2534 **
2535 ** {F12801} The [sqlite3_errcode(D)] interface returns the numeric
2536 **          [SQLITE_OK | result code] or
2537 **          [SQLITE_IOERR_READ | extended result code]
2538 **          for the most recently failed interface call associated
2539 **          with [database connection] D.
2540 **
2541 ** {F12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)]
2542 **          interfaces return English-language text that describes
2543 **          the error in the mostly recently failed interface call,
2544 **          encoded as either UTF8 or UTF16 respectively.
2545 **
2546 ** {F12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]
2547 **          are valid until the next SQLite interface call.
2548 **
2549 ** {F12808} Calls to API routines that do not return an error code
2550 **          (example: [sqlite3_data_count()]) do not
2551 **          change the error code or message returned by
2552 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
2553 **
2554 ** {F12809} Interfaces that are not associated with a specific
2555 **          [database connection] (examples:
2556 **          [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()]
2557 **          do not change the values returned by
2558 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
2559 */
2560 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2561 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2562 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2563
2564 /*
2565 ** CAPI3REF: SQL Statement Object {F13000}
2566 ** KEYWORDS: {prepared statement} {prepared statements}
2567 **
2568 ** An instance of this object represent single SQL statements.  This
2569 ** object is variously known as a "prepared statement" or a 
2570 ** "compiled SQL statement" or simply as a "statement".
2571 ** 
2572 ** The life of a statement object goes something like this:
2573 **
2574 ** <ol>
2575 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2576 **      function.
2577 ** <li> Bind values to host parameters using
2578 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
2579 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2580 ** <li> Reset the statement using [sqlite3_reset()] then go back
2581 **      to step 2.  Do this zero or more times.
2582 ** <li> Destroy the object using [sqlite3_finalize()].
2583 ** </ol>
2584 **
2585 ** Refer to documentation on individual methods above for additional
2586 ** information.
2587 */
2588 typedef struct sqlite3_stmt sqlite3_stmt;
2589
2590 /*
2591 ** CAPI3REF: Compiling An SQL Statement {F13010}
2592 **
2593 ** To execute an SQL query, it must first be compiled into a byte-code
2594 ** program using one of these routines. 
2595 **
2596 ** The first argument "db" is an [database connection] 
2597 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
2598 ** or [sqlite3_open16()]. 
2599 ** The second argument "zSql" is the statement to be compiled, encoded
2600 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
2601 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
2602 ** use UTF-16. {END}
2603 **
2604 ** If the nByte argument is less
2605 ** than zero, then zSql is read up to the first zero terminator.
2606 ** If nByte is non-negative, then it is the maximum number of 
2607 ** bytes read from zSql.  When nByte is non-negative, the
2608 ** zSql string ends at either the first '\000' or '\u0000' character or 
2609 ** until the nByte-th byte, whichever comes first. {END}
2610 **
2611 ** *pzTail is made to point to the first byte past the end of the
2612 ** first SQL statement in zSql.  These routines only compiles the first
2613 ** statement in zSql, so *pzTail is left pointing to what remains
2614 ** uncompiled.
2615 **
2616 ** *ppStmt is left pointing to a compiled [prepared statement] that can be
2617 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt is
2618 ** set to NULL.  If the input text contains no SQL (if the input
2619 ** is and empty string or a comment) then *ppStmt is set to NULL.
2620 ** {U13018} The calling procedure is responsible for deleting the
2621 ** compiled SQL statement
2622 ** using [sqlite3_finalize()] after it has finished with it.
2623 **
2624 ** On success, [SQLITE_OK] is returned.  Otherwise an 
2625 ** [error code] is returned.
2626 **
2627 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
2628 ** recommended for all new programs. The two older interfaces are retained
2629 ** for backwards compatibility, but their use is discouraged.
2630 ** In the "v2" interfaces, the prepared statement
2631 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
2632 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
2633 ** behave a differently in two ways:
2634 **
2635 ** <ol>
2636 ** <li>
2637 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2638 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
2639 ** statement and try to run it again.  If the schema has changed in
2640 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
2641 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, 
2642 ** [SQLITE_SCHEMA] is now a fatal error.  Calling
2643 ** [sqlite3_prepare_v2()] again will not make the
2644 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
2645 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
2646 ** </li>
2647 **
2648 ** <li>
2649 ** When an error occurs, 
2650 ** [sqlite3_step()] will return one of the detailed 
2651 ** [error codes] or [extended error codes]. 
2652 ** The legacy behavior was that [sqlite3_step()] would only return a generic
2653 ** [SQLITE_ERROR] result code and you would have to make a second call to
2654 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
2655 ** With the "v2" prepare interfaces, the underlying reason for the error is
2656 ** returned immediately.
2657 ** </li>
2658 ** </ol>
2659 **
2660 ** INVARIANTS:
2661 **
2662 ** {F13011} The [sqlite3_prepare(db,zSql,...)] and
2663 **          [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the
2664 **          text in their zSql parameter as UTF-8.
2665 **
2666 ** {F13012} The [sqlite3_prepare16(db,zSql,...)] and
2667 **          [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the
2668 **          text in their zSql parameter as UTF-16 in the native byte order.
2669 **
2670 ** {F13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
2671 **          and its variants is less than zero, then SQL text is
2672 **          read from zSql is read up to the first zero terminator.
2673 **
2674 ** {F13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
2675 **          and its variants is non-negative, then nBytes bytes
2676 **          SQL text is read from zSql.
2677 **
2678 ** {F13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants
2679 **          if the zSql input text contains more than one SQL statement
2680 **          and pzTail is not NULL, then *pzTail is made to point to the
2681 **          first byte past the end of the first SQL statement in zSql.
2682 **          <todo>What does *pzTail point to if there is one statement?</todo>
2683 **
2684 ** {F13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)]
2685 **          or one of its variants writes into *ppStmt a pointer to a new
2686 **          [prepared statement] or a pointer to NULL
2687 **          if zSql contains nothing other than whitespace or comments. 
2688 **
2689 ** {F13019} The [sqlite3_prepare_v2()] interface and its variants return
2690 **          [SQLITE_OK] or an appropriate [error code] upon failure.
2691 **
2692 ** {F13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its
2693 **          variants returns an error (any value other than [SQLITE_OK])
2694 **          it first sets *ppStmt to NULL.
2695 */
2696 SQLITE_API int sqlite3_prepare(
2697   sqlite3 *db,            /* Database handle */
2698   const char *zSql,       /* SQL statement, UTF-8 encoded */
2699   int nByte,              /* Maximum length of zSql in bytes. */
2700   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2701   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2702 );
2703 SQLITE_API int sqlite3_prepare_v2(
2704   sqlite3 *db,            /* Database handle */
2705   const char *zSql,       /* SQL statement, UTF-8 encoded */
2706   int nByte,              /* Maximum length of zSql in bytes. */
2707   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2708   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2709 );
2710 SQLITE_API int sqlite3_prepare16(
2711   sqlite3 *db,            /* Database handle */
2712   const void *zSql,       /* SQL statement, UTF-16 encoded */
2713   int nByte,              /* Maximum length of zSql in bytes. */
2714   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2715   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2716 );
2717 SQLITE_API int sqlite3_prepare16_v2(
2718   sqlite3 *db,            /* Database handle */
2719   const void *zSql,       /* SQL statement, UTF-16 encoded */
2720   int nByte,              /* Maximum length of zSql in bytes. */
2721   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2722   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2723 );
2724
2725 /*
2726 ** CAPIREF: Retrieving Statement SQL {F13100}
2727 **
2728 ** This intereface can be used to retrieve a saved copy of the original
2729 ** SQL text used to create a [prepared statement].
2730 **
2731 ** INVARIANTS:
2732 **
2733 ** {F13101} If the [prepared statement] passed as 
2734 **          the an argument to [sqlite3_sql()] was compiled
2735 **          compiled using either [sqlite3_prepare_v2()] or
2736 **          [sqlite3_prepare16_v2()],
2737 **          then [sqlite3_sql()] function returns a pointer to a
2738 **          zero-terminated string containing a UTF-8 rendering
2739 **          of the original SQL statement.
2740 **
2741 ** {F13102} If the [prepared statement] passed as 
2742 **          the an argument to [sqlite3_sql()] was compiled
2743 **          compiled using either [sqlite3_prepare()] or
2744 **          [sqlite3_prepare16()],
2745 **          then [sqlite3_sql()] function returns a NULL pointer.
2746 **
2747 ** {F13103} The string returned by [sqlite3_sql(S)] is valid until the
2748 **          [prepared statement] S is deleted using [sqlite3_finalize(S)].
2749 */
2750 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
2751
2752 /*
2753 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
2754 **
2755 ** SQLite uses the sqlite3_value object to represent all values
2756 ** that are or can be stored in a database table.
2757 ** SQLite uses dynamic typing for the values it stores.  
2758 ** Values stored in sqlite3_value objects can be
2759 ** be integers, floating point values, strings, BLOBs, or NULL.
2760 */
2761 typedef struct Mem sqlite3_value;
2762
2763 /*
2764 ** CAPI3REF:  SQL Function Context Object {F16001}
2765 **
2766 ** The context in which an SQL function executes is stored in an
2767 ** sqlite3_context object.  A pointer to an sqlite3_context
2768 ** object is always first parameter to application-defined SQL functions.
2769 */
2770 typedef struct sqlite3_context sqlite3_context;
2771
2772 /*
2773 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
2774 **
2775 ** In the SQL strings input to [sqlite3_prepare_v2()] and its
2776 ** variants, literals may be replace by a parameter in one
2777 ** of these forms:
2778 **
2779 ** <ul>
2780 ** <li>  ?
2781 ** <li>  ?NNN
2782 ** <li>  :VVV
2783 ** <li>  @VVV
2784 ** <li>  $VVV
2785 ** </ul>
2786 **
2787 ** In the parameter forms shown above NNN is an integer literal,
2788 ** VVV alpha-numeric parameter name.
2789 ** The values of these parameters (also called "host parameter names"
2790 ** or "SQL parameters")
2791 ** can be set using the sqlite3_bind_*() routines defined here.
2792 **
2793 ** The first argument to the sqlite3_bind_*() routines always
2794 ** is a pointer to the [sqlite3_stmt] object returned from
2795 ** [sqlite3_prepare_v2()] or its variants. The second
2796 ** argument is the index of the parameter to be set. The
2797 ** first parameter has an index of 1.  When the same named
2798 ** parameter is used more than once, second and subsequent
2799 ** occurrences have the same index as the first occurrence. 
2800 ** The index for named parameters can be looked up using the
2801 ** [sqlite3_bind_parameter_name()] API if desired.  The index
2802 ** for "?NNN" parameters is the value of NNN.
2803 ** The NNN value must be between 1 and the compile-time
2804 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999).
2805 **
2806 ** The third argument is the value to bind to the parameter.
2807 **
2808 ** In those
2809 ** routines that have a fourth argument, its value is the number of bytes
2810 ** in the parameter.  To be clear: the value is the number of <u>bytes</u>
2811 ** in the value, not the number of characters.   The number
2812 ** of bytes does not include the zero-terminator at the end of strings.
2813 ** If the fourth parameter is negative, the length of the string is
2814 ** number of bytes up to the first zero terminator.
2815 **
2816 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
2817 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
2818 ** string after SQLite has finished with it. If the fifth argument is
2819 ** the special value [SQLITE_STATIC], then SQLite assumes that the
2820 ** information is in static, unmanaged space and does not need to be freed.
2821 ** If the fifth argument has the value [SQLITE_TRANSIENT], then
2822 ** SQLite makes its own private copy of the data immediately, before
2823 ** the sqlite3_bind_*() routine returns.
2824 **
2825 ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
2826 ** is filled with zeros.  A zeroblob uses a fixed amount of memory
2827 ** (just an integer to hold it size) while it is being processed.
2828 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
2829 ** content is later written using 
2830 ** [sqlite3_blob_open | increment BLOB I/O] routines. A negative
2831 ** value for the zeroblob results in a zero-length BLOB.
2832 **
2833 ** The sqlite3_bind_*() routines must be called after
2834 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
2835 ** before [sqlite3_step()].
2836 ** Bindings are not cleared by the [sqlite3_reset()] routine.
2837 ** Unbound parameters are interpreted as NULL.
2838 **
2839 ** These routines return [SQLITE_OK] on success or an error code if
2840 ** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
2841 ** index is out of range.  [SQLITE_NOMEM] is returned if malloc fails.
2842 ** [SQLITE_MISUSE] might be returned if these routines are called on a
2843 ** virtual machine that is the wrong state or which has already been finalized.
2844 ** Detection of misuse is unreliable.  Applications should not depend
2845 ** on SQLITE_MISUSE returns.  SQLITE_MISUSE is intended to indicate a
2846 ** a logic error in the application.  Future versions of SQLite might
2847 ** panic rather than return SQLITE_MISUSE.
2848 **
2849 ** See also: [sqlite3_bind_parameter_count()],
2850 ** [sqlite3_bind_parameter_name()], and
2851 ** [sqlite3_bind_parameter_index()].
2852 **
2853 ** INVARIANTS:
2854 **
2855 ** {F13506} The [sqlite3_prepare | SQL statement compiler] recognizes
2856 **          tokens of the forms "?", "?NNN", "$VVV", ":VVV", and "@VVV"
2857 **          as SQL parameters, where NNN is any sequence of one or more
2858 **          digits and where VVV is any sequence of one or more 
2859 **          alphanumeric characters or "::" optionally followed by
2860 **          a string containing no spaces and contained within parentheses.
2861 **
2862 ** {F13509} The initial value of an SQL parameter is NULL.
2863 **
2864 ** {F13512} The index of an "?" SQL parameter is one larger than the
2865 **          largest index of SQL parameter to the left, or 1 if
2866 **          the "?" is the leftmost SQL parameter.
2867 **
2868 ** {F13515} The index of an "?NNN" SQL parameter is the integer NNN.
2869 **
2870 ** {F13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is
2871 **          the same as the index of leftmost occurances of the same
2872 **          parameter, or one more than the largest index over all
2873 **          parameters to the left if this is the first occurrance
2874 **          of this parameter, or 1 if this is the leftmost parameter.
2875 **
2876 ** {F13521} The [sqlite3_prepare | SQL statement compiler] fail with
2877 **          an [SQLITE_RANGE] error if the index of an SQL parameter
2878 **          is less than 1 or greater than SQLITE_MAX_VARIABLE_NUMBER.
2879 **
2880 ** {F13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)]
2881 **          associate the value V with all SQL parameters having an
2882 **          index of N in the [prepared statement] S.
2883 **
2884 ** {F13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)]
2885 **          override prior calls with the same values of S and N.
2886 **
2887 ** {F13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)]
2888 **          persist across calls to [sqlite3_reset(S)].
2889 **
2890 ** {F13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
2891 **          [sqlite3_bind_text(S,N,V,L,D)], or
2892 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L
2893 **          bytes of the blob or string pointed to by V, when L
2894 **          is non-negative.
2895 **
2896 ** {F13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or
2897 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters
2898 **          from V through the first zero character when L is negative.
2899 **
2900 ** {F13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
2901 **          [sqlite3_bind_text(S,N,V,L,D)], or
2902 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
2903 **          constant [SQLITE_STATIC], SQLite assumes that the value V
2904 **          is held in static unmanaged space that will not change
2905 **          during the lifetime of the binding.
2906 **
2907 ** {F13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
2908 **          [sqlite3_bind_text(S,N,V,L,D)], or
2909 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
2910 **          constant [SQLITE_TRANSIENT], the routine makes a 
2911 **          private copy of V value before it returns.
2912 **
2913 ** {F13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
2914 **          [sqlite3_bind_text(S,N,V,L,D)], or
2915 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to
2916 **          a function, SQLite invokes that function to destroy the
2917 **          V value after it has finished using the V value.
2918 **
2919 ** {F13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound
2920 **          is a blob of L bytes, or a zero-length blob if L is negative.
2921 */
2922 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
2923 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
2924 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
2925 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
2926 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
2927 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
2928 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
2929 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
2930 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
2931
2932 /*
2933 ** CAPI3REF: Number Of SQL Parameters {F13600}
2934 **
2935 ** This routine can be used to find the number of SQL parameters
2936 ** in a prepared statement.  SQL parameters are tokens of the
2937 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
2938 ** place-holders for values that are [sqlite3_bind_blob | bound]
2939 ** to the parameters at a later time.
2940 **
2941 ** This routine actually returns the index of the largest parameter.
2942 ** For all forms except ?NNN, this will correspond to the number of
2943 ** unique parameters.  If parameters of the ?NNN are used, there may
2944 ** be gaps in the list.
2945 **
2946 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
2947 ** [sqlite3_bind_parameter_name()], and
2948 ** [sqlite3_bind_parameter_index()].
2949 **
2950 ** INVARIANTS:
2951 **
2952 ** {F13601} The [sqlite3_bind_parameter_count(S)] interface returns
2953 **          the largest index of all SQL parameters in the
2954 **          [prepared statement] S, or 0 if S
2955 **          contains no SQL parameters.
2956 */
2957 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
2958
2959 /*
2960 ** CAPI3REF: Name Of A Host Parameter {F13620}
2961 **
2962 ** This routine returns a pointer to the name of the n-th
2963 ** SQL parameter in a [prepared statement].
2964 ** SQL parameters of the form ":AAA" or "@AAA" or "$AAA" have a name
2965 ** which is the string ":AAA" or "@AAA" or "$VVV". 
2966 ** In other words, the initial ":" or "$" or "@"
2967 ** is included as part of the name.
2968 ** Parameters of the form "?" or "?NNN" have no name.
2969 **
2970 ** The first host parameter has an index of 1, not 0.
2971 **
2972 ** If the value n is out of range or if the n-th parameter is
2973 ** nameless, then NULL is returned.  The returned string is
2974 ** always in the UTF-8 encoding even if the named parameter was
2975 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
2976 ** [sqlite3_prepare16_v2()].
2977 **
2978 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
2979 ** [sqlite3_bind_parameter_count()], and
2980 ** [sqlite3_bind_parameter_index()].
2981 **
2982 ** INVARIANTS:
2983 **
2984 ** {F13621} The [sqlite3_bind_parameter_name(S,N)] interface returns
2985 **          a UTF-8 rendering of the name of the SQL parameter in
2986 **          [prepared statement] S having index N, or
2987 **          NULL if there is no SQL parameter with index N or if the
2988 **          parameter with index N is an anonymous parameter "?" or
2989 **          a numbered parameter "?NNN".
2990 */
2991 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
2992
2993 /*
2994 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
2995 **
2996 ** Return the index of an SQL parameter given its name.  The
2997 ** index value returned is suitable for use as the second
2998 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  A zero
2999 ** is returned if no matching parameter is found.  The parameter
3000 ** name must be given in UTF-8 even if the original statement
3001 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3002 **
3003 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3004 ** [sqlite3_bind_parameter_count()], and
3005 ** [sqlite3_bind_parameter_index()].
3006 **
3007 ** INVARIANTS:
3008 **
3009 ** {F13641} The [sqlite3_bind_parameter_index(S,N)] interface returns
3010 **          the index of SQL parameter in [prepared statement]
3011 **          S whose name matches the UTF-8 string N, or 0 if there is
3012 **          no match.
3013 */
3014 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3015
3016 /*
3017 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
3018 **
3019 ** Contrary to the intuition of many, [sqlite3_reset()] does not
3020 ** reset the [sqlite3_bind_blob | bindings] on a 
3021 ** [prepared statement].  Use this routine to
3022 ** reset all host parameters to NULL.
3023 **
3024 ** INVARIANTS:
3025 **
3026 ** {F13661} The [sqlite3_clear_bindings(S)] interface resets all
3027 **          SQL parameter bindings in [prepared statement] S
3028 **          back to NULL.
3029 */
3030 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3031
3032 /*
3033 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
3034 **
3035 ** Return the number of columns in the result set returned by the 
3036 ** [prepared statement]. This routine returns 0
3037 ** if pStmt is an SQL statement that does not return data (for 
3038 ** example an UPDATE).
3039 **
3040 ** INVARIANTS:
3041 **
3042 ** {F13711} The [sqlite3_column_count(S)] interface returns the number of
3043 **          columns in the result set generated by the
3044 **          [prepared statement] S, or 0 if S does not generate
3045 **          a result set.
3046 */
3047 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3048
3049 /*
3050 ** CAPI3REF: Column Names In A Result Set {F13720}
3051 **
3052 ** These routines return the name assigned to a particular column
3053 ** in the result set of a SELECT statement.  The sqlite3_column_name()
3054 ** interface returns a pointer to a zero-terminated UTF8 string
3055 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3056 ** UTF16 string.  The first parameter is the
3057 ** [prepared statement] that implements the SELECT statement.
3058 ** The second parameter is the column number.  The left-most column is
3059 ** number 0.
3060 **
3061 ** The returned string pointer is valid until either the 
3062 ** [prepared statement] is destroyed by [sqlite3_finalize()]
3063 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
3064 ** on the same column.
3065 **
3066 ** If sqlite3_malloc() fails during the processing of either routine
3067 ** (for example during a conversion from UTF-8 to UTF-16) then a
3068 ** NULL pointer is returned.
3069 **
3070 ** The name of a result column is the value of the "AS" clause for
3071 ** that column, if there is an AS clause.  If there is no AS clause
3072 ** then the name of the column is unspecified and may change from
3073 ** one release of SQLite to the next.
3074 **
3075 ** INVARIANTS:
3076 **
3077 ** {F13721} A successful invocation of the [sqlite3_column_name(S,N)]
3078 **          interface returns the name
3079 **          of the Nth column (where 0 is the left-most column) for the
3080 **          result set of [prepared statement] S as a
3081 **          zero-terminated UTF-8 string.
3082 **
3083 ** {F13723} A successful invocation of the [sqlite3_column_name16(S,N)]
3084 **          interface returns the name
3085 **          of the Nth column (where 0 is the left-most column) for the
3086 **          result set of [prepared statement] S as a
3087 **          zero-terminated UTF-16 string in the native byte order.
3088 **
3089 ** {F13724} The [sqlite3_column_name()] and [sqlite3_column_name16()]
3090 **          interfaces return a NULL pointer if they are unable to
3091 **          allocate memory memory to hold there normal return strings.
3092 **
3093 ** {F13725} If the N parameter to [sqlite3_column_name(S,N)] or
3094 **          [sqlite3_column_name16(S,N)] is out of range, then the
3095 **          interfaces returns a NULL pointer.
3096 ** 
3097 ** {F13726} The strings returned by [sqlite3_column_name(S,N)] and
3098 **          [sqlite3_column_name16(S,N)] are valid until the next
3099 **          call to either routine with the same S and N parameters
3100 **          or until [sqlite3_finalize(S)] is called.
3101 **
3102 ** {F13727} When a result column of a [SELECT] statement contains
3103 **          an AS clause, the name of that column is the indentifier
3104 **          to the right of the AS keyword.
3105 */
3106 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3107 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3108
3109 /*
3110 ** CAPI3REF: Source Of Data In A Query Result {F13740}
3111 **
3112 ** These routines provide a means to determine what column of what
3113 ** table in which database a result of a SELECT statement comes from.
3114 ** The name of the database or table or column can be returned as
3115 ** either a UTF8 or UTF16 string.  The _database_ routines return
3116 ** the database name, the _table_ routines return the table name, and
3117 ** the origin_ routines return the column name.
3118 ** The returned string is valid until
3119 ** the [prepared statement] is destroyed using
3120 ** [sqlite3_finalize()] or until the same information is requested
3121 ** again in a different encoding.
3122 **
3123 ** The names returned are the original un-aliased names of the
3124 ** database, table, and column.
3125 **
3126 ** The first argument to the following calls is a [prepared statement].
3127 ** These functions return information about the Nth column returned by 
3128 ** the statement, where N is the second function argument.
3129 **
3130 ** If the Nth column returned by the statement is an expression
3131 ** or subquery and is not a column value, then all of these functions
3132 ** return NULL.  These routine might also return NULL if a memory
3133 ** allocation error occurs.  Otherwise, they return the 
3134 ** name of the attached database, table and column that query result
3135 ** column was extracted from.
3136 **
3137 ** As with all other SQLite APIs, those postfixed with "16" return
3138 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
3139 **
3140 ** These APIs are only available if the library was compiled with the 
3141 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
3142 **
3143 ** {U13751}
3144 ** If two or more threads call one or more of these routines against the same
3145 ** prepared statement and column at the same time then the results are
3146 ** undefined.
3147 **
3148 ** INVARIANTS:
3149 **
3150 ** {F13741} The [sqlite3_column_database_name(S,N)] interface returns either
3151 **          the UTF-8 zero-terminated name of the database from which the 
3152 **          Nth result column of [prepared statement] S 
3153 **          is extracted, or NULL if the the Nth column of S is a
3154 **          general expression or if unable to allocate memory
3155 **          to store the name.
3156 **          
3157 ** {F13742} The [sqlite3_column_database_name16(S,N)] interface returns either
3158 **          the UTF-16 native byte order
3159 **          zero-terminated name of the database from which the 
3160 **          Nth result column of [prepared statement] S 
3161 **          is extracted, or NULL if the the Nth column of S is a
3162 **          general expression or if unable to allocate memory
3163 **          to store the name.
3164 **          
3165 ** {F13743} The [sqlite3_column_table_name(S,N)] interface returns either
3166 **          the UTF-8 zero-terminated name of the table from which the 
3167 **          Nth result column of [prepared statement] S 
3168 **          is extracted, or NULL if the the Nth column of S is a
3169 **          general expression or if unable to allocate memory
3170 **          to store the name.
3171 **          
3172 ** {F13744} The [sqlite3_column_table_name16(S,N)] interface returns either
3173 **          the UTF-16 native byte order
3174 **          zero-terminated name of the table from which the 
3175 **          Nth result column of [prepared statement] S 
3176 **          is extracted, or NULL if the the Nth column of S is a
3177 **          general expression or if unable to allocate memory
3178 **          to store the name.
3179 **          
3180 ** {F13745} The [sqlite3_column_origin_name(S,N)] interface returns either
3181 **          the UTF-8 zero-terminated name of the table column from which the 
3182 **          Nth result column of [prepared statement] S 
3183 **          is extracted, or NULL if the the Nth column of S is a
3184 **          general expression or if unable to allocate memory
3185 **          to store the name.
3186 **          
3187 ** {F13746} The [sqlite3_column_origin_name16(S,N)] interface returns either
3188 **          the UTF-16 native byte order
3189 **          zero-terminated name of the table column from which the 
3190 **          Nth result column of [prepared statement] S 
3191 **          is extracted, or NULL if the the Nth column of S is a
3192 **          general expression or if unable to allocate memory
3193 **          to store the name.
3194 **          
3195 ** {F13748} The return values from
3196 **          [sqlite3_column_database_name|column metadata interfaces]
3197 **          are valid
3198 **          for the lifetime of the [prepared statement]
3199 **          or until the encoding is changed by another metadata
3200 **          interface call for the same prepared statement and column.
3201 **
3202 ** LIMITATIONS:
3203 **
3204 ** {U13751} If two or more threads call one or more
3205 **          [sqlite3_column_database_name|column metadata interfaces]
3206 **          the same [prepared statement] and result column
3207 **          at the same time then the results are undefined.
3208 */
3209 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3210 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3211 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3212 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3213 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3214 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3215
3216 /*
3217 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
3218 **
3219 ** The first parameter is a [prepared statement]. 
3220 ** If this statement is a SELECT statement and the Nth column of the 
3221 ** returned result set of that SELECT is a table column (not an
3222 ** expression or subquery) then the declared type of the table
3223 ** column is returned.  If the Nth column of the result set is an
3224 ** expression or subquery, then a NULL pointer is returned.
3225 ** The returned string is always UTF-8 encoded.  {END} 
3226 ** For example, in the database schema:
3227 **
3228 ** CREATE TABLE t1(c1 VARIANT);
3229 **
3230 ** And the following statement compiled:
3231 **
3232 ** SELECT c1 + 1, c1 FROM t1;
3233 **
3234 ** Then this routine would return the string "VARIANT" for the second
3235 ** result column (i==1), and a NULL pointer for the first result column
3236 ** (i==0).
3237 **
3238 ** SQLite uses dynamic run-time typing.  So just because a column
3239 ** is declared to contain a particular type does not mean that the
3240 ** data stored in that column is of the declared type.  SQLite is
3241 ** strongly typed, but the typing is dynamic not static.  Type
3242 ** is associated with individual values, not with the containers
3243 ** used to hold those values.
3244 **
3245 ** INVARIANTS:
3246 **
3247 ** {F13761}  A successful call to [sqlite3_column_decltype(S,N)]
3248 **           returns a zero-terminated UTF-8 string containing the
3249 **           the declared datatype of the table column that appears
3250 **           as the Nth column (numbered from 0) of the result set to the
3251 **           [prepared statement] S.
3252 **
3253 ** {F13762}  A successful call to [sqlite3_column_decltype16(S,N)]
3254 **           returns a zero-terminated UTF-16 native byte order string
3255 **           containing the declared datatype of the table column that appears
3256 **           as the Nth column (numbered from 0) of the result set to the
3257 **           [prepared statement] S.
3258 **
3259 ** {F13763}  If N is less than 0 or N is greater than or equal to
3260 **           the number of columns in [prepared statement] S
3261 **           or if the Nth column of S is an expression or subquery rather
3262 **           than a table column or if a memory allocation failure
3263 **           occurs during encoding conversions, then
3264 **           calls to [sqlite3_column_decltype(S,N)] or
3265 **           [sqlite3_column_decltype16(S,N)] return NULL.
3266 */
3267 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3268 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3269
3270 /* 
3271 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
3272 **
3273 ** After an [prepared statement] has been prepared with a call
3274 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
3275 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
3276 ** then this function must be called one or more times to evaluate the 
3277 ** statement.
3278 **
3279 ** The details of the behavior of this sqlite3_step() interface depend
3280 ** on whether the statement was prepared using the newer "v2" interface
3281 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3282 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3283 ** new "v2" interface is recommended for new applications but the legacy
3284 ** interface will continue to be supported.
3285 **
3286 ** In the lagacy interface, the return value will be either [SQLITE_BUSY], 
3287 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3288 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
3289 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
3290 ** well.
3291 **
3292 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
3293 ** database locks it needs to do its job.  If the statement is a COMMIT
3294 ** or occurs outside of an explicit transaction, then you can retry the
3295 ** statement.  If the statement is not a COMMIT and occurs within a
3296 ** explicit transaction then you should rollback the transaction before
3297 ** continuing.
3298 **
3299 ** [SQLITE_DONE] means that the statement has finished executing
3300 ** successfully.  sqlite3_step() should not be called again on this virtual
3301 ** machine without first calling [sqlite3_reset()] to reset the virtual
3302 ** machine back to its initial state.
3303 **
3304 ** If the SQL statement being executed returns any data, then 
3305 ** [SQLITE_ROW] is returned each time a new row of data is ready
3306 ** for processing by the caller. The values may be accessed using
3307 ** the [sqlite3_column_int | column access functions].
3308 ** sqlite3_step() is called again to retrieve the next row of data.
3309 ** 
3310 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
3311 ** violation) has occurred.  sqlite3_step() should not be called again on
3312 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3313 ** With the legacy interface, a more specific error code (example:
3314 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3315 ** can be obtained by calling [sqlite3_reset()] on the
3316 ** [prepared statement].  In the "v2" interface,
3317 ** the more specific error code is returned directly by sqlite3_step().
3318 **
3319 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3320 ** Perhaps it was called on a [prepared statement] that has
3321 ** already been [sqlite3_finalize | finalized] or on one that had 
3322 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3323 ** be the case that the same database connection is being used by two or
3324 ** more threads at the same moment in time.
3325 **
3326 ** <b>Goofy Interface Alert:</b>
3327 ** In the legacy interface, 
3328 ** the sqlite3_step() API always returns a generic error code,
3329 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
3330 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
3331 ** [sqlite3_finalize()] in order to find one of the specific
3332 ** [error codes] that better describes the error.
3333 ** We admit that this is a goofy design.  The problem has been fixed
3334 ** with the "v2" interface.  If you prepare all of your SQL statements
3335 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3336 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
3337 ** more specific [error codes] are returned directly
3338 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3339 **
3340 ** INVARIANTS:
3341 **
3342 ** {F13202}  If [prepared statement] S is ready to be
3343 **           run, then [sqlite3_step(S)] advances that prepared statement
3344 **           until to completion or until it is ready to return another
3345 **           row of the result set or an interrupt or run-time error occurs.
3346 **
3347 ** {F15304}  When a call to [sqlite3_step(S)] causes the 
3348 **           [prepared statement] S to run to completion,
3349 **           the function returns [SQLITE_DONE].
3350 **
3351 ** {F15306}  When a call to [sqlite3_step(S)] stops because it is ready
3352 **           to return another row of the result set, it returns
3353 **           [SQLITE_ROW].
3354 **
3355 ** {F15308}  If a call to [sqlite3_step(S)] encounters an
3356 **           [sqlite3_interrupt|interrupt] or a run-time error,
3357 **           it returns an appropraite error code that is not one of
3358 **           [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE].
3359 **
3360 ** {F15310}  If an [sqlite3_interrupt|interrupt] or run-time error
3361 **           occurs during a call to [sqlite3_step(S)]
3362 **           for a [prepared statement] S created using
3363 **           legacy interfaces [sqlite3_prepare()] or
3364 **           [sqlite3_prepare16()] then the function returns either
3365 **           [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE].
3366 */
3367 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3368
3369 /*
3370 ** CAPI3REF: Number of columns in a result set {F13770}
3371 **
3372 ** Return the number of values in the current row of the result set.
3373 **
3374 ** INVARIANTS:
3375 **
3376 ** {F13771}  After a call to [sqlite3_step(S)] that returns
3377 **           [SQLITE_ROW], the [sqlite3_data_count(S)] routine
3378 **           will return the same value as the
3379 **           [sqlite3_column_count(S)] function.
3380 **
3381 ** {F13772}  After [sqlite3_step(S)] has returned any value other than
3382 **           [SQLITE_ROW] or before [sqlite3_step(S)] has been 
3383 **           called on the [prepared statement] for
3384 **           the first time since it was [sqlite3_prepare|prepared]
3385 **           or [sqlite3_reset|reset], the [sqlite3_data_count(S)]
3386 **           routine returns zero.
3387 */
3388 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3389
3390 /*
3391 ** CAPI3REF: Fundamental Datatypes {F10265}
3392 ** KEYWORDS: SQLITE_TEXT
3393 **
3394 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
3395 **
3396 ** <ul>
3397 ** <li> 64-bit signed integer
3398 ** <li> 64-bit IEEE floating point number
3399 ** <li> string
3400 ** <li> BLOB
3401 ** <li> NULL
3402 ** </ul> {END}
3403 **
3404 ** These constants are codes for each of those types.
3405 **
3406 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3407 ** for a completely different meaning.  Software that links against both
3408 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
3409 ** SQLITE_TEXT.
3410 */
3411 #define SQLITE_INTEGER  1
3412 #define SQLITE_FLOAT    2
3413 #define SQLITE_BLOB     4
3414 #define SQLITE_NULL     5
3415 #ifdef SQLITE_TEXT
3416 # undef SQLITE_TEXT
3417 #else
3418 # define SQLITE_TEXT     3
3419 #endif
3420 #define SQLITE3_TEXT     3
3421
3422 /*
3423 ** CAPI3REF: Results Values From A Query {F13800}
3424 **
3425 ** These routines form the "result set query" interface.
3426 **
3427 ** These routines return information about
3428 ** a single column of the current result row of a query.  In every
3429 ** case the first argument is a pointer to the 
3430 ** [prepared statement] that is being
3431 ** evaluated (the [sqlite3_stmt*] that was returned from 
3432 ** [sqlite3_prepare_v2()] or one of its variants) and
3433 ** the second argument is the index of the column for which information 
3434 ** should be returned.  The left-most column of the result set
3435 ** has an index of 0.
3436 **
3437 ** If the SQL statement is not currently point to a valid row, or if the
3438 ** the column index is out of range, the result is undefined. 
3439 ** These routines may only be called when the most recent call to
3440 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3441 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
3442 ** If any of these routines are called after [sqlite3_reset()] or
3443 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3444 ** something other than [SQLITE_ROW], the results are undefined.
3445 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3446 ** are called from a different thread while any of these routines
3447 ** are pending, then the results are undefined.  
3448 **
3449 ** The sqlite3_column_type() routine returns 
3450 ** [SQLITE_INTEGER | datatype code] for the initial data type
3451 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
3452 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3453 ** returned by sqlite3_column_type() is only meaningful if no type
3454 ** conversions have occurred as described below.  After a type conversion,
3455 ** the value returned by sqlite3_column_type() is undefined.  Future
3456 ** versions of SQLite may change the behavior of sqlite3_column_type()
3457 ** following a type conversion.
3458 **
3459 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
3460 ** routine returns the number of bytes in that BLOB or string.
3461 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3462 ** the string to UTF-8 and then returns the number of bytes.
3463 ** If the result is a numeric value then sqlite3_column_bytes() uses
3464 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3465 ** the number of bytes in that string.
3466 ** The value returned does not include the zero terminator at the end
3467 ** of the string.  For clarity: the value returned is the number of
3468 ** bytes in the string, not the number of characters.
3469 **
3470 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3471 ** even empty strings, are always zero terminated.  The return
3472 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
3473 ** pointer, possibly even a NULL pointer.
3474 **
3475 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3476 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.  
3477 ** The zero terminator is not included in this count.
3478 **
3479 ** These routines attempt to convert the value where appropriate.  For
3480 ** example, if the internal representation is FLOAT and a text result
3481 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
3482 ** automatically.  The following table details the conversions that
3483 ** are applied:
3484 **
3485 ** <blockquote>
3486 ** <table border="1">
3487 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3488 **
3489 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3490 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3491 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3492 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3493 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3494 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3495 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
3496 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3497 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3498 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3499 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3500 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3501 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3502 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3503 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3504 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3505 ** </table>
3506 ** </blockquote>
3507 **
3508 ** The table above makes reference to standard C library functions atoi()
3509 ** and atof().  SQLite does not really use these functions.  It has its
3510 ** on equavalent internal routines.  The atoi() and atof() names are
3511 ** used in the table for brevity and because they are familiar to most
3512 ** C programmers.
3513 **
3514 ** Note that when type conversions occur, pointers returned by prior
3515 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3516 ** sqlite3_column_text16() may be invalidated. 
3517 ** Type conversions and pointer invalidations might occur
3518 ** in the following cases:
3519 **
3520 ** <ul>
3521 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
3522 **          or sqlite3_column_text16() is called.  A zero-terminator might
3523 **          need to be added to the string.</p></li>
3524 **
3525 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
3526 **          sqlite3_column_text16() is called.  The content must be converted
3527 **          to UTF-16.</p></li>
3528 **
3529 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
3530 **          sqlite3_column_text() is called.  The content must be converted
3531 **          to UTF-8.</p></li>
3532 ** </ul>
3533 **
3534 ** Conversions between UTF-16be and UTF-16le are always done in place and do
3535 ** not invalidate a prior pointer, though of course the content of the buffer
3536 ** that the prior pointer points to will have been modified.  Other kinds
3537 ** of conversion are done in place when it is possible, but sometime it is
3538 ** not possible and in those cases prior pointers are invalidated.  
3539 **
3540 ** The safest and easiest to remember policy is to invoke these routines
3541 ** in one of the following ways:
3542 **
3543 **  <ul>
3544 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3545 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3546 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3547 **  </ul>
3548 **
3549 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
3550 ** or sqlite3_column_text16() first to force the result into the desired
3551 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
3552 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
3553 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
3554 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
3555 **
3556 ** The pointers returned are valid until a type conversion occurs as
3557 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3558 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
3559 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
3560 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
3561 ** [sqlite3_free()].
3562 **
3563 ** If a memory allocation error occurs during the evaluation of any
3564 ** of these routines, a default value is returned.  The default value
3565 ** is either the integer 0, the floating point number 0.0, or a NULL
3566 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3567 ** [SQLITE_NOMEM].
3568 **
3569 ** INVARIANTS:
3570 **
3571 ** {F13803} The [sqlite3_column_blob(S,N)] interface converts the
3572 **          Nth column in the current row of the result set for
3573 **          [prepared statement] S into a blob and then returns a
3574 **          pointer to the converted value.
3575 **
3576 ** {F13806} The [sqlite3_column_bytes(S,N)] interface returns the
3577 **          number of bytes in the blob or string (exclusive of the
3578 **          zero terminator on the string) that was returned by the
3579 **          most recent call to [sqlite3_column_blob(S,N)] or
3580 **          [sqlite3_column_text(S,N)].
3581 **
3582 ** {F13809} The [sqlite3_column_bytes16(S,N)] interface returns the
3583 **          number of bytes in the string (exclusive of the
3584 **          zero terminator on the string) that was returned by the
3585 **          most recent call to [sqlite3_column_text16(S,N)].
3586 **
3587 ** {F13812} The [sqlite3_column_double(S,N)] interface converts the
3588 **          Nth column in the current row of the result set for
3589 **          [prepared statement] S into a floating point value and
3590 **          returns a copy of that value.
3591 **
3592 ** {F13815} The [sqlite3_column_int(S,N)] interface converts the
3593 **          Nth column in the current row of the result set for
3594 **          [prepared statement] S into a 64-bit signed integer and
3595 **          returns the lower 32 bits of that integer.
3596 **
3597 ** {F13818} The [sqlite3_column_int64(S,N)] interface converts the
3598 **          Nth column in the current row of the result set for
3599 **          [prepared statement] S into a 64-bit signed integer and
3600 **          returns a copy of that integer.
3601 **
3602 ** {F13821} The [sqlite3_column_text(S,N)] interface converts the
3603 **          Nth column in the current row of the result set for
3604 **          [prepared statement] S into a zero-terminated UTF-8 
3605 **          string and returns a pointer to that string.
3606 **
3607 ** {F13824} The [sqlite3_column_text16(S,N)] interface converts the
3608 **          Nth column in the current row of the result set for
3609 **          [prepared statement] S into a zero-terminated 2-byte
3610 **          aligned UTF-16 native byte order
3611 **          string and returns a pointer to that string.
3612 **
3613 ** {F13827} The [sqlite3_column_type(S,N)] interface returns
3614 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
3615 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
3616 **          the Nth column in the current row of the result set for
3617 **          [prepared statement] S.
3618 **
3619 ** {F13830} The [sqlite3_column_value(S,N)] interface returns a
3620 **          pointer to the [sqlite3_value] object that for the
3621 **          Nth column in the current row of the result set for
3622 **          [prepared statement] S.
3623 */
3624 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3625 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3626 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3627 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3628 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3629 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3630 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3631 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3632 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3633 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3634
3635 /*
3636 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
3637 **
3638 ** The sqlite3_finalize() function is called to delete a 
3639 ** [prepared statement]. If the statement was
3640 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
3641 ** If execution of the statement failed then an 
3642 ** [error code] or [extended error code]
3643 ** is returned. 
3644 **
3645 ** This routine can be called at any point during the execution of the
3646 ** [prepared statement].  If the virtual machine has not 
3647 ** completed execution when this routine is called, that is like
3648 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
3649 ** Incomplete updates may be rolled back and transactions cancelled,  
3650 ** depending on the circumstances, and the 
3651 ** [error code] returned will be [SQLITE_ABORT].
3652 **
3653 ** INVARIANTS:
3654 **
3655 ** {F11302} The [sqlite3_finalize(S)] interface destroys the
3656 **          [prepared statement] S and releases all
3657 **          memory and file resources held by that object.
3658 **
3659 ** {F11304} If the most recent call to [sqlite3_step(S)] for the
3660 **          [prepared statement] S returned an error,
3661 **          then [sqlite3_finalize(S)] returns that same error.
3662 */
3663 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3664
3665 /*
3666 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
3667 **
3668 ** The sqlite3_reset() function is called to reset a 
3669 ** [prepared statement] object.
3670 ** back to its initial state, ready to be re-executed.
3671 ** Any SQL statement variables that had values bound to them using
3672 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3673 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3674 **
3675 ** {F11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
3676 **          back to the beginning of its program.
3677 **
3678 ** {F11334} If the most recent call to [sqlite3_step(S)] for 
3679 **          [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3680 **          or if [sqlite3_step(S)] has never before been called on S,
3681 **          then [sqlite3_reset(S)] returns [SQLITE_OK].
3682 **
3683 ** {F11336} If the most recent call to [sqlite3_step(S)] for
3684 **          [prepared statement] S indicated an error, then
3685 **          [sqlite3_reset(S)] returns an appropriate [error code].
3686 **
3687 ** {F11338} The [sqlite3_reset(S)] interface does not change the values
3688 **          of any [sqlite3_bind_blob|bindings] on [prepared statement] S.
3689 */
3690 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3691
3692 /*
3693 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
3694 ** KEYWORDS: {function creation routines} 
3695 **
3696 ** These two functions (collectively known as
3697 ** "function creation routines") are used to add SQL functions or aggregates
3698 ** or to redefine the behavior of existing SQL functions or aggregates.  The
3699 ** difference only between the two is that the second parameter, the
3700 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
3701 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
3702 **
3703 ** The first parameter is the [database connection] to which the SQL
3704 ** function is to be added.  If a single
3705 ** program uses more than one [database connection] internally, then SQL
3706 ** functions must be added individually to each [database connection].
3707 **
3708 ** The second parameter is the name of the SQL function to be created
3709 ** or redefined.
3710 ** The length of the name is limited to 255 bytes, exclusive of the 
3711 ** zero-terminator.  Note that the name length limit is in bytes, not
3712 ** characters.  Any attempt to create a function with a longer name
3713 ** will result in an SQLITE_ERROR error.
3714 **
3715 ** The third parameter is the number of arguments that the SQL function or
3716 ** aggregate takes. If this parameter is negative, then the SQL function or
3717 ** aggregate may take any number of arguments.
3718 **
3719 ** The fourth parameter, eTextRep, specifies what 
3720 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3721 ** its parameters.  Any SQL function implementation should be able to work
3722 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3723 ** more efficient with one encoding than another.  It is allowed to
3724 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3725 ** times with the same function but with different values of eTextRep.
3726 ** When multiple implementations of the same function are available, SQLite
3727 ** will pick the one that involves the least amount of data conversion.
3728 ** If there is only a single implementation which does not care what
3729 ** text encoding is used, then the fourth argument should be
3730 ** [SQLITE_ANY].
3731 **
3732 ** The fifth parameter is an arbitrary pointer.  The implementation
3733 ** of the function can gain access to this pointer using
3734 ** [sqlite3_user_data()].
3735 **
3736 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3737 ** pointers to C-language functions that implement the SQL
3738 ** function or aggregate. A scalar SQL function requires an implementation of
3739 ** the xFunc callback only, NULL pointers should be passed as the xStep
3740 ** and xFinal parameters. An aggregate SQL function requires an implementation
3741 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
3742 ** existing SQL function or aggregate, pass NULL for all three function
3743 ** callback.
3744 **
3745 ** It is permitted to register multiple implementations of the same
3746 ** functions with the same name but with either differing numbers of
3747 ** arguments or differing perferred text encodings.  SQLite will use
3748 ** the implementation most closely matches the way in which the
3749 ** SQL function is used.
3750 **
3751 ** INVARIANTS:
3752 **
3753 ** {F16103} The [sqlite3_create_function16()] interface behaves exactly
3754 **          like [sqlite3_create_function()] in every way except that it
3755 **          interprets the zFunctionName argument as
3756 **          zero-terminated UTF-16 native byte order instead of as a
3757 **          zero-terminated UTF-8.
3758 **
3759 ** {F16106} A successful invocation of
3760 **          the [sqlite3_create_function(D,X,N,E,...)] interface registers
3761 **          or replaces callback functions in [database connection] D
3762 **          used to implement the SQL function named X with N parameters
3763 **          and having a perferred text encoding of E.
3764 **
3765 ** {F16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)]
3766 **          replaces the P, F, S, and L values from any prior calls with
3767 **          the same D, X, N, and E values.
3768 **
3769 ** {F16112} The [sqlite3_create_function(D,X,...)] interface fails with
3770 **          a return code of [SQLITE_ERROR] if the SQL function name X is
3771 **          longer than 255 bytes exclusive of the zero terminator.
3772 **
3773 ** {F16118} Either F must be NULL and S and L are non-NULL or else F
3774 **          is non-NULL and S and L are NULL, otherwise
3775 **          [sqlite3_create_function(D,X,N,E,P,F,S,L)] returns [SQLITE_ERROR].
3776 **
3777 ** {F16121} The [sqlite3_create_function(D,...)] interface fails with an
3778 **          error code of [SQLITE_BUSY] if there exist [prepared statements]
3779 **          associated with the [database connection] D.
3780 **
3781 ** {F16124} The [sqlite3_create_function(D,X,N,...)] interface fails with an
3782 **          error code of [SQLITE_ERROR] if parameter N (specifying the number
3783 **          of arguments to the SQL function being registered) is less
3784 **          than -1 or greater than 127.
3785 **
3786 ** {F16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)]
3787 **          interface causes callbacks to be invoked for the SQL function
3788 **          named X when the number of arguments to the SQL function is
3789 **          exactly N.
3790 **
3791 ** {F16130} When N is -1, the [sqlite3_create_function(D,X,N,...)]
3792 **          interface causes callbacks to be invoked for the SQL function
3793 **          named X with any number of arguments.
3794 **
3795 ** {F16133} When calls to [sqlite3_create_function(D,X,N,...)]
3796 **          specify multiple implementations of the same function X
3797 **          and when one implementation has N>=0 and the other has N=(-1)
3798 **          the implementation with a non-zero N is preferred.
3799 **
3800 ** {F16136} When calls to [sqlite3_create_function(D,X,N,E,...)]
3801 **          specify multiple implementations of the same function X with
3802 **          the same number of arguments N but with different
3803 **          encodings E, then the implementation where E matches the
3804 **          database encoding is preferred.
3805 **
3806 ** {F16139} For an aggregate SQL function created using
3807 **          [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finializer
3808 **          function L will always be invoked exactly once if the
3809 **          step function S is called one or more times.
3810 */
3811 SQLITE_API int sqlite3_create_function(
3812   sqlite3 *db,
3813   const char *zFunctionName,
3814   int nArg,
3815   int eTextRep,
3816   void *pApp,
3817   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3818   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3819   void (*xFinal)(sqlite3_context*)
3820 );
3821 SQLITE_API int sqlite3_create_function16(
3822   sqlite3 *db,
3823   const void *zFunctionName,
3824   int nArg,
3825   int eTextRep,
3826   void *pApp,
3827   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3828   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3829   void (*xFinal)(sqlite3_context*)
3830 );
3831
3832 /*
3833 ** CAPI3REF: Text Encodings {F10267}
3834 **
3835 ** These constant define integer codes that represent the various
3836 ** text encodings supported by SQLite.
3837 */
3838 #define SQLITE_UTF8           1
3839 #define SQLITE_UTF16LE        2
3840 #define SQLITE_UTF16BE        3
3841 #define SQLITE_UTF16          4    /* Use native byte order */
3842 #define SQLITE_ANY            5    /* sqlite3_create_function only */
3843 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3844
3845 /*
3846 ** CAPI3REF: Obsolete Functions
3847 **
3848 ** These functions are all now obsolete.  In order to maintain
3849 ** backwards compatibility with older code, we continue to support
3850 ** these functions.  However, new development projects should avoid
3851 ** the use of these functions.  To help encourage people to avoid
3852 ** using these functions, we are not going to tell you want they do.
3853 */
3854 SQLITE_API int sqlite3_aggregate_count(sqlite3_context*);
3855 SQLITE_API int sqlite3_expired(sqlite3_stmt*);
3856 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3857 SQLITE_API int sqlite3_global_recover(void);
3858 SQLITE_API void sqlite3_thread_cleanup(void);
3859 SQLITE_API int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3860
3861 /*
3862 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
3863 **
3864 ** The C-language implementation of SQL functions and aggregates uses
3865 ** this set of interface routines to access the parameter values on
3866 ** the function or aggregate.
3867 **
3868 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3869 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3870 ** define callbacks that implement the SQL functions and aggregates.
3871 ** The 4th parameter to these callbacks is an array of pointers to
3872 ** [sqlite3_value] objects.  There is one [sqlite3_value] object for
3873 ** each parameter to the SQL function.  These routines are used to
3874 ** extract values from the [sqlite3_value] objects.
3875 **
3876 ** These routines work just like the corresponding 
3877 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
3878 ** these routines take a single [sqlite3_value*] pointer instead
3879 ** of an [sqlite3_stmt*] pointer and an integer column number.
3880 **
3881 ** The sqlite3_value_text16() interface extracts a UTF16 string
3882 ** in the native byte-order of the host machine.  The
3883 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3884 ** extract UTF16 strings as big-endian and little-endian respectively.
3885 **
3886 ** The sqlite3_value_numeric_type() interface attempts to apply
3887 ** numeric affinity to the value.  This means that an attempt is
3888 ** made to convert the value to an integer or floating point.  If
3889 ** such a conversion is possible without loss of information (in other
3890 ** words if the value is a string that looks like a number)
3891 ** then the conversion is done.  Otherwise no conversion occurs.  The 
3892 ** [SQLITE_INTEGER | datatype] after conversion is returned.
3893 **
3894 ** Please pay particular attention to the fact that the pointer that
3895 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
3896 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3897 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3898 ** or [sqlite3_value_text16()].  
3899 **
3900 ** These routines must be called from the same thread as
3901 ** the SQL function that supplied the sqlite3_value* parameters.
3902 ** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()]
3903 ** interface, then these routines should be called from the same thread
3904 ** that ran [sqlite3_column_value()].
3905 **
3906 **
3907 ** INVARIANTS:
3908 **
3909 ** {F15103} The [sqlite3_value_blob(V)] interface converts the
3910 **          [sqlite3_value] object V into a blob and then returns a
3911 **          pointer to the converted value.
3912 **
3913 ** {F15106} The [sqlite3_value_bytes(V)] interface returns the
3914 **          number of bytes in the blob or string (exclusive of the
3915 **          zero terminator on the string) that was returned by the
3916 **          most recent call to [sqlite3_value_blob(V)] or
3917 **          [sqlite3_value_text(V)].
3918 **
3919 ** {F15109} The [sqlite3_value_bytes16(V)] interface returns the
3920 **          number of bytes in the string (exclusive of the
3921 **          zero terminator on the string) that was returned by the
3922 **          most recent call to [sqlite3_value_text16(V)],
3923 **          [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)].
3924 **
3925 ** {F15112} The [sqlite3_value_double(V)] interface converts the
3926 **          [sqlite3_value] object V into a floating point value and
3927 **          returns a copy of that value.
3928 **
3929 ** {F15115} The [sqlite3_value_int(V)] interface converts the
3930 **          [sqlite3_value] object V into a 64-bit signed integer and
3931 **          returns the lower 32 bits of that integer.
3932 **
3933 ** {F15118} The [sqlite3_value_int64(V)] interface converts the
3934 **          [sqlite3_value] object V into a 64-bit signed integer and
3935 **          returns a copy of that integer.
3936 **
3937 ** {F15121} The [sqlite3_value_text(V)] interface converts the
3938 **          [sqlite3_value] object V into a zero-terminated UTF-8 
3939 **          string and returns a pointer to that string.
3940 **
3941 ** {F15124} The [sqlite3_value_text16(V)] interface converts the
3942 **          [sqlite3_value] object V into a zero-terminated 2-byte
3943 **          aligned UTF-16 native byte order
3944 **          string and returns a pointer to that string.
3945 **
3946 ** {F15127} The [sqlite3_value_text16be(V)] interface converts the
3947 **          [sqlite3_value] object V into a zero-terminated 2-byte
3948 **          aligned UTF-16 big-endian
3949 **          string and returns a pointer to that string.
3950 **
3951 ** {F15130} The [sqlite3_value_text16le(V)] interface converts the
3952 **          [sqlite3_value] object V into a zero-terminated 2-byte
3953 **          aligned UTF-16 little-endian
3954 **          string and returns a pointer to that string.
3955 **
3956 ** {F15133} The [sqlite3_value_type(V)] interface returns
3957 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
3958 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
3959 **          the [sqlite3_value] object V.
3960 **
3961 ** {F15136} The [sqlite3_value_numeric_type(V)] interface converts
3962 **          the [sqlite3_value] object V into either an integer or
3963 **          a floating point value if it can do so without loss of
3964 **          information, and returns one of [SQLITE_NULL],
3965 **          [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or
3966 **          [SQLITE_BLOB] as appropriate for
3967 **          the [sqlite3_value] object V after the conversion attempt.
3968 */
3969 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3970 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3971 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3972 SQLITE_API double sqlite3_value_double(sqlite3_value*);
3973 SQLITE_API int sqlite3_value_int(sqlite3_value*);
3974 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3975 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3976 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3977 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3978 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3979 SQLITE_API int sqlite3_value_type(sqlite3_value*);
3980 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3981
3982 /*
3983 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
3984 **
3985 ** The implementation of aggregate SQL functions use this routine to allocate
3986 ** a structure for storing their state.  
3987 ** The first time the sqlite3_aggregate_context() routine is
3988 ** is called for a particular aggregate, SQLite allocates nBytes of memory
3989 ** zeros that memory, and returns a pointer to it.
3990 ** On second and subsequent calls to sqlite3_aggregate_context()
3991 ** for the same aggregate function index, the same buffer is returned.
3992 ** The implementation
3993 ** of the aggregate can use the returned buffer to accumulate data.
3994 **
3995 ** SQLite automatically frees the allocated buffer when the aggregate
3996 ** query concludes.
3997 **
3998 ** The first parameter should be a copy of the 
3999 ** [sqlite3_context | SQL function context] that is the first
4000 ** parameter to the callback routine that implements the aggregate
4001 ** function.
4002 **
4003 ** This routine must be called from the same thread in which
4004 ** the aggregate SQL function is running.
4005 **
4006 ** INVARIANTS:
4007 **
4008 ** {F16211} The first invocation of [sqlite3_aggregate_context(C,N)] for
4009 **          a particular instance of an aggregate function (for a particular
4010 **          context C) causes SQLite to allocation N bytes of memory,
4011 **          zero that memory, and return a pointer to the allocationed
4012 **          memory.
4013 **
4014 ** {F16213} If a memory allocation error occurs during
4015 **          [sqlite3_aggregate_context(C,N)] then the function returns 0.
4016 **
4017 ** {F16215} Second and subsequent invocations of
4018 **          [sqlite3_aggregate_context(C,N)] for the same context pointer C
4019 **          ignore the N parameter and return a pointer to the same
4020 **          block of memory returned by the first invocation.
4021 **
4022 ** {F16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is
4023 **          automatically freed on the next call to [sqlite3_reset()]
4024 **          or [sqlite3_finalize()] for the [prepared statement] containing
4025 **          the aggregate function associated with context C.
4026 */
4027 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4028
4029 /*
4030 ** CAPI3REF: User Data For Functions {F16240}
4031 **
4032 ** The sqlite3_user_data() interface returns a copy of
4033 ** the pointer that was the pUserData parameter (the 5th parameter)
4034 ** of the the [sqlite3_create_function()]
4035 ** and [sqlite3_create_function16()] routines that originally
4036 ** registered the application defined function. {END}
4037 **
4038 ** This routine must be called from the same thread in which
4039 ** the application-defined function is running.
4040 **
4041 ** INVARIANTS:
4042 **
4043 ** {F16243} The [sqlite3_user_data(C)] interface returns a copy of the
4044 **          P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4045 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4046 **          registered the SQL function associated with 
4047 **          [sqlite3_context] C.
4048 */
4049 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4050
4051 /*
4052 ** CAPI3REF: Function Auxiliary Data {F16270}
4053 **
4054 ** The following two functions may be used by scalar SQL functions to
4055 ** associate meta-data with argument values. If the same value is passed to
4056 ** multiple invocations of the same SQL function during query execution, under
4057 ** some circumstances the associated meta-data may be preserved. This may
4058 ** be used, for example, to add a regular-expression matching scalar
4059 ** function. The compiled version of the regular expression is stored as
4060 ** meta-data associated with the SQL value passed as the regular expression
4061 ** pattern.  The compiled regular expression can be reused on multiple
4062 ** invocations of the same function so that the original pattern string
4063 ** does not need to be recompiled on each invocation.
4064 **
4065 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
4066 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4067 ** value to the application-defined function.
4068 ** If no meta-data has been ever been set for the Nth
4069 ** argument of the function, or if the cooresponding function parameter
4070 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
4071 ** returns a NULL pointer.
4072 **
4073 ** The sqlite3_set_auxdata() interface saves the meta-data
4074 ** pointed to by its 3rd parameter as the meta-data for the N-th
4075 ** argument of the application-defined function.  Subsequent
4076 ** calls to sqlite3_get_auxdata() might return this data, if it has
4077 ** not been destroyed. 
4078 ** If it is not NULL, SQLite will invoke the destructor 
4079 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4080 ** the meta-data when the corresponding function parameter changes
4081 ** or when the SQL statement completes, whichever comes first.
4082 **
4083 ** SQLite is free to call the destructor and drop meta-data on
4084 ** any parameter of any function at any time.  The only guarantee
4085 ** is that the destructor will be called before the metadata is
4086 ** dropped.
4087 **
4088 ** In practice, meta-data is preserved between function calls for
4089 ** expressions that are constant at compile time. This includes literal
4090 ** values and SQL variables.
4091 **
4092 ** These routines must be called from the same thread in which
4093 ** the SQL function is running.
4094 **
4095 ** INVARIANTS:
4096 **
4097 ** {F16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer
4098 **          to metadata associated with the Nth parameter of the SQL function
4099 **          whose context is C, or NULL if there is no metadata associated
4100 **          with that parameter.
4101 **
4102 ** {F16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata
4103 **          pointer P to the Nth parameter of the SQL function with context
4104 **          C.
4105 **
4106 ** {F16276} SQLite will invoke the destructor D with a single argument
4107 **          which is the metadata pointer P following a call to
4108 **          [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold
4109 **          the metadata.
4110 **
4111 ** {F16277} SQLite ceases to hold metadata for an SQL function parameter
4112 **          when the value of that parameter changes.
4113 **
4114 ** {F16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor
4115 **          is called for any prior metadata associated with the same function
4116 **          context C and parameter N.
4117 **
4118 ** {F16279} SQLite will call destructors for any metadata it is holding
4119 **          in a particular [prepared statement] S when either
4120 **          [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called.
4121 */
4122 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4123 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4124
4125
4126 /*
4127 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
4128 **
4129 ** These are special value for the destructor that is passed in as the
4130 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
4131 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4132 ** and will never change.  It does not need to be destroyed.  The 
4133 ** SQLITE_TRANSIENT value means that the content will likely change in
4134 ** the near future and that SQLite should make its own private copy of
4135 ** the content before returning.
4136 **
4137 ** The typedef is necessary to work around problems in certain
4138 ** C++ compilers.  See ticket #2191.
4139 */
4140 typedef void (*sqlite3_destructor_type)(void*);
4141 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4142 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4143
4144 /*
4145 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
4146 **
4147 ** These routines are used by the xFunc or xFinal callbacks that
4148 ** implement SQL functions and aggregates.  See
4149 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4150 ** for additional information.
4151 **
4152 ** These functions work very much like the 
4153 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
4154 ** to bind values to host parameters in prepared statements.
4155 ** Refer to the
4156 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
4157 ** additional information.
4158 **
4159 ** The sqlite3_result_blob() interface sets the result from
4160 ** an application defined function to be the BLOB whose content is pointed
4161 ** to by the second parameter and which is N bytes long where N is the
4162 ** third parameter. 
4163 ** The sqlite3_result_zeroblob() inerfaces set the result of
4164 ** the application defined function to be a BLOB containing all zero
4165 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4166 **
4167 ** The sqlite3_result_double() interface sets the result from
4168 ** an application defined function to be a floating point value specified
4169 ** by its 2nd argument.
4170 **
4171 ** The sqlite3_result_error() and sqlite3_result_error16() functions
4172 ** cause the implemented SQL function to throw an exception.
4173 ** SQLite uses the string pointed to by the
4174 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4175 ** as the text of an error message.  SQLite interprets the error
4176 ** message string from sqlite3_result_error() as UTF8. SQLite
4177 ** interprets the string from sqlite3_result_error16() as UTF16 in native
4178 ** byte order.  If the third parameter to sqlite3_result_error()
4179 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4180 ** message all text up through the first zero character.
4181 ** If the third parameter to sqlite3_result_error() or
4182 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4183 ** bytes (not characters) from the 2nd parameter as the error message.
4184 ** The sqlite3_result_error() and sqlite3_result_error16()
4185 ** routines make a copy private copy of the error message text before
4186 ** they return.  Hence, the calling function can deallocate or
4187 ** modify the text after they return without harm.
4188 ** The sqlite3_result_error_code() function changes the error code
4189 ** returned by SQLite as a result of an error in a function.  By default,
4190 ** the error code is SQLITE_ERROR. 
4191 **
4192 ** The sqlite3_result_toobig() interface causes SQLite
4193 ** to throw an error indicating that a string or BLOB is to long
4194 ** to represent.  The sqlite3_result_nomem() interface
4195 ** causes SQLite to throw an exception indicating that the a
4196 ** memory allocation failed.
4197 **
4198 ** The sqlite3_result_int() interface sets the return value
4199 ** of the application-defined function to be the 32-bit signed integer
4200 ** value given in the 2nd argument.
4201 ** The sqlite3_result_int64() interface sets the return value
4202 ** of the application-defined function to be the 64-bit signed integer
4203 ** value given in the 2nd argument.
4204 **
4205 ** The sqlite3_result_null() interface sets the return value
4206 ** of the application-defined function to be NULL.
4207 **
4208 ** The sqlite3_result_text(), sqlite3_result_text16(), 
4209 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4210 ** set the return value of the application-defined function to be
4211 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4212 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4213 ** SQLite takes the text result from the application from
4214 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4215 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4216 ** is negative, then SQLite takes result text from the 2nd parameter 
4217 ** through the first zero character.
4218 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4219 ** is non-negative, then as many bytes (not characters) of the text
4220 ** pointed to by the 2nd parameter are taken as the application-defined
4221 ** function result.
4222 ** If the 4th parameter to the sqlite3_result_text* interfaces
4223 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4224 ** function as the destructor on the text or blob result when it has
4225 ** finished using that result.
4226 ** If the 4th parameter to the sqlite3_result_text* interfaces
4227 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
4228 ** SQLite assumes that the text or blob result is constant space and
4229 ** does not copy the space or call a destructor when it has
4230 ** finished using that result.
4231 ** If the 4th parameter to the sqlite3_result_text* interfaces
4232 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4233 ** then SQLite makes a copy of the result into space obtained from
4234 ** from [sqlite3_malloc()] before it returns.
4235 **
4236 ** The sqlite3_result_value() interface sets the result of
4237 ** the application-defined function to be a copy the [sqlite3_value]
4238 ** object specified by the 2nd parameter.  The
4239 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4240 ** so that [sqlite3_value] specified in the parameter may change or
4241 ** be deallocated after sqlite3_result_value() returns without harm.
4242 **
4243 ** If these routines are called from within the different thread 
4244 ** than the one containing the application-defined function that recieved
4245 ** the [sqlite3_context] pointer, the results are undefined.
4246 **
4247 ** INVARIANTS:
4248 **
4249 ** {F16403} The default return value from any SQL function is NULL.
4250 **
4251 ** {F16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the
4252 **          return value of function C to be a blob that is N bytes
4253 **          in length and with content pointed to by V.
4254 **
4255 ** {F16409} The [sqlite3_result_double(C,V)] interface changes the
4256 **          return value of function C to be the floating point value V.
4257 **
4258 ** {F16412} The [sqlite3_result_error(C,V,N)] interface changes the return
4259 **          value of function C to be an exception with error code
4260 **          [SQLITE_ERROR] and a UTF8 error message copied from V up to the
4261 **          first zero byte or until N bytes are read if N is positive.
4262 **
4263 ** {F16415} The [sqlite3_result_error16(C,V,N)] interface changes the return
4264 **          value of function C to be an exception with error code
4265 **          [SQLITE_ERROR] and a UTF16 native byte order error message
4266 **          copied from V up to the first zero terminator or until N bytes
4267 **          are read if N is positive.
4268 **
4269 ** {F16418} The [sqlite3_result_error_toobig(C)] interface changes the return
4270 **          value of the function C to be an exception with error code
4271 **          [SQLITE_TOOBIG] and an appropriate error message.
4272 **
4273 ** {F16421} The [sqlite3_result_error_nomem(C)] interface changes the return
4274 **          value of the function C to be an exception with error code
4275 **          [SQLITE_NOMEM] and an appropriate error message.
4276 **
4277 ** {F16424} The [sqlite3_result_error_code(C,E)] interface changes the return
4278 **          value of the function C to be an exception with error code E.
4279 **          The error message text is unchanged.
4280 **
4281 ** {F16427} The [sqlite3_result_int(C,V)] interface changes the
4282 **          return value of function C to be the 32-bit integer value V.
4283 **
4284 ** {F16430} The [sqlite3_result_int64(C,V)] interface changes the
4285 **          return value of function C to be the 64-bit integer value V.
4286 **
4287 ** {F16433} The [sqlite3_result_null(C)] interface changes the
4288 **          return value of function C to be NULL.
4289 **
4290 ** {F16436} The [sqlite3_result_text(C,V,N,D)] interface changes the
4291 **          return value of function C to be the UTF8 string
4292 **          V up through the first zero or until N bytes are read if N
4293 **          is positive.
4294 **
4295 ** {F16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the
4296 **          return value of function C to be the UTF16 native byte order
4297 **          string  V up through the first zero or until N bytes are read if N
4298 **          is positive.
4299 **
4300 ** {F16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the
4301 **          return value of function C to be the UTF16 big-endian
4302 **          string  V up through the first zero or until N bytes are read if N
4303 **          is positive.
4304 **
4305 ** {F16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the
4306 **          return value of function C to be the UTF16 little-endian
4307 **          string  V up through the first zero or until N bytes are read if N
4308 **          is positive.
4309 **
4310 ** {F16448} The [sqlite3_result_value(C,V)] interface changes the
4311 **          return value of function C to be [sqlite3_value] object V.
4312 **
4313 ** {F16451} The [sqlite3_result_zeroblob(C,N)] interface changes the
4314 **          return value of function C to be an N-byte blob of all zeros.
4315 **
4316 ** {F16454} The [sqlite3_result_error()] and [sqlite3_result_error16()]
4317 **          interfaces make a copy of their error message strings before
4318 **          returning.
4319 **
4320 ** {F16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4321 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4322 **          [sqlite3_result_text16be(C,V,N,D)], or
4323 **          [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC]
4324 **          then no destructor is ever called on the pointer V and SQLite
4325 **          assumes that V is immutable.
4326 **
4327 ** {F16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4328 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4329 **          [sqlite3_result_text16be(C,V,N,D)], or
4330 **          [sqlite3_result_text16le(C,V,N,D)] is the constant
4331 **          [SQLITE_TRANSIENT] then the interfaces makes a copy of the
4332 **          content of V and retains the copy.
4333 **
4334 ** {F16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4335 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4336 **          [sqlite3_result_text16be(C,V,N,D)], or
4337 **          [sqlite3_result_text16le(C,V,N,D)] is some value other than
4338 **          the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then 
4339 **          SQLite will invoke the destructor D with V as its only argument
4340 **          when it has finished with the V value.
4341 */
4342 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4343 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4344 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4345 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4346 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4347 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4348 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4349 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4350 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4351 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4352 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4353 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4354 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4355 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4356 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4357 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4358
4359 /*
4360 ** CAPI3REF: Define New Collating Sequences {F16600}
4361 **
4362 ** These functions are used to add new collation sequences to the
4363 ** [sqlite3*] handle specified as the first argument. 
4364 **
4365 ** The name of the new collation sequence is specified as a UTF-8 string
4366 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4367 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
4368 ** the name is passed as the second function argument.
4369 **
4370 ** The third argument may be one of the constants [SQLITE_UTF8],
4371 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
4372 ** routine expects to be passed pointers to strings encoded using UTF-8,
4373 ** UTF-16 little-endian or UTF-16 big-endian respectively. The
4374 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
4375 ** the routine expects pointers to 16-bit word aligned strings
4376 ** of UTF16 in the native byte order of the host computer.
4377 **
4378 ** A pointer to the user supplied routine must be passed as the fifth
4379 ** argument.  If it is NULL, this is the same as deleting the collation
4380 ** sequence (so that SQLite cannot call it anymore).
4381 ** Each time the application
4382 ** supplied function is invoked, it is passed a copy of the void* passed as
4383 ** the fourth argument to sqlite3_create_collation() or
4384 ** sqlite3_create_collation16() as its first parameter.
4385 **
4386 ** The remaining arguments to the application-supplied routine are two strings,
4387 ** each represented by a (length, data) pair and encoded in the encoding
4388 ** that was passed as the third argument when the collation sequence was
4389 ** registered. {END} The application defined collation routine should
4390 ** return negative, zero or positive if
4391 ** the first string is less than, equal to, or greater than the second
4392 ** string. i.e. (STRING1 - STRING2).
4393 **
4394 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4395 ** excapt that it takes an extra argument which is a destructor for
4396 ** the collation.  The destructor is called when the collation is
4397 ** destroyed and is passed a copy of the fourth parameter void* pointer
4398 ** of the sqlite3_create_collation_v2().
4399 ** Collations are destroyed when
4400 ** they are overridden by later calls to the collation creation functions
4401 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
4402 **
4403 ** INVARIANTS:
4404 **
4405 ** {F16603} A successful call to the
4406 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface
4407 **          registers function F as the comparison function used to
4408 **          implement collation X on [database connection] B for
4409 **          databases having encoding E.
4410 **
4411 ** {F16604} SQLite understands the X parameter to
4412 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated
4413 **          UTF-8 string in which case is ignored for ASCII characters and
4414 **          is significant for non-ASCII characters.
4415 **
4416 ** {F16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4417 **          with the same values for B, X, and E, override prior values
4418 **          of P, F, and D.
4419 **
4420 ** {F16609} The destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4421 **          is not NULL then it is called with argument P when the
4422 **          collating function is dropped by SQLite.
4423 **
4424 ** {F16612} A collating function is dropped when it is overloaded.
4425 **
4426 ** {F16615} A collating function is dropped when the database connection
4427 **          is closed using [sqlite3_close()].
4428 **
4429 ** {F16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4430 **          is passed through as the first parameter to the comparison
4431 **          function F for all subsequent invocations of F.
4432 **
4433 ** {F16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly
4434 **          the same as a call to [sqlite3_create_collation_v2()] with
4435 **          the same parameters and a NULL destructor.
4436 **
4437 ** {F16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)],
4438 **          SQLite uses the comparison function F for all text comparison
4439 **          operations on [database connection] B on text values that
4440 **          use the collating sequence name X.
4441 **
4442 ** {F16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same
4443 **          as [sqlite3_create_collation(B,X,E,P,F)] except that the
4444 **          collation name X is understood as UTF-16 in native byte order
4445 **          instead of UTF-8.
4446 **
4447 ** {F16630} When multiple comparison functions are available for the same
4448 **          collating sequence, SQLite chooses the one whose text encoding
4449 **          requires the least amount of conversion from the default
4450 **          text encoding of the database.
4451 */
4452 SQLITE_API int sqlite3_create_collation(
4453   sqlite3*, 
4454   const char *zName, 
4455   int eTextRep, 
4456   void*,
4457   int(*xCompare)(void*,int,const void*,int,const void*)
4458 );
4459 SQLITE_API int sqlite3_create_collation_v2(
4460   sqlite3*, 
4461   const char *zName, 
4462   int eTextRep, 
4463   void*,
4464   int(*xCompare)(void*,int,const void*,int,const void*),
4465   void(*xDestroy)(void*)
4466 );
4467 SQLITE_API int sqlite3_create_collation16(
4468   sqlite3*, 
4469   const char *zName, 
4470   int eTextRep, 
4471   void*,
4472   int(*xCompare)(void*,int,const void*,int,const void*)
4473 );
4474
4475 /*
4476 ** CAPI3REF: Collation Needed Callbacks {F16700}
4477 **
4478 ** To avoid having to register all collation sequences before a database
4479 ** can be used, a single callback function may be registered with the
4480 ** database handle to be called whenever an undefined collation sequence is
4481 ** required.
4482 **
4483 ** If the function is registered using the sqlite3_collation_needed() API,
4484 ** then it is passed the names of undefined collation sequences as strings
4485 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
4486 ** are passed as UTF-16 in machine native byte order. A call to either
4487 ** function replaces any existing callback.
4488 **
4489 ** When the callback is invoked, the first argument passed is a copy
4490 ** of the second argument to sqlite3_collation_needed() or
4491 ** sqlite3_collation_needed16().  The second argument is the database
4492 ** handle.  The third argument is one of [SQLITE_UTF8],
4493 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
4494 ** desirable form of the collation sequence function required.
4495 ** The fourth parameter is the name of the
4496 ** required collation sequence.
4497 **
4498 ** The callback function should register the desired collation using
4499 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4500 ** [sqlite3_create_collation_v2()].
4501 **
4502 ** INVARIANTS:
4503 **
4504 ** {F16702} A successful call to [sqlite3_collation_needed(D,P,F)]
4505 **          or [sqlite3_collation_needed16(D,P,F)] causes
4506 **          the [database connection] D to invoke callback F with first
4507 **          parameter P whenever it needs a comparison function for a
4508 **          collating sequence that it does not know about.
4509 **
4510 ** {F16704} Each successful call to [sqlite3_collation_needed()] or
4511 **          [sqlite3_collation_needed16()] overrides the callback registered
4512 **          on the same [database connection] by prior calls to either
4513 **          interface.
4514 **
4515 ** {F16706} The name of the requested collating function passed in the
4516 **          4th parameter to the callback is in UTF-8 if the callback
4517 **          was registered using [sqlite3_collation_needed()] and
4518 **          is in UTF-16 native byte order if the callback was
4519 **          registered using [sqlite3_collation_needed16()].
4520 **
4521 ** 
4522 */
4523 SQLITE_API int sqlite3_collation_needed(
4524   sqlite3*, 
4525   void*, 
4526   void(*)(void*,sqlite3*,int eTextRep,const char*)
4527 );
4528 SQLITE_API int sqlite3_collation_needed16(
4529   sqlite3*, 
4530   void*,
4531   void(*)(void*,sqlite3*,int eTextRep,const void*)
4532 );
4533
4534 /*
4535 ** Specify the key for an encrypted database.  This routine should be
4536 ** called right after sqlite3_open().
4537 **
4538 ** The code to implement this API is not available in the public release
4539 ** of SQLite.
4540 */
4541 SQLITE_API int sqlite3_key(
4542   sqlite3 *db,                   /* Database to be rekeyed */
4543   const void *pKey, int nKey     /* The key */
4544 );
4545
4546 /*
4547 ** Change the key on an open database.  If the current database is not
4548 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4549 ** database is decrypted.
4550 **
4551 ** The code to implement this API is not available in the public release
4552 ** of SQLite.
4553 */
4554 SQLITE_API int sqlite3_rekey(
4555   sqlite3 *db,                   /* Database to be rekeyed */
4556   const void *pKey, int nKey     /* The new key */
4557 );
4558
4559 /*
4560 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
4561 **
4562 ** The sqlite3_sleep() function
4563 ** causes the current thread to suspend execution
4564 ** for at least a number of milliseconds specified in its parameter.
4565 **
4566 ** If the operating system does not support sleep requests with 
4567 ** millisecond time resolution, then the time will be rounded up to 
4568 ** the nearest second. The number of milliseconds of sleep actually 
4569 ** requested from the operating system is returned.
4570 **
4571 ** SQLite implements this interface by calling the xSleep()
4572 ** method of the default [sqlite3_vfs] object.
4573 **
4574 ** INVARIANTS:
4575 **
4576 ** {F10533} The [sqlite3_sleep(M)] interface invokes the xSleep
4577 **          method of the default [sqlite3_vfs|VFS] in order to
4578 **          suspend execution of the current thread for at least
4579 **          M milliseconds.
4580 **
4581 ** {F10536} The [sqlite3_sleep(M)] interface returns the number of
4582 **          milliseconds of sleep actually requested of the operating
4583 **          system, which might be larger than the parameter M.
4584 */
4585 SQLITE_API int sqlite3_sleep(int);
4586
4587 /*
4588 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
4589 **
4590 ** If this global variable is made to point to a string which is
4591 ** the name of a folder (a.ka. directory), then all temporary files
4592 ** created by SQLite will be placed in that directory.  If this variable
4593 ** is NULL pointer, then SQLite does a search for an appropriate temporary
4594 ** file directory.
4595 **
4596 ** It is not safe to modify this variable once a database connection
4597 ** has been opened.  It is intended that this variable be set once
4598 ** as part of process initialization and before any SQLite interface
4599 ** routines have been call and remain unchanged thereafter.
4600 */
4601 SQLITE_API char *sqlite3_temp_directory;
4602
4603 /*
4604 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
4605 **
4606 ** The sqlite3_get_autocommit() interfaces returns non-zero or
4607 ** zero if the given database connection is or is not in autocommit mode,
4608 ** respectively.   Autocommit mode is on
4609 ** by default.  Autocommit mode is disabled by a [BEGIN] statement.
4610 ** Autocommit mode is reenabled by a [COMMIT] or [ROLLBACK].
4611 **
4612 ** If certain kinds of errors occur on a statement within a multi-statement
4613 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
4614 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4615 ** transaction might be rolled back automatically.  The only way to
4616 ** find out if SQLite automatically rolled back the transaction after
4617 ** an error is to use this function.
4618 **
4619 ** INVARIANTS:
4620 **
4621 ** {F12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or
4622 **          zero if the [database connection] D is or is not in autocommit
4623 **          mode, respectively.
4624 **
4625 ** {F12932} Autocommit mode is on by default.
4626 **
4627 ** {F12933} Autocommit mode is disabled by a successful [BEGIN] statement.
4628 **
4629 ** {F12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK]
4630 **          statement.
4631 ** 
4632 **
4633 ** LIMITATIONS:
4634 ***
4635 ** {U12936} If another thread changes the autocommit status of the database
4636 **          connection while this routine is running, then the return value
4637 **          is undefined.
4638 */
4639 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4640
4641 /*
4642 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
4643 **
4644 ** The sqlite3_db_handle interface
4645 ** returns the [sqlite3*] database handle to which a
4646 ** [prepared statement] belongs.
4647 ** The database handle returned by sqlite3_db_handle
4648 ** is the same database handle that was
4649 ** the first argument to the [sqlite3_prepare_v2()] or its variants
4650 ** that was used to create the statement in the first place.
4651 **
4652 ** INVARIANTS:
4653 **
4654 ** {F13123} The [sqlite3_db_handle(S)] interface returns a pointer
4655 **          to the [database connection] associated with
4656 **          [prepared statement] S.
4657 */
4658 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4659
4660
4661 /*
4662 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
4663 **
4664 ** The sqlite3_commit_hook() interface registers a callback
4665 ** function to be invoked whenever a transaction is committed.
4666 ** Any callback set by a previous call to sqlite3_commit_hook()
4667 ** for the same database connection is overridden.
4668 ** The sqlite3_rollback_hook() interface registers a callback
4669 ** function to be invoked whenever a transaction is committed.
4670 ** Any callback set by a previous call to sqlite3_commit_hook()
4671 ** for the same database connection is overridden.
4672 ** The pArg argument is passed through
4673 ** to the callback.  If the callback on a commit hook function 
4674 ** returns non-zero, then the commit is converted into a rollback.
4675 **
4676 ** If another function was previously registered, its
4677 ** pArg value is returned.  Otherwise NULL is returned.
4678 **
4679 ** Registering a NULL function disables the callback.
4680 **
4681 ** For the purposes of this API, a transaction is said to have been 
4682 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4683 ** an error or constraint causes an implicit rollback to occur.
4684 ** The rollback callback is not invoked if a transaction is
4685 ** automatically rolled back because the database connection is closed.
4686 ** The rollback callback is not invoked if a transaction is
4687 ** rolled back because a commit callback returned non-zero.
4688 ** <todo> Check on this </todo>
4689 **
4690 ** These are experimental interfaces and are subject to change.
4691 **
4692 ** INVARIANTS:
4693 **
4694 ** {F12951} The [sqlite3_commit_hook(D,F,P)] interface registers the
4695 **          callback function F to be invoked with argument P whenever
4696 **          a transaction commits on [database connection] D.
4697 **
4698 ** {F12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P
4699 **          argument from the previous call with the same 
4700 **          [database connection ] D , or NULL on the first call
4701 **          for a particular [database connection] D.
4702 **
4703 ** {F12953} Each call to [sqlite3_commit_hook()] overwrites the callback
4704 **          registered by prior calls.
4705 **
4706 ** {F12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL
4707 **          then the commit hook callback is cancelled and no callback
4708 **          is invoked when a transaction commits.
4709 **
4710 ** {F12955} If the commit callback returns non-zero then the commit is
4711 **          converted into a rollback.
4712 **
4713 ** {F12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the
4714 **          callback function F to be invoked with argument P whenever
4715 **          a transaction rolls back on [database connection] D.
4716 **
4717 ** {F12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P
4718 **          argument from the previous call with the same 
4719 **          [database connection ] D , or NULL on the first call
4720 **          for a particular [database connection] D.
4721 **
4722 ** {F12963} Each call to [sqlite3_rollback_hook()] overwrites the callback
4723 **          registered by prior calls.
4724 **
4725 ** {F12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL
4726 **          then the rollback hook callback is cancelled and no callback
4727 **          is invoked when a transaction rolls back.
4728 */
4729 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4730 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4731
4732 /*
4733 ** CAPI3REF: Data Change Notification Callbacks {F12970}
4734 **
4735 ** The sqlite3_update_hook() interface
4736 ** registers a callback function with the database connection identified by the 
4737 ** first argument to be invoked whenever a row is updated, inserted or deleted.
4738 ** Any callback set by a previous call to this function for the same 
4739 ** database connection is overridden.
4740 **
4741 ** The second argument is a pointer to the function to invoke when a 
4742 ** row is updated, inserted or deleted. 
4743 ** The first argument to the callback is
4744 ** a copy of the third argument to sqlite3_update_hook().
4745 ** The second callback 
4746 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
4747 ** depending on the operation that caused the callback to be invoked.
4748 ** The third and 
4749 ** fourth arguments to the callback contain pointers to the database and 
4750 ** table name containing the affected row.
4751 ** The final callback parameter is 
4752 ** the rowid of the row.
4753 ** In the case of an update, this is the rowid after 
4754 ** the update takes place.
4755 **
4756 ** The update hook is not invoked when internal system tables are
4757 ** modified (i.e. sqlite_master and sqlite_sequence).
4758 **
4759 ** If another function was previously registered, its pArg value
4760 ** is returned.  Otherwise NULL is returned.
4761 **
4762 ** INVARIANTS:
4763 **
4764 ** {F12971} The [sqlite3_update_hook(D,F,P)] interface causes callback
4765 **          function F to be invoked with first parameter P whenever
4766 **          a table row is modified, inserted, or deleted on
4767 **          [database connection] D.
4768 **
4769 ** {F12973} The [sqlite3_update_hook(D,F,P)] interface returns the value
4770 **          of P for the previous call on the same [database connection] D,
4771 **          or NULL for the first call.
4772 **
4773 ** {F12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)]
4774 **          is NULL then the no update callbacks are made.
4775 **
4776 ** {F12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls
4777 **          to the same interface on the same [database connection] D.
4778 **
4779 ** {F12979} The update hook callback is not invoked when internal system
4780 **          tables such as sqlite_master and sqlite_sequence are modified.
4781 **
4782 ** {F12981} The second parameter to the update callback 
4783 **          is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
4784 **          depending on the operation that caused the callback to be invoked.
4785 **
4786 ** {F12983} The third and fourth arguments to the callback contain pointers
4787 **          to zero-terminated UTF-8 strings which are the names of the
4788 **          database and table that is being updated.
4789
4790 ** {F12985} The final callback parameter is the rowid of the row after
4791 **          the change occurs.
4792 */
4793 SQLITE_API void *sqlite3_update_hook(
4794   sqlite3*, 
4795   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4796   void*
4797 );
4798
4799 /*
4800 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
4801 **
4802 ** This routine enables or disables the sharing of the database cache
4803 ** and schema data structures between connections to the same database.
4804 ** Sharing is enabled if the argument is true and disabled if the argument
4805 ** is false.
4806 **
4807 ** Cache sharing is enabled and disabled
4808 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
4809 ** In prior versions of SQLite, sharing was
4810 ** enabled or disabled for each thread separately.
4811 **
4812 ** The cache sharing mode set by this interface effects all subsequent
4813 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4814 ** Existing database connections continue use the sharing mode
4815 ** that was in effect at the time they were opened.
4816 **
4817 ** Virtual tables cannot be used with a shared cache.   When shared
4818 ** cache is enabled, the [sqlite3_create_module()] API used to register
4819 ** virtual tables will always return an error.
4820 **
4821 ** This routine returns [SQLITE_OK] if shared cache was
4822 ** enabled or disabled successfully.  An [error code]
4823 ** is returned otherwise.
4824 **
4825 ** Shared cache is disabled by default. But this might change in
4826 ** future releases of SQLite.  Applications that care about shared
4827 ** cache setting should set it explicitly.
4828 **
4829 ** INVARIANTS:
4830 ** 
4831 ** {F10331} A successful invocation of [sqlite3_enable_shared_cache(B)]
4832 **          will enable or disable shared cache mode for any subsequently
4833 **          created [database connection] in the same process.
4834 **
4835 ** {F10336} When shared cache is enabled, the [sqlite3_create_module()]
4836 **          interface will always return an error.
4837 **
4838 ** {F10337} The [sqlite3_enable_shared_cache(B)] interface returns
4839 **          [SQLITE_OK] if shared cache was enabled or disabled successfully.
4840 **
4841 ** {F10339} Shared cache is disabled by default.
4842 */
4843 SQLITE_API int sqlite3_enable_shared_cache(int);
4844
4845 /*
4846 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
4847 **
4848 ** The sqlite3_release_memory() interface attempts to
4849 ** free N bytes of heap memory by deallocating non-essential memory
4850 ** allocations held by the database labrary. {END}  Memory used
4851 ** to cache database pages to improve performance is an example of
4852 ** non-essential memory.  Sqlite3_release_memory() returns
4853 ** the number of bytes actually freed, which might be more or less
4854 ** than the amount requested.
4855 **
4856 ** INVARIANTS:
4857 **
4858 ** {F17341} The [sqlite3_release_memory(N)] interface attempts to
4859 **          free N bytes of heap memory by deallocating non-essential
4860 **          memory allocations held by the database labrary.
4861 **
4862 ** {F16342} The [sqlite3_release_memory(N)] returns the number
4863 **          of bytes actually freed, which might be more or less
4864 **          than the amount requested.
4865 */
4866 SQLITE_API int sqlite3_release_memory(int);
4867
4868 /*
4869 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
4870 **
4871 ** The sqlite3_soft_heap_limit() interface
4872 ** places a "soft" limit on the amount of heap memory that may be allocated
4873 ** by SQLite. If an internal allocation is requested 
4874 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
4875 ** invoked one or more times to free up some space before the allocation
4876 ** is made.
4877 **
4878 ** The limit is called "soft", because if
4879 ** [sqlite3_release_memory()] cannot
4880 ** free sufficient memory to prevent the limit from being exceeded,
4881 ** the memory is allocated anyway and the current operation proceeds.
4882 **
4883 ** A negative or zero value for N means that there is no soft heap limit and
4884 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
4885 ** The default value for the soft heap limit is zero.
4886 **
4887 ** SQLite makes a best effort to honor the soft heap limit.  
4888 ** But if the soft heap limit cannot honored, execution will
4889 ** continue without error or notification.  This is why the limit is 
4890 ** called a "soft" limit.  It is advisory only.
4891 **
4892 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
4893 ** allocated by a single thread - the same thread in which this routine
4894 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4895 ** applied to all threads. The value specified for the soft heap limit
4896 ** is an upper bound on the total memory allocation for all threads. In
4897 ** version 3.5.0 there is no mechanism for limiting the heap usage for
4898 ** individual threads.
4899 **
4900 ** INVARIANTS:
4901 **
4902 ** {F16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit
4903 **          of N bytes on the amount of heap memory that may be allocated
4904 **          using [sqlite3_malloc()] or [sqlite3_realloc()] at any point
4905 **          in time.
4906 **
4907 ** {F16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would
4908 **          cause the total amount of allocated memory to exceed the
4909 **          soft heap limit, then [sqlite3_release_memory()] is invoked
4910 **          in an attempt to reduce the memory usage prior to proceeding
4911 **          with the memory allocation attempt.
4912 **
4913 ** {F16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger
4914 **          attempts to reduce memory usage through the soft heap limit
4915 **          mechanism continue even if the attempt to reduce memory
4916 **          usage is unsuccessful.
4917 **
4918 ** {F16354} A negative or zero value for N in a call to
4919 **          [sqlite3_soft_heap_limit(N)] means that there is no soft
4920 **          heap limit and [sqlite3_release_memory()] will only be
4921 **          called when memory is completely exhausted.
4922 **
4923 ** {F16355} The default value for the soft heap limit is zero.
4924 **
4925 ** {F16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the
4926 **          values set by all prior calls.
4927 */
4928 SQLITE_API void sqlite3_soft_heap_limit(int);
4929
4930 /*
4931 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
4932 **
4933 ** This routine
4934 ** returns meta-data about a specific column of a specific database
4935 ** table accessible using the connection handle passed as the first function 
4936 ** argument.
4937 **
4938 ** The column is identified by the second, third and fourth parameters to 
4939 ** this function. The second parameter is either the name of the database
4940 ** (i.e. "main", "temp" or an attached database) containing the specified
4941 ** table or NULL. If it is NULL, then all attached databases are searched
4942 ** for the table using the same algorithm as the database engine uses to 
4943 ** resolve unqualified table references.
4944 **
4945 ** The third and fourth parameters to this function are the table and column 
4946 ** name of the desired column, respectively. Neither of these parameters 
4947 ** may be NULL.
4948 **
4949 ** Meta information is returned by writing to the memory locations passed as
4950 ** the 5th and subsequent parameters to this function. Any of these 
4951 ** arguments may be NULL, in which case the corresponding element of meta 
4952 ** information is ommitted.
4953 **
4954 ** <pre>
4955 ** Parameter     Output Type      Description
4956 ** -----------------------------------
4957 **
4958 **   5th         const char*      Data type
4959 **   6th         const char*      Name of the default collation sequence 
4960 **   7th         int              True if the column has a NOT NULL constraint
4961 **   8th         int              True if the column is part of the PRIMARY KEY
4962 **   9th         int              True if the column is AUTOINCREMENT
4963 ** </pre>
4964 **
4965 **
4966 ** The memory pointed to by the character pointers returned for the 
4967 ** declaration type and collation sequence is valid only until the next 
4968 ** call to any sqlite API function.
4969 **
4970 ** If the specified table is actually a view, then an error is returned.
4971 **
4972 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
4973 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
4974 ** parameters are set for the explicitly declared column. If there is no
4975 ** explicitly declared IPK column, then the output parameters are set as 
4976 ** follows:
4977 **
4978 ** <pre>
4979 **     data type: "INTEGER"
4980 **     collation sequence: "BINARY"
4981 **     not null: 0
4982 **     primary key: 1
4983 **     auto increment: 0
4984 ** </pre>
4985 **
4986 ** This function may load one or more schemas from database files. If an
4987 ** error occurs during this process, or if the requested table or column
4988 ** cannot be found, an SQLITE error code is returned and an error message
4989 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
4990 **
4991 ** This API is only available if the library was compiled with the
4992 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
4993 */
4994 SQLITE_API int sqlite3_table_column_metadata(
4995   sqlite3 *db,                /* Connection handle */
4996   const char *zDbName,        /* Database name or NULL */
4997   const char *zTableName,     /* Table name */
4998   const char *zColumnName,    /* Column name */
4999   char const **pzDataType,    /* OUTPUT: Declared data type */
5000   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5001   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5002   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5003   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5004 );
5005
5006 /*
5007 ** CAPI3REF: Load An Extension {F12600}
5008 **
5009 ** {F12601} The sqlite3_load_extension() interface
5010 ** attempts to load an SQLite extension library contained in the file
5011 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
5012 ** in which case the name of the entry point defaults
5013 ** to "sqlite3_extension_init".
5014 **
5015 ** {F12604} The sqlite3_load_extension() interface shall
5016 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5017 **
5018 ** {F12605}
5019 ** If an error occurs and pzErrMsg is not 0, then the
5020 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
5021 ** error message text stored in memory obtained from [sqlite3_malloc()].
5022 ** {END}  The calling function should free this memory
5023 ** by calling [sqlite3_free()].
5024 **
5025 ** {F12606}
5026 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
5027 ** prior to calling this API or an error will be returned.
5028 */
5029 SQLITE_API int sqlite3_load_extension(
5030   sqlite3 *db,          /* Load the extension into this database connection */
5031   const char *zFile,    /* Name of the shared library containing extension */
5032   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5033   char **pzErrMsg       /* Put error message here if not 0 */
5034 );
5035
5036 /*
5037 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
5038 **
5039 ** So as not to open security holes in older applications that are
5040 ** unprepared to deal with extension loading, and as a means of disabling
5041 ** extension loading while evaluating user-entered SQL, the following
5042 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
5043 ** off.  {F12622} It is off by default. {END} See ticket #1863.
5044 **
5045 ** {F12621} Call the sqlite3_enable_load_extension() routine
5046 ** with onoff==1 to turn extension loading on
5047 ** and call it with onoff==0 to turn it back off again. {END}
5048 */
5049 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5050
5051 /*
5052 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
5053 **
5054 ** {F12641} This function
5055 ** registers an extension entry point that is automatically invoked
5056 ** whenever a new database connection is opened using
5057 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
5058 **
5059 ** This API can be invoked at program startup in order to register
5060 ** one or more statically linked extensions that will be available
5061 ** to all new database connections.
5062 **
5063 ** {F12642} Duplicate extensions are detected so calling this routine multiple
5064 ** times with the same extension is harmless.
5065 **
5066 ** {F12643} This routine stores a pointer to the extension in an array
5067 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
5068 ** checker on your program and it reports a leak because of this
5069 ** array, then invoke [sqlite3_reset_auto_extension()] prior
5070 ** to shutdown to free the memory.
5071 **
5072 ** {F12644} Automatic extensions apply across all threads. {END}
5073 **
5074 ** This interface is experimental and is subject to change or
5075 ** removal in future releases of SQLite.
5076 */
5077 SQLITE_API int sqlite3_auto_extension(void *xEntryPoint);
5078
5079
5080 /*
5081 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
5082 **
5083 ** {F12661} This function disables all previously registered
5084 ** automatic extensions. {END}  This
5085 ** routine undoes the effect of all prior [sqlite3_auto_extension()]
5086 ** calls.
5087 **
5088 ** {F12662} This call disabled automatic extensions in all threads. {END}
5089 **
5090 ** This interface is experimental and is subject to change or
5091 ** removal in future releases of SQLite.
5092 */
5093 SQLITE_API void sqlite3_reset_auto_extension(void);
5094
5095
5096 /*
5097 ****** EXPERIMENTAL - subject to change without notice **************
5098 **
5099 ** The interface to the virtual-table mechanism is currently considered
5100 ** to be experimental.  The interface might change in incompatible ways.
5101 ** If this is a problem for you, do not use the interface at this time.
5102 **
5103 ** When the virtual-table mechanism stablizes, we will declare the
5104 ** interface fixed, support it indefinitely, and remove this comment.
5105 */
5106
5107 /*
5108 ** Structures used by the virtual table interface
5109 */
5110 typedef struct sqlite3_vtab sqlite3_vtab;
5111 typedef struct sqlite3_index_info sqlite3_index_info;
5112 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5113 typedef struct sqlite3_module sqlite3_module;
5114
5115 /*
5116 ** CAPI3REF: Virtual Table Object {F18000}
5117 ** KEYWORDS: sqlite3_module
5118 **
5119 ** A module is a class of virtual tables.  Each module is defined
5120 ** by an instance of the following structure.  This structure consists
5121 ** mostly of methods for the module.
5122 */
5123 struct sqlite3_module {
5124   int iVersion;
5125   int (*xCreate)(sqlite3*, void *pAux,
5126                int argc, const char *const*argv,
5127                sqlite3_vtab **ppVTab, char**);
5128   int (*xConnect)(sqlite3*, void *pAux,
5129                int argc, const char *const*argv,
5130                sqlite3_vtab **ppVTab, char**);
5131   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5132   int (*xDisconnect)(sqlite3_vtab *pVTab);
5133   int (*xDestroy)(sqlite3_vtab *pVTab);
5134   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5135   int (*xClose)(sqlite3_vtab_cursor*);
5136   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5137                 int argc, sqlite3_value **argv);
5138   int (*xNext)(sqlite3_vtab_cursor*);
5139   int (*xEof)(sqlite3_vtab_cursor*);
5140   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5141   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5142   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5143   int (*xBegin)(sqlite3_vtab *pVTab);
5144   int (*xSync)(sqlite3_vtab *pVTab);
5145   int (*xCommit)(sqlite3_vtab *pVTab);
5146   int (*xRollback)(sqlite3_vtab *pVTab);
5147   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5148                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5149                        void **ppArg);
5150
5151   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5152 };
5153
5154 /*
5155 ** CAPI3REF: Virtual Table Indexing Information {F18100}
5156 ** KEYWORDS: sqlite3_index_info
5157 **
5158 ** The sqlite3_index_info structure and its substructures is used to
5159 ** pass information into and receive the reply from the xBestIndex
5160 ** method of an sqlite3_module.  The fields under **Inputs** are the
5161 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5162 ** results into the **Outputs** fields.
5163 **
5164 ** The aConstraint[] array records WHERE clause constraints of the
5165 ** form:
5166 **
5167 **         column OP expr
5168 **
5169 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
5170 ** The particular operator is stored
5171 ** in aConstraint[].op.  The index of the column is stored in 
5172 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
5173 ** expr on the right-hand side can be evaluated (and thus the constraint
5174 ** is usable) and false if it cannot.
5175 **
5176 ** The optimizer automatically inverts terms of the form "expr OP column"
5177 ** and makes other simplifications to the WHERE clause in an attempt to
5178 ** get as many WHERE clause terms into the form shown above as possible.
5179 ** The aConstraint[] array only reports WHERE clause terms in the correct
5180 ** form that refer to the particular virtual table being queried.
5181 **
5182 ** Information about the ORDER BY clause is stored in aOrderBy[].
5183 ** Each term of aOrderBy records a column of the ORDER BY clause.
5184 **
5185 ** The xBestIndex method must fill aConstraintUsage[] with information
5186 ** about what parameters to pass to xFilter.  If argvIndex>0 then
5187 ** the right-hand side of the corresponding aConstraint[] is evaluated
5188 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
5189 ** is true, then the constraint is assumed to be fully handled by the
5190 ** virtual table and is not checked again by SQLite.
5191 **
5192 ** The idxNum and idxPtr values are recorded and passed into xFilter.
5193 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
5194 **
5195 ** The orderByConsumed means that output from xFilter will occur in
5196 ** the correct order to satisfy the ORDER BY clause so that no separate
5197 ** sorting step is required.
5198 **
5199 ** The estimatedCost value is an estimate of the cost of doing the
5200 ** particular lookup.  A full scan of a table with N entries should have
5201 ** a cost of N.  A binary search of a table of N entries should have a
5202 ** cost of approximately log(N).
5203 */
5204 struct sqlite3_index_info {
5205   /* Inputs */
5206   int nConstraint;           /* Number of entries in aConstraint */
5207   struct sqlite3_index_constraint {
5208      int iColumn;              /* Column on left-hand side of constraint */
5209      unsigned char op;         /* Constraint operator */
5210      unsigned char usable;     /* True if this constraint is usable */
5211      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5212   } *aConstraint;            /* Table of WHERE clause constraints */
5213   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5214   struct sqlite3_index_orderby {
5215      int iColumn;              /* Column number */
5216      unsigned char desc;       /* True for DESC.  False for ASC. */
5217   } *aOrderBy;               /* The ORDER BY clause */
5218
5219   /* Outputs */
5220   struct sqlite3_index_constraint_usage {
5221     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5222     unsigned char omit;      /* Do not code a test for this constraint */
5223   } *aConstraintUsage;
5224   int idxNum;                /* Number used to identify the index */
5225   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5226   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5227   int orderByConsumed;       /* True if output is already ordered */
5228   double estimatedCost;      /* Estimated cost of using this index */
5229 };
5230 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5231 #define SQLITE_INDEX_CONSTRAINT_GT    4
5232 #define SQLITE_INDEX_CONSTRAINT_LE    8
5233 #define SQLITE_INDEX_CONSTRAINT_LT    16
5234 #define SQLITE_INDEX_CONSTRAINT_GE    32
5235 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5236
5237 /*
5238 ** CAPI3REF: Register A Virtual Table Implementation {F18200}
5239 **
5240 ** This routine is used to register a new module name with an SQLite
5241 ** connection.  Module names must be registered before creating new
5242 ** virtual tables on the module, or before using preexisting virtual
5243 ** tables of the module.
5244 */
5245 SQLITE_API int sqlite3_create_module(
5246   sqlite3 *db,               /* SQLite connection to register module with */
5247   const char *zName,         /* Name of the module */
5248   const sqlite3_module *,    /* Methods for the module */
5249   void *                     /* Client data for xCreate/xConnect */
5250 );
5251
5252 /*
5253 ** CAPI3REF: Register A Virtual Table Implementation {F18210}
5254 **
5255 ** This routine is identical to the sqlite3_create_module() method above,
5256 ** except that it allows a destructor function to be specified. It is
5257 ** even more experimental than the rest of the virtual tables API.
5258 */
5259 SQLITE_API int sqlite3_create_module_v2(
5260   sqlite3 *db,               /* SQLite connection to register module with */
5261   const char *zName,         /* Name of the module */
5262   const sqlite3_module *,    /* Methods for the module */
5263   void *,                    /* Client data for xCreate/xConnect */
5264   void(*xDestroy)(void*)     /* Module destructor function */
5265 );
5266
5267 /*
5268 ** CAPI3REF: Virtual Table Instance Object {F18010}
5269 ** KEYWORDS: sqlite3_vtab
5270 **
5271 ** Every module implementation uses a subclass of the following structure
5272 ** to describe a particular instance of the module.  Each subclass will
5273 ** be tailored to the specific needs of the module implementation.   The
5274 ** purpose of this superclass is to define certain fields that are common
5275 ** to all module implementations.
5276 **
5277 ** Virtual tables methods can set an error message by assigning a
5278 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
5279 ** take care that any prior string is freed by a call to sqlite3_free()
5280 ** prior to assigning a new string to zErrMsg.  After the error message
5281 ** is delivered up to the client application, the string will be automatically
5282 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
5283 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
5284 ** since virtual tables are commonly implemented in loadable extensions which
5285 ** do not have access to sqlite3MPrintf() or sqlite3Free().
5286 */
5287 struct sqlite3_vtab {
5288   const sqlite3_module *pModule;  /* The module for this virtual table */
5289   int nRef;                       /* Used internally */
5290   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5291   /* Virtual table implementations will typically add additional fields */
5292 };
5293
5294 /*
5295 ** CAPI3REF: Virtual Table Cursor Object  {F18020}
5296 ** KEYWORDS: sqlite3_vtab_cursor
5297 **
5298 ** Every module implementation uses a subclass of the following structure
5299 ** to describe cursors that point into the virtual table and are used
5300 ** to loop through the virtual table.  Cursors are created using the
5301 ** xOpen method of the module.  Each module implementation will define
5302 ** the content of a cursor structure to suit its own needs.
5303 **
5304 ** This superclass exists in order to define fields of the cursor that
5305 ** are common to all implementations.
5306 */
5307 struct sqlite3_vtab_cursor {
5308   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5309   /* Virtual table implementations will typically add additional fields */
5310 };
5311
5312 /*
5313 ** CAPI3REF: Declare The Schema Of A Virtual Table {F18280}
5314 **
5315 ** The xCreate and xConnect methods of a module use the following API
5316 ** to declare the format (the names and datatypes of the columns) of
5317 ** the virtual tables they implement.
5318 */
5319 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
5320
5321 /*
5322 ** CAPI3REF: Overload A Function For A Virtual Table {F18300}
5323 **
5324 ** Virtual tables can provide alternative implementations of functions
5325 ** using the xFindFunction method.  But global versions of those functions
5326 ** must exist in order to be overloaded.
5327 **
5328 ** This API makes sure a global version of a function with a particular
5329 ** name and number of parameters exists.  If no such function exists
5330 ** before this API is called, a new function is created.  The implementation
5331 ** of the new function always causes an exception to be thrown.  So
5332 ** the new function is not good for anything by itself.  Its only
5333 ** purpose is to be a place-holder function that can be overloaded
5334 ** by virtual tables.
5335 **
5336 ** This API should be considered part of the virtual table interface,
5337 ** which is experimental and subject to change.
5338 */
5339 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5340
5341 /*
5342 ** The interface to the virtual-table mechanism defined above (back up
5343 ** to a comment remarkably similar to this one) is currently considered
5344 ** to be experimental.  The interface might change in incompatible ways.
5345 ** If this is a problem for you, do not use the interface at this time.
5346 **
5347 ** When the virtual-table mechanism stabilizes, we will declare the
5348 ** interface fixed, support it indefinitely, and remove this comment.
5349 **
5350 ****** EXPERIMENTAL - subject to change without notice **************
5351 */
5352
5353 /*
5354 ** CAPI3REF: A Handle To An Open BLOB {F17800}
5355 **
5356 ** An instance of this object represents an open BLOB on which
5357 ** incremental I/O can be preformed.
5358 ** Objects of this type are created by
5359 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
5360 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5361 ** can be used to read or write small subsections of the blob.
5362 ** The [sqlite3_blob_bytes()] interface returns the size of the
5363 ** blob in bytes.
5364 */
5365 typedef struct sqlite3_blob sqlite3_blob;
5366
5367 /*
5368 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
5369 **
5370 ** This interfaces opens a handle to the blob located
5371 ** in row iRow,, column zColumn, table zTable in database zDb;
5372 ** in other words,  the same blob that would be selected by:
5373 **
5374 ** <pre>
5375 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
5376 ** </pre> {END}
5377 **
5378 ** If the flags parameter is non-zero, the blob is opened for 
5379 ** read and write access. If it is zero, the blob is opened for read 
5380 ** access.
5381 **
5382 ** On success, [SQLITE_OK] is returned and the new 
5383 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
5384 ** Otherwise an error code is returned and 
5385 ** any value written to *ppBlob should not be used by the caller.
5386 ** This function sets the database-handle error code and message
5387 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
5388 ** 
5389 ** INVARIANTS:
5390 **
5391 ** {F17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)]
5392 **          interface opens an [sqlite3_blob] object P on the blob
5393 **          in column C of table T in database B on [database connection] D.
5394 **
5395 ** {F17814} A successful invocation of [sqlite3_blob_open(D,...)] starts
5396 **          a new transaction on [database connection] D if that connection
5397 **          is not already in a transaction.
5398 **
5399 ** {F17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface opens the blob
5400 **          for read and write access if and only if the F parameter
5401 **          is non-zero.
5402 **
5403 ** {F17819} The [sqlite3_blob_open()] interface returns [SQLITE_OK] on 
5404 **          success and an appropriate [error code] on failure.
5405 **
5406 ** {F17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)]
5407 **          then subsequent calls to [sqlite3_errcode(D)],
5408 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] will return
5409 **          information approprate for that error.
5410 */
5411 SQLITE_API int sqlite3_blob_open(
5412   sqlite3*,
5413   const char *zDb,
5414   const char *zTable,
5415   const char *zColumn,
5416   sqlite3_int64 iRow,
5417   int flags,
5418   sqlite3_blob **ppBlob
5419 );
5420
5421 /*
5422 ** CAPI3REF:  Close A BLOB Handle {F17830}
5423 **
5424 ** Close an open [sqlite3_blob | blob handle].
5425 **
5426 ** Closing a BLOB shall cause the current transaction to commit
5427 ** if there are no other BLOBs, no pending prepared statements, and the
5428 ** database connection is in autocommit mode.
5429 ** If any writes were made to the BLOB, they might be held in cache
5430 ** until the close operation if they will fit. {END}
5431 ** Closing the BLOB often forces the changes
5432 ** out to disk and so if any I/O errors occur, they will likely occur
5433 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
5434 ** closing are reported as a non-zero return value.
5435 **
5436 ** The BLOB is closed unconditionally.  Even if this routine returns
5437 ** an error code, the BLOB is still closed.
5438 **
5439 ** INVARIANTS:
5440 **
5441 ** {F17833} The [sqlite3_blob_close(P)] interface closes an
5442 **          [sqlite3_blob] object P previously opened using
5443 **          [sqlite3_blob_open()].
5444 **
5445 ** {F17836} Closing an [sqlite3_blob] object using
5446 **          [sqlite3_blob_close()] shall cause the current transaction to
5447 **          commit if there are no other open [sqlite3_blob] objects
5448 **          or [prepared statements] on the same [database connection] and
5449 **          the [database connection] is in
5450 **          [sqlite3_get_autocommit | autocommit mode].
5451 **
5452 ** {F17839} The [sqlite3_blob_close(P)] interfaces closes the 
5453 **          [sqlite3_blob] object P unconditionally, even if
5454 **          [sqlite3_blob_close(P)] returns something other than [SQLITE_OK].
5455 **          
5456 */
5457 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5458
5459 /*
5460 ** CAPI3REF:  Return The Size Of An Open BLOB {F17840}
5461 **
5462 ** Return the size in bytes of the blob accessible via the open 
5463 ** [sqlite3_blob] object in its only argument.
5464 **
5465 ** INVARIANTS:
5466 **
5467 ** {F17843} The [sqlite3_blob_bytes(P)] interface returns the size
5468 **          in bytes of the BLOB that the [sqlite3_blob] object P
5469 **          refers to.
5470 */
5471 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5472
5473 /*
5474 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
5475 **
5476 ** This function is used to read data from an open 
5477 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
5478 ** N bytes of data are copied into buffer
5479 ** Z from the open blob, starting at offset iOffset.
5480 **
5481 ** If offset iOffset is less than N bytes from the end of the blob, 
5482 ** [SQLITE_ERROR] is returned and no data is read.  If N or iOffset is
5483 ** less than zero [SQLITE_ERROR] is returned and no data is read.
5484 **
5485 ** On success, SQLITE_OK is returned. Otherwise, an 
5486 ** [error code] or an [extended error code] is returned.
5487 **
5488 ** INVARIANTS:
5489 **
5490 ** {F17853} The [sqlite3_blob_read(P,Z,N,X)] interface reads N bytes
5491 **          beginning at offset X from
5492 **          the blob that [sqlite3_blob] object P refers to
5493 **          and writes those N bytes into buffer Z.
5494 **
5495 ** {F17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the blob
5496 **          is less than N+X bytes, then the function returns [SQLITE_ERROR]
5497 **          and nothing is read from the blob.
5498 **
5499 ** {F17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero
5500 **          then the function returns [SQLITE_ERROR]
5501 **          and nothing is read from the blob.
5502 **
5503 ** {F17862} The [sqlite3_blob_read(P,Z,N,X)] interface returns [SQLITE_OK]
5504 **          if N bytes where successfully read into buffer Z.
5505 **
5506 ** {F17865} If the requested read could not be completed,
5507 **          the [sqlite3_blob_read(P,Z,N,X)] interface returns an
5508 **          appropriate [error code] or [extended error code].
5509 **
5510 ** {F17868} If an error occurs during evaluation of [sqlite3_blob_read(D,...)]
5511 **          then subsequent calls to [sqlite3_errcode(D)],
5512 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] will return
5513 **          information approprate for that error.
5514 */
5515 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5516
5517 /*
5518 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
5519 **
5520 ** This function is used to write data into an open 
5521 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
5522 ** n bytes of data are copied from the buffer
5523 ** pointed to by z into the open blob, starting at offset iOffset.
5524 **
5525 ** If the [sqlite3_blob | blob-handle] passed as the first argument
5526 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
5527 *** was zero), this function returns [SQLITE_READONLY].
5528 **
5529 ** This function may only modify the contents of the blob; it is
5530 ** not possible to increase the size of a blob using this API.
5531 ** If offset iOffset is less than n bytes from the end of the blob, 
5532 ** [SQLITE_ERROR] is returned and no data is written.  If n is
5533 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5534 **
5535 ** On success, SQLITE_OK is returned. Otherwise, an 
5536 ** [error code] or an [extended error code] is returned.
5537 **
5538 ** INVARIANTS:
5539 **
5540 ** {F17873} The [sqlite3_blob_write(P,Z,N,X)] interface writes N bytes
5541 **          from buffer Z into
5542 **          the blob that [sqlite3_blob] object P refers to
5543 **          beginning at an offset of X into the blob.
5544 **
5545 ** {F17875} The [sqlite3_blob_write(P,Z,N,X)] interface returns
5546 **          [SQLITE_READONLY] if the [sqlite3_blob] object P was
5547 **          [sqlite3_blob_open | opened] for reading only.
5548 **
5549 ** {F17876} In [sqlite3_blob_write(P,Z,N,X)] if the size of the blob
5550 **          is less than N+X bytes, then the function returns [SQLITE_ERROR]
5551 **          and nothing is written into the blob.
5552 **
5553 ** {F17879} In [sqlite3_blob_write(P,Z,N,X)] if X or N is less than zero
5554 **          then the function returns [SQLITE_ERROR]
5555 **          and nothing is written into the blob.
5556 **
5557 ** {F17882} The [sqlite3_blob_write(P,Z,N,X)] interface returns [SQLITE_OK]
5558 **          if N bytes where successfully written into blob.
5559 **
5560 ** {F17885} If the requested write could not be completed,
5561 **          the [sqlite3_blob_write(P,Z,N,X)] interface returns an
5562 **          appropriate [error code] or [extended error code].
5563 **
5564 ** {F17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)]
5565 **          then subsequent calls to [sqlite3_errcode(D)],
5566 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] will return
5567 **          information approprate for that error.
5568 */
5569 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5570
5571 /*
5572 ** CAPI3REF:  Virtual File System Objects {F11200}
5573 **
5574 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5575 ** that SQLite uses to interact
5576 ** with the underlying operating system.  Most SQLite builds come with a
5577 ** single default VFS that is appropriate for the host computer.
5578 ** New VFSes can be registered and existing VFSes can be unregistered.
5579 ** The following interfaces are provided.
5580 **
5581 ** The sqlite3_vfs_find() interface returns a pointer to 
5582 ** a VFS given its name.  Names are case sensitive.
5583 ** Names are zero-terminated UTF-8 strings.
5584 ** If there is no match, a NULL
5585 ** pointer is returned.  If zVfsName is NULL then the default 
5586 ** VFS is returned. 
5587 **
5588 ** New VFSes are registered with sqlite3_vfs_register().
5589 ** Each new VFS becomes the default VFS if the makeDflt flag is set.
5590 ** The same VFS can be registered multiple times without injury.
5591 ** To make an existing VFS into the default VFS, register it again
5592 ** with the makeDflt flag set.  If two different VFSes with the
5593 ** same name are registered, the behavior is undefined.  If a
5594 ** VFS is registered with a name that is NULL or an empty string,
5595 ** then the behavior is undefined.
5596 ** 
5597 ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
5598 ** If the default VFS is unregistered, another VFS is chosen as
5599 ** the default.  The choice for the new VFS is arbitrary.
5600 **
5601 ** INVARIANTS:
5602 **
5603 ** {F11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the
5604 **          registered [sqlite3_vfs] object whose name exactly matches
5605 **          the zero-terminated UTF-8 string N, or it returns NULL if
5606 **          there is no match.
5607 **
5608 ** {F11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then
5609 **          the function returns a pointer to the default [sqlite3_vfs]
5610 **          object if there is one, or NULL if there is no default 
5611 **          [sqlite3_vfs] object.
5612 **
5613 ** {F11209} The [sqlite3_vfs_register(P,F)] interface registers the
5614 **          well-formed [sqlite3_vfs] object P using the name given
5615 **          by the zName field of the object.
5616 **
5617 ** {F11212} Using the [sqlite3_vfs_register(P,F)] interface to register
5618 **          the same [sqlite3_vfs] object multiple times is a harmless no-op.
5619 **
5620 ** {F11215} The [sqlite3_vfs_register(P,F)] interface makes the
5621 **          the [sqlite3_vfs] object P the default [sqlite3_vfs] object
5622 **          if F is non-zero.
5623 **
5624 ** {F11218} The [sqlite3_vfs_unregister(P)] interface unregisters the
5625 **          [sqlite3_vfs] object P so that it is no longer returned by
5626 **          subsequent calls to [sqlite3_vfs_find()].
5627 */
5628 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5629 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5630 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5631
5632 /*
5633 ** CAPI3REF: Mutexes {F17000}
5634 **
5635 ** The SQLite core uses these routines for thread
5636 ** synchronization.  Though they are intended for internal
5637 ** use by SQLite, code that links against SQLite is
5638 ** permitted to use any of these routines.
5639 **
5640 ** The SQLite source code contains multiple implementations 
5641 ** of these mutex routines.  An appropriate implementation
5642 ** is selected automatically at compile-time.  The following
5643 ** implementations are available in the SQLite core:
5644 **
5645 ** <ul>
5646 ** <li>   SQLITE_MUTEX_OS2
5647 ** <li>   SQLITE_MUTEX_PTHREAD
5648 ** <li>   SQLITE_MUTEX_W32
5649 ** <li>   SQLITE_MUTEX_NOOP
5650 ** </ul>
5651 **
5652 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
5653 ** that does no real locking and is appropriate for use in 
5654 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
5655 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5656 ** are appropriate for use on os/2, unix, and windows.
5657 ** 
5658 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5659 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5660 ** implementation is included with the library.  The
5661 ** mutex interface routines defined here become external
5662 ** references in the SQLite library for which implementations
5663 ** must be provided by the application.  This facility allows an
5664 ** application that links against SQLite to provide its own mutex
5665 ** implementation without having to modify the SQLite core.
5666 **
5667 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
5668 ** mutex and returns a pointer to it. {F17012} If it returns NULL
5669 ** that means that a mutex could not be allocated. {F17013} SQLite
5670 ** will unwind its stack and return an error. {F17014} The argument
5671 ** to sqlite3_mutex_alloc() is one of these integer constants:
5672 **
5673 ** <ul>
5674 ** <li>  SQLITE_MUTEX_FAST
5675 ** <li>  SQLITE_MUTEX_RECURSIVE
5676 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5677 ** <li>  SQLITE_MUTEX_STATIC_MEM
5678 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5679 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5680 ** <li>  SQLITE_MUTEX_STATIC_LRU
5681 ** </ul> {END}
5682 **
5683 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
5684 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5685 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
5686 ** The mutex implementation does not need to make a distinction
5687 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5688 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
5689 ** cases where it really needs one.  {END} If a faster non-recursive mutex
5690 ** implementation is available on the host platform, the mutex subsystem
5691 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5692 **
5693 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
5694 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
5695 ** used by the current version of SQLite.  Future versions of SQLite
5696 ** may add additional static mutexes.  Static mutexes are for internal
5697 ** use by SQLite only.  Applications that use SQLite mutexes should
5698 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5699 ** SQLITE_MUTEX_RECURSIVE.
5700 **
5701 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5702 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5703 ** returns a different mutex on every call.  {F17034} But for the static 
5704 ** mutex types, the same mutex is returned on every call that has
5705 ** the same type number. {END}
5706 **
5707 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
5708 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
5709 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
5710 ** use when they are deallocated. {U17022} Attempting to deallocate a static
5711 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
5712 ** a static mutex. {END}
5713 **
5714 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5715 ** to enter a mutex. {F17024} If another thread is already within the mutex,
5716 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5717 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
5718 ** upon successful entry.  {F17026} Mutexes created using
5719 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5720 ** {F17027} In such cases the,
5721 ** mutex must be exited an equal number of times before another thread
5722 ** can enter.  {U17028} If the same thread tries to enter any other
5723 ** kind of mutex more than once, the behavior is undefined.
5724 ** {F17029} SQLite will never exhibit
5725 ** such behavior in its own use of mutexes. {END}
5726 **
5727 ** Some systems (ex: windows95) do not the operation implemented by
5728 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
5729 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
5730 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
5731 **
5732 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
5733 ** previously entered by the same thread.  {U17032} The behavior
5734 ** is undefined if the mutex is not currently entered by the
5735 ** calling thread or is not currently allocated.  {F17033} SQLite will
5736 ** never do either. {END}
5737 **
5738 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5739 */
5740 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5741 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5742 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5743 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5744 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5745
5746 /*
5747 ** CAPI3REF: Mutex Verifcation Routines {F17080}
5748 **
5749 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5750 ** are intended for use inside assert() statements. {F17081} The SQLite core
5751 ** never uses these routines except inside an assert() and applications
5752 ** are advised to follow the lead of the core.  {F17082} The core only
5753 ** provides implementations for these routines when it is compiled
5754 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
5755 ** are only required to provide these routines if SQLITE_DEBUG is
5756 ** defined and if NDEBUG is not defined.
5757 **
5758 ** {F17083} These routines should return true if the mutex in their argument
5759 ** is held or not held, respectively, by the calling thread. {END}
5760 **
5761 ** {X17084} The implementation is not required to provided versions of these
5762 ** routines that actually work.
5763 ** If the implementation does not provide working
5764 ** versions of these routines, it should at least provide stubs
5765 ** that always return true so that one does not get spurious
5766 ** assertion failures. {END}
5767 **
5768 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
5769 ** the routine should return 1.  {END} This seems counter-intuitive since
5770 ** clearly the mutex cannot be held if it does not exist.  But the
5771 ** the reason the mutex does not exist is because the build is not
5772 ** using mutexes.  And we do not want the assert() containing the
5773 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5774 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
5775 ** interface should also return 1 when given a NULL pointer.
5776 */
5777 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5778 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5779
5780 /*
5781 ** CAPI3REF: Mutex Types {F17001}
5782 **
5783 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
5784 ** which is one of these integer constants. {END}
5785 */
5786 #define SQLITE_MUTEX_FAST             0
5787 #define SQLITE_MUTEX_RECURSIVE        1
5788 #define SQLITE_MUTEX_STATIC_MASTER    2
5789 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5790 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
5791 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5792 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5793
5794 /*
5795 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
5796 **
5797 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
5798 ** xFileControl method for the [sqlite3_io_methods] object associated
5799 ** with a particular database identified by the second argument. {F11302} The
5800 ** name of the database is the name assigned to the database by the
5801 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
5802 ** database. {F11303} To control the main database file, use the name "main"
5803 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
5804 ** are passed directly through to the second and third parameters of
5805 ** the xFileControl method.  {F11305} The return value of the xFileControl
5806 ** method becomes the return value of this routine.
5807 **
5808 ** {F11306} If the second parameter (zDbName) does not match the name of any
5809 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
5810 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5811 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
5812 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
5813 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5814 ** xFileControl method. {END}
5815 **
5816 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5817 */
5818 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5819
5820 /*
5821 ** CAPI3REF: Testing Interface {F11400}
5822 **
5823 ** The sqlite3_test_control() interface is used to read out internal
5824 ** state of SQLite and to inject faults into SQLite for testing
5825 ** purposes.  The first parameter a operation code that determines
5826 ** the number, meaning, and operation of all subsequent parameters.
5827 **
5828 ** This interface is not for use by applications.  It exists solely
5829 ** for verifying the correct operation of the SQLite library.  Depending
5830 ** on how the SQLite library is compiled, this interface might not exist.
5831 **
5832 ** The details of the operation codes, their meanings, the parameters
5833 ** they take, and what they do are all subject to change without notice.
5834 ** Unlike most of the SQLite API, this function is not guaranteed to
5835 ** operate consistently from one release to the next.
5836 */
5837 SQLITE_API int sqlite3_test_control(int op, ...);
5838
5839 /*
5840 ** CAPI3REF: Testing Interface Operation Codes {F11410}
5841 **
5842 ** These constants are the valid operation code parameters used
5843 ** as the first argument to [sqlite3_test_control()].
5844 **
5845 ** These parameters and their meansing are subject to change
5846 ** without notice.  These values are for testing purposes only.
5847 ** Applications should not use any of these parameters or the
5848 ** [sqlite3_test_control()] interface.
5849 */
5850 #define SQLITE_TESTCTRL_FAULT_CONFIG             1
5851 #define SQLITE_TESTCTRL_FAULT_FAILURES           2
5852 #define SQLITE_TESTCTRL_FAULT_BENIGN_FAILURES    3
5853 #define SQLITE_TESTCTRL_FAULT_PENDING            4
5854
5855
5856
5857
5858
5859 /*
5860 ** Undo the hack that converts floating point types to integer for
5861 ** builds on processors without floating point support.
5862 */
5863 #ifdef SQLITE_OMIT_FLOATING_POINT
5864 # undef double
5865 #endif
5866
5867 #if 0
5868 }  /* End of the 'extern "C"' block */
5869 #endif
5870 #endif
5871
5872 /************** End of sqlite3.h *********************************************/
5873 /************** Continuing where we left off in sqliteInt.h ******************/
5874 /************** Include hash.h in the middle of sqliteInt.h ******************/
5875 /************** Begin file hash.h ********************************************/
5876 /*
5877 ** 2001 September 22
5878 **
5879 ** The author disclaims copyright to this source code.  In place of
5880 ** a legal notice, here is a blessing:
5881 **
5882 **    May you do good and not evil.
5883 **    May you find forgiveness for yourself and forgive others.
5884 **    May you share freely, never taking more than you give.
5885 **
5886 *************************************************************************
5887 ** This is the header file for the generic hash-table implemenation
5888 ** used in SQLite.
5889 **
5890 ** $Id: hash.h,v 1.11 2007/09/04 14:31:47 danielk1977 Exp $
5891 */
5892 #ifndef _SQLITE_HASH_H_
5893 #define _SQLITE_HASH_H_
5894
5895 /* Forward declarations of structures. */
5896 typedef struct Hash Hash;
5897 typedef struct HashElem HashElem;
5898
5899 /* A complete hash table is an instance of the following structure.
5900 ** The internals of this structure are intended to be opaque -- client
5901 ** code should not attempt to access or modify the fields of this structure
5902 ** directly.  Change this structure only by using the routines below.
5903 ** However, many of the "procedures" and "functions" for modifying and
5904 ** accessing this structure are really macros, so we can't really make
5905 ** this structure opaque.
5906 */
5907 struct Hash {
5908   char keyClass;          /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
5909   char copyKey;           /* True if copy of key made on insert */
5910   int count;              /* Number of entries in this table */
5911   int htsize;             /* Number of buckets in the hash table */
5912   HashElem *first;        /* The first element of the array */
5913   struct _ht {            /* the hash table */
5914     int count;               /* Number of entries with this hash */
5915     HashElem *chain;         /* Pointer to first entry with this hash */
5916   } *ht;
5917 };
5918
5919 /* Each element in the hash table is an instance of the following 
5920 ** structure.  All elements are stored on a single doubly-linked list.
5921 **
5922 ** Again, this structure is intended to be opaque, but it can't really
5923 ** be opaque because it is used by macros.
5924 */
5925 struct HashElem {
5926   HashElem *next, *prev;   /* Next and previous elements in the table */
5927   void *data;              /* Data associated with this element */
5928   void *pKey; int nKey;    /* Key associated with this element */
5929 };
5930
5931 /*
5932 ** There are 4 different modes of operation for a hash table:
5933 **
5934 **   SQLITE_HASH_INT         nKey is used as the key and pKey is ignored.
5935 **
5936 **   SQLITE_HASH_POINTER     pKey is used as the key and nKey is ignored.
5937 **
5938 **   SQLITE_HASH_STRING      pKey points to a string that is nKey bytes long
5939 **                           (including the null-terminator, if any).  Case
5940 **                           is ignored in comparisons.
5941 **
5942 **   SQLITE_HASH_BINARY      pKey points to binary data nKey bytes long. 
5943 **                           memcmp() is used to compare keys.
5944 **
5945 ** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
5946 ** if the copyKey parameter to HashInit is 1.  
5947 */
5948 /* #define SQLITE_HASH_INT       1 // NOT USED */
5949 /* #define SQLITE_HASH_POINTER   2 // NOT USED */
5950 #define SQLITE_HASH_STRING    3
5951 #define SQLITE_HASH_BINARY    4
5952
5953 /*
5954 ** Access routines.  To delete, insert a NULL pointer.
5955 */
5956 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int keytype, int copyKey);
5957 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
5958 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
5959 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
5960 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
5961
5962 /*
5963 ** Macros for looping over all elements of a hash table.  The idiom is
5964 ** like this:
5965 **
5966 **   Hash h;
5967 **   HashElem *p;
5968 **   ...
5969 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
5970 **     SomeStructure *pData = sqliteHashData(p);
5971 **     // do something with pData
5972 **   }
5973 */
5974 #define sqliteHashFirst(H)  ((H)->first)
5975 #define sqliteHashNext(E)   ((E)->next)
5976 #define sqliteHashData(E)   ((E)->data)
5977 #define sqliteHashKey(E)    ((E)->pKey)
5978 #define sqliteHashKeysize(E) ((E)->nKey)
5979
5980 /*
5981 ** Number of entries in a hash table
5982 */
5983 #define sqliteHashCount(H)  ((H)->count)
5984
5985 #endif /* _SQLITE_HASH_H_ */
5986
5987 /************** End of hash.h ************************************************/
5988 /************** Continuing where we left off in sqliteInt.h ******************/
5989 /************** Include parse.h in the middle of sqliteInt.h *****************/
5990 /************** Begin file parse.h *******************************************/
5991 #define TK_SEMI                            1
5992 #define TK_EXPLAIN                         2
5993 #define TK_QUERY                           3
5994 #define TK_PLAN                            4
5995 #define TK_BEGIN                           5
5996 #define TK_TRANSACTION                     6
5997 #define TK_DEFERRED                        7
5998 #define TK_IMMEDIATE                       8
5999 #define TK_EXCLUSIVE                       9
6000 #define TK_COMMIT                         10
6001 #define TK_END                            11
6002 #define TK_ROLLBACK                       12
6003 #define TK_CREATE                         13
6004 #define TK_TABLE                          14
6005 #define TK_IF                             15
6006 #define TK_NOT                            16
6007 #define TK_EXISTS                         17
6008 #define TK_TEMP                           18
6009 #define TK_LP                             19
6010 #define TK_RP                             20
6011 #define TK_AS                             21
6012 #define TK_COMMA                          22
6013 #define TK_ID                             23
6014 #define TK_ABORT                          24
6015 #define TK_AFTER                          25
6016 #define TK_ANALYZE                        26
6017 #define TK_ASC                            27
6018 #define TK_ATTACH                         28
6019 #define TK_BEFORE                         29
6020 #define TK_CASCADE                        30
6021 #define TK_CAST                           31
6022 #define TK_CONFLICT                       32
6023 #define TK_DATABASE                       33
6024 #define TK_DESC                           34
6025 #define TK_DETACH                         35
6026 #define TK_EACH                           36
6027 #define TK_FAIL                           37
6028 #define TK_FOR                            38
6029 #define TK_IGNORE                         39
6030 #define TK_INITIALLY                      40
6031 #define TK_INSTEAD                        41
6032 #define TK_LIKE_KW                        42
6033 #define TK_MATCH                          43
6034 #define TK_KEY                            44
6035 #define TK_OF                             45
6036 #define TK_OFFSET                         46
6037 #define TK_PRAGMA                         47
6038 #define TK_RAISE                          48
6039 #define TK_REPLACE                        49
6040 #define TK_RESTRICT                       50
6041 #define TK_ROW                            51
6042 #define TK_TRIGGER                        52
6043 #define TK_VACUUM                         53
6044 #define TK_VIEW                           54
6045 #define TK_VIRTUAL                        55
6046 #define TK_REINDEX                        56
6047 #define TK_RENAME                         57
6048 #define TK_CTIME_KW                       58
6049 #define TK_ANY                            59
6050 #define TK_OR                             60
6051 #define TK_AND                            61
6052 #define TK_IS                             62
6053 #define TK_BETWEEN                        63
6054 #define TK_IN                             64
6055 #define TK_ISNULL                         65
6056 #define TK_NOTNULL                        66
6057 #define TK_NE                             67
6058 #define TK_EQ                             68
6059 #define TK_GT                             69
6060 #define TK_LE                             70
6061 #define TK_LT                             71
6062 #define TK_GE                             72
6063 #define TK_ESCAPE                         73
6064 #define TK_BITAND                         74
6065 #define TK_BITOR                          75
6066 #define TK_LSHIFT                         76
6067 #define TK_RSHIFT                         77
6068 #define TK_PLUS                           78
6069 #define TK_MINUS                          79
6070 #define TK_STAR                           80
6071 #define TK_SLASH                          81
6072 #define TK_REM                            82
6073 #define TK_CONCAT                         83
6074 #define TK_COLLATE                        84
6075 #define TK_UMINUS                         85
6076 #define TK_UPLUS                          86
6077 #define TK_BITNOT                         87
6078 #define TK_STRING                         88
6079 #define TK_JOIN_KW                        89
6080 #define TK_CONSTRAINT                     90
6081 #define TK_DEFAULT                        91
6082 #define TK_NULL                           92
6083 #define TK_PRIMARY                        93
6084 #define TK_UNIQUE                         94
6085 #define TK_CHECK                          95
6086 #define TK_REFERENCES                     96
6087 #define TK_AUTOINCR                       97
6088 #define TK_ON                             98
6089 #define TK_DELETE                         99
6090 #define TK_UPDATE                         100
6091 #define TK_INSERT                         101
6092 #define TK_SET                            102
6093 #define TK_DEFERRABLE                     103
6094 #define TK_FOREIGN                        104
6095 #define TK_DROP                           105
6096 #define TK_UNION                          106
6097 #define TK_ALL                            107
6098 #define TK_EXCEPT                         108
6099 #define TK_INTERSECT                      109
6100 #define TK_SELECT                         110
6101 #define TK_DISTINCT                       111
6102 #define TK_DOT                            112
6103 #define TK_FROM                           113
6104 #define TK_JOIN                           114
6105 #define TK_USING                          115
6106 #define TK_ORDER                          116
6107 #define TK_BY                             117
6108 #define TK_GROUP                          118
6109 #define TK_HAVING                         119
6110 #define TK_LIMIT                          120
6111 #define TK_WHERE                          121
6112 #define TK_INTO                           122
6113 #define TK_VALUES                         123
6114 #define TK_INTEGER                        124
6115 #define TK_FLOAT                          125
6116 #define TK_BLOB                           126
6117 #define TK_REGISTER                       127
6118 #define TK_VARIABLE                       128
6119 #define TK_CASE                           129
6120 #define TK_WHEN                           130
6121 #define TK_THEN                           131
6122 #define TK_ELSE                           132
6123 #define TK_INDEX                          133
6124 #define TK_ALTER                          134
6125 #define TK_TO                             135
6126 #define TK_ADD                            136
6127 #define TK_COLUMNKW                       137
6128 #define TK_TO_TEXT                        138
6129 #define TK_TO_BLOB                        139
6130 #define TK_TO_NUMERIC                     140
6131 #define TK_TO_INT                         141
6132 #define TK_TO_REAL                        142
6133 #define TK_END_OF_FILE                    143
6134 #define TK_ILLEGAL                        144
6135 #define TK_SPACE                          145
6136 #define TK_UNCLOSED_STRING                146
6137 #define TK_COMMENT                        147
6138 #define TK_FUNCTION                       148
6139 #define TK_COLUMN                         149
6140 #define TK_AGG_FUNCTION                   150
6141 #define TK_AGG_COLUMN                     151
6142 #define TK_CONST_FUNC                     152
6143
6144 /************** End of parse.h ***********************************************/
6145 /************** Continuing where we left off in sqliteInt.h ******************/
6146 #include <stdio.h>
6147 #include <stdlib.h>
6148 #include <string.h>
6149 #include <assert.h>
6150 #include <stddef.h>
6151
6152 #define sqlite3_isnan(X)  ((X)!=(X))
6153
6154 /*
6155 ** If compiling for a processor that lacks floating point support,
6156 ** substitute integer for floating-point
6157 */
6158 #ifdef SQLITE_OMIT_FLOATING_POINT
6159 # define double sqlite_int64
6160 # define LONGDOUBLE_TYPE sqlite_int64
6161 # ifndef SQLITE_BIG_DBL
6162 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
6163 # endif
6164 # define SQLITE_OMIT_DATETIME_FUNCS 1
6165 # define SQLITE_OMIT_TRACE 1
6166 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6167 #endif
6168 #ifndef SQLITE_BIG_DBL
6169 # define SQLITE_BIG_DBL (1e99)
6170 #endif
6171
6172 /*
6173 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6174 ** afterward. Having this macro allows us to cause the C compiler 
6175 ** to omit code used by TEMP tables without messy #ifndef statements.
6176 */
6177 #ifdef SQLITE_OMIT_TEMPDB
6178 #define OMIT_TEMPDB 1
6179 #else
6180 #define OMIT_TEMPDB 0
6181 #endif
6182
6183 /*
6184 ** If the following macro is set to 1, then NULL values are considered
6185 ** distinct when determining whether or not two entries are the same
6186 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
6187 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
6188 ** is the way things are suppose to work.
6189 **
6190 ** If the following macro is set to 0, the NULLs are indistinct for
6191 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
6192 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
6193 ** work.
6194 */
6195 #define NULL_DISTINCT_FOR_UNIQUE 1
6196
6197 /*
6198 ** The "file format" number is an integer that is incremented whenever
6199 ** the VDBE-level file format changes.  The following macros define the
6200 ** the default file format for new databases and the maximum file format
6201 ** that the library can read.
6202 */
6203 #define SQLITE_MAX_FILE_FORMAT 4
6204 #ifndef SQLITE_DEFAULT_FILE_FORMAT
6205 # define SQLITE_DEFAULT_FILE_FORMAT 1
6206 #endif
6207
6208 /*
6209 ** Provide a default value for TEMP_STORE in case it is not specified
6210 ** on the command-line
6211 */
6212 #ifndef TEMP_STORE
6213 # define TEMP_STORE 1
6214 #endif
6215
6216 /*
6217 ** GCC does not define the offsetof() macro so we'll have to do it
6218 ** ourselves.
6219 */
6220 #ifndef offsetof
6221 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6222 #endif
6223
6224 /*
6225 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6226 ** not, there are still machines out there that use EBCDIC.)
6227 */
6228 #if 'A' == '\301'
6229 # define SQLITE_EBCDIC 1
6230 #else
6231 # define SQLITE_ASCII 1
6232 #endif
6233
6234 /*
6235 ** Integers of known sizes.  These typedefs might change for architectures
6236 ** where the sizes very.  Preprocessor macros are available so that the
6237 ** types can be conveniently redefined at compile-type.  Like this:
6238 **
6239 **         cc '-DUINTPTR_TYPE=long long int' ...
6240 */
6241 #ifndef UINT32_TYPE
6242 # ifdef HAVE_UINT32_T
6243 #  define UINT32_TYPE uint32_t
6244 # else
6245 #  define UINT32_TYPE unsigned int
6246 # endif
6247 #endif
6248 #ifndef UINT16_TYPE
6249 # ifdef HAVE_UINT16_T
6250 #  define UINT16_TYPE uint16_t
6251 # else
6252 #  define UINT16_TYPE unsigned short int
6253 # endif
6254 #endif
6255 #ifndef INT16_TYPE
6256 # ifdef HAVE_INT16_T
6257 #  define INT16_TYPE int16_t
6258 # else
6259 #  define INT16_TYPE short int
6260 # endif
6261 #endif
6262 #ifndef UINT8_TYPE
6263 # ifdef HAVE_UINT8_T
6264 #  define UINT8_TYPE uint8_t
6265 # else
6266 #  define UINT8_TYPE unsigned char
6267 # endif
6268 #endif
6269 #ifndef INT8_TYPE
6270 # ifdef HAVE_INT8_T
6271 #  define INT8_TYPE int8_t
6272 # else
6273 #  define INT8_TYPE signed char
6274 # endif
6275 #endif
6276 #ifndef LONGDOUBLE_TYPE
6277 # define LONGDOUBLE_TYPE long double
6278 #endif
6279 typedef sqlite_int64 i64;          /* 8-byte signed integer */
6280 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6281 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6282 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6283 typedef INT16_TYPE i16;            /* 2-byte signed integer */
6284 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6285 typedef UINT8_TYPE i8;             /* 1-byte signed integer */
6286
6287 /*
6288 ** Macros to determine whether the machine is big or little endian,
6289 ** evaluated at runtime.
6290 */
6291 #ifdef SQLITE_AMALGAMATION
6292 SQLITE_PRIVATE const int sqlite3one;
6293 #else
6294 SQLITE_PRIVATE const int sqlite3one;
6295 #endif
6296 #if defined(i386) || defined(__i386__) || defined(_M_IX86)
6297 # define SQLITE_BIGENDIAN    0
6298 # define SQLITE_LITTLEENDIAN 1
6299 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6300 #else
6301 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6302 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6303 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6304 #endif
6305
6306 /*
6307 ** An instance of the following structure is used to store the busy-handler
6308 ** callback for a given sqlite handle. 
6309 **
6310 ** The sqlite.busyHandler member of the sqlite struct contains the busy
6311 ** callback for the database handle. Each pager opened via the sqlite
6312 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6313 ** callback is currently invoked only from within pager.c.
6314 */
6315 typedef struct BusyHandler BusyHandler;
6316 struct BusyHandler {
6317   int (*xFunc)(void *,int);  /* The busy callback */
6318   void *pArg;                /* First arg to busy callback */
6319   int nBusy;                 /* Incremented with each busy call */
6320 };
6321
6322 /*
6323 ** Name of the master database table.  The master database table
6324 ** is a special table that holds the names and attributes of all
6325 ** user tables and indices.
6326 */
6327 #define MASTER_NAME       "sqlite_master"
6328 #define TEMP_MASTER_NAME  "sqlite_temp_master"
6329
6330 /*
6331 ** The root-page of the master database table.
6332 */
6333 #define MASTER_ROOT       1
6334
6335 /*
6336 ** The name of the schema table.
6337 */
6338 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6339
6340 /*
6341 ** A convenience macro that returns the number of elements in
6342 ** an array.
6343 */
6344 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
6345
6346 /*
6347 ** Forward references to structures
6348 */
6349 typedef struct AggInfo AggInfo;
6350 typedef struct AuthContext AuthContext;
6351 typedef struct Bitvec Bitvec;
6352 typedef struct CollSeq CollSeq;
6353 typedef struct Column Column;
6354 typedef struct Db Db;
6355 typedef struct Schema Schema;
6356 typedef struct Expr Expr;
6357 typedef struct ExprList ExprList;
6358 typedef struct FKey FKey;
6359 typedef struct FuncDef FuncDef;
6360 typedef struct IdList IdList;
6361 typedef struct Index Index;
6362 typedef struct KeyClass KeyClass;
6363 typedef struct KeyInfo KeyInfo;
6364 typedef struct Module Module;
6365 typedef struct NameContext NameContext;
6366 typedef struct Parse Parse;
6367 typedef struct Select Select;
6368 typedef struct SrcList SrcList;
6369 typedef struct StrAccum StrAccum;
6370 typedef struct Table Table;
6371 typedef struct TableLock TableLock;
6372 typedef struct Token Token;
6373 typedef struct TriggerStack TriggerStack;
6374 typedef struct TriggerStep TriggerStep;
6375 typedef struct Trigger Trigger;
6376 typedef struct WhereInfo WhereInfo;
6377 typedef struct WhereLevel WhereLevel;
6378
6379 /*
6380 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
6381 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
6382 ** pointer types (i.e. FuncDef) defined above.
6383 */
6384 /************** Include btree.h in the middle of sqliteInt.h *****************/
6385 /************** Begin file btree.h *******************************************/
6386 /*
6387 ** 2001 September 15
6388 **
6389 ** The author disclaims copyright to this source code.  In place of
6390 ** a legal notice, here is a blessing:
6391 **
6392 **    May you do good and not evil.
6393 **    May you find forgiveness for yourself and forgive others.
6394 **    May you share freely, never taking more than you give.
6395 **
6396 *************************************************************************
6397 ** This header file defines the interface that the sqlite B-Tree file
6398 ** subsystem.  See comments in the source code for a detailed description
6399 ** of what each interface routine does.
6400 **
6401 ** @(#) $Id: btree.h,v 1.94 2007/12/07 18:55:28 drh Exp $
6402 */
6403 #ifndef _BTREE_H_
6404 #define _BTREE_H_
6405
6406 /* TODO: This definition is just included so other modules compile. It
6407 ** needs to be revisited.
6408 */
6409 #define SQLITE_N_BTREE_META 10
6410
6411 /*
6412 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
6413 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
6414 */
6415 #ifndef SQLITE_DEFAULT_AUTOVACUUM
6416   #define SQLITE_DEFAULT_AUTOVACUUM 0
6417 #endif
6418
6419 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
6420 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
6421 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
6422
6423 /*
6424 ** Forward declarations of structure
6425 */
6426 typedef struct Btree Btree;
6427 typedef struct BtCursor BtCursor;
6428 typedef struct BtShared BtShared;
6429 typedef struct BtreeMutexArray BtreeMutexArray;
6430
6431 /*
6432 ** This structure records all of the Btrees that need to hold
6433 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
6434 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
6435 ** we can always lock and unlock them all quickly.
6436 */
6437 struct BtreeMutexArray {
6438   int nMutex;
6439   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
6440 };
6441
6442
6443 SQLITE_PRIVATE int sqlite3BtreeOpen(
6444   const char *zFilename,   /* Name of database file to open */
6445   sqlite3 *db,             /* Associated database connection */
6446   Btree **,                /* Return open Btree* here */
6447   int flags,               /* Flags */
6448   int vfsFlags             /* Flags passed through to VFS open */
6449 );
6450
6451 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
6452 ** following values.
6453 **
6454 ** NOTE:  These values must match the corresponding PAGER_ values in
6455 ** pager.h.
6456 */
6457 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
6458 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
6459 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
6460 #define BTREE_READONLY      8  /* Open the database in read-only mode */
6461 #define BTREE_READWRITE    16  /* Open for both reading and writing */
6462 #define BTREE_CREATE       32  /* Create the database if it does not exist */
6463
6464 /* Additional values for the 4th argument of sqlite3BtreeOpen that
6465 ** are not associated with PAGER_ values.
6466 */
6467 #define BTREE_PRIVATE      64  /* Never share with other connections */
6468
6469 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
6470 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
6471 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
6472 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
6473 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
6474 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6475 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
6476 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6477 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
6478 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
6479 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
6480 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
6481 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
6482 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
6483 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
6484 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
6485 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
6486 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
6487 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
6488 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
6489 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
6490 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
6491 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
6492 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
6493 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
6494
6495 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
6496 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
6497 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
6498 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
6499
6500 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
6501
6502 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
6503 ** of the following flags:
6504 */
6505 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
6506 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
6507 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
6508
6509 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
6510 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int);
6511 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
6512 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
6513 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
6514
6515 SQLITE_PRIVATE int sqlite3BtreeCursor(
6516   Btree*,                              /* BTree containing table to open */
6517   int iTable,                          /* Index of root page */
6518   int wrFlag,                          /* 1 for writing.  0 for read-only */
6519   int(*)(void*,int,const void*,int,const void*),  /* Key comparison function */
6520   void*,                               /* First argument to compare function */
6521   BtCursor **ppCursor                  /* Returned cursor */
6522 );
6523
6524 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
6525 SQLITE_PRIVATE int sqlite3BtreeMoveto(BtCursor*,const void *pKey,i64 nKey,int bias,int *pRes);
6526 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
6527 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
6528                                   const void *pData, int nData,
6529                                   int nZero, int bias);
6530 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
6531 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
6532 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
6533 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
6534 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
6535 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
6536 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
6537 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
6538 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
6539 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
6540 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
6541 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
6542 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
6543
6544 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
6545 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
6546
6547 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
6548 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
6549
6550 #ifdef SQLITE_TEST
6551 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
6552 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
6553 SQLITE_PRIVATE int sqlite3BtreePageDump(Btree*, int, int recursive);
6554 #endif
6555
6556 /*
6557 ** If we are not using shared cache, then there is no need to
6558 ** use mutexes to access the BtShared structures.  So make the
6559 ** Enter and Leave procedures no-ops.
6560 */
6561 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
6562 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
6563 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
6564 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
6565 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
6566 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
6567 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
6568 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
6569 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
6570 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
6571 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
6572 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
6573 #else
6574 # define sqlite3BtreeEnter(X)
6575 # define sqlite3BtreeLeave(X)
6576 # define sqlite3BtreeHoldsMutex(X) 1
6577 # define sqlite3BtreeEnterCursor(X)
6578 # define sqlite3BtreeLeaveCursor(X)
6579 # define sqlite3BtreeEnterAll(X)
6580 # define sqlite3BtreeLeaveAll(X)
6581 # define sqlite3BtreeHoldsAllMutexes(X) 1
6582 # define sqlite3BtreeMutexArrayEnter(X)
6583 # define sqlite3BtreeMutexArrayLeave(X)
6584 # define sqlite3BtreeMutexArrayInsert(X,Y)
6585 #endif
6586
6587
6588 #endif /* _BTREE_H_ */
6589
6590 /************** End of btree.h ***********************************************/
6591 /************** Continuing where we left off in sqliteInt.h ******************/
6592 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
6593 /************** Begin file vdbe.h ********************************************/
6594 /*
6595 ** 2001 September 15
6596 **
6597 ** The author disclaims copyright to this source code.  In place of
6598 ** a legal notice, here is a blessing:
6599 **
6600 **    May you do good and not evil.
6601 **    May you find forgiveness for yourself and forgive others.
6602 **    May you share freely, never taking more than you give.
6603 **
6604 *************************************************************************
6605 ** Header file for the Virtual DataBase Engine (VDBE)
6606 **
6607 ** This header defines the interface to the virtual database engine
6608 ** or VDBE.  The VDBE implements an abstract machine that runs a
6609 ** simple program to access and modify the underlying database.
6610 **
6611 ** $Id: vdbe.h,v 1.125 2008/01/17 17:27:31 drh Exp $
6612 */
6613 #ifndef _SQLITE_VDBE_H_
6614 #define _SQLITE_VDBE_H_
6615
6616 /*
6617 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
6618 ** in the source file sqliteVdbe.c are allowed to see the insides
6619 ** of this structure.
6620 */
6621 typedef struct Vdbe Vdbe;
6622
6623 /*
6624 ** The names of the following types declared in vdbeInt.h are required
6625 ** for the VdbeOp definition.
6626 */
6627 typedef struct VdbeFunc VdbeFunc;
6628 typedef struct Mem Mem;
6629
6630 /*
6631 ** A single instruction of the virtual machine has an opcode
6632 ** and as many as three operands.  The instruction is recorded
6633 ** as an instance of the following structure:
6634 */
6635 struct VdbeOp {
6636   u8 opcode;          /* What operation to perform */
6637   signed char p4type; /* One of the P4_xxx constants for p4 */
6638   u8 flags;           /* Flags for internal use */
6639   u8 p5;              /* Fifth parameter is an unsigned character */
6640   int p1;             /* First operand */
6641   int p2;             /* Second parameter (often the jump destination) */
6642   int p3;             /* The third parameter */
6643   union {             /* forth parameter */
6644     int i;                 /* Integer value if p4type==P4_INT32 */
6645     void *p;               /* Generic pointer */
6646     char *z;               /* Pointer to data for string (char array) types */
6647     i64 *pI64;             /* Used when p4type is P4_INT64 */
6648     double *pReal;         /* Used when p4type is P4_REAL */
6649     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
6650     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
6651     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
6652     Mem *pMem;             /* Used when p4type is P4_MEM */
6653     sqlite3_vtab *pVtab;   /* Used when p4type is P4_VTAB */
6654     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
6655   } p4;
6656 #ifdef SQLITE_DEBUG
6657   char *zComment;     /* Comment to improve readability */
6658 #endif
6659 #ifdef VDBE_PROFILE
6660   int cnt;            /* Number of times this instruction was executed */
6661   long long cycles;   /* Total time spend executing this instruction */
6662 #endif
6663 };
6664 typedef struct VdbeOp VdbeOp;
6665
6666 /*
6667 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
6668 ** it takes up less space.
6669 */
6670 struct VdbeOpList {
6671   u8 opcode;          /* What operation to perform */
6672   signed char p1;     /* First operand */
6673   signed char p2;     /* Second parameter (often the jump destination) */
6674   signed char p3;     /* Third parameter */
6675 };
6676 typedef struct VdbeOpList VdbeOpList;
6677
6678 /*
6679 ** Allowed values of VdbeOp.p3type
6680 */
6681 #define P4_NOTUSED    0   /* The P4 parameter is not used */
6682 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
6683 #define P4_STATIC   (-2)  /* Pointer to a static string */
6684 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
6685 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
6686 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
6687 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
6688 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
6689 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
6690 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
6691 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
6692 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
6693 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
6694 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
6695
6696 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
6697 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
6698 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
6699 ** gets freed when the Vdbe is finalized so it still should be obtained
6700 ** from a single sqliteMalloc().  But no copy is made and the calling
6701 ** function should *not* try to free the KeyInfo.
6702 */
6703 #define P4_KEYINFO_HANDOFF (-9)
6704
6705 /*
6706 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
6707 ** number of columns of data returned by the statement.
6708 */
6709 #define COLNAME_NAME     0
6710 #define COLNAME_DECLTYPE 1
6711 #define COLNAME_DATABASE 2
6712 #define COLNAME_TABLE    3
6713 #define COLNAME_COLUMN   4
6714 #define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
6715
6716 /*
6717 ** The following macro converts a relative address in the p2 field
6718 ** of a VdbeOp structure into a negative number so that 
6719 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
6720 ** the macro again restores the address.
6721 */
6722 #define ADDR(X)  (-1-(X))
6723
6724 /*
6725 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
6726 ** header file that defines a number for each opcode used by the VDBE.
6727 */
6728 /************** Include opcodes.h in the middle of vdbe.h ********************/
6729 /************** Begin file opcodes.h *****************************************/
6730 /* Automatically generated.  Do not edit */
6731 /* See the mkopcodeh.awk script for details */
6732 #define OP_VNext                                1
6733 #define OP_Column                               2
6734 #define OP_SetCookie                            3
6735 #define OP_Real                               125   /* same as TK_FLOAT    */
6736 #define OP_Sequence                             4
6737 #define OP_MoveGt                               5
6738 #define OP_Ge                                  72   /* same as TK_GE       */
6739 #define OP_RowKey                               6
6740 #define OP_SCopy                                7
6741 #define OP_Eq                                  68   /* same as TK_EQ       */
6742 #define OP_OpenWrite                            8
6743 #define OP_NotNull                             66   /* same as TK_NOTNULL  */
6744 #define OP_If                                   9
6745 #define OP_ToInt                              141   /* same as TK_TO_INT   */
6746 #define OP_String8                             88   /* same as TK_STRING   */
6747 #define OP_VRowid                              10
6748 #define OP_CollSeq                             11
6749 #define OP_OpenRead                            12
6750 #define OP_Expire                              13
6751 #define OP_AutoCommit                          14
6752 #define OP_Gt                                  69   /* same as TK_GT       */
6753 #define OP_IntegrityCk                         15
6754 #define OP_Sort                                17
6755 #define OP_Copy                                18
6756 #define OP_Trace                               19
6757 #define OP_Function                            20
6758 #define OP_IfNeg                               21
6759 #define OP_And                                 61   /* same as TK_AND      */
6760 #define OP_Subtract                            79   /* same as TK_MINUS    */
6761 #define OP_Noop                                22
6762 #define OP_Return                              23
6763 #define OP_Remainder                           82   /* same as TK_REM      */
6764 #define OP_NewRowid                            24
6765 #define OP_Multiply                            80   /* same as TK_STAR     */
6766 #define OP_Variable                            25
6767 #define OP_String                              26
6768 #define OP_RealAffinity                        27
6769 #define OP_VRename                             28
6770 #define OP_ParseSchema                         29
6771 #define OP_VOpen                               30
6772 #define OP_Close                               31
6773 #define OP_CreateIndex                         32
6774 #define OP_IsUnique                            33
6775 #define OP_NotFound                            34
6776 #define OP_Int64                               35
6777 #define OP_MustBeInt                           36
6778 #define OP_Halt                                37
6779 #define OP_Rowid                               38
6780 #define OP_IdxLT                               39
6781 #define OP_AddImm                              40
6782 #define OP_Statement                           41
6783 #define OP_RowData                             42
6784 #define OP_MemMax                              43
6785 #define OP_Or                                  60   /* same as TK_OR       */
6786 #define OP_NotExists                           44
6787 #define OP_Gosub                               45
6788 #define OP_Divide                              81   /* same as TK_SLASH    */
6789 #define OP_Integer                             46
6790 #define OP_ToNumeric                          140   /* same as TK_TO_NUMERIC*/
6791 #define OP_Prev                                47
6792 #define OP_Concat                              83   /* same as TK_CONCAT   */
6793 #define OP_BitAnd                              74   /* same as TK_BITAND   */
6794 #define OP_VColumn                             48
6795 #define OP_CreateTable                         49
6796 #define OP_Last                                50
6797 #define OP_IsNull                              65   /* same as TK_ISNULL   */
6798 #define OP_IncrVacuum                          51
6799 #define OP_IdxRowid                            52
6800 #define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
6801 #define OP_ResetCount                          53
6802 #define OP_FifoWrite                           54
6803 #define OP_ContextPush                         55
6804 #define OP_DropTrigger                         56
6805 #define OP_DropIndex                           57
6806 #define OP_IdxGE                               58
6807 #define OP_IdxDelete                           59
6808 #define OP_Vacuum                              62
6809 #define OP_MoveLe                              63
6810 #define OP_IfNot                               64
6811 #define OP_DropTable                           73
6812 #define OP_MakeRecord                          84
6813 #define OP_ToBlob                             139   /* same as TK_TO_BLOB  */
6814 #define OP_ResultRow                           85
6815 #define OP_Delete                              86
6816 #define OP_AggFinal                            89
6817 #define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
6818 #define OP_Goto                                90
6819 #define OP_TableLock                           91
6820 #define OP_FifoRead                            92
6821 #define OP_Clear                               93
6822 #define OP_MoveLt                              94
6823 #define OP_Le                                  70   /* same as TK_LE       */
6824 #define OP_VerifyCookie                        95
6825 #define OP_AggStep                             96
6826 #define OP_ToText                             138   /* same as TK_TO_TEXT  */
6827 #define OP_Not                                 16   /* same as TK_NOT      */
6828 #define OP_ToReal                             142   /* same as TK_TO_REAL  */
6829 #define OP_SetNumColumns                       97
6830 #define OP_Transaction                         98
6831 #define OP_VFilter                             99
6832 #define OP_Ne                                  67   /* same as TK_NE       */
6833 #define OP_VDestroy                           100
6834 #define OP_ContextPop                         101
6835 #define OP_BitOr                               75   /* same as TK_BITOR    */
6836 #define OP_Next                               102
6837 #define OP_IdxInsert                          103
6838 #define OP_Lt                                  71   /* same as TK_LT       */
6839 #define OP_Insert                             104
6840 #define OP_Destroy                            105
6841 #define OP_ReadCookie                         106
6842 #define OP_ForceInt                           107
6843 #define OP_LoadAnalysis                       108
6844 #define OP_Explain                            109
6845 #define OP_OpenPseudo                         110
6846 #define OP_OpenEphemeral                      111
6847 #define OP_Null                               112
6848 #define OP_Move                               113
6849 #define OP_Blob                               114
6850 #define OP_Add                                 78   /* same as TK_PLUS     */
6851 #define OP_Rewind                             115
6852 #define OP_MoveGe                             116
6853 #define OP_VBegin                             117
6854 #define OP_VUpdate                            118
6855 #define OP_IfZero                             119
6856 #define OP_BitNot                              87   /* same as TK_BITNOT   */
6857 #define OP_VCreate                            120
6858 #define OP_Found                              121
6859 #define OP_IfPos                              122
6860 #define OP_NullRow                            123
6861
6862 /* The following opcode values are never used */
6863 #define OP_NotUsed_124                        124
6864 #define OP_NotUsed_126                        126
6865 #define OP_NotUsed_127                        127
6866 #define OP_NotUsed_128                        128
6867 #define OP_NotUsed_129                        129
6868 #define OP_NotUsed_130                        130
6869 #define OP_NotUsed_131                        131
6870 #define OP_NotUsed_132                        132
6871 #define OP_NotUsed_133                        133
6872 #define OP_NotUsed_134                        134
6873 #define OP_NotUsed_135                        135
6874 #define OP_NotUsed_136                        136
6875 #define OP_NotUsed_137                        137
6876
6877
6878 /* Properties such as "out2" or "jump" that are specified in
6879 ** comments following the "case" for each opcode in the vdbe.c
6880 ** are encoded into bitvectors as follows:
6881 */
6882 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
6883 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
6884 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
6885 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
6886 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
6887 #define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
6888 #define OPFLG_INITIALIZER {\
6889 /*   0 */ 0x00, 0x01, 0x00, 0x10, 0x02, 0x11, 0x00, 0x00,\
6890 /*   8 */ 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
6891 /*  16 */ 0x04, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00,\
6892 /*  24 */ 0x02, 0x02, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00,\
6893 /*  32 */ 0x02, 0x11, 0x11, 0x02, 0x05, 0x00, 0x02, 0x11,\
6894 /*  40 */ 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01, 0x02, 0x01,\
6895 /*  48 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x04, 0x00,\
6896 /*  56 */ 0x00, 0x00, 0x11, 0x08, 0x2c, 0x2c, 0x00, 0x11,\
6897 /*  64 */ 0x05, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
6898 /*  72 */ 0x15, 0x00, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
6899 /*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04,\
6900 /*  88 */ 0x02, 0x00, 0x01, 0x00, 0x01, 0x00, 0x11, 0x00,\
6901 /*  96 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x08,\
6902 /* 104 */ 0x00, 0x02, 0x02, 0x05, 0x00, 0x00, 0x00, 0x00,\
6903 /* 112 */ 0x02, 0x00, 0x02, 0x01, 0x11, 0x00, 0x00, 0x05,\
6904 /* 120 */ 0x00, 0x11, 0x05, 0x00, 0x00, 0x02, 0x00, 0x00,\
6905 /* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
6906 /* 136 */ 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,}
6907
6908 /************** End of opcodes.h *********************************************/
6909 /************** Continuing where we left off in vdbe.h ***********************/
6910
6911 /*
6912 ** Prototypes for the VDBE interface.  See comments on the implementation
6913 ** for a description of what each of these routines does.
6914 */
6915 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
6916 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
6917 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
6918 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
6919 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
6920 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
6921 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
6922 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
6923 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
6924 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
6925 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
6926 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
6927 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
6928 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
6929 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
6930 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
6931 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
6932 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
6933 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
6934 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
6935 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
6936 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
6937 #ifdef SQLITE_DEBUG
6938 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
6939 #endif
6940 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
6941 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
6942 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
6943 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
6944 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
6945 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
6946 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
6947 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
6948
6949 #ifndef NDEBUG
6950 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
6951 # define VdbeComment(X)  sqlite3VdbeComment X
6952 #else
6953 # define VdbeComment(X)
6954 #endif
6955
6956 #endif
6957
6958 /************** End of vdbe.h ************************************************/
6959 /************** Continuing where we left off in sqliteInt.h ******************/
6960 /************** Include pager.h in the middle of sqliteInt.h *****************/
6961 /************** Begin file pager.h *******************************************/
6962 /*
6963 ** 2001 September 15
6964 **
6965 ** The author disclaims copyright to this source code.  In place of
6966 ** a legal notice, here is a blessing:
6967 **
6968 **    May you do good and not evil.
6969 **    May you find forgiveness for yourself and forgive others.
6970 **    May you share freely, never taking more than you give.
6971 **
6972 *************************************************************************
6973 ** This header file defines the interface that the sqlite page cache
6974 ** subsystem.  The page cache subsystem reads and writes a file a page
6975 ** at a time and provides a journal for rollback.
6976 **
6977 ** @(#) $Id: pager.h,v 1.69 2008/02/02 20:47:38 drh Exp $
6978 */
6979
6980 #ifndef _PAGER_H_
6981 #define _PAGER_H_
6982
6983 /*
6984 ** The type used to represent a page number.  The first page in a file
6985 ** is called page 1.  0 is used to represent "not a page".
6986 */
6987 typedef unsigned int Pgno;
6988
6989 /*
6990 ** Each open file is managed by a separate instance of the "Pager" structure.
6991 */
6992 typedef struct Pager Pager;
6993
6994 /*
6995 ** Handle type for pages.
6996 */
6997 typedef struct PgHdr DbPage;
6998
6999 /*
7000 ** Allowed values for the flags parameter to sqlite3PagerOpen().
7001 **
7002 ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
7003 */
7004 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7005 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7006
7007 /*
7008 ** Valid values for the second argument to sqlite3PagerLockingMode().
7009 */
7010 #define PAGER_LOCKINGMODE_QUERY      -1
7011 #define PAGER_LOCKINGMODE_NORMAL      0
7012 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
7013
7014 /*
7015 ** See source code comments for a detailed description of the following
7016 ** routines:
7017 */
7018 SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
7019 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
7020 SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
7021 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
7022 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
7023 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7024 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7025 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7026 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7027 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7028 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7029 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7030 SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
7031 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
7032 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7033 SQLITE_PRIVATE int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void*);
7034 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*);
7035 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno);
7036 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
7037 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno);
7038 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7039 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7040 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*);
7041 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager*);
7042 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager*);
7043 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager*);
7044 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
7045 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7046 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7047 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7048 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7049 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7050 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7051 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
7052 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7053 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7054 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno);
7055 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
7056 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7057 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7058 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7059
7060 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
7061 SQLITE_PRIVATE   int sqlite3PagerReleaseMemory(int);
7062 #endif
7063
7064 #ifdef SQLITE_HAS_CODEC
7065 SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
7066 #endif
7067
7068 #if !defined(NDEBUG) || defined(SQLITE_TEST)
7069 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7070 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7071 #endif
7072
7073 #ifdef SQLITE_TEST
7074 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7075 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7076 #endif
7077
7078 #ifdef SQLITE_TEST
7079 void disable_simulated_io_errors(void);
7080 void enable_simulated_io_errors(void);
7081 #else
7082 # define disable_simulated_io_errors()
7083 # define enable_simulated_io_errors()
7084 #endif
7085
7086 #endif /* _PAGER_H_ */
7087
7088 /************** End of pager.h ***********************************************/
7089 /************** Continuing where we left off in sqliteInt.h ******************/
7090
7091 /************** Include os.h in the middle of sqliteInt.h ********************/
7092 /************** Begin file os.h **********************************************/
7093 /*
7094 ** 2001 September 16
7095 **
7096 ** The author disclaims copyright to this source code.  In place of
7097 ** a legal notice, here is a blessing:
7098 **
7099 **    May you do good and not evil.
7100 **    May you find forgiveness for yourself and forgive others.
7101 **    May you share freely, never taking more than you give.
7102 **
7103 ******************************************************************************
7104 **
7105 ** This header file (together with is companion C source-code file
7106 ** "os.c") attempt to abstract the underlying operating system so that
7107 ** the SQLite library will work on both POSIX and windows systems.
7108 **
7109 ** This header file is #include-ed by sqliteInt.h and thus ends up
7110 ** being included by every source file.
7111 */
7112 #ifndef _SQLITE_OS_H_
7113 #define _SQLITE_OS_H_
7114
7115 /*
7116 ** Figure out if we are dealing with Unix, Windows, or some other
7117 ** operating system.  After the following block of preprocess macros,
7118 ** all of OS_UNIX, OS_WIN, OS_OS2, and OS_OTHER will defined to either
7119 ** 1 or 0.  One of the four will be 1.  The other three will be 0.
7120 */
7121 #if defined(OS_OTHER)
7122 # if OS_OTHER==1
7123 #   undef OS_UNIX
7124 #   define OS_UNIX 0
7125 #   undef OS_WIN
7126 #   define OS_WIN 0
7127 #   undef OS_OS2
7128 #   define OS_OS2 0
7129 # else
7130 #   undef OS_OTHER
7131 # endif
7132 #endif
7133 #if !defined(OS_UNIX) && !defined(OS_OTHER)
7134 # define OS_OTHER 0
7135 # ifndef OS_WIN
7136 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
7137 #     define OS_WIN 1
7138 #     define OS_UNIX 0
7139 #     define OS_OS2 0
7140 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
7141 #     define OS_WIN 0
7142 #     define OS_UNIX 0
7143 #     define OS_OS2 1
7144 #   else
7145 #     define OS_WIN 0
7146 #     define OS_UNIX 1
7147 #     define OS_OS2 0
7148 #  endif
7149 # else
7150 #  define OS_UNIX 0
7151 #  define OS_OS2 0
7152 # endif
7153 #else
7154 # ifndef OS_WIN
7155 #  define OS_WIN 0
7156 # endif
7157 #endif
7158
7159
7160
7161 /*
7162 ** Define the maximum size of a temporary filename
7163 */
7164 #if OS_WIN
7165 # include <windows.h>
7166 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
7167 #elif OS_OS2
7168 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
7169 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
7170 # endif
7171 # define INCL_DOSDATETIME
7172 # define INCL_DOSFILEMGR
7173 # define INCL_DOSERRORS
7174 # define INCL_DOSMISC
7175 # define INCL_DOSPROCESS
7176 # define INCL_DOSMODULEMGR
7177 # define INCL_DOSSEMAPHORES
7178 # include <os2.h>
7179 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
7180 #else
7181 # define SQLITE_TEMPNAME_SIZE 200
7182 #endif
7183
7184 /* If the SET_FULLSYNC macro is not defined above, then make it
7185 ** a no-op
7186 */
7187 #ifndef SET_FULLSYNC
7188 # define SET_FULLSYNC(x,y)
7189 #endif
7190
7191 /*
7192 ** The default size of a disk sector
7193 */
7194 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
7195 # define SQLITE_DEFAULT_SECTOR_SIZE 512
7196 #endif
7197
7198 /*
7199 ** Temporary files are named starting with this prefix followed by 16 random
7200 ** alphanumeric characters, and no file extension. They are stored in the
7201 ** OS's standard temporary file directory, and are deleted prior to exit.
7202 ** If sqlite is being embedded in another program, you may wish to change the
7203 ** prefix to reflect your program's name, so that if your program exits
7204 ** prematurely, old temporary files can be easily identified. This can be done
7205 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
7206 **
7207 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
7208 ** Mcafee started using SQLite in their anti-virus product and it
7209 ** started putting files with the "sqlite" name in the c:/temp folder.
7210 ** This annoyed many windows users.  Those users would then do a 
7211 ** Google search for "sqlite", find the telephone numbers of the
7212 ** developers and call to wake them up at night and complain.
7213 ** For this reason, the default name prefix is changed to be "sqlite" 
7214 ** spelled backwards.  So the temp files are still identified, but
7215 ** anybody smart enough to figure out the code is also likely smart
7216 ** enough to know that calling the developer will not help get rid
7217 ** of the file.
7218 */
7219 #ifndef SQLITE_TEMP_FILE_PREFIX
7220 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
7221 #endif
7222
7223 /*
7224 ** The following values may be passed as the second argument to
7225 ** sqlite3OsLock(). The various locks exhibit the following semantics:
7226 **
7227 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
7228 ** RESERVED:  A single process may hold a RESERVED lock on a file at
7229 **            any time. Other processes may hold and obtain new SHARED locks.
7230 ** PENDING:   A single process may hold a PENDING lock on a file at
7231 **            any one time. Existing SHARED locks may persist, but no new
7232 **            SHARED locks may be obtained by other processes.
7233 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
7234 **
7235 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
7236 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
7237 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
7238 ** sqlite3OsLock().
7239 */
7240 #define NO_LOCK         0
7241 #define SHARED_LOCK     1
7242 #define RESERVED_LOCK   2
7243 #define PENDING_LOCK    3
7244 #define EXCLUSIVE_LOCK  4
7245
7246 /*
7247 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
7248 **
7249 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
7250 ** those functions are not available.  So we use only LockFile() and
7251 ** UnlockFile().
7252 **
7253 ** LockFile() prevents not just writing but also reading by other processes.
7254 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
7255 ** byte out of a specific range of bytes. The lock byte is obtained at 
7256 ** random so two separate readers can probably access the file at the 
7257 ** same time, unless they are unlucky and choose the same lock byte.
7258 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
7259 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
7260 ** a single byte of the file that is designated as the reserved lock byte.
7261 ** A PENDING_LOCK is obtained by locking a designated byte different from
7262 ** the RESERVED_LOCK byte.
7263 **
7264 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
7265 ** which means we can use reader/writer locks.  When reader/writer locks
7266 ** are used, the lock is placed on the same range of bytes that is used
7267 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
7268 ** will support two or more Win95 readers or two or more WinNT readers.
7269 ** But a single Win95 reader will lock out all WinNT readers and a single
7270 ** WinNT reader will lock out all other Win95 readers.
7271 **
7272 ** The following #defines specify the range of bytes used for locking.
7273 ** SHARED_SIZE is the number of bytes available in the pool from which
7274 ** a random byte is selected for a shared lock.  The pool of bytes for
7275 ** shared locks begins at SHARED_FIRST. 
7276 **
7277 ** These #defines are available in sqlite_aux.h so that adaptors for
7278 ** connecting SQLite to other operating systems can use the same byte
7279 ** ranges for locking.  In particular, the same locking strategy and
7280 ** byte ranges are used for Unix.  This leaves open the possiblity of having
7281 ** clients on win95, winNT, and unix all talking to the same shared file
7282 ** and all locking correctly.  To do so would require that samba (or whatever
7283 ** tool is being used for file sharing) implements locks correctly between
7284 ** windows and unix.  I'm guessing that isn't likely to happen, but by
7285 ** using the same locking range we are at least open to the possibility.
7286 **
7287 ** Locking in windows is manditory.  For this reason, we cannot store
7288 ** actual data in the bytes used for locking.  The pager never allocates
7289 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
7290 ** that all locks will fit on a single page even at the minimum page size.
7291 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
7292 ** is set high so that we don't have to allocate an unused page except
7293 ** for very large databases.  But one should test the page skipping logic 
7294 ** by setting PENDING_BYTE low and running the entire regression suite.
7295 **
7296 ** Changing the value of PENDING_BYTE results in a subtly incompatible
7297 ** file format.  Depending on how it is changed, you might not notice
7298 ** the incompatibility right away, even running a full regression test.
7299 ** The default location of PENDING_BYTE is the first byte past the
7300 ** 1GB boundary.
7301 **
7302 */
7303 #ifndef SQLITE_TEST
7304 #define PENDING_BYTE      0x40000000  /* First byte past the 1GB boundary */
7305 #else
7306 SQLITE_API extern unsigned int sqlite3_pending_byte;
7307 #define PENDING_BYTE sqlite3_pending_byte
7308 #endif
7309
7310 #define RESERVED_BYTE     (PENDING_BYTE+1)
7311 #define SHARED_FIRST      (PENDING_BYTE+2)
7312 #define SHARED_SIZE       510
7313
7314 /* 
7315 ** Functions for accessing sqlite3_file methods 
7316 */
7317 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
7318 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
7319 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
7320 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
7321 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
7322 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
7323 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
7324 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
7325 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id);
7326 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
7327 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
7328 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
7329
7330 /* 
7331 ** Functions for accessing sqlite3_vfs methods 
7332 */
7333 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
7334 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
7335 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int);
7336 SQLITE_PRIVATE int sqlite3OsGetTempname(sqlite3_vfs *, int, char *);
7337 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
7338 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
7339 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
7340 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *, void *, const char *);
7341 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
7342 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
7343 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
7344 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
7345
7346 /*
7347 ** Convenience functions for opening and closing files using 
7348 ** sqlite3_malloc() to obtain space for the file-handle structure.
7349 */
7350 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
7351 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
7352
7353 /*
7354 ** Each OS-specific backend defines an instance of the following
7355 ** structure for returning a pointer to its sqlite3_vfs.  If OS_OTHER
7356 ** is defined (meaning that the application-defined OS interface layer
7357 ** is used) then there is no default VFS.   The application must
7358 ** register one or more VFS structures using sqlite3_vfs_register()
7359 ** before attempting to use SQLite.
7360 */
7361 #if OS_UNIX || OS_WIN || OS_OS2
7362 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void);
7363 #else
7364 # define sqlite3OsDefaultVfs(X) 0
7365 #endif
7366
7367 #endif /* _SQLITE_OS_H_ */
7368
7369 /************** End of os.h **************************************************/
7370 /************** Continuing where we left off in sqliteInt.h ******************/
7371 /************** Include mutex.h in the middle of sqliteInt.h *****************/
7372 /************** Begin file mutex.h *******************************************/
7373 /*
7374 ** 2007 August 28
7375 **
7376 ** The author disclaims copyright to this source code.  In place of
7377 ** a legal notice, here is a blessing:
7378 **
7379 **    May you do good and not evil.
7380 **    May you find forgiveness for yourself and forgive others.
7381 **    May you share freely, never taking more than you give.
7382 **
7383 *************************************************************************
7384 **
7385 ** This file contains the common header for all mutex implementations.
7386 ** The sqliteInt.h header #includes this file so that it is available
7387 ** to all source files.  We break it out in an effort to keep the code
7388 ** better organized.
7389 **
7390 ** NOTE:  source files should *not* #include this header file directly.
7391 ** Source files should #include the sqliteInt.h file and let that file
7392 ** include this one indirectly.
7393 **
7394 ** $Id: mutex.h,v 1.2 2007/08/30 14:10:30 drh Exp $
7395 */
7396
7397
7398 #ifdef SQLITE_MUTEX_APPDEF
7399 /*
7400 ** If SQLITE_MUTEX_APPDEF is defined, then this whole module is
7401 ** omitted and equivalent functionality must be provided by the
7402 ** application that links against the SQLite library.
7403 */
7404 #else
7405 /*
7406 ** Figure out what version of the code to use.  The choices are
7407 **
7408 **   SQLITE_MUTEX_NOOP         For single-threaded applications that
7409 **                             do not desire error checking.
7410 **
7411 **   SQLITE_MUTEX_NOOP_DEBUG   For single-threaded applications with
7412 **                             error checking to help verify that mutexes
7413 **                             are being used correctly even though they
7414 **                             are not needed.  Used when SQLITE_DEBUG is
7415 **                             defined on single-threaded builds.
7416 **
7417 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
7418 **
7419 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
7420 **
7421 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
7422 */
7423 #define SQLITE_MUTEX_NOOP 1   /* The default */
7424 #if defined(SQLITE_DEBUG) && !SQLITE_THREADSAFE
7425 # undef SQLITE_MUTEX_NOOP
7426 # define SQLITE_MUTEX_NOOP_DEBUG
7427 #endif
7428 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_UNIX
7429 # undef SQLITE_MUTEX_NOOP
7430 # define SQLITE_MUTEX_PTHREADS
7431 #endif
7432 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_WIN
7433 # undef SQLITE_MUTEX_NOOP
7434 # define SQLITE_MUTEX_W32
7435 #endif
7436 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_OS2
7437 # undef SQLITE_MUTEX_NOOP
7438 # define SQLITE_MUTEX_OS2
7439 #endif
7440
7441 #ifdef SQLITE_MUTEX_NOOP
7442 /*
7443 ** If this is a no-op implementation, implement everything as macros.
7444 */
7445 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
7446 #define sqlite3_mutex_free(X)
7447 #define sqlite3_mutex_enter(X)
7448 #define sqlite3_mutex_try(X)      SQLITE_OK
7449 #define sqlite3_mutex_leave(X)
7450 #define sqlite3_mutex_held(X)     1
7451 #define sqlite3_mutex_notheld(X)  1
7452 #endif
7453
7454 #endif /* SQLITE_MUTEX_APPDEF */
7455
7456 /************** End of mutex.h ***********************************************/
7457 /************** Continuing where we left off in sqliteInt.h ******************/
7458
7459
7460 /*
7461 ** Each database file to be accessed by the system is an instance
7462 ** of the following structure.  There are normally two of these structures
7463 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
7464 ** aDb[1] is the database file used to hold temporary tables.  Additional
7465 ** databases may be attached.
7466 */
7467 struct Db {
7468   char *zName;         /* Name of this database */
7469   Btree *pBt;          /* The B*Tree structure for this database file */
7470   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
7471   u8 safety_level;     /* How aggressive at synching data to disk */
7472   void *pAux;               /* Auxiliary data.  Usually NULL */
7473   void (*xFreeAux)(void*);  /* Routine to free pAux */
7474   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
7475 };
7476
7477 /*
7478 ** An instance of the following structure stores a database schema.
7479 **
7480 ** If there are no virtual tables configured in this schema, the
7481 ** Schema.db variable is set to NULL. After the first virtual table
7482 ** has been added, it is set to point to the database connection 
7483 ** used to create the connection. Once a virtual table has been
7484 ** added to the Schema structure and the Schema.db variable populated, 
7485 ** only that database connection may use the Schema to prepare 
7486 ** statements.
7487 */
7488 struct Schema {
7489   int schema_cookie;   /* Database schema version number for this file */
7490   Hash tblHash;        /* All tables indexed by name */
7491   Hash idxHash;        /* All (named) indices indexed by name */
7492   Hash trigHash;       /* All triggers indexed by name */
7493   Hash aFKey;          /* Foreign keys indexed by to-table */
7494   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
7495   u8 file_format;      /* Schema format version for this file */
7496   u8 enc;              /* Text encoding used by this database */
7497   u16 flags;           /* Flags associated with this schema */
7498   int cache_size;      /* Number of pages to use in the cache */
7499 #ifndef SQLITE_OMIT_VIRTUALTABLE
7500   sqlite3 *db;         /* "Owner" connection. See comment above */
7501 #endif
7502 };
7503
7504 /*
7505 ** These macros can be used to test, set, or clear bits in the 
7506 ** Db.flags field.
7507 */
7508 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
7509 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
7510 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
7511 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
7512
7513 /*
7514 ** Allowed values for the DB.flags field.
7515 **
7516 ** The DB_SchemaLoaded flag is set after the database schema has been
7517 ** read into internal hash tables.
7518 **
7519 ** DB_UnresetViews means that one or more views have column names that
7520 ** have been filled out.  If the schema changes, these column names might
7521 ** changes and so the view will need to be reset.
7522 */
7523 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
7524 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
7525 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
7526
7527
7528 /*
7529 ** Each database is an instance of the following structure.
7530 **
7531 ** The sqlite.lastRowid records the last insert rowid generated by an
7532 ** insert statement.  Inserts on views do not affect its value.  Each
7533 ** trigger has its own context, so that lastRowid can be updated inside
7534 ** triggers as usual.  The previous value will be restored once the trigger
7535 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
7536 ** longer (since after version 2.8.12) reset to -1.
7537 **
7538 ** The sqlite.nChange does not count changes within triggers and keeps no
7539 ** context.  It is reset at start of sqlite3_exec.
7540 ** The sqlite.lsChange represents the number of changes made by the last
7541 ** insert, update, or delete statement.  It remains constant throughout the
7542 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
7543 ** context stack just like lastRowid so that the count of changes
7544 ** within a trigger is not seen outside the trigger.  Changes to views do not
7545 ** affect the value of lsChange.
7546 ** The sqlite.csChange keeps track of the number of current changes (since
7547 ** the last statement) and is used to update sqlite_lsChange.
7548 **
7549 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
7550 ** store the most recent error code and, if applicable, string. The
7551 ** internal function sqlite3Error() is used to set these variables
7552 ** consistently.
7553 */
7554 struct sqlite3 {
7555   sqlite3_vfs *pVfs;            /* OS Interface */
7556   int nDb;                      /* Number of backends currently in use */
7557   Db *aDb;                      /* All backends */
7558   int flags;                    /* Miscellanous flags. See below */
7559   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
7560   int errCode;                  /* Most recent error code (SQLITE_*) */
7561   int errMask;                  /* & result codes with this before returning */
7562   u8 autoCommit;                /* The auto-commit flag. */
7563   u8 temp_store;                /* 1: file 2: memory 0: default */
7564   u8 mallocFailed;              /* True if we have seen a malloc failure */
7565   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
7566   int nTable;                   /* Number of tables in the database */
7567   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
7568   i64 lastRowid;                /* ROWID of most recent insert (see above) */
7569   i64 priorNewRowid;            /* Last randomly generated ROWID */
7570   int magic;                    /* Magic number for detect library misuse */
7571   int nChange;                  /* Value returned by sqlite3_changes() */
7572   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
7573   sqlite3_mutex *mutex;         /* Connection mutex */
7574   struct sqlite3InitInfo {      /* Information used during initialization */
7575     int iDb;                    /* When back is being initialized */
7576     int newTnum;                /* Rootpage of table being initialized */
7577     u8 busy;                    /* TRUE if currently initializing */
7578   } init;
7579   int nExtension;               /* Number of loaded extensions */
7580   void **aExtension;            /* Array of shared libraray handles */
7581   struct Vdbe *pVdbe;           /* List of active virtual machines */
7582   int activeVdbeCnt;            /* Number of vdbes currently executing */
7583   void (*xTrace)(void*,const char*);        /* Trace function */
7584   void *pTraceArg;                          /* Argument to the trace function */
7585   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
7586   void *pProfileArg;                        /* Argument to profile function */
7587   void *pCommitArg;                 /* Argument to xCommitCallback() */   
7588   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
7589   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
7590   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
7591   void *pUpdateArg;
7592   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
7593   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
7594   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
7595   void *pCollNeededArg;
7596   sqlite3_value *pErr;          /* Most recent error message */
7597   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
7598   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
7599   union {
7600     int isInterrupted;          /* True if sqlite3_interrupt has been called */
7601     double notUsed1;            /* Spacer */
7602   } u1;
7603 #ifndef SQLITE_OMIT_AUTHORIZATION
7604   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
7605                                 /* Access authorization function */
7606   void *pAuthArg;               /* 1st argument to the access auth function */
7607 #endif
7608 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
7609   int (*xProgress)(void *);     /* The progress callback */
7610   void *pProgressArg;           /* Argument to the progress callback */
7611   int nProgressOps;             /* Number of opcodes for progress callback */
7612 #endif
7613 #ifndef SQLITE_OMIT_VIRTUALTABLE
7614   Hash aModule;                 /* populated by sqlite3_create_module() */
7615   Table *pVTab;                 /* vtab with active Connect/Create method */
7616   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
7617   int nVTrans;                  /* Allocated size of aVTrans */
7618 #endif
7619   Hash aFunc;                   /* All functions that can be in SQL exprs */
7620   Hash aCollSeq;                /* All collating sequences */
7621   BusyHandler busyHandler;      /* Busy callback */
7622   int busyTimeout;              /* Busy handler timeout, in msec */
7623   Db aDbStatic[2];              /* Static space for the 2 default backends */
7624 #ifdef SQLITE_SSE
7625   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
7626 #endif
7627   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
7628 };
7629
7630 /*
7631 ** A macro to discover the encoding of a database.
7632 */
7633 #define ENC(db) ((db)->aDb[0].pSchema->enc)
7634
7635 /*
7636 ** Possible values for the sqlite.flags and or Db.flags fields.
7637 **
7638 ** On sqlite.flags, the SQLITE_InTrans value means that we have
7639 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
7640 ** transaction is active on that particular database file.
7641 */
7642 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
7643 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
7644 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
7645 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
7646 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
7647 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
7648                                           /*   DELETE, or UPDATE and return */
7649                                           /*   the count using a callback. */
7650 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
7651                                           /*   result set is empty */
7652 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
7653 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
7654 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
7655 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
7656                                           ** accessing read-only databases */
7657 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
7658 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
7659 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
7660 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
7661 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
7662
7663 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
7664 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
7665 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
7666
7667 /*
7668 ** Possible values for the sqlite.magic field.
7669 ** The numbers are obtained at random and have no special meaning, other
7670 ** than being distinct from one another.
7671 */
7672 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
7673 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
7674 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
7675 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
7676 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
7677
7678 /*
7679 ** Each SQL function is defined by an instance of the following
7680 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
7681 ** hash table.  When multiple functions have the same name, the hash table
7682 ** points to a linked list of these structures.
7683 */
7684 struct FuncDef {
7685   i16 nArg;            /* Number of arguments.  -1 means unlimited */
7686   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
7687   u8 needCollSeq;      /* True if sqlite3GetFuncCollSeq() might be called */
7688   u8 flags;            /* Some combination of SQLITE_FUNC_* */
7689   void *pUserData;     /* User data parameter */
7690   FuncDef *pNext;      /* Next function with same name */
7691   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
7692   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
7693   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
7694   char zName[1];       /* SQL name of the function.  MUST BE LAST */
7695 };
7696
7697 /*
7698 ** Each SQLite module (virtual table definition) is defined by an
7699 ** instance of the following structure, stored in the sqlite3.aModule
7700 ** hash table.
7701 */
7702 struct Module {
7703   const sqlite3_module *pModule;       /* Callback pointers */
7704   const char *zName;                   /* Name passed to create_module() */
7705   void *pAux;                          /* pAux passed to create_module() */
7706   void (*xDestroy)(void *);            /* Module destructor function */
7707 };
7708
7709 /*
7710 ** Possible values for FuncDef.flags
7711 */
7712 #define SQLITE_FUNC_LIKE   0x01  /* Candidate for the LIKE optimization */
7713 #define SQLITE_FUNC_CASE   0x02  /* Case-sensitive LIKE-type function */
7714 #define SQLITE_FUNC_EPHEM  0x04  /* Ephermeral.  Delete with VDBE */
7715
7716 /*
7717 ** information about each column of an SQL table is held in an instance
7718 ** of this structure.
7719 */
7720 struct Column {
7721   char *zName;     /* Name of this column */
7722   Expr *pDflt;     /* Default value of this column */
7723   char *zType;     /* Data type for this column */
7724   char *zColl;     /* Collating sequence.  If NULL, use the default */
7725   u8 notNull;      /* True if there is a NOT NULL constraint */
7726   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
7727   char affinity;   /* One of the SQLITE_AFF_... values */
7728 #ifndef SQLITE_OMIT_VIRTUALTABLE
7729   u8 isHidden;     /* True if this column is 'hidden' */
7730 #endif
7731 };
7732
7733 /*
7734 ** A "Collating Sequence" is defined by an instance of the following
7735 ** structure. Conceptually, a collating sequence consists of a name and
7736 ** a comparison routine that defines the order of that sequence.
7737 **
7738 ** There may two seperate implementations of the collation function, one
7739 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
7740 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
7741 ** native byte order. When a collation sequence is invoked, SQLite selects
7742 ** the version that will require the least expensive encoding
7743 ** translations, if any.
7744 **
7745 ** The CollSeq.pUser member variable is an extra parameter that passed in
7746 ** as the first argument to the UTF-8 comparison function, xCmp.
7747 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
7748 ** xCmp16.
7749 **
7750 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
7751 ** collating sequence is undefined.  Indices built on an undefined
7752 ** collating sequence may not be read or written.
7753 */
7754 struct CollSeq {
7755   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
7756   u8 enc;               /* Text encoding handled by xCmp() */
7757   u8 type;              /* One of the SQLITE_COLL_... values below */
7758   void *pUser;          /* First argument to xCmp() */
7759   int (*xCmp)(void*,int, const void*, int, const void*);
7760   void (*xDel)(void*);  /* Destructor for pUser */
7761 };
7762
7763 /*
7764 ** Allowed values of CollSeq flags:
7765 */
7766 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
7767 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
7768 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
7769 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
7770
7771 /*
7772 ** A sort order can be either ASC or DESC.
7773 */
7774 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
7775 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
7776
7777 /*
7778 ** Column affinity types.
7779 **
7780 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
7781 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
7782 ** the speed a little by number the values consecutively.  
7783 **
7784 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
7785 ** when multiple affinity types are concatenated into a string and
7786 ** used as the P4 operand, they will be more readable.
7787 **
7788 ** Note also that the numeric types are grouped together so that testing
7789 ** for a numeric type is a single comparison.
7790 */
7791 #define SQLITE_AFF_TEXT     'a'
7792 #define SQLITE_AFF_NONE     'b'
7793 #define SQLITE_AFF_NUMERIC  'c'
7794 #define SQLITE_AFF_INTEGER  'd'
7795 #define SQLITE_AFF_REAL     'e'
7796
7797 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
7798
7799 /*
7800 ** The SQLITE_AFF_MASK values masks off the significant bits of an
7801 ** affinity value. 
7802 */
7803 #define SQLITE_AFF_MASK     0x67
7804
7805 /*
7806 ** Additional bit values that can be ORed with an affinity without
7807 ** changing the affinity.
7808 */
7809 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
7810 #define SQLITE_NULLEQUAL    0x10  /* compare NULLs equal */
7811 #define SQLITE_STOREP2      0x80  /* Store result in reg[P2] rather than jump */
7812
7813 /*
7814 ** Each SQL table is represented in memory by an instance of the
7815 ** following structure.
7816 **
7817 ** Table.zName is the name of the table.  The case of the original
7818 ** CREATE TABLE statement is stored, but case is not significant for
7819 ** comparisons.
7820 **
7821 ** Table.nCol is the number of columns in this table.  Table.aCol is a
7822 ** pointer to an array of Column structures, one for each column.
7823 **
7824 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
7825 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
7826 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
7827 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
7828 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
7829 ** is generated for each row of the table.  Table.hasPrimKey is true if
7830 ** the table has any PRIMARY KEY, INTEGER or otherwise.
7831 **
7832 ** Table.tnum is the page number for the root BTree page of the table in the
7833 ** database file.  If Table.iDb is the index of the database table backend
7834 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
7835 ** holds temporary tables and indices.  If Table.isEphem
7836 ** is true, then the table is stored in a file that is automatically deleted
7837 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
7838 ** refers VDBE cursor number that holds the table open, not to the root
7839 ** page number.  Transient tables are used to hold the results of a
7840 ** sub-query that appears instead of a real table name in the FROM clause 
7841 ** of a SELECT statement.
7842 */
7843 struct Table {
7844   char *zName;     /* Name of the table */
7845   int nCol;        /* Number of columns in this table */
7846   Column *aCol;    /* Information about each column */
7847   int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
7848   Index *pIndex;   /* List of SQL indexes on this table. */
7849   int tnum;        /* Root BTree node for this table (see note above) */
7850   Select *pSelect; /* NULL for tables.  Points to definition if a view. */
7851   int nRef;          /* Number of pointers to this Table */
7852   Trigger *pTrigger; /* List of SQL triggers on this table */
7853   FKey *pFKey;       /* Linked list of all foreign keys in this table */
7854   char *zColAff;     /* String defining the affinity of each column */
7855 #ifndef SQLITE_OMIT_CHECK
7856   Expr *pCheck;      /* The AND of all CHECK constraints */
7857 #endif
7858 #ifndef SQLITE_OMIT_ALTERTABLE
7859   int addColOffset;  /* Offset in CREATE TABLE statement to add a new column */
7860 #endif
7861   u8 readOnly;     /* True if this table should not be written by the user */
7862   u8 isEphem;      /* True if created using OP_OpenEphermeral */
7863   u8 hasPrimKey;   /* True if there exists a primary key */
7864   u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
7865   u8 autoInc;      /* True if the integer primary key is autoincrement */
7866 #ifndef SQLITE_OMIT_VIRTUALTABLE
7867   u8 isVirtual;             /* True if this is a virtual table */
7868   u8 isCommit;              /* True once the CREATE TABLE has been committed */
7869   Module *pMod;             /* Pointer to the implementation of the module */
7870   sqlite3_vtab *pVtab;      /* Pointer to the module instance */
7871   int nModuleArg;           /* Number of arguments to the module */
7872   char **azModuleArg;       /* Text of all module args. [0] is module name */
7873 #endif
7874   Schema *pSchema;          /* Schema that contains this table */
7875 };
7876
7877 /*
7878 ** Test to see whether or not a table is a virtual table.  This is
7879 ** done as a macro so that it will be optimized out when virtual
7880 ** table support is omitted from the build.
7881 */
7882 #ifndef SQLITE_OMIT_VIRTUALTABLE
7883 #  define IsVirtual(X)      ((X)->isVirtual)
7884 #  define IsHiddenColumn(X) ((X)->isHidden)
7885 #else
7886 #  define IsVirtual(X)      0
7887 #  define IsHiddenColumn(X) 0
7888 #endif
7889
7890 /*
7891 ** Each foreign key constraint is an instance of the following structure.
7892 **
7893 ** A foreign key is associated with two tables.  The "from" table is
7894 ** the table that contains the REFERENCES clause that creates the foreign
7895 ** key.  The "to" table is the table that is named in the REFERENCES clause.
7896 ** Consider this example:
7897 **
7898 **     CREATE TABLE ex1(
7899 **       a INTEGER PRIMARY KEY,
7900 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
7901 **     );
7902 **
7903 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
7904 **
7905 ** Each REFERENCES clause generates an instance of the following structure
7906 ** which is attached to the from-table.  The to-table need not exist when
7907 ** the from-table is created.  The existance of the to-table is not checked
7908 ** until an attempt is made to insert data into the from-table.
7909 **
7910 ** The sqlite.aFKey hash table stores pointers to this structure
7911 ** given the name of a to-table.  For each to-table, all foreign keys
7912 ** associated with that table are on a linked list using the FKey.pNextTo
7913 ** field.
7914 */
7915 struct FKey {
7916   Table *pFrom;     /* The table that constains the REFERENCES clause */
7917   FKey *pNextFrom;  /* Next foreign key in pFrom */
7918   char *zTo;        /* Name of table that the key points to */
7919   FKey *pNextTo;    /* Next foreign key that points to zTo */
7920   int nCol;         /* Number of columns in this key */
7921   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
7922     int iFrom;         /* Index of column in pFrom */
7923     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
7924   } *aCol;          /* One entry for each of nCol column s */
7925   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
7926   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
7927   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
7928   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
7929 };
7930
7931 /*
7932 ** SQLite supports many different ways to resolve a constraint
7933 ** error.  ROLLBACK processing means that a constraint violation
7934 ** causes the operation in process to fail and for the current transaction
7935 ** to be rolled back.  ABORT processing means the operation in process
7936 ** fails and any prior changes from that one operation are backed out,
7937 ** but the transaction is not rolled back.  FAIL processing means that
7938 ** the operation in progress stops and returns an error code.  But prior
7939 ** changes due to the same operation are not backed out and no rollback
7940 ** occurs.  IGNORE means that the particular row that caused the constraint
7941 ** error is not inserted or updated.  Processing continues and no error
7942 ** is returned.  REPLACE means that preexisting database rows that caused
7943 ** a UNIQUE constraint violation are removed so that the new insert or
7944 ** update can proceed.  Processing continues and no error is reported.
7945 **
7946 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
7947 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
7948 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
7949 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
7950 ** referenced table row is propagated into the row that holds the
7951 ** foreign key.
7952 ** 
7953 ** The following symbolic values are used to record which type
7954 ** of action to take.
7955 */
7956 #define OE_None     0   /* There is no constraint to check */
7957 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
7958 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
7959 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
7960 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
7961 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
7962
7963 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
7964 #define OE_SetNull  7   /* Set the foreign key value to NULL */
7965 #define OE_SetDflt  8   /* Set the foreign key value to its default */
7966 #define OE_Cascade  9   /* Cascade the changes */
7967
7968 #define OE_Default  99  /* Do whatever the default action is */
7969
7970
7971 /*
7972 ** An instance of the following structure is passed as the first
7973 ** argument to sqlite3VdbeKeyCompare and is used to control the 
7974 ** comparison of the two index keys.
7975 **
7976 ** If the KeyInfo.incrKey value is true and the comparison would
7977 ** otherwise be equal, then return a result as if the second key
7978 ** were larger.
7979 */
7980 struct KeyInfo {
7981   sqlite3 *db;        /* The database connection */
7982   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
7983   u8 incrKey;         /* Increase 2nd key by epsilon before comparison */
7984   u8 prefixIsEqual;   /* Treat a prefix as equal */
7985   int nField;         /* Number of entries in aColl[] */
7986   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
7987   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
7988 };
7989
7990 /*
7991 ** Each SQL index is represented in memory by an
7992 ** instance of the following structure.
7993 **
7994 ** The columns of the table that are to be indexed are described
7995 ** by the aiColumn[] field of this structure.  For example, suppose
7996 ** we have the following table and index:
7997 **
7998 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
7999 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
8000 **
8001 ** In the Table structure describing Ex1, nCol==3 because there are
8002 ** three columns in the table.  In the Index structure describing
8003 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8004 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
8005 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8006 ** The second column to be indexed (c1) has an index of 0 in
8007 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8008 **
8009 ** The Index.onError field determines whether or not the indexed columns
8010 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
8011 ** it means this is not a unique index.  Otherwise it is a unique index
8012 ** and the value of Index.onError indicate the which conflict resolution 
8013 ** algorithm to employ whenever an attempt is made to insert a non-unique
8014 ** element.
8015 */
8016 struct Index {
8017   char *zName;     /* Name of this index */
8018   int nColumn;     /* Number of columns in the table used by this index */
8019   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
8020   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
8021   Table *pTable;   /* The SQL table being indexed */
8022   int tnum;        /* Page containing root of this index in database file */
8023   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
8024   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
8025   char *zColAff;   /* String defining the affinity of each column */
8026   Index *pNext;    /* The next index associated with the same table */
8027   Schema *pSchema; /* Schema containing this index */
8028   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
8029   char **azColl;   /* Array of collation sequence names for index */
8030 };
8031
8032 /*
8033 ** Each token coming out of the lexer is an instance of
8034 ** this structure.  Tokens are also used as part of an expression.
8035 **
8036 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
8037 ** may contain random values.  Do not make any assuptions about Token.dyn
8038 ** and Token.n when Token.z==0.
8039 */
8040 struct Token {
8041   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
8042   unsigned dyn  : 1;      /* True for malloced memory, false for static */
8043   unsigned n    : 31;     /* Number of characters in this token */
8044 };
8045
8046 /*
8047 ** An instance of this structure contains information needed to generate
8048 ** code for a SELECT that contains aggregate functions.
8049 **
8050 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
8051 ** pointer to this structure.  The Expr.iColumn field is the index in
8052 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
8053 ** code for that node.
8054 **
8055 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
8056 ** original Select structure that describes the SELECT statement.  These
8057 ** fields do not need to be freed when deallocating the AggInfo structure.
8058 */
8059 struct AggInfo {
8060   u8 directMode;          /* Direct rendering mode means take data directly
8061                           ** from source tables rather than from accumulators */
8062   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
8063                           ** than the source table */
8064   int sortingIdx;         /* Cursor number of the sorting index */
8065   ExprList *pGroupBy;     /* The group by clause */
8066   int nSortingColumn;     /* Number of columns in the sorting index */
8067   struct AggInfo_col {    /* For each column used in source tables */
8068     Table *pTab;             /* Source table */
8069     int iTable;              /* Cursor number of the source table */
8070     int iColumn;             /* Column number within the source table */
8071     int iSorterColumn;       /* Column number in the sorting index */
8072     int iMem;                /* Memory location that acts as accumulator */
8073     Expr *pExpr;             /* The original expression */
8074   } *aCol;
8075   int nColumn;            /* Number of used entries in aCol[] */
8076   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
8077   int nAccumulator;       /* Number of columns that show through to the output.
8078                           ** Additional columns are used only as parameters to
8079                           ** aggregate functions */
8080   struct AggInfo_func {   /* For each aggregate function */
8081     Expr *pExpr;             /* Expression encoding the function */
8082     FuncDef *pFunc;          /* The aggregate function implementation */
8083     int iMem;                /* Memory location that acts as accumulator */
8084     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
8085   } *aFunc;
8086   int nFunc;              /* Number of entries in aFunc[] */
8087   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
8088 };
8089
8090 /*
8091 ** Each node of an expression in the parse tree is an instance
8092 ** of this structure.
8093 **
8094 ** Expr.op is the opcode.  The integer parser token codes are reused
8095 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
8096 ** code representing the ">=" operator.  This same integer code is reused
8097 ** to represent the greater-than-or-equal-to operator in the expression
8098 ** tree.
8099 **
8100 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
8101 ** of argument if the expression is a function.
8102 **
8103 ** Expr.token is the operator token for this node.  For some expressions
8104 ** that have subexpressions, Expr.token can be the complete text that gave
8105 ** rise to the Expr.  In the latter case, the token is marked as being
8106 ** a compound token.
8107 **
8108 ** An expression of the form ID or ID.ID refers to a column in a table.
8109 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
8110 ** the integer cursor number of a VDBE cursor pointing to that table and
8111 ** Expr.iColumn is the column number for the specific column.  If the
8112 ** expression is used as a result in an aggregate SELECT, then the
8113 ** value is also stored in the Expr.iAgg column in the aggregate so that
8114 ** it can be accessed after all aggregates are computed.
8115 **
8116 ** If the expression is a function, the Expr.iTable is an integer code
8117 ** representing which function.  If the expression is an unbound variable
8118 ** marker (a question mark character '?' in the original SQL) then the
8119 ** Expr.iTable holds the index number for that variable.
8120 **
8121 ** If the expression is a subquery then Expr.iColumn holds an integer
8122 ** register number containing the result of the subquery.  If the
8123 ** subquery gives a constant result, then iTable is -1.  If the subquery
8124 ** gives a different answer at different times during statement processing
8125 ** then iTable is the address of a subroutine that computes the subquery.
8126 **
8127 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
8128 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
8129 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
8130 ** operand.
8131 **
8132 ** If the Expr is of type OP_Column, and the table it is selecting from
8133 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
8134 ** corresponding table definition.
8135 */
8136 struct Expr {
8137   u8 op;                 /* Operation performed by this node */
8138   char affinity;         /* The affinity of the column or 0 if not a column */
8139   u16 flags;             /* Various flags.  See below */
8140   CollSeq *pColl;        /* The collation type of the column or 0 */
8141   Expr *pLeft, *pRight;  /* Left and right subnodes */
8142   ExprList *pList;       /* A list of expressions used as function arguments
8143                          ** or in "<expr> IN (<expr-list)" */
8144   Token token;           /* An operand token */
8145   Token span;            /* Complete text of the expression */
8146   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
8147                          ** iColumn-th field of the iTable-th table. */
8148   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
8149   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
8150   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
8151   Select *pSelect;       /* When the expression is a sub-select.  Also the
8152                          ** right side of "<expr> IN (<select>)" */
8153   Table *pTab;           /* Table for OP_Column expressions. */
8154 /*  Schema *pSchema; */
8155 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
8156   int nHeight;           /* Height of the tree headed by this node */
8157 #endif
8158 };
8159
8160 /*
8161 ** The following are the meanings of bits in the Expr.flags field.
8162 */
8163 #define EP_FromJoin     0x01  /* Originated in ON or USING clause of a join */
8164 #define EP_Agg          0x02  /* Contains one or more aggregate functions */
8165 #define EP_Resolved     0x04  /* IDs have been resolved to COLUMNs */
8166 #define EP_Error        0x08  /* Expression contains one or more errors */
8167 #define EP_Distinct     0x10  /* Aggregate function with DISTINCT keyword */
8168 #define EP_VarSelect    0x20  /* pSelect is correlated, not constant */
8169 #define EP_Dequoted     0x40  /* True if the string has been dequoted */
8170 #define EP_InfixFunc    0x80  /* True for an infix function: LIKE, GLOB, etc */
8171 #define EP_ExpCollate  0x100  /* Collating sequence specified explicitly */
8172
8173 /*
8174 ** These macros can be used to test, set, or clear bits in the 
8175 ** Expr.flags field.
8176 */
8177 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
8178 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
8179 #define ExprSetProperty(E,P)     (E)->flags|=(P)
8180 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
8181
8182 /*
8183 ** A list of expressions.  Each expression may optionally have a
8184 ** name.  An expr/name combination can be used in several ways, such
8185 ** as the list of "expr AS ID" fields following a "SELECT" or in the
8186 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
8187 ** also be used as the argument to a function, in which case the a.zName
8188 ** field is not used.
8189 */
8190 struct ExprList {
8191   int nExpr;             /* Number of expressions on the list */
8192   int nAlloc;            /* Number of entries allocated below */
8193   int iECursor;          /* VDBE Cursor associated with this ExprList */
8194   struct ExprList_item {
8195     Expr *pExpr;           /* The list of expressions */
8196     char *zName;           /* Token associated with this expression */
8197     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
8198     u8 isAgg;              /* True if this is an aggregate like count(*) */
8199     u8 done;               /* A flag to indicate when processing is finished */
8200   } *a;                  /* One entry for each expression */
8201 };
8202
8203 /*
8204 ** An instance of this structure can hold a simple list of identifiers,
8205 ** such as the list "a,b,c" in the following statements:
8206 **
8207 **      INSERT INTO t(a,b,c) VALUES ...;
8208 **      CREATE INDEX idx ON t(a,b,c);
8209 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
8210 **
8211 ** The IdList.a.idx field is used when the IdList represents the list of
8212 ** column names after a table name in an INSERT statement.  In the statement
8213 **
8214 **     INSERT INTO t(a,b,c) ...
8215 **
8216 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
8217 */
8218 struct IdList {
8219   struct IdList_item {
8220     char *zName;      /* Name of the identifier */
8221     int idx;          /* Index in some Table.aCol[] of a column named zName */
8222   } *a;
8223   int nId;         /* Number of identifiers on the list */
8224   int nAlloc;      /* Number of entries allocated for a[] below */
8225 };
8226
8227 /*
8228 ** The bitmask datatype defined below is used for various optimizations.
8229 **
8230 ** Changing this from a 64-bit to a 32-bit type limits the number of
8231 ** tables in a join to 32 instead of 64.  But it also reduces the size
8232 ** of the library by 738 bytes on ix86.
8233 */
8234 typedef u64 Bitmask;
8235
8236 /*
8237 ** The following structure describes the FROM clause of a SELECT statement.
8238 ** Each table or subquery in the FROM clause is a separate element of
8239 ** the SrcList.a[] array.
8240 **
8241 ** With the addition of multiple database support, the following structure
8242 ** can also be used to describe a particular table such as the table that
8243 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
8244 ** such a table must be a simple name: ID.  But in SQLite, the table can
8245 ** now be identified by a database name, a dot, then the table name: ID.ID.
8246 **
8247 ** The jointype starts out showing the join type between the current table
8248 ** and the next table on the list.  The parser builds the list this way.
8249 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
8250 ** jointype expresses the join between the table and the previous table.
8251 */
8252 struct SrcList {
8253   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
8254   i16 nAlloc;      /* Number of entries allocated in a[] below */
8255   struct SrcList_item {
8256     char *zDatabase;  /* Name of database holding this table */
8257     char *zName;      /* Name of the table */
8258     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
8259     Table *pTab;      /* An SQL table corresponding to zName */
8260     Select *pSelect;  /* A SELECT statement used in place of a table name */
8261     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
8262     u8 jointype;      /* Type of join between this able and the previous */
8263     int iCursor;      /* The VDBE cursor number used to access this table */
8264     Expr *pOn;        /* The ON clause of a join */
8265     IdList *pUsing;   /* The USING clause of a join */
8266     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
8267   } a[1];             /* One entry for each identifier on the list */
8268 };
8269
8270 /*
8271 ** Permitted values of the SrcList.a.jointype field
8272 */
8273 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
8274 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
8275 #define JT_NATURAL   0x0004    /* True for a "natural" join */
8276 #define JT_LEFT      0x0008    /* Left outer join */
8277 #define JT_RIGHT     0x0010    /* Right outer join */
8278 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
8279 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
8280
8281 /*
8282 ** For each nested loop in a WHERE clause implementation, the WhereInfo
8283 ** structure contains a single instance of this structure.  This structure
8284 ** is intended to be private the the where.c module and should not be
8285 ** access or modified by other modules.
8286 **
8287 ** The pIdxInfo and pBestIdx fields are used to help pick the best
8288 ** index on a virtual table.  The pIdxInfo pointer contains indexing
8289 ** information for the i-th table in the FROM clause before reordering.
8290 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
8291 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
8292 ** FROM clause ordering.  This is a little confusing so I will repeat
8293 ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
8294 ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
8295 ** index information for the i-th loop of the join.  pBestInfo is always
8296 ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
8297 ** sufficient to free all of the pIdxInfo pointers.
8298 ** 
8299 */
8300 struct WhereLevel {
8301   int iFrom;            /* Which entry in the FROM clause */
8302   int flags;            /* Flags associated with this level */
8303   int iMem;             /* First memory cell used by this level */
8304   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
8305   Index *pIdx;          /* Index used.  NULL if no index */
8306   int iTabCur;          /* The VDBE cursor used to access the table */
8307   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
8308   int brk;              /* Jump here to break out of the loop */
8309   int nxt;              /* Jump here to start the next IN combination */
8310   int cont;             /* Jump here to continue with the next loop cycle */
8311   int top;              /* First instruction of interior of the loop */
8312   int op, p1, p2;       /* Opcode used to terminate the loop */
8313   int nEq;              /* Number of == or IN constraints on this loop */
8314   int nIn;              /* Number of IN operators constraining this loop */
8315   struct InLoop {
8316     int iCur;              /* The VDBE cursor used by this IN operator */
8317     int topAddr;           /* Top of the IN loop */
8318   } *aInLoop;           /* Information about each nested IN operator */
8319   sqlite3_index_info *pBestIdx;  /* Index information for this level */
8320
8321   /* The following field is really not part of the current level.  But
8322   ** we need a place to cache index information for each table in the
8323   ** FROM clause and the WhereLevel structure is a convenient place.
8324   */
8325   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
8326 };
8327
8328 #define ORDERBY_NORMAL 0
8329 #define ORDERBY_MIN    1
8330 #define ORDERBY_MAX    2
8331
8332 /*
8333 ** The WHERE clause processing routine has two halves.  The
8334 ** first part does the start of the WHERE loop and the second
8335 ** half does the tail of the WHERE loop.  An instance of
8336 ** this structure is returned by the first half and passed
8337 ** into the second half to give some continuity.
8338 */
8339 struct WhereInfo {
8340   Parse *pParse;
8341   SrcList *pTabList;   /* List of tables in the join */
8342   int iTop;            /* The very beginning of the WHERE loop */
8343   int iContinue;       /* Jump here to continue with next record */
8344   int iBreak;          /* Jump here to break out of the loop */
8345   int nLevel;          /* Number of nested loop */
8346   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
8347   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
8348 };
8349
8350 /*
8351 ** A NameContext defines a context in which to resolve table and column
8352 ** names.  The context consists of a list of tables (the pSrcList) field and
8353 ** a list of named expression (pEList).  The named expression list may
8354 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
8355 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
8356 ** pEList corresponds to the result set of a SELECT and is NULL for
8357 ** other statements.
8358 **
8359 ** NameContexts can be nested.  When resolving names, the inner-most 
8360 ** context is searched first.  If no match is found, the next outer
8361 ** context is checked.  If there is still no match, the next context
8362 ** is checked.  This process continues until either a match is found
8363 ** or all contexts are check.  When a match is found, the nRef member of
8364 ** the context containing the match is incremented. 
8365 **
8366 ** Each subquery gets a new NameContext.  The pNext field points to the
8367 ** NameContext in the parent query.  Thus the process of scanning the
8368 ** NameContext list corresponds to searching through successively outer
8369 ** subqueries looking for a match.
8370 */
8371 struct NameContext {
8372   Parse *pParse;       /* The parser */
8373   SrcList *pSrcList;   /* One or more tables used to resolve names */
8374   ExprList *pEList;    /* Optional list of named expressions */
8375   int nRef;            /* Number of names resolved by this context */
8376   int nErr;            /* Number of errors encountered while resolving names */
8377   u8 allowAgg;         /* Aggregate functions allowed here */
8378   u8 hasAgg;           /* True if aggregates are seen */
8379   u8 isCheck;          /* True if resolving names in a CHECK constraint */
8380   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
8381   AggInfo *pAggInfo;   /* Information about aggregates at this level */
8382   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
8383 };
8384
8385 /*
8386 ** An instance of the following structure contains all information
8387 ** needed to generate code for a single SELECT statement.
8388 **
8389 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
8390 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
8391 ** limit and nOffset to the value of the offset (or 0 if there is not
8392 ** offset).  But later on, nLimit and nOffset become the memory locations
8393 ** in the VDBE that record the limit and offset counters.
8394 **
8395 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
8396 ** These addresses must be stored so that we can go back and fill in
8397 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
8398 ** the number of columns in P2 can be computed at the same time
8399 ** as the OP_OpenEphm instruction is coded because not
8400 ** enough information about the compound query is known at that point.
8401 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
8402 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
8403 ** sequences for the ORDER BY clause.
8404 */
8405 struct Select {
8406   ExprList *pEList;      /* The fields of the result */
8407   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
8408   u8 isDistinct;         /* True if the DISTINCT keyword is present */
8409   u8 isResolved;         /* True once sqlite3SelectResolve() has run. */
8410   u8 isAgg;              /* True if this is an aggregate query */
8411   u8 usesEphm;           /* True if uses an OpenEphemeral opcode */
8412   u8 disallowOrderBy;    /* Do not allow an ORDER BY to be attached if TRUE */
8413   char affinity;         /* MakeRecord with this affinity for SRT_Set */
8414   SrcList *pSrc;         /* The FROM clause */
8415   Expr *pWhere;          /* The WHERE clause */
8416   ExprList *pGroupBy;    /* The GROUP BY clause */
8417   Expr *pHaving;         /* The HAVING clause */
8418   ExprList *pOrderBy;    /* The ORDER BY clause */
8419   Select *pPrior;        /* Prior select in a compound select statement */
8420   Select *pNext;         /* Next select to the left in a compound */
8421   Select *pRightmost;    /* Right-most select in a compound select statement */
8422   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
8423   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
8424   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
8425   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
8426 };
8427
8428 /*
8429 ** The results of a select can be distributed in several ways.
8430 */
8431 #define SRT_Union        1  /* Store result as keys in an index */
8432 #define SRT_Except       2  /* Remove result from a UNION index */
8433 #define SRT_Exists       3  /* Store 1 if the result is not empty */
8434 #define SRT_Discard      4  /* Do not save the results anywhere */
8435
8436 /* The ORDER BY clause is ignored for all of the above */
8437 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
8438
8439 #define SRT_Callback     5  /* Invoke a callback with each row of result */
8440 #define SRT_Mem          6  /* Store result in a memory cell */
8441 #define SRT_Set          7  /* Store non-null results as keys in an index */
8442 #define SRT_Table        8  /* Store result as data with an automatic rowid */
8443 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
8444 #define SRT_Subroutine  10  /* Call a subroutine to handle results */
8445
8446 /*
8447 ** A structure used to customize the behaviour of sqlite3Select(). See
8448 ** comments above sqlite3Select() for details.
8449 */
8450 typedef struct SelectDest SelectDest;
8451 struct SelectDest {
8452   u8 eDest;         /* How to dispose of the results */
8453   u8 affinity;      /* Affinity used when eDest==SRT_Set */
8454   int iParm;        /* A parameter used by the eDest disposal method */
8455   int iMem;         /* Base register where results are written */
8456 };
8457
8458 /*
8459 ** An SQL parser context.  A copy of this structure is passed through
8460 ** the parser and down into all the parser action routine in order to
8461 ** carry around information that is global to the entire parse.
8462 **
8463 ** The structure is divided into two parts.  When the parser and code
8464 ** generate call themselves recursively, the first part of the structure
8465 ** is constant but the second part is reset at the beginning and end of
8466 ** each recursion.
8467 **
8468 ** The nTableLock and aTableLock variables are only used if the shared-cache 
8469 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
8470 ** used to store the set of table-locks required by the statement being
8471 ** compiled. Function sqlite3TableLock() is used to add entries to the
8472 ** list.
8473 */
8474 struct Parse {
8475   sqlite3 *db;         /* The main database structure */
8476   int rc;              /* Return code from execution */
8477   char *zErrMsg;       /* An error message */
8478   Vdbe *pVdbe;         /* An engine for executing database bytecode */
8479   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
8480   u8 nameClash;        /* A permanent table name clashes with temp table name */
8481   u8 checkSchema;      /* Causes schema cookie check after an error */
8482   u8 nested;           /* Number of nested calls to the parser/code generator */
8483   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
8484   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
8485   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
8486   int aTempReg[8];     /* Holding area for temporary registers */
8487   int nRangeReg;       /* Size of the temporary register block */
8488   int iRangeReg;       /* First register in temporary register block */
8489   int nErr;            /* Number of errors seen */
8490   int nTab;            /* Number of previously allocated VDBE cursors */
8491   int nMem;            /* Number of memory cells used so far */
8492   int nSet;            /* Number of sets used so far */
8493   int ckBase;          /* Base register of data during check constraints */
8494   u32 writeMask;       /* Start a write transaction on these databases */
8495   u32 cookieMask;      /* Bitmask of schema verified databases */
8496   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
8497   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
8498 #ifndef SQLITE_OMIT_SHARED_CACHE
8499   int nTableLock;        /* Number of locks in aTableLock */
8500   TableLock *aTableLock; /* Required table locks for shared-cache mode */
8501 #endif
8502   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
8503   int regRoot;         /* Register holding root page number for new objects */
8504
8505   /* Above is constant between recursions.  Below is reset before and after
8506   ** each recursion */
8507
8508   int nVar;            /* Number of '?' variables seen in the SQL so far */
8509   int nVarExpr;        /* Number of used slots in apVarExpr[] */
8510   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
8511   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
8512   u8 explain;          /* True if the EXPLAIN flag is found on the query */
8513   Token sErrToken;     /* The token at which the error occurred */
8514   Token sNameToken;    /* Token with unqualified schema object name */
8515   Token sLastToken;    /* The last token parsed */
8516   const char *zSql;    /* All SQL text */
8517   const char *zTail;   /* All SQL text past the last semicolon parsed */
8518   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
8519   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
8520   TriggerStack *trigStack;  /* Trigger actions being coded */
8521   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
8522 #ifndef SQLITE_OMIT_VIRTUALTABLE
8523   Token sArg;                /* Complete text of a module argument */
8524   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
8525   Table *pVirtualLock;       /* Require virtual table lock on this table */
8526 #endif
8527 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
8528   int nHeight;            /* Expression tree height of current sub-select */
8529 #endif
8530 };
8531
8532 #ifdef SQLITE_OMIT_VIRTUALTABLE
8533   #define IN_DECLARE_VTAB 0
8534 #else
8535   #define IN_DECLARE_VTAB (pParse->declareVtab)
8536 #endif
8537
8538 /*
8539 ** An instance of the following structure can be declared on a stack and used
8540 ** to save the Parse.zAuthContext value so that it can be restored later.
8541 */
8542 struct AuthContext {
8543   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
8544   Parse *pParse;              /* The Parse structure */
8545 };
8546
8547 /*
8548 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
8549 */
8550 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
8551 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
8552 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
8553 #define OPFLAG_APPEND    8    /* This is likely to be an append */
8554
8555 /*
8556  * Each trigger present in the database schema is stored as an instance of
8557  * struct Trigger. 
8558  *
8559  * Pointers to instances of struct Trigger are stored in two ways.
8560  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
8561  *    database). This allows Trigger structures to be retrieved by name.
8562  * 2. All triggers associated with a single table form a linked list, using the
8563  *    pNext member of struct Trigger. A pointer to the first element of the
8564  *    linked list is stored as the "pTrigger" member of the associated
8565  *    struct Table.
8566  *
8567  * The "step_list" member points to the first element of a linked list
8568  * containing the SQL statements specified as the trigger program.
8569  */
8570 struct Trigger {
8571   char *name;             /* The name of the trigger                        */
8572   char *table;            /* The table or view to which the trigger applies */
8573   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
8574   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
8575   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
8576   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
8577                              the <column-list> is stored here */
8578   Token nameToken;        /* Token containing zName. Use during parsing only */
8579   Schema *pSchema;        /* Schema containing the trigger */
8580   Schema *pTabSchema;     /* Schema containing the table */
8581   TriggerStep *step_list; /* Link list of trigger program steps             */
8582   Trigger *pNext;         /* Next trigger associated with the table */
8583 };
8584
8585 /*
8586 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
8587 ** determine which. 
8588 **
8589 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
8590 ** In that cases, the constants below can be ORed together.
8591 */
8592 #define TRIGGER_BEFORE  1
8593 #define TRIGGER_AFTER   2
8594
8595 /*
8596  * An instance of struct TriggerStep is used to store a single SQL statement
8597  * that is a part of a trigger-program. 
8598  *
8599  * Instances of struct TriggerStep are stored in a singly linked list (linked
8600  * using the "pNext" member) referenced by the "step_list" member of the 
8601  * associated struct Trigger instance. The first element of the linked list is
8602  * the first step of the trigger-program.
8603  * 
8604  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
8605  * "SELECT" statement. The meanings of the other members is determined by the 
8606  * value of "op" as follows:
8607  *
8608  * (op == TK_INSERT)
8609  * orconf    -> stores the ON CONFLICT algorithm
8610  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
8611  *              this stores a pointer to the SELECT statement. Otherwise NULL.
8612  * target    -> A token holding the name of the table to insert into.
8613  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
8614  *              this stores values to be inserted. Otherwise NULL.
8615  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
8616  *              statement, then this stores the column-names to be
8617  *              inserted into.
8618  *
8619  * (op == TK_DELETE)
8620  * target    -> A token holding the name of the table to delete from.
8621  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
8622  *              Otherwise NULL.
8623  * 
8624  * (op == TK_UPDATE)
8625  * target    -> A token holding the name of the table to update rows of.
8626  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
8627  *              Otherwise NULL.
8628  * pExprList -> A list of the columns to update and the expressions to update
8629  *              them to. See sqlite3Update() documentation of "pChanges"
8630  *              argument.
8631  * 
8632  */
8633 struct TriggerStep {
8634   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
8635   int orconf;          /* OE_Rollback etc. */
8636   Trigger *pTrig;      /* The trigger that this step is a part of */
8637
8638   Select *pSelect;     /* Valid for SELECT and sometimes 
8639                           INSERT steps (when pExprList == 0) */
8640   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
8641   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
8642   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
8643                            INSERT steps (when pSelect == 0)         */
8644   IdList *pIdList;     /* Valid for INSERT statements only */
8645   TriggerStep *pNext;  /* Next in the link-list */
8646   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
8647 };
8648
8649 /*
8650  * An instance of struct TriggerStack stores information required during code
8651  * generation of a single trigger program. While the trigger program is being
8652  * coded, its associated TriggerStack instance is pointed to by the
8653  * "pTriggerStack" member of the Parse structure.
8654  *
8655  * The pTab member points to the table that triggers are being coded on. The 
8656  * newIdx member contains the index of the vdbe cursor that points at the temp
8657  * table that stores the new.* references. If new.* references are not valid
8658  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
8659  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
8660  *
8661  * The ON CONFLICT policy to be used for the trigger program steps is stored 
8662  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
8663  * specified for individual triggers steps is used.
8664  *
8665  * struct TriggerStack has a "pNext" member, to allow linked lists to be
8666  * constructed. When coding nested triggers (triggers fired by other triggers)
8667  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
8668  * pointer. Once the nested trigger has been coded, the pNext value is restored
8669  * to the pTriggerStack member of the Parse stucture and coding of the parent
8670  * trigger continues.
8671  *
8672  * Before a nested trigger is coded, the linked list pointed to by the 
8673  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
8674  * recursively. If this condition is detected, the nested trigger is not coded.
8675  */
8676 struct TriggerStack {
8677   Table *pTab;         /* Table that triggers are currently being coded on */
8678   int newIdx;          /* Index of vdbe cursor to "new" temp table */
8679   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
8680   u32 newColMask;
8681   u32 oldColMask;
8682   int orconf;          /* Current orconf policy */
8683   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
8684   Trigger *pTrigger;   /* The trigger currently being coded */
8685   TriggerStack *pNext; /* Next trigger down on the trigger stack */
8686 };
8687
8688 /*
8689 ** The following structure contains information used by the sqliteFix...
8690 ** routines as they walk the parse tree to make database references
8691 ** explicit.  
8692 */
8693 typedef struct DbFixer DbFixer;
8694 struct DbFixer {
8695   Parse *pParse;      /* The parsing context.  Error messages written here */
8696   const char *zDb;    /* Make sure all objects are contained in this database */
8697   const char *zType;  /* Type of the container - used for error messages */
8698   const Token *pName; /* Name of the container - used for error messages */
8699 };
8700
8701 /*
8702 ** An objected used to accumulate the text of a string where we
8703 ** do not necessarily know how big the string will be in the end.
8704 */
8705 struct StrAccum {
8706   char *zBase;     /* A base allocation.  Not from malloc. */
8707   char *zText;     /* The string collected so far */
8708   int  nChar;      /* Length of the string so far */
8709   int  nAlloc;     /* Amount of space allocated in zText */
8710   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
8711   u8   useMalloc;      /* True if zText is enlargable using realloc */
8712   u8   tooBig;         /* Becomes true if string size exceeds limits */
8713 };
8714
8715 /*
8716 ** A pointer to this structure is used to communicate information
8717 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
8718 */
8719 typedef struct {
8720   sqlite3 *db;        /* The database being initialized */
8721   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
8722   char **pzErrMsg;    /* Error message stored here */
8723   int rc;             /* Result code stored here */
8724 } InitData;
8725
8726 /*
8727 ** Assuming zIn points to the first byte of a UTF-8 character,
8728 ** advance zIn to point to the first byte of the next UTF-8 character.
8729 */
8730 #define SQLITE_SKIP_UTF8(zIn) {                        \
8731   if( (*(zIn++))>=0xc0 ){                              \
8732     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
8733   }                                                    \
8734 }
8735
8736 /*
8737 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
8738 ** builds) or a function call (for debugging).  If it is a function call,
8739 ** it allows the operator to set a breakpoint at the spot where database
8740 ** corruption is first detected.
8741 */
8742 #ifdef SQLITE_DEBUG
8743 SQLITE_PRIVATE   int sqlite3Corrupt(void);
8744 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
8745 # define DEBUGONLY(X)        X
8746 #else
8747 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
8748 # define DEBUGONLY(X)
8749 #endif
8750
8751 /*
8752 ** Internal function prototypes
8753 */
8754 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
8755 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
8756 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
8757
8758 SQLITE_PRIVATE void *sqlite3MallocZero(unsigned);
8759 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, unsigned);
8760 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, unsigned);
8761 SQLITE_PRIVATE char *sqlite3StrDup(const char*);
8762 SQLITE_PRIVATE char *sqlite3StrNDup(const char*, int);
8763 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
8764 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
8765 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
8766 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
8767 SQLITE_PRIVATE int sqlite3MallocSize(void *);
8768
8769 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
8770 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
8771 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
8772 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
8773 #endif
8774 #if defined(SQLITE_TEST)
8775 SQLITE_PRIVATE   void *sqlite3TextToPtr(const char*);
8776 #endif
8777 SQLITE_PRIVATE void sqlite3SetString(char **, ...);
8778 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
8779 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
8780 SQLITE_PRIVATE void sqlite3Dequote(char*);
8781 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
8782 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
8783 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
8784 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
8785 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
8786 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
8787 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
8788 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
8789 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
8790 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
8791 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
8792 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
8793 SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
8794 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
8795 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
8796 SQLITE_PRIVATE void sqlite3ExprDelete(Expr*);
8797 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
8798 SQLITE_PRIVATE void sqlite3ExprListDelete(ExprList*);
8799 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
8800 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
8801 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
8802 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
8803 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
8804 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
8805 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
8806 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
8807 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
8808 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
8809 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
8810 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
8811 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
8812 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
8813 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
8814 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
8815 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
8816
8817 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
8818 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
8819 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
8820 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
8821 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
8822
8823 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
8824
8825 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
8826 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
8827 #else
8828 # define sqlite3ViewGetColumnNames(A,B) 0
8829 #endif
8830
8831 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
8832 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
8833 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
8834 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
8835 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
8836 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
8837 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
8838 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*,
8839                                       Select*, Expr*, IdList*);
8840 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
8841 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
8842 SQLITE_PRIVATE void sqlite3IdListDelete(IdList*);
8843 SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList*);
8844 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
8845                         Token*, int, int);
8846 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
8847 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*, Select*, int, int*, char *aff);
8848 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
8849                          Expr*,ExprList*,int,Expr*,Expr*);
8850 SQLITE_PRIVATE void sqlite3SelectDelete(Select*);
8851 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
8852 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
8853 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
8854 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
8855 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
8856 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8);
8857 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
8858 SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int, int);
8859 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
8860 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
8861 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
8862 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int);
8863 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
8864 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
8865 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
8866 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
8867 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
8868 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
8869 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
8870 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
8871 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
8872 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
8873 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
8874 SQLITE_PRIVATE int sqlite3ExprResolveNames(NameContext *, Expr *);
8875 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
8876 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
8877 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
8878 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
8879 SQLITE_PRIVATE void sqlite3Randomness(int, void*);
8880 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
8881 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
8882 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
8883 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
8884 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
8885 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
8886 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
8887 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
8888 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
8889 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
8890 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
8891 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
8892 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int);
8893 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
8894                                      int*,int,int,int,int);
8895 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*,int,int,int,int);
8896 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
8897 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
8898 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
8899 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
8900 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
8901 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
8902 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
8903 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
8904 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
8905 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
8906 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3*);
8907 #ifdef SQLITE_DEBUG
8908 SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
8909 SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
8910 #else
8911 # define sqlite3SafetyOn(A) 0
8912 # define sqlite3SafetyOff(A) 0
8913 #endif
8914 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
8915 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
8916 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
8917 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Select*, Expr*, u32, int);
8918
8919 #ifndef SQLITE_OMIT_TRIGGER
8920 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
8921                            Expr*,int, int);
8922 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
8923 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
8924 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
8925 SQLITE_PRIVATE   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
8926 SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
8927                            int, int, u32*, u32*);
8928   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
8929 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(TriggerStep*);
8930 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
8931 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
8932                                         ExprList*,Select*,int);
8933 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
8934 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
8935 SQLITE_PRIVATE   void sqlite3DeleteTrigger(Trigger*);
8936 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
8937 SQLITE_PRIVATE   void sqlite3SelectMask(Parse *, Select *, u32);
8938 #else
8939 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
8940 # define sqlite3DeleteTrigger(A)
8941 # define sqlite3DropTriggerPtr(A,B)
8942 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
8943 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
8944 # define sqlite3SelectMask(A, B, C)
8945 #endif
8946
8947 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
8948 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
8949 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
8950 #ifndef SQLITE_OMIT_AUTHORIZATION
8951 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
8952 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
8953 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
8954 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
8955 #else
8956 # define sqlite3AuthRead(a,b,c,d)
8957 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
8958 # define sqlite3AuthContextPush(a,b,c)
8959 # define sqlite3AuthContextPop(a)  ((void)(a))
8960 #endif
8961 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
8962 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
8963 SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
8964                        int omitJournal, int nCache, int flags, Btree **ppBtree);
8965 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
8966 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
8967 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
8968 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
8969 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
8970 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
8971 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
8972 SQLITE_API char *sqlite3_snprintf(int,char*,const char*,...);
8973 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
8974 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
8975 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
8976 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
8977 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
8978 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *, u64);
8979 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *, u64 *);
8980 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *, u32 *);
8981 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
8982 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
8983 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
8984 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
8985 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
8986 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
8987 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
8988 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
8989 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
8990 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
8991 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
8992 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
8993 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
8994 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
8995 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
8996 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
8997 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
8998 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
8999 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
9000
9001 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
9002 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
9003 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
9004                         void(*)(void*));
9005 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
9006 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
9007 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
9008 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
9009 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
9010 #ifndef SQLITE_AMALGAMATION
9011 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
9012 #endif
9013 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
9014 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
9015 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
9016 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
9017 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
9018 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
9019 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
9020 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *);
9021 SQLITE_PRIVATE int sqlite3SelectResolve(Parse *, Select *, NameContext *);
9022 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
9023 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
9024 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
9025 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
9026 SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
9027 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
9028 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
9029 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
9030 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
9031 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
9032 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
9033 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
9034 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *);
9035 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
9036 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
9037 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
9038 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
9039 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
9040 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
9041   void (*)(sqlite3_context*,int,sqlite3_value **),
9042   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
9043 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
9044 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
9045
9046 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
9047 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
9048 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
9049 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
9050
9051 /*
9052 ** The interface to the LEMON-generated parser
9053 */
9054 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
9055 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
9056 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
9057
9058 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9059 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
9060 SQLITE_PRIVATE   int sqlite3AutoLoadExtensions(sqlite3*);
9061 #else
9062 # define sqlite3CloseExtensions(X)
9063 # define sqlite3AutoLoadExtensions(X)  SQLITE_OK
9064 #endif
9065
9066 #ifndef SQLITE_OMIT_SHARED_CACHE
9067 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
9068 #else
9069   #define sqlite3TableLock(v,w,x,y,z)
9070 #endif
9071
9072 #ifdef SQLITE_TEST
9073 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
9074 #endif
9075
9076 #ifdef SQLITE_OMIT_VIRTUALTABLE
9077 #  define sqlite3VtabClear(X)
9078 #  define sqlite3VtabSync(X,Y) (Y)
9079 #  define sqlite3VtabRollback(X)
9080 #  define sqlite3VtabCommit(X)
9081 #else
9082 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
9083 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, int rc);
9084 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
9085 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
9086 #endif
9087 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
9088 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
9089 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
9090 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
9091 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
9092 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
9093 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
9094 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
9095 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
9096 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
9097 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
9098 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
9099 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
9100 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, int, const char*);
9101 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
9102
9103
9104 /*
9105 ** Available fault injectors.  Should be numbered beginning with 0.
9106 */
9107 #define SQLITE_FAULTINJECTOR_MALLOC     0
9108 #define SQLITE_FAULTINJECTOR_COUNT      1
9109
9110 /*
9111 ** The interface to the fault injector subsystem.  If the fault injector
9112 ** mechanism is disabled at compile-time then set up macros so that no
9113 ** unnecessary code is generated.
9114 */
9115 #ifndef SQLITE_OMIT_FAULTINJECTOR
9116 SQLITE_PRIVATE   void sqlite3FaultConfig(int,int,int);
9117 SQLITE_PRIVATE   int sqlite3FaultFailures(int);
9118 SQLITE_PRIVATE   int sqlite3FaultBenignFailures(int);
9119 SQLITE_PRIVATE   int sqlite3FaultPending(int);
9120 SQLITE_PRIVATE   void sqlite3FaultBenign(int,int);
9121 SQLITE_PRIVATE   int sqlite3FaultStep(int);
9122 #else
9123 # define sqlite3FaultConfig(A,B,C)
9124 # define sqlite3FaultFailures(A)         0
9125 # define sqlite3FaultBenignFailures(A)   0
9126 # define sqlite3FaultPending(A)          (-1)
9127 # define sqlite3FaultBenign(A,B)
9128 # define sqlite3FaultStep(A)             0
9129 #endif
9130   
9131   
9132
9133 #define IN_INDEX_ROWID           1
9134 #define IN_INDEX_EPH             2
9135 #define IN_INDEX_INDEX           3
9136 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int);
9137
9138 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
9139 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
9140 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
9141 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
9142 #else
9143   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
9144 #endif
9145
9146 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
9147 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Expr *);
9148 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
9149 #else
9150   #define sqlite3ExprSetHeight(x)
9151 #endif
9152
9153 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
9154 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
9155
9156 #ifdef SQLITE_SSE
9157 #include "sseInt.h"
9158 #endif
9159
9160 #ifdef SQLITE_DEBUG
9161 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
9162 #endif
9163
9164 /*
9165 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
9166 ** sqlite3IoTrace is a pointer to a printf-like routine used to
9167 ** print I/O tracing messages. 
9168 */
9169 #ifdef SQLITE_ENABLE_IOTRACE
9170 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
9171 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
9172 #else
9173 # define IOTRACE(A)
9174 # define sqlite3VdbeIOTraceSql(X)
9175 #endif
9176 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
9177
9178 #endif
9179
9180 /************** End of sqliteInt.h *******************************************/
9181 /************** Begin file date.c ********************************************/
9182 /*
9183 ** 2003 October 31
9184 **
9185 ** The author disclaims copyright to this source code.  In place of
9186 ** a legal notice, here is a blessing:
9187 **
9188 **    May you do good and not evil.
9189 **    May you find forgiveness for yourself and forgive others.
9190 **    May you share freely, never taking more than you give.
9191 **
9192 *************************************************************************
9193 ** This file contains the C functions that implement date and time
9194 ** functions for SQLite.  
9195 **
9196 ** There is only one exported symbol in this file - the function
9197 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
9198 ** All other code has file scope.
9199 **
9200 ** $Id: date.c,v 1.76 2008/02/21 20:40:44 drh Exp $
9201 **
9202 ** SQLite processes all times and dates as Julian Day numbers.  The
9203 ** dates and times are stored as the number of days since noon
9204 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
9205 ** calendar system. 
9206 **
9207 ** 1970-01-01 00:00:00 is JD 2440587.5
9208 ** 2000-01-01 00:00:00 is JD 2451544.5
9209 **
9210 ** This implemention requires years to be expressed as a 4-digit number
9211 ** which means that only dates between 0000-01-01 and 9999-12-31 can
9212 ** be represented, even though julian day numbers allow a much wider
9213 ** range of dates.
9214 **
9215 ** The Gregorian calendar system is used for all dates and times,
9216 ** even those that predate the Gregorian calendar.  Historians usually
9217 ** use the Julian calendar for dates prior to 1582-10-15 and for some
9218 ** dates afterwards, depending on locale.  Beware of this difference.
9219 **
9220 ** The conversion algorithms are implemented based on descriptions
9221 ** in the following text:
9222 **
9223 **      Jean Meeus
9224 **      Astronomical Algorithms, 2nd Edition, 1998
9225 **      ISBM 0-943396-61-1
9226 **      Willmann-Bell, Inc
9227 **      Richmond, Virginia (USA)
9228 */
9229 #include <ctype.h>
9230 #include <time.h>
9231
9232 #ifndef SQLITE_OMIT_DATETIME_FUNCS
9233
9234 /*
9235 ** A structure for holding a single date and time.
9236 */
9237 typedef struct DateTime DateTime;
9238 struct DateTime {
9239   double rJD;      /* The julian day number */
9240   int Y, M, D;     /* Year, month, and day */
9241   int h, m;        /* Hour and minutes */
9242   int tz;          /* Timezone offset in minutes */
9243   double s;        /* Seconds */
9244   char validYMD;   /* True if Y,M,D are valid */
9245   char validHMS;   /* True if h,m,s are valid */
9246   char validJD;    /* True if rJD is valid */
9247   char validTZ;    /* True if tz is valid */
9248 };
9249
9250
9251 /*
9252 ** Convert zDate into one or more integers.  Additional arguments
9253 ** come in groups of 5 as follows:
9254 **
9255 **       N       number of digits in the integer
9256 **       min     minimum allowed value of the integer
9257 **       max     maximum allowed value of the integer
9258 **       nextC   first character after the integer
9259 **       pVal    where to write the integers value.
9260 **
9261 ** Conversions continue until one with nextC==0 is encountered.
9262 ** The function returns the number of successful conversions.
9263 */
9264 static int getDigits(const char *zDate, ...){
9265   va_list ap;
9266   int val;
9267   int N;
9268   int min;
9269   int max;
9270   int nextC;
9271   int *pVal;
9272   int cnt = 0;
9273   va_start(ap, zDate);
9274   do{
9275     N = va_arg(ap, int);
9276     min = va_arg(ap, int);
9277     max = va_arg(ap, int);
9278     nextC = va_arg(ap, int);
9279     pVal = va_arg(ap, int*);
9280     val = 0;
9281     while( N-- ){
9282       if( !isdigit(*(u8*)zDate) ){
9283         goto end_getDigits;
9284       }
9285       val = val*10 + *zDate - '0';
9286       zDate++;
9287     }
9288     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
9289       goto end_getDigits;
9290     }
9291     *pVal = val;
9292     zDate++;
9293     cnt++;
9294   }while( nextC );
9295 end_getDigits:
9296   va_end(ap);
9297   return cnt;
9298 }
9299
9300 /*
9301 ** Read text from z[] and convert into a floating point number.  Return
9302 ** the number of digits converted.
9303 */
9304 #define getValue sqlite3AtoF
9305
9306 /*
9307 ** Parse a timezone extension on the end of a date-time.
9308 ** The extension is of the form:
9309 **
9310 **        (+/-)HH:MM
9311 **
9312 ** Or the "zulu" notation:
9313 **
9314 **        Z
9315 **
9316 ** If the parse is successful, write the number of minutes
9317 ** of change in p->tz and return 0.  If a parser error occurs,
9318 ** return non-zero.
9319 **
9320 ** A missing specifier is not considered an error.
9321 */
9322 static int parseTimezone(const char *zDate, DateTime *p){
9323   int sgn = 0;
9324   int nHr, nMn;
9325   int c;
9326   while( isspace(*(u8*)zDate) ){ zDate++; }
9327   p->tz = 0;
9328   c = *zDate;
9329   if( c=='-' ){
9330     sgn = -1;
9331   }else if( c=='+' ){
9332     sgn = +1;
9333   }else if( c=='Z' || c=='z' ){
9334     zDate++;
9335     goto zulu_time;
9336   }else{
9337     return c!=0;
9338   }
9339   zDate++;
9340   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
9341     return 1;
9342   }
9343   zDate += 5;
9344   p->tz = sgn*(nMn + nHr*60);
9345 zulu_time:
9346   while( isspace(*(u8*)zDate) ){ zDate++; }
9347   return *zDate!=0;
9348 }
9349
9350 /*
9351 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
9352 ** The HH, MM, and SS must each be exactly 2 digits.  The
9353 ** fractional seconds FFFF can be one or more digits.
9354 **
9355 ** Return 1 if there is a parsing error and 0 on success.
9356 */
9357 static int parseHhMmSs(const char *zDate, DateTime *p){
9358   int h, m, s;
9359   double ms = 0.0;
9360   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
9361     return 1;
9362   }
9363   zDate += 5;
9364   if( *zDate==':' ){
9365     zDate++;
9366     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
9367       return 1;
9368     }
9369     zDate += 2;
9370     if( *zDate=='.' && isdigit((u8)zDate[1]) ){
9371       double rScale = 1.0;
9372       zDate++;
9373       while( isdigit(*(u8*)zDate) ){
9374         ms = ms*10.0 + *zDate - '0';
9375         rScale *= 10.0;
9376         zDate++;
9377       }
9378       ms /= rScale;
9379     }
9380   }else{
9381     s = 0;
9382   }
9383   p->validJD = 0;
9384   p->validHMS = 1;
9385   p->h = h;
9386   p->m = m;
9387   p->s = s + ms;
9388   if( parseTimezone(zDate, p) ) return 1;
9389   p->validTZ = p->tz!=0;
9390   return 0;
9391 }
9392
9393 /*
9394 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
9395 ** that the YYYY-MM-DD is according to the Gregorian calendar.
9396 **
9397 ** Reference:  Meeus page 61
9398 */
9399 static void computeJD(DateTime *p){
9400   int Y, M, D, A, B, X1, X2;
9401
9402   if( p->validJD ) return;
9403   if( p->validYMD ){
9404     Y = p->Y;
9405     M = p->M;
9406     D = p->D;
9407   }else{
9408     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
9409     M = 1;
9410     D = 1;
9411   }
9412   if( M<=2 ){
9413     Y--;
9414     M += 12;
9415   }
9416   A = Y/100;
9417   B = 2 - A + (A/4);
9418   X1 = 365.25*(Y+4716);
9419   X2 = 30.6001*(M+1);
9420   p->rJD = X1 + X2 + D + B - 1524.5;
9421   p->validJD = 1;
9422   if( p->validHMS ){
9423     p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
9424     if( p->validTZ ){
9425       p->rJD -= p->tz*60/86400.0;
9426       p->validYMD = 0;
9427       p->validHMS = 0;
9428       p->validTZ = 0;
9429     }
9430   }
9431 }
9432
9433 /*
9434 ** Parse dates of the form
9435 **
9436 **     YYYY-MM-DD HH:MM:SS.FFF
9437 **     YYYY-MM-DD HH:MM:SS
9438 **     YYYY-MM-DD HH:MM
9439 **     YYYY-MM-DD
9440 **
9441 ** Write the result into the DateTime structure and return 0
9442 ** on success and 1 if the input string is not a well-formed
9443 ** date.
9444 */
9445 static int parseYyyyMmDd(const char *zDate, DateTime *p){
9446   int Y, M, D, neg;
9447
9448   if( zDate[0]=='-' ){
9449     zDate++;
9450     neg = 1;
9451   }else{
9452     neg = 0;
9453   }
9454   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
9455     return 1;
9456   }
9457   zDate += 10;
9458   while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
9459   if( parseHhMmSs(zDate, p)==0 ){
9460     /* We got the time */
9461   }else if( *zDate==0 ){
9462     p->validHMS = 0;
9463   }else{
9464     return 1;
9465   }
9466   p->validJD = 0;
9467   p->validYMD = 1;
9468   p->Y = neg ? -Y : Y;
9469   p->M = M;
9470   p->D = D;
9471   if( p->validTZ ){
9472     computeJD(p);
9473   }
9474   return 0;
9475 }
9476
9477 /*
9478 ** Attempt to parse the given string into a Julian Day Number.  Return
9479 ** the number of errors.
9480 **
9481 ** The following are acceptable forms for the input string:
9482 **
9483 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
9484 **      DDDD.DD 
9485 **      now
9486 **
9487 ** In the first form, the +/-HH:MM is always optional.  The fractional
9488 ** seconds extension (the ".FFF") is optional.  The seconds portion
9489 ** (":SS.FFF") is option.  The year and date can be omitted as long
9490 ** as there is a time string.  The time string can be omitted as long
9491 ** as there is a year and date.
9492 */
9493 static int parseDateOrTime(
9494   sqlite3_context *context, 
9495   const char *zDate, 
9496   DateTime *p
9497 ){
9498   memset(p, 0, sizeof(*p));
9499   if( parseYyyyMmDd(zDate,p)==0 ){
9500     return 0;
9501   }else if( parseHhMmSs(zDate, p)==0 ){
9502     return 0;
9503   }else if( sqlite3StrICmp(zDate,"now")==0){
9504     double r;
9505     sqlite3OsCurrentTime((sqlite3_vfs *)sqlite3_user_data(context), &r);
9506     p->rJD = r;
9507     p->validJD = 1;
9508     return 0;
9509   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
9510     getValue(zDate, &p->rJD);
9511     p->validJD = 1;
9512     return 0;
9513   }
9514   return 1;
9515 }
9516
9517 /*
9518 ** Compute the Year, Month, and Day from the julian day number.
9519 */
9520 static void computeYMD(DateTime *p){
9521   int Z, A, B, C, D, E, X1;
9522   if( p->validYMD ) return;
9523   if( !p->validJD ){
9524     p->Y = 2000;
9525     p->M = 1;
9526     p->D = 1;
9527   }else{
9528     Z = p->rJD + 0.5;
9529     A = (Z - 1867216.25)/36524.25;
9530     A = Z + 1 + A - (A/4);
9531     B = A + 1524;
9532     C = (B - 122.1)/365.25;
9533     D = 365.25*C;
9534     E = (B-D)/30.6001;
9535     X1 = 30.6001*E;
9536     p->D = B - D - X1;
9537     p->M = E<14 ? E-1 : E-13;
9538     p->Y = p->M>2 ? C - 4716 : C - 4715;
9539   }
9540   p->validYMD = 1;
9541 }
9542
9543 /*
9544 ** Compute the Hour, Minute, and Seconds from the julian day number.
9545 */
9546 static void computeHMS(DateTime *p){
9547   int Z, s;
9548   if( p->validHMS ) return;
9549   computeJD(p);
9550   Z = p->rJD + 0.5;
9551   s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
9552   p->s = 0.001*s;
9553   s = p->s;
9554   p->s -= s;
9555   p->h = s/3600;
9556   s -= p->h*3600;
9557   p->m = s/60;
9558   p->s += s - p->m*60;
9559   p->validHMS = 1;
9560 }
9561
9562 /*
9563 ** Compute both YMD and HMS
9564 */
9565 static void computeYMD_HMS(DateTime *p){
9566   computeYMD(p);
9567   computeHMS(p);
9568 }
9569
9570 /*
9571 ** Clear the YMD and HMS and the TZ
9572 */
9573 static void clearYMD_HMS_TZ(DateTime *p){
9574   p->validYMD = 0;
9575   p->validHMS = 0;
9576   p->validTZ = 0;
9577 }
9578
9579 /*
9580 ** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
9581 ** for the time value p where p is in UTC.
9582 */
9583 static double localtimeOffset(DateTime *p){
9584   DateTime x, y;
9585   time_t t;
9586   x = *p;
9587   computeYMD_HMS(&x);
9588   if( x.Y<1971 || x.Y>=2038 ){
9589     x.Y = 2000;
9590     x.M = 1;
9591     x.D = 1;
9592     x.h = 0;
9593     x.m = 0;
9594     x.s = 0.0;
9595   } else {
9596     int s = x.s + 0.5;
9597     x.s = s;
9598   }
9599   x.tz = 0;
9600   x.validJD = 0;
9601   computeJD(&x);
9602   t = (x.rJD-2440587.5)*86400.0 + 0.5;
9603 #ifdef HAVE_LOCALTIME_R
9604   {
9605     struct tm sLocal;
9606     localtime_r(&t, &sLocal);
9607     y.Y = sLocal.tm_year + 1900;
9608     y.M = sLocal.tm_mon + 1;
9609     y.D = sLocal.tm_mday;
9610     y.h = sLocal.tm_hour;
9611     y.m = sLocal.tm_min;
9612     y.s = sLocal.tm_sec;
9613   }
9614 #else
9615   {
9616     struct tm *pTm;
9617     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
9618     pTm = localtime(&t);
9619     y.Y = pTm->tm_year + 1900;
9620     y.M = pTm->tm_mon + 1;
9621     y.D = pTm->tm_mday;
9622     y.h = pTm->tm_hour;
9623     y.m = pTm->tm_min;
9624     y.s = pTm->tm_sec;
9625     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
9626   }
9627 #endif
9628   y.validYMD = 1;
9629   y.validHMS = 1;
9630   y.validJD = 0;
9631   y.validTZ = 0;
9632   computeJD(&y);
9633   return y.rJD - x.rJD;
9634 }
9635
9636 /*
9637 ** Process a modifier to a date-time stamp.  The modifiers are
9638 ** as follows:
9639 **
9640 **     NNN days
9641 **     NNN hours
9642 **     NNN minutes
9643 **     NNN.NNNN seconds
9644 **     NNN months
9645 **     NNN years
9646 **     start of month
9647 **     start of year
9648 **     start of week
9649 **     start of day
9650 **     weekday N
9651 **     unixepoch
9652 **     localtime
9653 **     utc
9654 **
9655 ** Return 0 on success and 1 if there is any kind of error.
9656 */
9657 static int parseModifier(const char *zMod, DateTime *p){
9658   int rc = 1;
9659   int n;
9660   double r;
9661   char *z, zBuf[30];
9662   z = zBuf;
9663   for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
9664     z[n] = tolower(zMod[n]);
9665   }
9666   z[n] = 0;
9667   switch( z[0] ){
9668     case 'l': {
9669       /*    localtime
9670       **
9671       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
9672       ** show local time.
9673       */
9674       if( strcmp(z, "localtime")==0 ){
9675         computeJD(p);
9676         p->rJD += localtimeOffset(p);
9677         clearYMD_HMS_TZ(p);
9678         rc = 0;
9679       }
9680       break;
9681     }
9682     case 'u': {
9683       /*
9684       **    unixepoch
9685       **
9686       ** Treat the current value of p->rJD as the number of
9687       ** seconds since 1970.  Convert to a real julian day number.
9688       */
9689       if( strcmp(z, "unixepoch")==0 && p->validJD ){
9690         p->rJD = p->rJD/86400.0 + 2440587.5;
9691         clearYMD_HMS_TZ(p);
9692         rc = 0;
9693       }else if( strcmp(z, "utc")==0 ){
9694         double c1;
9695         computeJD(p);
9696         c1 = localtimeOffset(p);
9697         p->rJD -= c1;
9698         clearYMD_HMS_TZ(p);
9699         p->rJD += c1 - localtimeOffset(p);
9700         rc = 0;
9701       }
9702       break;
9703     }
9704     case 'w': {
9705       /*
9706       **    weekday N
9707       **
9708       ** Move the date to the same time on the next occurrence of
9709       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
9710       ** date is already on the appropriate weekday, this is a no-op.
9711       */
9712       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
9713                  && (n=r)==r && n>=0 && r<7 ){
9714         int Z;
9715         computeYMD_HMS(p);
9716         p->validTZ = 0;
9717         p->validJD = 0;
9718         computeJD(p);
9719         Z = p->rJD + 1.5;
9720         Z %= 7;
9721         if( Z>n ) Z -= 7;
9722         p->rJD += n - Z;
9723         clearYMD_HMS_TZ(p);
9724         rc = 0;
9725       }
9726       break;
9727     }
9728     case 's': {
9729       /*
9730       **    start of TTTTT
9731       **
9732       ** Move the date backwards to the beginning of the current day,
9733       ** or month or year.
9734       */
9735       if( strncmp(z, "start of ", 9)!=0 ) break;
9736       z += 9;
9737       computeYMD(p);
9738       p->validHMS = 1;
9739       p->h = p->m = 0;
9740       p->s = 0.0;
9741       p->validTZ = 0;
9742       p->validJD = 0;
9743       if( strcmp(z,"month")==0 ){
9744         p->D = 1;
9745         rc = 0;
9746       }else if( strcmp(z,"year")==0 ){
9747         computeYMD(p);
9748         p->M = 1;
9749         p->D = 1;
9750         rc = 0;
9751       }else if( strcmp(z,"day")==0 ){
9752         rc = 0;
9753       }
9754       break;
9755     }
9756     case '+':
9757     case '-':
9758     case '0':
9759     case '1':
9760     case '2':
9761     case '3':
9762     case '4':
9763     case '5':
9764     case '6':
9765     case '7':
9766     case '8':
9767     case '9': {
9768       n = getValue(z, &r);
9769       assert( n>=1 );
9770       if( z[n]==':' ){
9771         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
9772         ** specified number of hours, minutes, seconds, and fractional seconds
9773         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
9774         ** omitted.
9775         */
9776         const char *z2 = z;
9777         DateTime tx;
9778         int day;
9779         if( !isdigit(*(u8*)z2) ) z2++;
9780         memset(&tx, 0, sizeof(tx));
9781         if( parseHhMmSs(z2, &tx) ) break;
9782         computeJD(&tx);
9783         tx.rJD -= 0.5;
9784         day = (int)tx.rJD;
9785         tx.rJD -= day;
9786         if( z[0]=='-' ) tx.rJD = -tx.rJD;
9787         computeJD(p);
9788         clearYMD_HMS_TZ(p);
9789         p->rJD += tx.rJD;
9790         rc = 0;
9791         break;
9792       }
9793       z += n;
9794       while( isspace(*(u8*)z) ) z++;
9795       n = strlen(z);
9796       if( n>10 || n<3 ) break;
9797       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
9798       computeJD(p);
9799       rc = 0;
9800       if( n==3 && strcmp(z,"day")==0 ){
9801         p->rJD += r;
9802       }else if( n==4 && strcmp(z,"hour")==0 ){
9803         p->rJD += r/24.0;
9804       }else if( n==6 && strcmp(z,"minute")==0 ){
9805         p->rJD += r/(24.0*60.0);
9806       }else if( n==6 && strcmp(z,"second")==0 ){
9807         p->rJD += r/(24.0*60.0*60.0);
9808       }else if( n==5 && strcmp(z,"month")==0 ){
9809         int x, y;
9810         computeYMD_HMS(p);
9811         p->M += r;
9812         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
9813         p->Y += x;
9814         p->M -= x*12;
9815         p->validJD = 0;
9816         computeJD(p);
9817         y = r;
9818         if( y!=r ){
9819           p->rJD += (r - y)*30.0;
9820         }
9821       }else if( n==4 && strcmp(z,"year")==0 ){
9822         computeYMD_HMS(p);
9823         p->Y += r;
9824         p->validJD = 0;
9825         computeJD(p);
9826       }else{
9827         rc = 1;
9828       }
9829       clearYMD_HMS_TZ(p);
9830       break;
9831     }
9832     default: {
9833       break;
9834     }
9835   }
9836   return rc;
9837 }
9838
9839 /*
9840 ** Process time function arguments.  argv[0] is a date-time stamp.
9841 ** argv[1] and following are modifiers.  Parse them all and write
9842 ** the resulting time into the DateTime structure p.  Return 0
9843 ** on success and 1 if there are any errors.
9844 **
9845 ** If there are zero parameters (if even argv[0] is undefined)
9846 ** then assume a default value of "now" for argv[0].
9847 */
9848 static int isDate(
9849   sqlite3_context *context, 
9850   int argc, 
9851   sqlite3_value **argv, 
9852   DateTime *p
9853 ){
9854   int i;
9855   const unsigned char *z;
9856   static const unsigned char zDflt[] = "now";
9857   if( argc==0 ){
9858     z = zDflt;
9859   }else{
9860     z = sqlite3_value_text(argv[0]);
9861   }
9862   if( !z || parseDateOrTime(context, (char*)z, p) ){
9863     return 1;
9864   }
9865   for(i=1; i<argc; i++){
9866     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
9867       return 1;
9868     }
9869   }
9870   return 0;
9871 }
9872
9873
9874 /*
9875 ** The following routines implement the various date and time functions
9876 ** of SQLite.
9877 */
9878
9879 /*
9880 **    julianday( TIMESTRING, MOD, MOD, ...)
9881 **
9882 ** Return the julian day number of the date specified in the arguments
9883 */
9884 static void juliandayFunc(
9885   sqlite3_context *context,
9886   int argc,
9887   sqlite3_value **argv
9888 ){
9889   DateTime x;
9890   if( isDate(context, argc, argv, &x)==0 ){
9891     computeJD(&x);
9892     sqlite3_result_double(context, x.rJD);
9893   }
9894 }
9895
9896 /*
9897 **    datetime( TIMESTRING, MOD, MOD, ...)
9898 **
9899 ** Return YYYY-MM-DD HH:MM:SS
9900 */
9901 static void datetimeFunc(
9902   sqlite3_context *context,
9903   int argc,
9904   sqlite3_value **argv
9905 ){
9906   DateTime x;
9907   if( isDate(context, argc, argv, &x)==0 ){
9908     char zBuf[100];
9909     computeYMD_HMS(&x);
9910     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
9911                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
9912     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
9913   }
9914 }
9915
9916 /*
9917 **    time( TIMESTRING, MOD, MOD, ...)
9918 **
9919 ** Return HH:MM:SS
9920 */
9921 static void timeFunc(
9922   sqlite3_context *context,
9923   int argc,
9924   sqlite3_value **argv
9925 ){
9926   DateTime x;
9927   if( isDate(context, argc, argv, &x)==0 ){
9928     char zBuf[100];
9929     computeHMS(&x);
9930     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
9931     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
9932   }
9933 }
9934
9935 /*
9936 **    date( TIMESTRING, MOD, MOD, ...)
9937 **
9938 ** Return YYYY-MM-DD
9939 */
9940 static void dateFunc(
9941   sqlite3_context *context,
9942   int argc,
9943   sqlite3_value **argv
9944 ){
9945   DateTime x;
9946   if( isDate(context, argc, argv, &x)==0 ){
9947     char zBuf[100];
9948     computeYMD(&x);
9949     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
9950     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
9951   }
9952 }
9953
9954 /*
9955 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
9956 **
9957 ** Return a string described by FORMAT.  Conversions as follows:
9958 **
9959 **   %d  day of month
9960 **   %f  ** fractional seconds  SS.SSS
9961 **   %H  hour 00-24
9962 **   %j  day of year 000-366
9963 **   %J  ** Julian day number
9964 **   %m  month 01-12
9965 **   %M  minute 00-59
9966 **   %s  seconds since 1970-01-01
9967 **   %S  seconds 00-59
9968 **   %w  day of week 0-6  sunday==0
9969 **   %W  week of year 00-53
9970 **   %Y  year 0000-9999
9971 **   %%  %
9972 */
9973 static void strftimeFunc(
9974   sqlite3_context *context,
9975   int argc,
9976   sqlite3_value **argv
9977 ){
9978   DateTime x;
9979   u64 n;
9980   int i, j;
9981   char *z;
9982   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
9983   char zBuf[100];
9984   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
9985   for(i=0, n=1; zFmt[i]; i++, n++){
9986     if( zFmt[i]=='%' ){
9987       switch( zFmt[i+1] ){
9988         case 'd':
9989         case 'H':
9990         case 'm':
9991         case 'M':
9992         case 'S':
9993         case 'W':
9994           n++;
9995           /* fall thru */
9996         case 'w':
9997         case '%':
9998           break;
9999         case 'f':
10000           n += 8;
10001           break;
10002         case 'j':
10003           n += 3;
10004           break;
10005         case 'Y':
10006           n += 8;
10007           break;
10008         case 's':
10009         case 'J':
10010           n += 50;
10011           break;
10012         default:
10013           return;  /* ERROR.  return a NULL */
10014       }
10015       i++;
10016     }
10017   }
10018   if( n<sizeof(zBuf) ){
10019     z = zBuf;
10020   }else if( n>SQLITE_MAX_LENGTH ){
10021     sqlite3_result_error_toobig(context);
10022     return;
10023   }else{
10024     z = sqlite3_malloc( n );
10025     if( z==0 ){
10026       sqlite3_result_error_nomem(context);
10027       return;
10028     }
10029   }
10030   computeJD(&x);
10031   computeYMD_HMS(&x);
10032   for(i=j=0; zFmt[i]; i++){
10033     if( zFmt[i]!='%' ){
10034       z[j++] = zFmt[i];
10035     }else{
10036       i++;
10037       switch( zFmt[i] ){
10038         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
10039         case 'f': {
10040           double s = x.s;
10041           if( s>59.999 ) s = 59.999;
10042           sqlite3_snprintf(7, &z[j],"%06.3f", s);
10043           j += strlen(&z[j]);
10044           break;
10045         }
10046         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
10047         case 'W': /* Fall thru */
10048         case 'j': {
10049           int nDay;             /* Number of days since 1st day of year */
10050           DateTime y = x;
10051           y.validJD = 0;
10052           y.M = 1;
10053           y.D = 1;
10054           computeJD(&y);
10055           nDay = x.rJD - y.rJD + 0.5;
10056           if( zFmt[i]=='W' ){
10057             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
10058             wd = ((int)(x.rJD+0.5)) % 7;
10059             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
10060             j += 2;
10061           }else{
10062             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
10063             j += 3;
10064           }
10065           break;
10066         }
10067         case 'J': {
10068           sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
10069           j+=strlen(&z[j]);
10070           break;
10071         }
10072         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
10073         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
10074         case 's': {
10075           sqlite3_snprintf(30,&z[j],"%d",
10076                            (int)((x.rJD-2440587.5)*86400.0 + 0.5));
10077           j += strlen(&z[j]);
10078           break;
10079         }
10080         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
10081         case 'w':  z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
10082         case 'Y':  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
10083         default:   z[j++] = '%'; break;
10084       }
10085     }
10086   }
10087   z[j] = 0;
10088   sqlite3_result_text(context, z, -1,
10089                       z==zBuf ? SQLITE_TRANSIENT : sqlite3_free);
10090 }
10091
10092 /*
10093 ** current_time()
10094 **
10095 ** This function returns the same value as time('now').
10096 */
10097 static void ctimeFunc(
10098   sqlite3_context *context,
10099   int argc,
10100   sqlite3_value **argv
10101 ){
10102   timeFunc(context, 0, 0);
10103 }
10104
10105 /*
10106 ** current_date()
10107 **
10108 ** This function returns the same value as date('now').
10109 */
10110 static void cdateFunc(
10111   sqlite3_context *context,
10112   int argc,
10113   sqlite3_value **argv
10114 ){
10115   dateFunc(context, 0, 0);
10116 }
10117
10118 /*
10119 ** current_timestamp()
10120 **
10121 ** This function returns the same value as datetime('now').
10122 */
10123 static void ctimestampFunc(
10124   sqlite3_context *context,
10125   int argc,
10126   sqlite3_value **argv
10127 ){
10128   datetimeFunc(context, 0, 0);
10129 }
10130 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
10131
10132 #ifdef SQLITE_OMIT_DATETIME_FUNCS
10133 /*
10134 ** If the library is compiled to omit the full-scale date and time
10135 ** handling (to get a smaller binary), the following minimal version
10136 ** of the functions current_time(), current_date() and current_timestamp()
10137 ** are included instead. This is to support column declarations that
10138 ** include "DEFAULT CURRENT_TIME" etc.
10139 **
10140 ** This function uses the C-library functions time(), gmtime()
10141 ** and strftime(). The format string to pass to strftime() is supplied
10142 ** as the user-data for the function.
10143 */
10144 static void currentTimeFunc(
10145   sqlite3_context *context,
10146   int argc,
10147   sqlite3_value **argv
10148 ){
10149   time_t t;
10150   char *zFormat = (char *)sqlite3_user_data(context);
10151   char zBuf[20];
10152
10153   time(&t);
10154 #ifdef SQLITE_TEST
10155   {
10156     extern int sqlite3_current_time;  /* See os_XXX.c */
10157     if( sqlite3_current_time ){
10158       t = sqlite3_current_time;
10159     }
10160   }
10161 #endif
10162
10163 #ifdef HAVE_GMTIME_R
10164   {
10165     struct tm sNow;
10166     gmtime_r(&t, &sNow);
10167     strftime(zBuf, 20, zFormat, &sNow);
10168   }
10169 #else
10170   {
10171     struct tm *pTm;
10172     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
10173     pTm = gmtime(&t);
10174     strftime(zBuf, 20, zFormat, pTm);
10175     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
10176   }
10177 #endif
10178
10179   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
10180 }
10181 #endif
10182
10183 /*
10184 ** This function registered all of the above C functions as SQL
10185 ** functions.  This should be the only routine in this file with
10186 ** external linkage.
10187 */
10188 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
10189 #ifndef SQLITE_OMIT_DATETIME_FUNCS
10190   static const struct {
10191      char *zName;
10192      int nArg;
10193      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
10194   } aFuncs[] = {
10195     { "julianday", -1, juliandayFunc   },
10196     { "date",      -1, dateFunc        },
10197     { "time",      -1, timeFunc        },
10198     { "datetime",  -1, datetimeFunc    },
10199     { "strftime",  -1, strftimeFunc    },
10200     { "current_time",       0, ctimeFunc      },
10201     { "current_timestamp",  0, ctimestampFunc },
10202     { "current_date",       0, cdateFunc      },
10203   };
10204   int i;
10205
10206   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
10207     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
10208         SQLITE_UTF8, (void *)(db->pVfs), aFuncs[i].xFunc, 0, 0);
10209   }
10210 #else
10211   static const struct {
10212      char *zName;
10213      char *zFormat;
10214   } aFuncs[] = {
10215     { "current_time", "%H:%M:%S" },
10216     { "current_date", "%Y-%m-%d" },
10217     { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
10218   };
10219   int i;
10220
10221   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
10222     sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8, 
10223         aFuncs[i].zFormat, currentTimeFunc, 0, 0);
10224   }
10225 #endif
10226 }
10227
10228 /************** End of date.c ************************************************/
10229 /************** Begin file os.c **********************************************/
10230 /*
10231 ** 2005 November 29
10232 **
10233 ** The author disclaims copyright to this source code.  In place of
10234 ** a legal notice, here is a blessing:
10235 **
10236 **    May you do good and not evil.
10237 **    May you find forgiveness for yourself and forgive others.
10238 **    May you share freely, never taking more than you give.
10239 **
10240 ******************************************************************************
10241 **
10242 ** This file contains OS interface code that is common to all
10243 ** architectures.
10244 */
10245 #define _SQLITE_OS_C_ 1
10246 #undef _SQLITE_OS_C_
10247
10248 /*
10249 ** The default SQLite sqlite3_vfs implementations do not allocate
10250 ** memory (actually, os_unix.c allocates a small amount of memory
10251 ** from within OsOpen()), but some third-party implementations may.
10252 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
10253 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
10254 **
10255 ** The following functions are instrumented for malloc() failure 
10256 ** testing:
10257 **
10258 **     sqlite3OsOpen()
10259 **     sqlite3OsRead()
10260 **     sqlite3OsWrite()
10261 **     sqlite3OsSync()
10262 **     sqlite3OsLock()
10263 **
10264 */
10265 #ifdef SQLITE_TEST
10266   #define DO_OS_MALLOC_TEST if (1) {            \
10267     void *pTstAlloc = sqlite3_malloc(10);       \
10268     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;  \
10269     sqlite3_free(pTstAlloc);                    \
10270   }
10271 #else
10272   #define DO_OS_MALLOC_TEST
10273 #endif
10274
10275 /*
10276 ** The following routines are convenience wrappers around methods
10277 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
10278 ** of this would be completely automatic if SQLite were coded using
10279 ** C++ instead of plain old C.
10280 */
10281 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
10282   int rc = SQLITE_OK;
10283   if( pId->pMethods ){
10284     rc = pId->pMethods->xClose(pId);
10285     pId->pMethods = 0;
10286   }
10287   return rc;
10288 }
10289 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
10290   DO_OS_MALLOC_TEST;
10291   return id->pMethods->xRead(id, pBuf, amt, offset);
10292 }
10293 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
10294   DO_OS_MALLOC_TEST;
10295   return id->pMethods->xWrite(id, pBuf, amt, offset);
10296 }
10297 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
10298   return id->pMethods->xTruncate(id, size);
10299 }
10300 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
10301   DO_OS_MALLOC_TEST;
10302   return id->pMethods->xSync(id, flags);
10303 }
10304 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
10305   return id->pMethods->xFileSize(id, pSize);
10306 }
10307 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
10308   DO_OS_MALLOC_TEST;
10309   return id->pMethods->xLock(id, lockType);
10310 }
10311 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
10312   return id->pMethods->xUnlock(id, lockType);
10313 }
10314 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id){
10315   return id->pMethods->xCheckReservedLock(id);
10316 }
10317 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
10318   return id->pMethods->xFileControl(id,op,pArg);
10319 }
10320 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
10321   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
10322   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
10323 }
10324 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
10325   return id->pMethods->xDeviceCharacteristics(id);
10326 }
10327
10328 /*
10329 ** The next group of routines are convenience wrappers around the
10330 ** VFS methods.
10331 */
10332 SQLITE_PRIVATE int sqlite3OsOpen(
10333   sqlite3_vfs *pVfs, 
10334   const char *zPath, 
10335   sqlite3_file *pFile, 
10336   int flags, 
10337   int *pFlagsOut
10338 ){
10339   DO_OS_MALLOC_TEST;
10340   return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
10341 }
10342 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
10343   return pVfs->xDelete(pVfs, zPath, dirSync);
10344 }
10345 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
10346   return pVfs->xAccess(pVfs, zPath, flags);
10347 }
10348 SQLITE_PRIVATE int sqlite3OsGetTempname(sqlite3_vfs *pVfs, int nBufOut, char *zBufOut){
10349   return pVfs->xGetTempname(pVfs, nBufOut, zBufOut);
10350 }
10351 SQLITE_PRIVATE int sqlite3OsFullPathname(
10352   sqlite3_vfs *pVfs, 
10353   const char *zPath, 
10354   int nPathOut, 
10355   char *zPathOut
10356 ){
10357   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
10358 }
10359 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
10360   return pVfs->xDlOpen(pVfs, zPath);
10361 }
10362 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
10363   pVfs->xDlError(pVfs, nByte, zBufOut);
10364 }
10365 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
10366   return pVfs->xDlSym(pVfs, pHandle, zSymbol);
10367 }
10368 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
10369   pVfs->xDlClose(pVfs, pHandle);
10370 }
10371 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
10372   return pVfs->xRandomness(pVfs, nByte, zBufOut);
10373 }
10374 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
10375   return pVfs->xSleep(pVfs, nMicro);
10376 }
10377 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
10378   return pVfs->xCurrentTime(pVfs, pTimeOut);
10379 }
10380
10381 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
10382   sqlite3_vfs *pVfs, 
10383   const char *zFile, 
10384   sqlite3_file **ppFile, 
10385   int flags,
10386   int *pOutFlags
10387 ){
10388   int rc = SQLITE_NOMEM;
10389   sqlite3_file *pFile;
10390   pFile = (sqlite3_file *)sqlite3_malloc(pVfs->szOsFile);
10391   if( pFile ){
10392     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
10393     if( rc!=SQLITE_OK ){
10394       sqlite3_free(pFile);
10395     }else{
10396       *ppFile = pFile;
10397     }
10398   }
10399   return rc;
10400 }
10401 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
10402   int rc = SQLITE_OK;
10403   if( pFile ){
10404     rc = sqlite3OsClose(pFile);
10405     sqlite3_free(pFile);
10406   }
10407   return rc;
10408 }
10409
10410 /*
10411 ** The list of all registered VFS implementations.  This list is
10412 ** initialized to the single VFS returned by sqlite3OsDefaultVfs()
10413 ** upon the first call to sqlite3_vfs_find().
10414 */
10415 static sqlite3_vfs *vfsList = 0;
10416
10417 /*
10418 ** Locate a VFS by name.  If no name is given, simply return the
10419 ** first VFS on the list.
10420 */
10421 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
10422 #ifndef SQLITE_MUTEX_NOOP
10423   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
10424 #endif
10425   sqlite3_vfs *pVfs = 0;
10426   static int isInit = 0;
10427   sqlite3_mutex_enter(mutex);
10428   if( !isInit ){
10429     vfsList = sqlite3OsDefaultVfs();
10430     isInit = 1;
10431   }
10432   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
10433     if( zVfs==0 ) break;
10434     if( strcmp(zVfs, pVfs->zName)==0 ) break;
10435   }
10436   sqlite3_mutex_leave(mutex);
10437   return pVfs;
10438 }
10439
10440 /*
10441 ** Unlink a VFS from the linked list
10442 */
10443 static void vfsUnlink(sqlite3_vfs *pVfs){
10444   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)) );
10445   if( pVfs==0 ){
10446     /* No-op */
10447   }else if( vfsList==pVfs ){
10448     vfsList = pVfs->pNext;
10449   }else if( vfsList ){
10450     sqlite3_vfs *p = vfsList;
10451     while( p->pNext && p->pNext!=pVfs ){
10452       p = p->pNext;
10453     }
10454     if( p->pNext==pVfs ){
10455       p->pNext = pVfs->pNext;
10456     }
10457   }
10458 }
10459
10460 /*
10461 ** Register a VFS with the system.  It is harmless to register the same
10462 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
10463 ** true.
10464 */
10465 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
10466 #ifndef SQLITE_MUTEX_NOOP
10467   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
10468 #endif
10469   sqlite3_vfs_find(0);  /* Make sure we are initialized */
10470   sqlite3_mutex_enter(mutex);
10471   vfsUnlink(pVfs);
10472   if( makeDflt || vfsList==0 ){
10473     pVfs->pNext = vfsList;
10474     vfsList = pVfs;
10475   }else{
10476     pVfs->pNext = vfsList->pNext;
10477     vfsList->pNext = pVfs;
10478   }
10479   assert(vfsList);
10480   sqlite3_mutex_leave(mutex);
10481   return SQLITE_OK;
10482 }
10483
10484 /*
10485 ** Unregister a VFS so that it is no longer accessible.
10486 */
10487 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
10488 #ifndef SQLITE_MUTEX_NOOP
10489   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
10490 #endif
10491   sqlite3_mutex_enter(mutex);
10492   vfsUnlink(pVfs);
10493   sqlite3_mutex_leave(mutex);
10494   return SQLITE_OK;
10495 }
10496
10497 /************** End of os.c **************************************************/
10498 /************** Begin file fault.c *******************************************/
10499 /*
10500 ** 2008 Jan 22
10501 **
10502 ** The author disclaims copyright to this source code.  In place of
10503 ** a legal notice, here is a blessing:
10504 **
10505 **    May you do good and not evil.
10506 **    May you find forgiveness for yourself and forgive others.
10507 **    May you share freely, never taking more than you give.
10508 **
10509 *************************************************************************
10510 ** This file contains code to implement a fault-injector used for
10511 ** testing and verification of SQLite.
10512 **
10513 ** Subsystems within SQLite can call sqlite3FaultStep() to see if
10514 ** they should simulate a fault.  sqlite3FaultStep() normally returns
10515 ** zero but will return non-zero if a fault should be simulated.
10516 ** Fault injectors can be used, for example, to simulate memory
10517 ** allocation failures or I/O errors.
10518 **
10519 ** The fault injector is omitted from the code if SQLite is
10520 ** compiled with -DSQLITE_OMIT_FAULTINJECTOR=1.  There is a very
10521 ** small performance hit for leaving the fault injector in the code.
10522 ** Commerical products will probably want to omit the fault injector
10523 ** from production builds.  But safety-critical systems who work
10524 ** under the motto "fly what you test and test what you fly" may
10525 ** choose to leave the fault injector enabled even in production.
10526 */
10527
10528 #ifndef SQLITE_OMIT_FAULTINJECTOR
10529
10530 /*
10531 ** There can be various kinds of faults.  For example, there can be
10532 ** a memory allocation failure.  Or an I/O failure.  For each different
10533 ** fault type, there is a separate FaultInjector structure to keep track
10534 ** of the status of that fault.
10535 */
10536 static struct FaultInjector {
10537   int iCountdown;   /* Number of pending successes before we hit a failure */
10538   int nRepeat;      /* Number of times to repeat the failure */
10539   int nBenign;      /* Number of benign failures seen since last config */
10540   int nFail;        /* Number of failures seen since last config */
10541   u8 enable;        /* True if enabled */
10542   u8 benign;        /* Ture if next failure will be benign */
10543 } aFault[SQLITE_FAULTINJECTOR_COUNT];
10544
10545 /*
10546 ** This routine configures and enables a fault injector.  After
10547 ** calling this routine, aFaultStep() will return false (zero)
10548 ** nDelay times, then it will return true nRepeat times,
10549 ** then it will again begin returning false.
10550 */
10551 SQLITE_PRIVATE void sqlite3FaultConfig(int id, int nDelay, int nRepeat){
10552   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10553   aFault[id].iCountdown = nDelay;
10554   aFault[id].nRepeat = nRepeat;
10555   aFault[id].nBenign = 0;
10556   aFault[id].nFail = 0;
10557   aFault[id].enable = nDelay>=0;
10558   aFault[id].benign = 0;
10559 }
10560
10561 /*
10562 ** Return the number of faults (both hard and benign faults) that have
10563 ** occurred since the injector was last configured.
10564 */
10565 SQLITE_PRIVATE int sqlite3FaultFailures(int id){
10566   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10567   return aFault[id].nFail;
10568 }
10569
10570 /*
10571 ** Return the number of benign faults that have occurred since the
10572 ** injector was last configured.
10573 */
10574 SQLITE_PRIVATE int sqlite3FaultBenignFailures(int id){
10575   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10576   return aFault[id].nBenign;
10577 }
10578
10579 /*
10580 ** Return the number of successes that will occur before the next failure.
10581 ** If no failures are scheduled, return -1.
10582 */
10583 SQLITE_PRIVATE int sqlite3FaultPending(int id){
10584   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10585   if( aFault[id].enable ){
10586     return aFault[id].iCountdown;
10587   }else{
10588     return -1;
10589   }
10590 }
10591
10592 /* 
10593 ** After this routine causes subsequent faults to be either benign
10594 ** or hard (not benign), according to the "enable" parameter.
10595 **
10596 ** Most faults are hard.  In other words, most faults cause
10597 ** an error to be propagated back up to the application interface.
10598 ** However, sometimes a fault is easily recoverable.  For example,
10599 ** if a malloc fails while resizing a hash table, this is completely
10600 ** recoverable simply by not carrying out the resize.  The hash table
10601 ** will continue to function normally.  So a malloc failure during
10602 ** a hash table resize is a benign fault.  
10603 */
10604 SQLITE_PRIVATE void sqlite3FaultBenign(int id, int enable){
10605   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10606   aFault[id].benign = enable;
10607 }
10608
10609 /*
10610 ** This routine exists as a place to set a breakpoint that will
10611 ** fire on any simulated fault.
10612 */
10613 static void sqlite3Fault(void){
10614   static int cnt = 0;
10615   cnt++;
10616 }
10617
10618
10619 /*
10620 ** Check to see if a fault should be simulated.  Return true to simulate
10621 ** the fault.  Return false if the fault should not be simulated.
10622 */
10623 SQLITE_PRIVATE int sqlite3FaultStep(int id){
10624   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10625   if( likely(!aFault[id].enable) ){
10626     return 0;
10627   }
10628   if( aFault[id].iCountdown>0 ){
10629     aFault[id].iCountdown--;
10630     return 0;
10631   }
10632   sqlite3Fault();
10633   aFault[id].nFail++;
10634   if( aFault[id].benign ){
10635     aFault[id].nBenign++;
10636   }
10637   aFault[id].nRepeat--;
10638   if( aFault[id].nRepeat<=0 ){
10639     aFault[id].enable = 0;
10640   }
10641   return 1;  
10642 }
10643
10644 #endif /* SQLITE_OMIT_FAULTINJECTOR */
10645
10646 /************** End of fault.c ***********************************************/
10647 /************** Begin file mem1.c ********************************************/
10648 /*
10649 ** 2007 August 14
10650 **
10651 ** The author disclaims copyright to this source code.  In place of
10652 ** a legal notice, here is a blessing:
10653 **
10654 **    May you do good and not evil.
10655 **    May you find forgiveness for yourself and forgive others.
10656 **    May you share freely, never taking more than you give.
10657 **
10658 *************************************************************************
10659 ** This file contains the C functions that implement a memory
10660 ** allocation subsystem for use by SQLite.  
10661 **
10662 ** $Id: mem1.c,v 1.16 2008/02/14 23:26:56 drh Exp $
10663 */
10664
10665 /*
10666 ** This version of the memory allocator is the default.  It is
10667 ** used when no other memory allocator is specified using compile-time
10668 ** macros.
10669 */
10670 #ifdef SQLITE_SYSTEM_MALLOC
10671
10672 /*
10673 ** All of the static variables used by this module are collected
10674 ** into a single structure named "mem".  This is to keep the
10675 ** static variables organized and to reduce namespace pollution
10676 ** when this module is combined with other in the amalgamation.
10677 */
10678 static struct {
10679   /*
10680   ** The alarm callback and its arguments.  The mem.mutex lock will
10681   ** be held while the callback is running.  Recursive calls into
10682   ** the memory subsystem are allowed, but no new callbacks will be
10683   ** issued.  The alarmBusy variable is set to prevent recursive
10684   ** callbacks.
10685   */
10686   sqlite3_int64 alarmThreshold;
10687   void (*alarmCallback)(void*, sqlite3_int64,int);
10688   void *alarmArg;
10689   int alarmBusy;
10690   
10691   /*
10692   ** Mutex to control access to the memory allocation subsystem.
10693   */
10694   sqlite3_mutex *mutex;
10695   
10696   /*
10697   ** Current allocation and high-water mark.
10698   */
10699   sqlite3_int64 nowUsed;
10700   sqlite3_int64 mxUsed;
10701   
10702  
10703 } mem;
10704
10705 /*
10706 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
10707 */
10708 static void enterMem(void){
10709   if( mem.mutex==0 ){
10710     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
10711   }
10712   sqlite3_mutex_enter(mem.mutex);
10713 }
10714
10715 /*
10716 ** Return the amount of memory currently checked out.
10717 */
10718 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
10719   sqlite3_int64 n;
10720   enterMem();
10721   n = mem.nowUsed;
10722   sqlite3_mutex_leave(mem.mutex);  
10723   return n;
10724 }
10725
10726 /*
10727 ** Return the maximum amount of memory that has ever been
10728 ** checked out since either the beginning of this process
10729 ** or since the most recent reset.
10730 */
10731 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
10732   sqlite3_int64 n;
10733   enterMem();
10734   n = mem.mxUsed;
10735   if( resetFlag ){
10736     mem.mxUsed = mem.nowUsed;
10737   }
10738   sqlite3_mutex_leave(mem.mutex);  
10739   return n;
10740 }
10741
10742 /*
10743 ** Change the alarm callback
10744 */
10745 SQLITE_API int sqlite3_memory_alarm(
10746   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
10747   void *pArg,
10748   sqlite3_int64 iThreshold
10749 ){
10750   enterMem();
10751   mem.alarmCallback = xCallback;
10752   mem.alarmArg = pArg;
10753   mem.alarmThreshold = iThreshold;
10754   sqlite3_mutex_leave(mem.mutex);
10755   return SQLITE_OK;
10756 }
10757
10758 /*
10759 ** Trigger the alarm 
10760 */
10761 static void sqlite3MemsysAlarm(int nByte){
10762   void (*xCallback)(void*,sqlite3_int64,int);
10763   sqlite3_int64 nowUsed;
10764   void *pArg;
10765   if( mem.alarmCallback==0 || mem.alarmBusy  ) return;
10766   mem.alarmBusy = 1;
10767   xCallback = mem.alarmCallback;
10768   nowUsed = mem.nowUsed;
10769   pArg = mem.alarmArg;
10770   sqlite3_mutex_leave(mem.mutex);
10771   xCallback(pArg, nowUsed, nByte);
10772   sqlite3_mutex_enter(mem.mutex);
10773   mem.alarmBusy = 0;
10774 }
10775
10776 /*
10777 ** Allocate nBytes of memory
10778 */
10779 SQLITE_API void *sqlite3_malloc(int nBytes){
10780   sqlite3_int64 *p = 0;
10781   if( nBytes>0 ){
10782     enterMem();
10783     if( mem.alarmCallback!=0 && mem.nowUsed+nBytes>=mem.alarmThreshold ){
10784       sqlite3MemsysAlarm(nBytes);
10785     }
10786     p = malloc(nBytes+8);
10787     if( p==0 ){
10788       sqlite3MemsysAlarm(nBytes);
10789       p = malloc(nBytes+8);
10790     }
10791     if( p ){
10792       p[0] = nBytes;
10793       p++;
10794       mem.nowUsed += nBytes;
10795       if( mem.nowUsed>mem.mxUsed ){
10796         mem.mxUsed = mem.nowUsed;
10797       }
10798     }
10799     sqlite3_mutex_leave(mem.mutex);
10800   }
10801   return (void*)p; 
10802 }
10803
10804 /*
10805 ** Free memory.
10806 */
10807 SQLITE_API void sqlite3_free(void *pPrior){
10808   sqlite3_int64 *p;
10809   int nByte;
10810   if( pPrior==0 ){
10811     return;
10812   }
10813   assert( mem.mutex!=0 );
10814   p = pPrior;
10815   p--;
10816   nByte = (int)*p;
10817   sqlite3_mutex_enter(mem.mutex);
10818   mem.nowUsed -= nByte;
10819   free(p);
10820   sqlite3_mutex_leave(mem.mutex);  
10821 }
10822
10823 /*
10824 ** Return the number of bytes allocated at p.
10825 */
10826 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
10827   sqlite3_int64 *pInt;
10828   if( !p ) return 0;
10829   pInt = p;
10830   return pInt[-1];
10831 }
10832
10833 /*
10834 ** Change the size of an existing memory allocation
10835 */
10836 SQLITE_API void *sqlite3_realloc(void *pPrior, int nBytes){
10837   int nOld;
10838   sqlite3_int64 *p;
10839   if( pPrior==0 ){
10840     return sqlite3_malloc(nBytes);
10841   }
10842   if( nBytes<=0 ){
10843     sqlite3_free(pPrior);
10844     return 0;
10845   }
10846   p = pPrior;
10847   p--;
10848   nOld = (int)p[0];
10849   assert( mem.mutex!=0 );
10850   sqlite3_mutex_enter(mem.mutex);
10851   if( mem.nowUsed+nBytes-nOld>=mem.alarmThreshold ){
10852     sqlite3MemsysAlarm(nBytes-nOld);
10853   }
10854   p = realloc(p, nBytes+8);
10855   if( p==0 ){
10856     sqlite3MemsysAlarm(nBytes);
10857     p = pPrior;
10858     p--;
10859     p = realloc(p, nBytes+8);
10860   }
10861   if( p ){
10862     p[0] = nBytes;
10863     p++;
10864     mem.nowUsed += nBytes-nOld;
10865     if( mem.nowUsed>mem.mxUsed ){
10866       mem.mxUsed = mem.nowUsed;
10867     }
10868   }
10869   sqlite3_mutex_leave(mem.mutex);
10870   return (void*)p;
10871 }
10872
10873 #endif /* SQLITE_SYSTEM_MALLOC */
10874
10875 /************** End of mem1.c ************************************************/
10876 /************** Begin file mem2.c ********************************************/
10877 /*
10878 ** 2007 August 15
10879 **
10880 ** The author disclaims copyright to this source code.  In place of
10881 ** a legal notice, here is a blessing:
10882 **
10883 **    May you do good and not evil.
10884 **    May you find forgiveness for yourself and forgive others.
10885 **    May you share freely, never taking more than you give.
10886 **
10887 *************************************************************************
10888 ** This file contains the C functions that implement a memory
10889 ** allocation subsystem for use by SQLite.  
10890 **
10891 ** $Id: mem2.c,v 1.22 2008/02/19 15:15:16 drh Exp $
10892 */
10893
10894 /*
10895 ** This version of the memory allocator is used only if the
10896 ** SQLITE_MEMDEBUG macro is defined
10897 */
10898 #ifdef SQLITE_MEMDEBUG
10899
10900 /*
10901 ** The backtrace functionality is only available with GLIBC
10902 */
10903 #ifdef __GLIBC__
10904   extern int backtrace(void**,int);
10905   extern void backtrace_symbols_fd(void*const*,int,int);
10906 #else
10907 # define backtrace(A,B) 0
10908 # define backtrace_symbols_fd(A,B,C)
10909 #endif
10910
10911 /*
10912 ** Each memory allocation looks like this:
10913 **
10914 **  ------------------------------------------------------------------------
10915 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
10916 **  ------------------------------------------------------------------------
10917 **
10918 ** The application code sees only a pointer to the allocation.  We have
10919 ** to back up from the allocation pointer to find the MemBlockHdr.  The
10920 ** MemBlockHdr tells us the size of the allocation and the number of
10921 ** backtrace pointers.  There is also a guard word at the end of the
10922 ** MemBlockHdr.
10923 */
10924 struct MemBlockHdr {
10925   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
10926   int iSize;                          /* Size of this allocation */
10927   char nBacktrace;                    /* Number of backtraces on this alloc */
10928   char nBacktraceSlots;               /* Available backtrace slots */
10929   short nTitle;                       /* Bytes of title; includes '\0' */
10930   int iForeGuard;                     /* Guard word for sanity */
10931 };
10932
10933 /*
10934 ** Guard words
10935 */
10936 #define FOREGUARD 0x80F5E153
10937 #define REARGUARD 0xE4676B53
10938
10939 /*
10940 ** Number of malloc size increments to track.
10941 */
10942 #define NCSIZE  1000
10943
10944 /*
10945 ** All of the static variables used by this module are collected
10946 ** into a single structure named "mem".  This is to keep the
10947 ** static variables organized and to reduce namespace pollution
10948 ** when this module is combined with other in the amalgamation.
10949 */
10950 static struct {
10951   /*
10952   ** The alarm callback and its arguments.  The mem.mutex lock will
10953   ** be held while the callback is running.  Recursive calls into
10954   ** the memory subsystem are allowed, but no new callbacks will be
10955   ** issued.  The alarmBusy variable is set to prevent recursive
10956   ** callbacks.
10957   */
10958   sqlite3_int64 alarmThreshold;
10959   void (*alarmCallback)(void*, sqlite3_int64, int);
10960   void *alarmArg;
10961   int alarmBusy;
10962   
10963   /*
10964   ** Mutex to control access to the memory allocation subsystem.
10965   */
10966   sqlite3_mutex *mutex;
10967   
10968   /*
10969   ** Current allocation and high-water mark.
10970   */
10971   sqlite3_int64 nowUsed;
10972   sqlite3_int64 mxUsed;
10973   
10974   /*
10975   ** Head and tail of a linked list of all outstanding allocations
10976   */
10977   struct MemBlockHdr *pFirst;
10978   struct MemBlockHdr *pLast;
10979   
10980   /*
10981   ** The number of levels of backtrace to save in new allocations.
10982   */
10983   int nBacktrace;
10984
10985   /*
10986   ** Title text to insert in front of each block
10987   */
10988   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
10989   char zTitle[100];  /* The title text */
10990
10991   /* 
10992   ** sqlite3MallocDisallow() increments the following counter.
10993   ** sqlite3MallocAllow() decrements it.
10994   */
10995   int disallow; /* Do not allow memory allocation */
10996
10997   /*
10998   ** Gather statistics on the sizes of memory allocations.
10999   ** sizeCnt[i] is the number of allocation attempts of i*8
11000   ** bytes.  i==NCSIZE is the number of allocation attempts for
11001   ** sizes more than NCSIZE*8 bytes.
11002   */
11003   int sizeCnt[NCSIZE];
11004
11005 } mem;
11006
11007
11008 /*
11009 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
11010 */
11011 static void enterMem(void){
11012   if( mem.mutex==0 ){
11013     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
11014   }
11015   sqlite3_mutex_enter(mem.mutex);
11016 }
11017
11018 /*
11019 ** Return the amount of memory currently checked out.
11020 */
11021 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
11022   sqlite3_int64 n;
11023   enterMem();
11024   n = mem.nowUsed;
11025   sqlite3_mutex_leave(mem.mutex);  
11026   return n;
11027 }
11028
11029 /*
11030 ** Return the maximum amount of memory that has ever been
11031 ** checked out since either the beginning of this process
11032 ** or since the most recent reset.
11033 */
11034 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
11035   sqlite3_int64 n;
11036   enterMem();
11037   n = mem.mxUsed;
11038   if( resetFlag ){
11039     mem.mxUsed = mem.nowUsed;
11040   }
11041   sqlite3_mutex_leave(mem.mutex);  
11042   return n;
11043 }
11044
11045 /*
11046 ** Change the alarm callback
11047 */
11048 SQLITE_API int sqlite3_memory_alarm(
11049   void(*xCallback)(void *pArg, sqlite3_int64 used, int N),
11050   void *pArg,
11051   sqlite3_int64 iThreshold
11052 ){
11053   enterMem();
11054   mem.alarmCallback = xCallback;
11055   mem.alarmArg = pArg;
11056   mem.alarmThreshold = iThreshold;
11057   sqlite3_mutex_leave(mem.mutex);
11058   return SQLITE_OK;
11059 }
11060
11061 /*
11062 ** Trigger the alarm 
11063 */
11064 static void sqlite3MemsysAlarm(int nByte){
11065   void (*xCallback)(void*,sqlite3_int64,int);
11066   sqlite3_int64 nowUsed;
11067   void *pArg;
11068   if( mem.alarmCallback==0 || mem.alarmBusy  ) return;
11069   mem.alarmBusy = 1;
11070   xCallback = mem.alarmCallback;
11071   nowUsed = mem.nowUsed;
11072   pArg = mem.alarmArg;
11073   sqlite3_mutex_leave(mem.mutex);
11074   xCallback(pArg, nowUsed, nByte);
11075   sqlite3_mutex_enter(mem.mutex);
11076   mem.alarmBusy = 0;
11077 }
11078
11079 /*
11080 ** Given an allocation, find the MemBlockHdr for that allocation.
11081 **
11082 ** This routine checks the guards at either end of the allocation and
11083 ** if they are incorrect it asserts.
11084 */
11085 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
11086   struct MemBlockHdr *p;
11087   int *pInt;
11088
11089   p = (struct MemBlockHdr*)pAllocation;
11090   p--;
11091   assert( p->iForeGuard==FOREGUARD );
11092   assert( (p->iSize & 3)==0 );
11093   pInt = (int*)pAllocation;
11094   assert( pInt[p->iSize/sizeof(int)]==REARGUARD );
11095   return p;
11096 }
11097
11098 /*
11099 ** Return the number of bytes currently allocated at address p.
11100 */
11101 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
11102   struct MemBlockHdr *pHdr;
11103   if( !p ){
11104     return 0;
11105   }
11106   pHdr = sqlite3MemsysGetHeader(p);
11107   return pHdr->iSize;
11108 }
11109
11110 /*
11111 ** Allocate nByte bytes of memory.
11112 */
11113 SQLITE_API void *sqlite3_malloc(int nByte){
11114   struct MemBlockHdr *pHdr;
11115   void **pBt;
11116   char *z;
11117   int *pInt;
11118   void *p = 0;
11119   int totalSize;
11120
11121   if( nByte>0 ){
11122     enterMem();
11123     assert( mem.disallow==0 );
11124     if( mem.alarmCallback!=0 && mem.nowUsed+nByte>=mem.alarmThreshold ){
11125       sqlite3MemsysAlarm(nByte);
11126     }
11127     nByte = (nByte+3)&~3;
11128     if( nByte/8>NCSIZE-1 ){
11129       mem.sizeCnt[NCSIZE-1]++;
11130     }else{
11131       mem.sizeCnt[nByte/8]++;
11132     }
11133     totalSize = nByte + sizeof(*pHdr) + sizeof(int) +
11134                  mem.nBacktrace*sizeof(void*) + mem.nTitle;
11135     if( sqlite3FaultStep(SQLITE_FAULTINJECTOR_MALLOC) ){
11136       p = 0;
11137     }else{
11138       p = malloc(totalSize);
11139       if( p==0 ){
11140         sqlite3MemsysAlarm(nByte);
11141         p = malloc(totalSize);
11142       }
11143     }
11144     if( p ){
11145       z = p;
11146       pBt = (void**)&z[mem.nTitle];
11147       pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
11148       pHdr->pNext = 0;
11149       pHdr->pPrev = mem.pLast;
11150       if( mem.pLast ){
11151         mem.pLast->pNext = pHdr;
11152       }else{
11153         mem.pFirst = pHdr;
11154       }
11155       mem.pLast = pHdr;
11156       pHdr->iForeGuard = FOREGUARD;
11157       pHdr->nBacktraceSlots = mem.nBacktrace;
11158       pHdr->nTitle = mem.nTitle;
11159       if( mem.nBacktrace ){
11160         void *aAddr[40];
11161         pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
11162         memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
11163       }else{
11164         pHdr->nBacktrace = 0;
11165       }
11166       if( mem.nTitle ){
11167         memcpy(z, mem.zTitle, mem.nTitle);
11168       }
11169       pHdr->iSize = nByte;
11170       pInt = (int*)&pHdr[1];
11171       pInt[nByte/sizeof(int)] = REARGUARD;
11172       memset(pInt, 0x65, nByte);
11173       mem.nowUsed += nByte;
11174       if( mem.nowUsed>mem.mxUsed ){
11175         mem.mxUsed = mem.nowUsed;
11176       }
11177       p = (void*)pInt;
11178     }
11179     sqlite3_mutex_leave(mem.mutex);
11180   }
11181   return p; 
11182 }
11183
11184 /*
11185 ** Free memory.
11186 */
11187 SQLITE_API void sqlite3_free(void *pPrior){
11188   struct MemBlockHdr *pHdr;
11189   void **pBt;
11190   char *z;
11191   if( pPrior==0 ){
11192     return;
11193   }
11194   assert( mem.mutex!=0 );
11195   pHdr = sqlite3MemsysGetHeader(pPrior);
11196   pBt = (void**)pHdr;
11197   pBt -= pHdr->nBacktraceSlots;
11198   sqlite3_mutex_enter(mem.mutex);
11199   mem.nowUsed -= pHdr->iSize;
11200   if( pHdr->pPrev ){
11201     assert( pHdr->pPrev->pNext==pHdr );
11202     pHdr->pPrev->pNext = pHdr->pNext;
11203   }else{
11204     assert( mem.pFirst==pHdr );
11205     mem.pFirst = pHdr->pNext;
11206   }
11207   if( pHdr->pNext ){
11208     assert( pHdr->pNext->pPrev==pHdr );
11209     pHdr->pNext->pPrev = pHdr->pPrev;
11210   }else{
11211     assert( mem.pLast==pHdr );
11212     mem.pLast = pHdr->pPrev;
11213   }
11214   z = (char*)pBt;
11215   z -= pHdr->nTitle;
11216   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
11217                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
11218   free(z);
11219   sqlite3_mutex_leave(mem.mutex);  
11220 }
11221
11222 /*
11223 ** Change the size of an existing memory allocation.
11224 **
11225 ** For this debugging implementation, we *always* make a copy of the
11226 ** allocation into a new place in memory.  In this way, if the 
11227 ** higher level code is using pointer to the old allocation, it is 
11228 ** much more likely to break and we are much more liking to find
11229 ** the error.
11230 */
11231 SQLITE_API void *sqlite3_realloc(void *pPrior, int nByte){
11232   struct MemBlockHdr *pOldHdr;
11233   void *pNew;
11234   if( pPrior==0 ){
11235     return sqlite3_malloc(nByte);
11236   }
11237   if( nByte<=0 ){
11238     sqlite3_free(pPrior);
11239     return 0;
11240   }
11241   assert( mem.disallow==0 );
11242   pOldHdr = sqlite3MemsysGetHeader(pPrior);
11243   pNew = sqlite3_malloc(nByte);
11244   if( pNew ){
11245     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
11246     if( nByte>pOldHdr->iSize ){
11247       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
11248     }
11249     sqlite3_free(pPrior);
11250   }
11251   return pNew;
11252 }
11253
11254 /*
11255 ** Set the number of backtrace levels kept for each allocation.
11256 ** A value of zero turns of backtracing.  The number is always rounded
11257 ** up to a multiple of 2.
11258 */
11259 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
11260   if( depth<0 ){ depth = 0; }
11261   if( depth>20 ){ depth = 20; }
11262   depth = (depth+1)&0xfe;
11263   mem.nBacktrace = depth;
11264 }
11265
11266 /*
11267 ** Set the title string for subsequent allocations.
11268 */
11269 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
11270   int n = strlen(zTitle) + 1;
11271   enterMem();
11272   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
11273   memcpy(mem.zTitle, zTitle, n);
11274   mem.zTitle[n] = 0;
11275   mem.nTitle = (n+3)&~3;
11276   sqlite3_mutex_leave(mem.mutex);
11277 }
11278
11279 /*
11280 ** Open the file indicated and write a log of all unfreed memory 
11281 ** allocations into that log.
11282 */
11283 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
11284   FILE *out;
11285   struct MemBlockHdr *pHdr;
11286   void **pBt;
11287   int i;
11288   out = fopen(zFilename, "w");
11289   if( out==0 ){
11290     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
11291                     zFilename);
11292     return;
11293   }
11294   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
11295     char *z = (char*)pHdr;
11296     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
11297     fprintf(out, "**** %d bytes at %p from %s ****\n", 
11298             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
11299     if( pHdr->nBacktrace ){
11300       fflush(out);
11301       pBt = (void**)pHdr;
11302       pBt -= pHdr->nBacktraceSlots;
11303       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
11304       fprintf(out, "\n");
11305     }
11306   }
11307   fprintf(out, "COUNTS:\n");
11308   for(i=0; i<NCSIZE-1; i++){
11309     if( mem.sizeCnt[i] ){
11310       fprintf(out, "   %3d: %d\n", i*8+8, mem.sizeCnt[i]);
11311     }
11312   }
11313   if( mem.sizeCnt[NCSIZE-1] ){
11314     fprintf(out, "  >%3d: %d\n", NCSIZE*8, mem.sizeCnt[NCSIZE-1]);
11315   }
11316   fclose(out);
11317 }
11318
11319 /*
11320 ** Return the number of times sqlite3_malloc() has been called.
11321 */
11322 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
11323   int i;
11324   int nTotal = 0;
11325   for(i=0; i<NCSIZE; i++){
11326     nTotal += mem.sizeCnt[i];
11327   }
11328   return nTotal;
11329 }
11330
11331
11332 #endif /* SQLITE_MEMDEBUG */
11333
11334 /************** End of mem2.c ************************************************/
11335 /************** Begin file mem3.c ********************************************/
11336 /*
11337 ** 2007 October 14
11338 **
11339 ** The author disclaims copyright to this source code.  In place of
11340 ** a legal notice, here is a blessing:
11341 **
11342 **    May you do good and not evil.
11343 **    May you find forgiveness for yourself and forgive others.
11344 **    May you share freely, never taking more than you give.
11345 **
11346 *************************************************************************
11347 ** This file contains the C functions that implement a memory
11348 ** allocation subsystem for use by SQLite. 
11349 **
11350 ** This version of the memory allocation subsystem omits all
11351 ** use of malloc().  All dynamically allocatable memory is
11352 ** contained in a static array, mem.aPool[].  The size of this
11353 ** fixed memory pool is SQLITE_MEMORY_SIZE bytes.
11354 **
11355 ** This version of the memory allocation subsystem is used if
11356 ** and only if SQLITE_MEMORY_SIZE is defined.
11357 **
11358 ** $Id: mem3.c,v 1.12 2008/02/19 15:15:16 drh Exp $
11359 */
11360
11361 /*
11362 ** This version of the memory allocator is used only when 
11363 ** SQLITE_MEMORY_SIZE is defined.
11364 */
11365 #ifdef SQLITE_MEMORY_SIZE
11366
11367 /*
11368 ** Maximum size (in Mem3Blocks) of a "small" chunk.
11369 */
11370 #define MX_SMALL 10
11371
11372
11373 /*
11374 ** Number of freelist hash slots
11375 */
11376 #define N_HASH  61
11377
11378 /*
11379 ** A memory allocation (also called a "chunk") consists of two or 
11380 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
11381 ** a header that is not returned to the user.
11382 **
11383 ** A chunk is two or more blocks that is either checked out or
11384 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
11385 ** size of the allocation in blocks if the allocation is free.
11386 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
11387 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
11388 ** is true if the previous chunk is checked out and false if the
11389 ** previous chunk is free.  The u.hdr.prevSize field is the size of
11390 ** the previous chunk in blocks if the previous chunk is on the
11391 ** freelist. If the previous chunk is checked out, then
11392 ** u.hdr.prevSize can be part of the data for that chunk and should
11393 ** not be read or written.
11394 **
11395 ** We often identify a chunk by its index in mem.aPool[].  When
11396 ** this is done, the chunk index refers to the second block of
11397 ** the chunk.  In this way, the first chunk has an index of 1.
11398 ** A chunk index of 0 means "no such chunk" and is the equivalent
11399 ** of a NULL pointer.
11400 **
11401 ** The second block of free chunks is of the form u.list.  The
11402 ** two fields form a double-linked list of chunks of related sizes.
11403 ** Pointers to the head of the list are stored in mem.aiSmall[] 
11404 ** for smaller chunks and mem.aiHash[] for larger chunks.
11405 **
11406 ** The second block of a chunk is user data if the chunk is checked 
11407 ** out.  If a chunk is checked out, the user data may extend into
11408 ** the u.hdr.prevSize value of the following chunk.
11409 */
11410 typedef struct Mem3Block Mem3Block;
11411 struct Mem3Block {
11412   union {
11413     struct {
11414       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
11415       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
11416     } hdr;
11417     struct {
11418       u32 next;       /* Index in mem.aPool[] of next free chunk */
11419       u32 prev;       /* Index in mem.aPool[] of previous free chunk */
11420     } list;
11421   } u;
11422 };
11423
11424 /*
11425 ** All of the static variables used by this module are collected
11426 ** into a single structure named "mem".  This is to keep the
11427 ** static variables organized and to reduce namespace pollution
11428 ** when this module is combined with other in the amalgamation.
11429 */
11430 static struct {
11431   /*
11432   ** True if we are evaluating an out-of-memory callback.
11433   */
11434   int alarmBusy;
11435   
11436   /*
11437   ** Mutex to control access to the memory allocation subsystem.
11438   */
11439   sqlite3_mutex *mutex;
11440   
11441   /*
11442   ** The minimum amount of free space that we have seen.
11443   */
11444   u32 mnMaster;
11445
11446   /*
11447   ** iMaster is the index of the master chunk.  Most new allocations
11448   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
11449   ** of the current master.  iMaster is 0 if there is not master chunk.
11450   ** The master chunk is not in either the aiHash[] or aiSmall[].
11451   */
11452   u32 iMaster;
11453   u32 szMaster;
11454
11455   /*
11456   ** Array of lists of free blocks according to the block size 
11457   ** for smaller chunks, or a hash on the block size for larger
11458   ** chunks.
11459   */
11460   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
11461   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
11462
11463   /*
11464   ** Memory available for allocation
11465   */
11466   Mem3Block aPool[SQLITE_MEMORY_SIZE/sizeof(Mem3Block)+2];
11467 } mem;
11468
11469 /*
11470 ** Unlink the chunk at mem.aPool[i] from list it is currently
11471 ** on.  *pRoot is the list that i is a member of.
11472 */
11473 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
11474   u32 next = mem.aPool[i].u.list.next;
11475   u32 prev = mem.aPool[i].u.list.prev;
11476   assert( sqlite3_mutex_held(mem.mutex) );
11477   if( prev==0 ){
11478     *pRoot = next;
11479   }else{
11480     mem.aPool[prev].u.list.next = next;
11481   }
11482   if( next ){
11483     mem.aPool[next].u.list.prev = prev;
11484   }
11485   mem.aPool[i].u.list.next = 0;
11486   mem.aPool[i].u.list.prev = 0;
11487 }
11488
11489 /*
11490 ** Unlink the chunk at index i from 
11491 ** whatever list is currently a member of.
11492 */
11493 static void memsys3Unlink(u32 i){
11494   u32 size, hash;
11495   assert( sqlite3_mutex_held(mem.mutex) );
11496   assert( (mem.aPool[i-1].u.hdr.size4x & 1)==0 );
11497   assert( i>=1 );
11498   size = mem.aPool[i-1].u.hdr.size4x/4;
11499   assert( size==mem.aPool[i+size-1].u.hdr.prevSize );
11500   assert( size>=2 );
11501   if( size <= MX_SMALL ){
11502     memsys3UnlinkFromList(i, &mem.aiSmall[size-2]);
11503   }else{
11504     hash = size % N_HASH;
11505     memsys3UnlinkFromList(i, &mem.aiHash[hash]);
11506   }
11507 }
11508
11509 /*
11510 ** Link the chunk at mem.aPool[i] so that is on the list rooted
11511 ** at *pRoot.
11512 */
11513 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
11514   assert( sqlite3_mutex_held(mem.mutex) );
11515   mem.aPool[i].u.list.next = *pRoot;
11516   mem.aPool[i].u.list.prev = 0;
11517   if( *pRoot ){
11518     mem.aPool[*pRoot].u.list.prev = i;
11519   }
11520   *pRoot = i;
11521 }
11522
11523 /*
11524 ** Link the chunk at index i into either the appropriate
11525 ** small chunk list, or into the large chunk hash table.
11526 */
11527 static void memsys3Link(u32 i){
11528   u32 size, hash;
11529   assert( sqlite3_mutex_held(mem.mutex) );
11530   assert( i>=1 );
11531   assert( (mem.aPool[i-1].u.hdr.size4x & 1)==0 );
11532   size = mem.aPool[i-1].u.hdr.size4x/4;
11533   assert( size==mem.aPool[i+size-1].u.hdr.prevSize );
11534   assert( size>=2 );
11535   if( size <= MX_SMALL ){
11536     memsys3LinkIntoList(i, &mem.aiSmall[size-2]);
11537   }else{
11538     hash = size % N_HASH;
11539     memsys3LinkIntoList(i, &mem.aiHash[hash]);
11540   }
11541 }
11542
11543 /*
11544 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
11545 **
11546 ** Also:  Initialize the memory allocation subsystem the first time
11547 ** this routine is called.
11548 */
11549 static void memsys3Enter(void){
11550   if( mem.mutex==0 ){
11551     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
11552     mem.aPool[0].u.hdr.size4x = SQLITE_MEMORY_SIZE/2 + 2;
11553     mem.aPool[SQLITE_MEMORY_SIZE/8].u.hdr.prevSize = SQLITE_MEMORY_SIZE/8;
11554     mem.aPool[SQLITE_MEMORY_SIZE/8].u.hdr.size4x = 1;
11555     mem.iMaster = 1;
11556     mem.szMaster = SQLITE_MEMORY_SIZE/8;
11557     mem.mnMaster = mem.szMaster;
11558   }
11559   sqlite3_mutex_enter(mem.mutex);
11560 }
11561
11562 /*
11563 ** Return the amount of memory currently checked out.
11564 */
11565 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
11566   sqlite3_int64 n;
11567   memsys3Enter();
11568   n = SQLITE_MEMORY_SIZE - mem.szMaster*8;
11569   sqlite3_mutex_leave(mem.mutex);  
11570   return n;
11571 }
11572
11573 /*
11574 ** Return the maximum amount of memory that has ever been
11575 ** checked out since either the beginning of this process
11576 ** or since the most recent reset.
11577 */
11578 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
11579   sqlite3_int64 n;
11580   memsys3Enter();
11581   n = SQLITE_MEMORY_SIZE - mem.mnMaster*8;
11582   if( resetFlag ){
11583     mem.mnMaster = mem.szMaster;
11584   }
11585   sqlite3_mutex_leave(mem.mutex);  
11586   return n;
11587 }
11588
11589 /*
11590 ** Change the alarm callback.
11591 **
11592 ** This is a no-op for the static memory allocator.  The purpose
11593 ** of the memory alarm is to support sqlite3_soft_heap_limit().
11594 ** But with this memory allocator, the soft_heap_limit is really
11595 ** a hard limit that is fixed at SQLITE_MEMORY_SIZE.
11596 */
11597 SQLITE_API int sqlite3_memory_alarm(
11598   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
11599   void *pArg,
11600   sqlite3_int64 iThreshold
11601 ){
11602   return SQLITE_OK;
11603 }
11604
11605 /*
11606 ** Called when we are unable to satisfy an allocation of nBytes.
11607 */
11608 static void memsys3OutOfMemory(int nByte){
11609   if( !mem.alarmBusy ){
11610     mem.alarmBusy = 1;
11611     assert( sqlite3_mutex_held(mem.mutex) );
11612     sqlite3_mutex_leave(mem.mutex);
11613     sqlite3_release_memory(nByte);
11614     sqlite3_mutex_enter(mem.mutex);
11615     mem.alarmBusy = 0;
11616   }
11617 }
11618
11619 /*
11620 ** Return the size of an outstanding allocation, in bytes.  The
11621 ** size returned omits the 8-byte header overhead.  This only
11622 ** works for chunks that are currently checked out.
11623 */
11624 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
11625   int iSize = 0;
11626   if( p ){
11627     Mem3Block *pBlock = (Mem3Block*)p;
11628     assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
11629     iSize = (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
11630   }
11631   return iSize;
11632 }
11633
11634 /*
11635 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
11636 ** size parameters for check-out and return a pointer to the 
11637 ** user portion of the chunk.
11638 */
11639 static void *memsys3Checkout(u32 i, int nBlock){
11640   u32 x;
11641   assert( sqlite3_mutex_held(mem.mutex) );
11642   assert( i>=1 );
11643   assert( mem.aPool[i-1].u.hdr.size4x/4==nBlock );
11644   assert( mem.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
11645   x = mem.aPool[i-1].u.hdr.size4x;
11646   mem.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
11647   mem.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
11648   mem.aPool[i+nBlock-1].u.hdr.size4x |= 2;
11649   return &mem.aPool[i];
11650 }
11651
11652 /*
11653 ** Carve a piece off of the end of the mem.iMaster free chunk.
11654 ** Return a pointer to the new allocation.  Or, if the master chunk
11655 ** is not large enough, return 0.
11656 */
11657 static void *memsys3FromMaster(int nBlock){
11658   assert( sqlite3_mutex_held(mem.mutex) );
11659   assert( mem.szMaster>=nBlock );
11660   if( nBlock>=mem.szMaster-1 ){
11661     /* Use the entire master */
11662     void *p = memsys3Checkout(mem.iMaster, mem.szMaster);
11663     mem.iMaster = 0;
11664     mem.szMaster = 0;
11665     mem.mnMaster = 0;
11666     return p;
11667   }else{
11668     /* Split the master block.  Return the tail. */
11669     u32 newi, x;
11670     newi = mem.iMaster + mem.szMaster - nBlock;
11671     assert( newi > mem.iMaster+1 );
11672     mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = nBlock;
11673     mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x |= 2;
11674     mem.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
11675     mem.szMaster -= nBlock;
11676     mem.aPool[newi-1].u.hdr.prevSize = mem.szMaster;
11677     x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2;
11678     mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x;
11679     if( mem.szMaster < mem.mnMaster ){
11680       mem.mnMaster = mem.szMaster;
11681     }
11682     return (void*)&mem.aPool[newi];
11683   }
11684 }
11685
11686 /*
11687 ** *pRoot is the head of a list of free chunks of the same size
11688 ** or same size hash.  In other words, *pRoot is an entry in either
11689 ** mem.aiSmall[] or mem.aiHash[].  
11690 **
11691 ** This routine examines all entries on the given list and tries
11692 ** to coalesce each entries with adjacent free chunks.  
11693 **
11694 ** If it sees a chunk that is larger than mem.iMaster, it replaces 
11695 ** the current mem.iMaster with the new larger chunk.  In order for
11696 ** this mem.iMaster replacement to work, the master chunk must be
11697 ** linked into the hash tables.  That is not the normal state of
11698 ** affairs, of course.  The calling routine must link the master
11699 ** chunk before invoking this routine, then must unlink the (possibly
11700 ** changed) master chunk once this routine has finished.
11701 */
11702 static void memsys3Merge(u32 *pRoot){
11703   u32 iNext, prev, size, i, x;
11704
11705   assert( sqlite3_mutex_held(mem.mutex) );
11706   for(i=*pRoot; i>0; i=iNext){
11707     iNext = mem.aPool[i].u.list.next;
11708     size = mem.aPool[i-1].u.hdr.size4x;
11709     assert( (size&1)==0 );
11710     if( (size&2)==0 ){
11711       memsys3UnlinkFromList(i, pRoot);
11712       assert( i > mem.aPool[i-1].u.hdr.prevSize );
11713       prev = i - mem.aPool[i-1].u.hdr.prevSize;
11714       if( prev==iNext ){
11715         iNext = mem.aPool[prev].u.list.next;
11716       }
11717       memsys3Unlink(prev);
11718       size = i + size/4 - prev;
11719       x = mem.aPool[prev-1].u.hdr.size4x & 2;
11720       mem.aPool[prev-1].u.hdr.size4x = size*4 | x;
11721       mem.aPool[prev+size-1].u.hdr.prevSize = size;
11722       memsys3Link(prev);
11723       i = prev;
11724     }else{
11725       size /= 4;
11726     }
11727     if( size>mem.szMaster ){
11728       mem.iMaster = i;
11729       mem.szMaster = size;
11730     }
11731   }
11732 }
11733
11734 /*
11735 ** Return a block of memory of at least nBytes in size.
11736 ** Return NULL if unable.
11737 */
11738 static void *memsys3Malloc(int nByte){
11739   u32 i;
11740   int nBlock;
11741   int toFree;
11742
11743   assert( sqlite3_mutex_held(mem.mutex) );
11744   assert( sizeof(Mem3Block)==8 );
11745   if( nByte<=12 ){
11746     nBlock = 2;
11747   }else{
11748     nBlock = (nByte + 11)/8;
11749   }
11750   assert( nBlock >= 2 );
11751
11752   /* STEP 1:
11753   ** Look for an entry of the correct size in either the small
11754   ** chunk table or in the large chunk hash table.  This is
11755   ** successful most of the time (about 9 times out of 10).
11756   */
11757   if( nBlock <= MX_SMALL ){
11758     i = mem.aiSmall[nBlock-2];
11759     if( i>0 ){
11760       memsys3UnlinkFromList(i, &mem.aiSmall[nBlock-2]);
11761       return memsys3Checkout(i, nBlock);
11762     }
11763   }else{
11764     int hash = nBlock % N_HASH;
11765     for(i=mem.aiHash[hash]; i>0; i=mem.aPool[i].u.list.next){
11766       if( mem.aPool[i-1].u.hdr.size4x/4==nBlock ){
11767         memsys3UnlinkFromList(i, &mem.aiHash[hash]);
11768         return memsys3Checkout(i, nBlock);
11769       }
11770     }
11771   }
11772
11773   /* STEP 2:
11774   ** Try to satisfy the allocation by carving a piece off of the end
11775   ** of the master chunk.  This step usually works if step 1 fails.
11776   */
11777   if( mem.szMaster>=nBlock ){
11778     return memsys3FromMaster(nBlock);
11779   }
11780
11781
11782   /* STEP 3:  
11783   ** Loop through the entire memory pool.  Coalesce adjacent free
11784   ** chunks.  Recompute the master chunk as the largest free chunk.
11785   ** Then try again to satisfy the allocation by carving a piece off
11786   ** of the end of the master chunk.  This step happens very
11787   ** rarely (we hope!)
11788   */
11789   for(toFree=nBlock*16; toFree<SQLITE_MEMORY_SIZE*2; toFree *= 2){
11790     memsys3OutOfMemory(toFree);
11791     if( mem.iMaster ){
11792       memsys3Link(mem.iMaster);
11793       mem.iMaster = 0;
11794       mem.szMaster = 0;
11795     }
11796     for(i=0; i<N_HASH; i++){
11797       memsys3Merge(&mem.aiHash[i]);
11798     }
11799     for(i=0; i<MX_SMALL-1; i++){
11800       memsys3Merge(&mem.aiSmall[i]);
11801     }
11802     if( mem.szMaster ){
11803       memsys3Unlink(mem.iMaster);
11804       if( mem.szMaster>=nBlock ){
11805         return memsys3FromMaster(nBlock);
11806       }
11807     }
11808   }
11809
11810   /* If none of the above worked, then we fail. */
11811   return 0;
11812 }
11813
11814 /*
11815 ** Free an outstanding memory allocation.
11816 */
11817 void memsys3Free(void *pOld){
11818   Mem3Block *p = (Mem3Block*)pOld;
11819   int i;
11820   u32 size, x;
11821   assert( sqlite3_mutex_held(mem.mutex) );
11822   assert( p>mem.aPool && p<&mem.aPool[SQLITE_MEMORY_SIZE/8] );
11823   i = p - mem.aPool;
11824   assert( (mem.aPool[i-1].u.hdr.size4x&1)==1 );
11825   size = mem.aPool[i-1].u.hdr.size4x/4;
11826   assert( i+size<=SQLITE_MEMORY_SIZE/8+1 );
11827   mem.aPool[i-1].u.hdr.size4x &= ~1;
11828   mem.aPool[i+size-1].u.hdr.prevSize = size;
11829   mem.aPool[i+size-1].u.hdr.size4x &= ~2;
11830   memsys3Link(i);
11831
11832   /* Try to expand the master using the newly freed chunk */
11833   if( mem.iMaster ){
11834     while( (mem.aPool[mem.iMaster-1].u.hdr.size4x&2)==0 ){
11835       size = mem.aPool[mem.iMaster-1].u.hdr.prevSize;
11836       mem.iMaster -= size;
11837       mem.szMaster += size;
11838       memsys3Unlink(mem.iMaster);
11839       x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2;
11840       mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x;
11841       mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster;
11842     }
11843     x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2;
11844     while( (mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x&1)==0 ){
11845       memsys3Unlink(mem.iMaster+mem.szMaster);
11846       mem.szMaster += mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x/4;
11847       mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x;
11848       mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster;
11849     }
11850   }
11851 }
11852
11853 /*
11854 ** Allocate nBytes of memory
11855 */
11856 SQLITE_API void *sqlite3_malloc(int nBytes){
11857   sqlite3_int64 *p = 0;
11858   if( nBytes>0 ){
11859     memsys3Enter();
11860     p = memsys3Malloc(nBytes);
11861     sqlite3_mutex_leave(mem.mutex);
11862   }
11863   return (void*)p; 
11864 }
11865
11866 /*
11867 ** Free memory.
11868 */
11869 SQLITE_API void sqlite3_free(void *pPrior){
11870   if( pPrior==0 ){
11871     return;
11872   }
11873   assert( mem.mutex!=0 );
11874   sqlite3_mutex_enter(mem.mutex);
11875   memsys3Free(pPrior);
11876   sqlite3_mutex_leave(mem.mutex);  
11877 }
11878
11879 /*
11880 ** Change the size of an existing memory allocation
11881 */
11882 SQLITE_API void *sqlite3_realloc(void *pPrior, int nBytes){
11883   int nOld;
11884   void *p;
11885   if( pPrior==0 ){
11886     return sqlite3_malloc(nBytes);
11887   }
11888   if( nBytes<=0 ){
11889     sqlite3_free(pPrior);
11890     return 0;
11891   }
11892   assert( mem.mutex!=0 );
11893   nOld = sqlite3MallocSize(pPrior);
11894   if( nBytes<=nOld && nBytes>=nOld-128 ){
11895     return pPrior;
11896   }
11897   sqlite3_mutex_enter(mem.mutex);
11898   p = memsys3Malloc(nBytes);
11899   if( p ){
11900     if( nOld<nBytes ){
11901       memcpy(p, pPrior, nOld);
11902     }else{
11903       memcpy(p, pPrior, nBytes);
11904     }
11905     memsys3Free(pPrior);
11906   }
11907   sqlite3_mutex_leave(mem.mutex);
11908   return p;
11909 }
11910
11911 /*
11912 ** Open the file indicated and write a log of all unfreed memory 
11913 ** allocations into that log.
11914 */
11915 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
11916 #ifdef SQLITE_DEBUG
11917   FILE *out;
11918   int i, j;
11919   u32 size;
11920   if( zFilename==0 || zFilename[0]==0 ){
11921     out = stdout;
11922   }else{
11923     out = fopen(zFilename, "w");
11924     if( out==0 ){
11925       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
11926                       zFilename);
11927       return;
11928     }
11929   }
11930   memsys3Enter();
11931   fprintf(out, "CHUNKS:\n");
11932   for(i=1; i<=SQLITE_MEMORY_SIZE/8; i+=size/4){
11933     size = mem.aPool[i-1].u.hdr.size4x;
11934     if( size/4<=1 ){
11935       fprintf(out, "%p size error\n", &mem.aPool[i]);
11936       assert( 0 );
11937       break;
11938     }
11939     if( (size&1)==0 && mem.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
11940       fprintf(out, "%p tail size does not match\n", &mem.aPool[i]);
11941       assert( 0 );
11942       break;
11943     }
11944     if( ((mem.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
11945       fprintf(out, "%p tail checkout bit is incorrect\n", &mem.aPool[i]);
11946       assert( 0 );
11947       break;
11948     }
11949     if( size&1 ){
11950       fprintf(out, "%p %6d bytes checked out\n", &mem.aPool[i], (size/4)*8-8);
11951     }else{
11952       fprintf(out, "%p %6d bytes free%s\n", &mem.aPool[i], (size/4)*8-8,
11953                   i==mem.iMaster ? " **master**" : "");
11954     }
11955   }
11956   for(i=0; i<MX_SMALL-1; i++){
11957     if( mem.aiSmall[i]==0 ) continue;
11958     fprintf(out, "small(%2d):", i);
11959     for(j = mem.aiSmall[i]; j>0; j=mem.aPool[j].u.list.next){
11960       fprintf(out, " %p(%d)", &mem.aPool[j],
11961               (mem.aPool[j-1].u.hdr.size4x/4)*8-8);
11962     }
11963     fprintf(out, "\n"); 
11964   }
11965   for(i=0; i<N_HASH; i++){
11966     if( mem.aiHash[i]==0 ) continue;
11967     fprintf(out, "hash(%2d):", i);
11968     for(j = mem.aiHash[i]; j>0; j=mem.aPool[j].u.list.next){
11969       fprintf(out, " %p(%d)", &mem.aPool[j],
11970               (mem.aPool[j-1].u.hdr.size4x/4)*8-8);
11971     }
11972     fprintf(out, "\n"); 
11973   }
11974   fprintf(out, "master=%d\n", mem.iMaster);
11975   fprintf(out, "nowUsed=%d\n", SQLITE_MEMORY_SIZE - mem.szMaster*8);
11976   fprintf(out, "mxUsed=%d\n", SQLITE_MEMORY_SIZE - mem.mnMaster*8);
11977   sqlite3_mutex_leave(mem.mutex);
11978   if( out==stdout ){
11979     fflush(stdout);
11980   }else{
11981     fclose(out);
11982   }
11983 #endif
11984 }
11985
11986
11987 #endif /* !SQLITE_MEMORY_SIZE */
11988
11989 /************** End of mem3.c ************************************************/
11990 /************** Begin file mem5.c ********************************************/
11991 /*
11992 ** 2007 October 14
11993 **
11994 ** The author disclaims copyright to this source code.  In place of
11995 ** a legal notice, here is a blessing:
11996 **
11997 **    May you do good and not evil.
11998 **    May you find forgiveness for yourself and forgive others.
11999 **    May you share freely, never taking more than you give.
12000 **
12001 *************************************************************************
12002 ** This file contains the C functions that implement a memory
12003 ** allocation subsystem for use by SQLite. 
12004 **
12005 ** This version of the memory allocation subsystem omits all
12006 ** use of malloc().  All dynamically allocatable memory is
12007 ** contained in a static array, mem.aPool[].  The size of this
12008 ** fixed memory pool is SQLITE_POW2_MEMORY_SIZE bytes.
12009 **
12010 ** This version of the memory allocation subsystem is used if
12011 ** and only if SQLITE_POW2_MEMORY_SIZE is defined.
12012 **
12013 ** $Id: mem5.c,v 1.4 2008/02/19 15:15:16 drh Exp $
12014 */
12015
12016 /*
12017 ** This version of the memory allocator is used only when 
12018 ** SQLITE_POW2_MEMORY_SIZE is defined.
12019 */
12020 #ifdef SQLITE_POW2_MEMORY_SIZE
12021
12022 /*
12023 ** Log2 of the minimum size of an allocation.  For example, if
12024 ** 4 then all allocations will be rounded up to at least 16 bytes.
12025 ** If 5 then all allocations will be rounded up to at least 32 bytes.
12026 */
12027 #ifndef SQLITE_POW2_LOGMIN
12028 # define SQLITE_POW2_LOGMIN 6
12029 #endif
12030 #define POW2_MIN (1<<SQLITE_POW2_LOGMIN)
12031
12032 /*
12033 ** Log2 of the maximum size of an allocation.
12034 */
12035 #ifndef SQLITE_POW2_LOGMAX
12036 # define SQLITE_POW2_LOGMAX 18
12037 #endif
12038 #define POW2_MAX (((unsigned int)1)<<SQLITE_POW2_LOGMAX)
12039
12040 /*
12041 ** Number of distinct allocation sizes.
12042 */
12043 #define NSIZE (SQLITE_POW2_LOGMAX - SQLITE_POW2_LOGMIN + 1)
12044
12045 /*
12046 ** A minimum allocation is an instance of the following structure.
12047 ** Larger allocations are an array of these structures where the
12048 ** size of the array is a power of 2.
12049 */
12050 typedef struct Mem5Block Mem5Block;
12051 struct Mem5Block {
12052   union {
12053     char aData[POW2_MIN];
12054     struct {
12055       int next;       /* Index in mem.aPool[] of next free chunk */
12056       int prev;       /* Index in mem.aPool[] of previous free chunk */
12057     } list;
12058   } u;
12059 };
12060
12061 /*
12062 ** Number of blocks of memory available for allocation.
12063 */
12064 #define NBLOCK (SQLITE_POW2_MEMORY_SIZE/POW2_MIN)
12065
12066 /*
12067 ** The size in blocks of an POW2_MAX allocation
12068 */
12069 #define SZ_MAX (1<<(NSIZE-1))
12070
12071 /*
12072 ** Masks used for mem.aCtrl[] elements.
12073 */
12074 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
12075 #define CTRL_FREE     0x20    /* True if not checked out */
12076
12077 /*
12078 ** All of the static variables used by this module are collected
12079 ** into a single structure named "mem".  This is to keep the
12080 ** static variables organized and to reduce namespace pollution
12081 ** when this module is combined with other in the amalgamation.
12082 */
12083 static struct {
12084   /*
12085   ** The alarm callback and its arguments.  The mem.mutex lock will
12086   ** be held while the callback is running.  Recursive calls into
12087   ** the memory subsystem are allowed, but no new callbacks will be
12088   ** issued.  The alarmBusy variable is set to prevent recursive
12089   ** callbacks.
12090   */
12091   sqlite3_int64 alarmThreshold;
12092   void (*alarmCallback)(void*, sqlite3_int64,int);
12093   void *alarmArg;
12094   int alarmBusy;
12095   
12096   /*
12097   ** Mutex to control access to the memory allocation subsystem.
12098   */
12099   sqlite3_mutex *mutex;
12100
12101   /*
12102   ** Performance statistics
12103   */
12104   u64 nAlloc;         /* Total number of calls to malloc */
12105   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
12106   u64 totalExcess;    /* Total internal fragmentation */
12107   u32 currentOut;     /* Current checkout, including internal fragmentation */
12108   u32 currentCount;   /* Current number of distinct checkouts */
12109   u32 maxOut;         /* Maximum instantaneous currentOut */
12110   u32 maxCount;       /* Maximum instantaneous currentCount */
12111   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
12112   
12113   /*
12114   ** Lists of free blocks of various sizes.
12115   */
12116   int aiFreelist[NSIZE];
12117
12118   /*
12119   ** Space for tracking which blocks are checked out and the size
12120   ** of each block.  One byte per block.
12121   */
12122   u8 aCtrl[NBLOCK];
12123
12124   /*
12125   ** Memory available for allocation
12126   */
12127   Mem5Block aPool[NBLOCK];
12128 } mem;
12129
12130 /*
12131 ** Unlink the chunk at mem.aPool[i] from list it is currently
12132 ** on.  It should be found on mem.aiFreelist[iLogsize].
12133 */
12134 static void memsys5Unlink(int i, int iLogsize){
12135   int next, prev;
12136   assert( i>=0 && i<NBLOCK );
12137   assert( iLogsize>=0 && iLogsize<NSIZE );
12138   assert( (mem.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
12139   assert( sqlite3_mutex_held(mem.mutex) );
12140
12141   next = mem.aPool[i].u.list.next;
12142   prev = mem.aPool[i].u.list.prev;
12143   if( prev<0 ){
12144     mem.aiFreelist[iLogsize] = next;
12145   }else{
12146     mem.aPool[prev].u.list.next = next;
12147   }
12148   if( next>=0 ){
12149     mem.aPool[next].u.list.prev = prev;
12150   }
12151 }
12152
12153 /*
12154 ** Link the chunk at mem.aPool[i] so that is on the iLogsize
12155 ** free list.
12156 */
12157 static void memsys5Link(int i, int iLogsize){
12158   int x;
12159   assert( sqlite3_mutex_held(mem.mutex) );
12160   assert( i>=0 && i<NBLOCK );
12161   assert( iLogsize>=0 && iLogsize<NSIZE );
12162   assert( (mem.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
12163
12164   mem.aPool[i].u.list.next = x = mem.aiFreelist[iLogsize];
12165   mem.aPool[i].u.list.prev = -1;
12166   if( x>=0 ){
12167     assert( x<NBLOCK );
12168     mem.aPool[x].u.list.prev = i;
12169   }
12170   mem.aiFreelist[iLogsize] = i;
12171 }
12172
12173 /*
12174 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
12175 **
12176 ** Also:  Initialize the memory allocation subsystem the first time
12177 ** this routine is called.
12178 */
12179 static void memsys5Enter(void){
12180   if( mem.mutex==0 ){
12181     int i;
12182     assert( sizeof(Mem5Block)==POW2_MIN );
12183     assert( (SQLITE_POW2_MEMORY_SIZE % POW2_MAX)==0 );
12184     assert( SQLITE_POW2_MEMORY_SIZE>=POW2_MAX );
12185     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
12186     sqlite3_mutex_enter(mem.mutex);
12187     for(i=0; i<NSIZE; i++) mem.aiFreelist[i] = -1;
12188     for(i=0; i<=NBLOCK-SZ_MAX; i += SZ_MAX){
12189       mem.aCtrl[i] = (NSIZE-1) | CTRL_FREE;
12190       memsys5Link(i, NSIZE-1);
12191     }
12192   }else{
12193     sqlite3_mutex_enter(mem.mutex);
12194   }
12195 }
12196
12197 /*
12198 ** Return the amount of memory currently checked out.
12199 */
12200 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
12201   return mem.currentOut;
12202 }
12203
12204 /*
12205 ** Return the maximum amount of memory that has ever been
12206 ** checked out since either the beginning of this process
12207 ** or since the most recent reset.
12208 */
12209 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
12210   sqlite3_int64 n;
12211   memsys5Enter();
12212   n = mem.maxOut;
12213   if( resetFlag ){
12214     mem.maxOut = mem.currentOut;
12215   }
12216   sqlite3_mutex_leave(mem.mutex);  
12217   return n;
12218 }
12219
12220
12221 /*
12222 ** Trigger the alarm 
12223 */
12224 static void memsys5Alarm(int nByte){
12225   void (*xCallback)(void*,sqlite3_int64,int);
12226   sqlite3_int64 nowUsed;
12227   void *pArg;
12228   if( mem.alarmCallback==0 || mem.alarmBusy  ) return;
12229   mem.alarmBusy = 1;
12230   xCallback = mem.alarmCallback;
12231   nowUsed = mem.currentOut;
12232   pArg = mem.alarmArg;
12233   sqlite3_mutex_leave(mem.mutex);
12234   xCallback(pArg, nowUsed, nByte);
12235   sqlite3_mutex_enter(mem.mutex);
12236   mem.alarmBusy = 0;
12237 }
12238
12239 /*
12240 ** Change the alarm callback.
12241 **
12242 ** This is a no-op for the static memory allocator.  The purpose
12243 ** of the memory alarm is to support sqlite3_soft_heap_limit().
12244 ** But with this memory allocator, the soft_heap_limit is really
12245 ** a hard limit that is fixed at SQLITE_POW2_MEMORY_SIZE.
12246 */
12247 SQLITE_API int sqlite3_memory_alarm(
12248   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
12249   void *pArg,
12250   sqlite3_int64 iThreshold
12251 ){
12252   memsys5Enter();
12253   mem.alarmCallback = xCallback;
12254   mem.alarmArg = pArg;
12255   mem.alarmThreshold = iThreshold;
12256   sqlite3_mutex_leave(mem.mutex);
12257   return SQLITE_OK;
12258 }
12259
12260 /*
12261 ** Return the size of an outstanding allocation, in bytes.  The
12262 ** size returned omits the 8-byte header overhead.  This only
12263 ** works for chunks that are currently checked out.
12264 */
12265 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
12266   int iSize = 0;
12267   if( p ){
12268     int i = ((Mem5Block*)p) - mem.aPool;
12269     assert( i>=0 && i<NBLOCK );
12270     iSize = 1 << ((mem.aCtrl[i]&CTRL_LOGSIZE) + SQLITE_POW2_LOGMIN);
12271   }
12272   return iSize;
12273 }
12274
12275 /*
12276 ** Find the first entry on the freelist iLogsize.  Unlink that
12277 ** entry and return its index. 
12278 */
12279 static int memsys5UnlinkFirst(int iLogsize){
12280   int i;
12281   int iFirst;
12282
12283   assert( iLogsize>=0 && iLogsize<NSIZE );
12284   i = iFirst = mem.aiFreelist[iLogsize];
12285   assert( iFirst>=0 );
12286   while( i>0 ){
12287     if( i<iFirst ) iFirst = i;
12288     i = mem.aPool[i].u.list.next;
12289   }
12290   memsys5Unlink(iFirst, iLogsize);
12291   return iFirst;
12292 }
12293
12294 /*
12295 ** Return a block of memory of at least nBytes in size.
12296 ** Return NULL if unable.
12297 */
12298 static void *memsys5Malloc(int nByte){
12299   int i;           /* Index of a mem.aPool[] slot */
12300   int iBin;        /* Index into mem.aiFreelist[] */
12301   int iFullSz;     /* Size of allocation rounded up to power of 2 */
12302   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
12303
12304   assert( sqlite3_mutex_held(mem.mutex) );
12305
12306   /* Keep track of the maximum allocation request.  Even unfulfilled
12307   ** requests are counted */
12308   if( nByte>mem.maxRequest ){
12309     mem.maxRequest = nByte;
12310   }
12311
12312   /* Simulate a memory allocation fault */
12313   if( sqlite3FaultStep(SQLITE_FAULTINJECTOR_MALLOC) ) return 0;
12314
12315   /* Round nByte up to the next valid power of two */
12316   if( nByte>POW2_MAX ) return 0;
12317   for(iFullSz=POW2_MIN, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
12318
12319   /* If we will be over the memory alarm threshold after this allocation,
12320   ** then trigger the memory overflow alarm */
12321   if( mem.alarmCallback!=0 && mem.currentOut+iFullSz>=mem.alarmThreshold ){
12322     memsys5Alarm(iFullSz);
12323   }
12324
12325   /* Make sure mem.aiFreelist[iLogsize] contains at least one free
12326   ** block.  If not, then split a block of the next larger power of
12327   ** two in order to create a new free block of size iLogsize.
12328   */
12329   for(iBin=iLogsize; mem.aiFreelist[iBin]<0 && iBin<NSIZE; iBin++){}
12330   if( iBin>=NSIZE ) return 0;
12331   i = memsys5UnlinkFirst(iBin);
12332   while( iBin>iLogsize ){
12333     int newSize;
12334
12335     iBin--;
12336     newSize = 1 << iBin;
12337     mem.aCtrl[i+newSize] = CTRL_FREE | iBin;
12338     memsys5Link(i+newSize, iBin);
12339   }
12340   mem.aCtrl[i] = iLogsize;
12341
12342   /* Update allocator performance statistics. */
12343   mem.nAlloc++;
12344   mem.totalAlloc += iFullSz;
12345   mem.totalExcess += iFullSz - nByte;
12346   mem.currentCount++;
12347   mem.currentOut += iFullSz;
12348   if( mem.maxCount<mem.currentCount ) mem.maxCount = mem.currentCount;
12349   if( mem.maxOut<mem.currentOut ) mem.maxOut = mem.currentOut;
12350
12351   /* Return a pointer to the allocated memory. */
12352   return (void*)&mem.aPool[i];
12353 }
12354
12355 /*
12356 ** Free an outstanding memory allocation.
12357 */
12358 void memsys5Free(void *pOld){
12359   u32 size, iLogsize;
12360   int i;
12361
12362   i = ((Mem5Block*)pOld) - mem.aPool;
12363   assert( sqlite3_mutex_held(mem.mutex) );
12364   assert( i>=0 && i<NBLOCK );
12365   assert( (mem.aCtrl[i] & CTRL_FREE)==0 );
12366   iLogsize = mem.aCtrl[i] & CTRL_LOGSIZE;
12367   size = 1<<iLogsize;
12368   assert( i+size-1<NBLOCK );
12369   mem.aCtrl[i] |= CTRL_FREE;
12370   mem.aCtrl[i+size-1] |= CTRL_FREE;
12371   assert( mem.currentCount>0 );
12372   assert( mem.currentOut>=0 );
12373   mem.currentCount--;
12374   mem.currentOut -= size*POW2_MIN;
12375   assert( mem.currentOut>0 || mem.currentCount==0 );
12376   assert( mem.currentCount>0 || mem.currentOut==0 );
12377
12378   mem.aCtrl[i] = CTRL_FREE | iLogsize;
12379   while( iLogsize<NSIZE-1 ){
12380     int iBuddy;
12381
12382     if( (i>>iLogsize) & 1 ){
12383       iBuddy = i - size;
12384     }else{
12385       iBuddy = i + size;
12386     }
12387     assert( iBuddy>=0 && iBuddy<NBLOCK );
12388     if( mem.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
12389     memsys5Unlink(iBuddy, iLogsize);
12390     iLogsize++;
12391     if( iBuddy<i ){
12392       mem.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
12393       mem.aCtrl[i] = 0;
12394       i = iBuddy;
12395     }else{
12396       mem.aCtrl[i] = CTRL_FREE | iLogsize;
12397       mem.aCtrl[iBuddy] = 0;
12398     }
12399     size *= 2;
12400   }
12401   memsys5Link(i, iLogsize);
12402 }
12403
12404 /*
12405 ** Allocate nBytes of memory
12406 */
12407 SQLITE_API void *sqlite3_malloc(int nBytes){
12408   sqlite3_int64 *p = 0;
12409   if( nBytes>0 ){
12410     memsys5Enter();
12411     p = memsys5Malloc(nBytes);
12412     sqlite3_mutex_leave(mem.mutex);
12413   }
12414   return (void*)p; 
12415 }
12416
12417 /*
12418 ** Free memory.
12419 */
12420 SQLITE_API void sqlite3_free(void *pPrior){
12421   if( pPrior==0 ){
12422     return;
12423   }
12424   assert( mem.mutex!=0 );
12425   sqlite3_mutex_enter(mem.mutex);
12426   memsys5Free(pPrior);
12427   sqlite3_mutex_leave(mem.mutex);  
12428 }
12429
12430 /*
12431 ** Change the size of an existing memory allocation
12432 */
12433 SQLITE_API void *sqlite3_realloc(void *pPrior, int nBytes){
12434   int nOld;
12435   void *p;
12436   if( pPrior==0 ){
12437     return sqlite3_malloc(nBytes);
12438   }
12439   if( nBytes<=0 ){
12440     sqlite3_free(pPrior);
12441     return 0;
12442   }
12443   assert( mem.mutex!=0 );
12444   nOld = sqlite3MallocSize(pPrior);
12445   if( nBytes<=nOld ){
12446     return pPrior;
12447   }
12448   sqlite3_mutex_enter(mem.mutex);
12449   p = memsys5Malloc(nBytes);
12450   if( p ){
12451     memcpy(p, pPrior, nOld);
12452     memsys5Free(pPrior);
12453   }
12454   sqlite3_mutex_leave(mem.mutex);
12455   return p;
12456 }
12457
12458 /*
12459 ** Open the file indicated and write a log of all unfreed memory 
12460 ** allocations into that log.
12461 */
12462 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
12463 #ifdef SQLITE_DEBUG
12464   FILE *out;
12465   int i, j, n;
12466
12467   if( zFilename==0 || zFilename[0]==0 ){
12468     out = stdout;
12469   }else{
12470     out = fopen(zFilename, "w");
12471     if( out==0 ){
12472       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
12473                       zFilename);
12474       return;
12475     }
12476   }
12477   memsys5Enter();
12478   for(i=0; i<NSIZE; i++){
12479     for(n=0, j=mem.aiFreelist[i]; j>=0; j = mem.aPool[j].u.list.next, n++){}
12480     fprintf(out, "freelist items of size %d: %d\n", POW2_MIN << i, n);
12481   }
12482   fprintf(out, "mem.nAlloc       = %llu\n", mem.nAlloc);
12483   fprintf(out, "mem.totalAlloc   = %llu\n", mem.totalAlloc);
12484   fprintf(out, "mem.totalExcess  = %llu\n", mem.totalExcess);
12485   fprintf(out, "mem.currentOut   = %u\n", mem.currentOut);
12486   fprintf(out, "mem.currentCount = %u\n", mem.currentCount);
12487   fprintf(out, "mem.maxOut       = %u\n", mem.maxOut);
12488   fprintf(out, "mem.maxCount     = %u\n", mem.maxCount);
12489   fprintf(out, "mem.maxRequest   = %u\n", mem.maxRequest);
12490   sqlite3_mutex_leave(mem.mutex);
12491   if( out==stdout ){
12492     fflush(stdout);
12493   }else{
12494     fclose(out);
12495   }
12496 #endif
12497 }
12498
12499
12500 #endif /* !SQLITE_POW2_MEMORY_SIZE */
12501
12502 /************** End of mem5.c ************************************************/
12503 /************** Begin file mutex.c *******************************************/
12504 /*
12505 ** 2007 August 14
12506 **
12507 ** The author disclaims copyright to this source code.  In place of
12508 ** a legal notice, here is a blessing:
12509 **
12510 **    May you do good and not evil.
12511 **    May you find forgiveness for yourself and forgive others.
12512 **    May you share freely, never taking more than you give.
12513 **
12514 *************************************************************************
12515 ** This file contains the C functions that implement mutexes.
12516 **
12517 ** The implementation in this file does not provide any mutual
12518 ** exclusion and is thus suitable for use only in applications
12519 ** that use SQLite in a single thread.  But this implementation
12520 ** does do a lot of error checking on mutexes to make sure they
12521 ** are called correctly and at appropriate times.  Hence, this
12522 ** implementation is suitable for testing.
12523 ** debugging purposes
12524 **
12525 ** $Id: mutex.c,v 1.16 2007/09/10 16:13:00 danielk1977 Exp $
12526 */
12527
12528 #ifdef SQLITE_MUTEX_NOOP_DEBUG
12529 /*
12530 ** In this implementation, mutexes do not provide any mutual exclusion.
12531 ** But the error checking is provided.  This implementation is useful
12532 ** for test purposes.
12533 */
12534
12535 /*
12536 ** The mutex object
12537 */
12538 struct sqlite3_mutex {
12539   int id;     /* The mutex type */
12540   int cnt;    /* Number of entries without a matching leave */
12541 };
12542
12543 /*
12544 ** The sqlite3_mutex_alloc() routine allocates a new
12545 ** mutex and returns a pointer to it.  If it returns NULL
12546 ** that means that a mutex could not be allocated. 
12547 */
12548 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
12549   static sqlite3_mutex aStatic[5];
12550   sqlite3_mutex *pNew = 0;
12551   switch( id ){
12552     case SQLITE_MUTEX_FAST:
12553     case SQLITE_MUTEX_RECURSIVE: {
12554       pNew = sqlite3_malloc(sizeof(*pNew));
12555       if( pNew ){
12556         pNew->id = id;
12557         pNew->cnt = 0;
12558       }
12559       break;
12560     }
12561     default: {
12562       assert( id-2 >= 0 );
12563       assert( id-2 < sizeof(aStatic)/sizeof(aStatic[0]) );
12564       pNew = &aStatic[id-2];
12565       pNew->id = id;
12566       break;
12567     }
12568   }
12569   return pNew;
12570 }
12571
12572 /*
12573 ** This routine deallocates a previously allocated mutex.
12574 */
12575 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
12576   assert( p );
12577   assert( p->cnt==0 );
12578   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
12579   sqlite3_free(p);
12580 }
12581
12582 /*
12583 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
12584 ** to enter a mutex.  If another thread is already within the mutex,
12585 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
12586 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
12587 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
12588 ** be entered multiple times by the same thread.  In such cases the,
12589 ** mutex must be exited an equal number of times before another thread
12590 ** can enter.  If the same thread tries to enter any other kind of mutex
12591 ** more than once, the behavior is undefined.
12592 */
12593 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
12594   assert( p );
12595   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
12596   p->cnt++;
12597 }
12598 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
12599   assert( p );
12600   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
12601   p->cnt++;
12602   return SQLITE_OK;
12603 }
12604
12605 /*
12606 ** The sqlite3_mutex_leave() routine exits a mutex that was
12607 ** previously entered by the same thread.  The behavior
12608 ** is undefined if the mutex is not currently entered or
12609 ** is not currently allocated.  SQLite will never do either.
12610 */
12611 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
12612   assert( p );
12613   assert( sqlite3_mutex_held(p) );
12614   p->cnt--;
12615   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
12616 }
12617
12618 /*
12619 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
12620 ** intended for use inside assert() statements.
12621 */
12622 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
12623   return p==0 || p->cnt>0;
12624 }
12625 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
12626   return p==0 || p->cnt==0;
12627 }
12628 #endif /* SQLITE_MUTEX_NOOP_DEBUG */
12629
12630 /************** End of mutex.c ***********************************************/
12631 /************** Begin file mutex_os2.c ***************************************/
12632 /*
12633 ** 2007 August 28
12634 **
12635 ** The author disclaims copyright to this source code.  In place of
12636 ** a legal notice, here is a blessing:
12637 **
12638 **    May you do good and not evil.
12639 **    May you find forgiveness for yourself and forgive others.
12640 **    May you share freely, never taking more than you give.
12641 **
12642 *************************************************************************
12643 ** This file contains the C functions that implement mutexes for OS/2
12644 **
12645 ** $Id: mutex_os2.c,v 1.5 2008/02/01 19:42:38 pweilbacher Exp $
12646 */
12647
12648 /*
12649 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
12650 ** See the mutex.h file for details.
12651 */
12652 #ifdef SQLITE_MUTEX_OS2
12653
12654 /********************** OS/2 Mutex Implementation **********************
12655 **
12656 ** This implementation of mutexes is built using the OS/2 API.
12657 */
12658
12659 /*
12660 ** The mutex object
12661 ** Each recursive mutex is an instance of the following structure.
12662 */
12663 struct sqlite3_mutex {
12664   HMTX mutex;       /* Mutex controlling the lock */
12665   int  id;          /* Mutex type */
12666   int  nRef;        /* Number of references */
12667   TID  owner;       /* Thread holding this mutex */
12668 };
12669
12670 #define OS2_MUTEX_INITIALIZER   0,0,0,0
12671
12672 /*
12673 ** The sqlite3_mutex_alloc() routine allocates a new
12674 ** mutex and returns a pointer to it.  If it returns NULL
12675 ** that means that a mutex could not be allocated. 
12676 ** SQLite will unwind its stack and return an error.  The argument
12677 ** to sqlite3_mutex_alloc() is one of these integer constants:
12678 **
12679 ** <ul>
12680 ** <li>  SQLITE_MUTEX_FAST               0
12681 ** <li>  SQLITE_MUTEX_RECURSIVE          1
12682 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
12683 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
12684 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
12685 ** </ul>
12686 **
12687 ** The first two constants cause sqlite3_mutex_alloc() to create
12688 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
12689 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
12690 ** The mutex implementation does not need to make a distinction
12691 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
12692 ** not want to.  But SQLite will only request a recursive mutex in
12693 ** cases where it really needs one.  If a faster non-recursive mutex
12694 ** implementation is available on the host platform, the mutex subsystem
12695 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
12696 **
12697 ** The other allowed parameters to sqlite3_mutex_alloc() each return
12698 ** a pointer to a static preexisting mutex.  Three static mutexes are
12699 ** used by the current version of SQLite.  Future versions of SQLite
12700 ** may add additional static mutexes.  Static mutexes are for internal
12701 ** use by SQLite only.  Applications that use SQLite mutexes should
12702 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
12703 ** SQLITE_MUTEX_RECURSIVE.
12704 **
12705 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
12706 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
12707 ** returns a different mutex on every call.  But for the static
12708 ** mutex types, the same mutex is returned on every call that has
12709 ** the same type number.
12710 */
12711 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
12712   sqlite3_mutex *p = NULL;
12713   switch( iType ){
12714     case SQLITE_MUTEX_FAST:
12715     case SQLITE_MUTEX_RECURSIVE: {
12716       p = sqlite3MallocZero( sizeof(*p) );
12717       if( p ){
12718         p->id = iType;
12719         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
12720           sqlite3_free( p );
12721           p = NULL;
12722         }
12723       }
12724       break;
12725     }
12726     default: {
12727       static volatile int isInit = 0;
12728       static sqlite3_mutex staticMutexes[] = {
12729         { OS2_MUTEX_INITIALIZER, },
12730         { OS2_MUTEX_INITIALIZER, },
12731         { OS2_MUTEX_INITIALIZER, },
12732         { OS2_MUTEX_INITIALIZER, },
12733         { OS2_MUTEX_INITIALIZER, },
12734       };
12735       if ( !isInit ){
12736         APIRET rc;
12737         PTIB ptib;
12738         PPIB ppib;
12739         HMTX mutex;
12740         char name[32];
12741         DosGetInfoBlocks( &ptib, &ppib );
12742         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
12743                           ppib->pib_ulpid );
12744         while( !isInit ){
12745           mutex = 0;
12746           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
12747           if( rc == NO_ERROR ){
12748             int i;
12749             if( !isInit ){
12750               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
12751                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
12752               }
12753               isInit = 1;
12754             }
12755             DosCloseMutexSem( mutex );
12756           }else if( rc == ERROR_DUPLICATE_NAME ){
12757             DosSleep( 1 );
12758           }else{
12759             return p;
12760           }
12761         }
12762       }
12763       assert( iType-2 >= 0 );
12764       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
12765       p = &staticMutexes[iType-2];
12766       p->id = iType;
12767       break;
12768     }
12769   }
12770   return p;
12771 }
12772
12773
12774 /*
12775 ** This routine deallocates a previously allocated mutex.
12776 ** SQLite is careful to deallocate every mutex that it allocates.
12777 */
12778 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
12779   assert( p );
12780   assert( p->nRef==0 );
12781   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
12782   DosCloseMutexSem( p->mutex );
12783   sqlite3_free( p );
12784 }
12785
12786 /*
12787 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
12788 ** to enter a mutex.  If another thread is already within the mutex,
12789 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
12790 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
12791 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
12792 ** be entered multiple times by the same thread.  In such cases the,
12793 ** mutex must be exited an equal number of times before another thread
12794 ** can enter.  If the same thread tries to enter any other kind of mutex
12795 ** more than once, the behavior is undefined.
12796 */
12797 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
12798   TID tid;
12799   PID holder1;
12800   ULONG holder2;
12801   assert( p );
12802   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
12803   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
12804   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
12805   p->owner = tid;
12806   p->nRef++;
12807 }
12808 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
12809   int rc;
12810   TID tid;
12811   PID holder1;
12812   ULONG holder2;
12813   assert( p );
12814   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
12815   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
12816     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
12817     p->owner = tid;
12818     p->nRef++;
12819     rc = SQLITE_OK;
12820   } else {
12821     rc = SQLITE_BUSY;
12822   }
12823
12824   return rc;
12825 }
12826
12827 /*
12828 ** The sqlite3_mutex_leave() routine exits a mutex that was
12829 ** previously entered by the same thread.  The behavior
12830 ** is undefined if the mutex is not currently entered or
12831 ** is not currently allocated.  SQLite will never do either.
12832 */
12833 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
12834   TID tid;
12835   PID holder1;
12836   ULONG holder2;
12837   assert( p->nRef>0 );
12838   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
12839   assert( p->owner==tid );
12840   p->nRef--;
12841   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
12842   DosReleaseMutexSem(p->mutex);
12843 }
12844
12845 /*
12846 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
12847 ** intended for use inside assert() statements.
12848 */
12849 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
12850   TID tid;
12851   PID pid;
12852   ULONG ulCount;
12853   PTIB ptib;
12854   if( p!=0 ) {
12855     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
12856   } else {
12857     DosGetInfoBlocks(&ptib, NULL);
12858     tid = ptib->tib_ptib2->tib2_ultid;
12859   }
12860   return p==0 || (p->nRef!=0 && p->owner==tid);
12861 }
12862 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
12863   TID tid;
12864   PID pid;
12865   ULONG ulCount;
12866   PTIB ptib;
12867   if( p!= 0 ) {
12868     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
12869   } else {
12870     DosGetInfoBlocks(&ptib, NULL);
12871     tid = ptib->tib_ptib2->tib2_ultid;
12872   }
12873   return p==0 || p->nRef==0 || p->owner!=tid;
12874 }
12875 #endif /* SQLITE_MUTEX_OS2 */
12876
12877 /************** End of mutex_os2.c *******************************************/
12878 /************** Begin file mutex_unix.c **************************************/
12879 /*
12880 ** 2007 August 28
12881 **
12882 ** The author disclaims copyright to this source code.  In place of
12883 ** a legal notice, here is a blessing:
12884 **
12885 **    May you do good and not evil.
12886 **    May you find forgiveness for yourself and forgive others.
12887 **    May you share freely, never taking more than you give.
12888 **
12889 *************************************************************************
12890 ** This file contains the C functions that implement mutexes for pthreads
12891 **
12892 ** $Id: mutex_unix.c,v 1.5 2007/11/28 14:04:57 drh Exp $
12893 */
12894
12895 /*
12896 ** The code in this file is only used if we are compiling threadsafe
12897 ** under unix with pthreads.
12898 **
12899 ** Note that this implementation requires a version of pthreads that
12900 ** supports recursive mutexes.
12901 */
12902 #ifdef SQLITE_MUTEX_PTHREADS
12903
12904 #include <pthread.h>
12905
12906
12907 /*
12908 ** Each recursive mutex is an instance of the following structure.
12909 */
12910 struct sqlite3_mutex {
12911   pthread_mutex_t mutex;     /* Mutex controlling the lock */
12912   int id;                    /* Mutex type */
12913   int nRef;                  /* Number of entrances */
12914   pthread_t owner;           /* Thread that is within this mutex */
12915 #ifdef SQLITE_DEBUG
12916   int trace;                 /* True to trace changes */
12917 #endif
12918 };
12919
12920 /*
12921 ** The sqlite3_mutex_alloc() routine allocates a new
12922 ** mutex and returns a pointer to it.  If it returns NULL
12923 ** that means that a mutex could not be allocated.  SQLite
12924 ** will unwind its stack and return an error.  The argument
12925 ** to sqlite3_mutex_alloc() is one of these integer constants:
12926 **
12927 ** <ul>
12928 ** <li>  SQLITE_MUTEX_FAST
12929 ** <li>  SQLITE_MUTEX_RECURSIVE
12930 ** <li>  SQLITE_MUTEX_STATIC_MASTER
12931 ** <li>  SQLITE_MUTEX_STATIC_MEM
12932 ** <li>  SQLITE_MUTEX_STATIC_MEM2
12933 ** <li>  SQLITE_MUTEX_STATIC_PRNG
12934 ** <li>  SQLITE_MUTEX_STATIC_LRU
12935 ** </ul>
12936 **
12937 ** The first two constants cause sqlite3_mutex_alloc() to create
12938 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
12939 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
12940 ** The mutex implementation does not need to make a distinction
12941 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
12942 ** not want to.  But SQLite will only request a recursive mutex in
12943 ** cases where it really needs one.  If a faster non-recursive mutex
12944 ** implementation is available on the host platform, the mutex subsystem
12945 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
12946 **
12947 ** The other allowed parameters to sqlite3_mutex_alloc() each return
12948 ** a pointer to a static preexisting mutex.  Three static mutexes are
12949 ** used by the current version of SQLite.  Future versions of SQLite
12950 ** may add additional static mutexes.  Static mutexes are for internal
12951 ** use by SQLite only.  Applications that use SQLite mutexes should
12952 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
12953 ** SQLITE_MUTEX_RECURSIVE.
12954 **
12955 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
12956 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
12957 ** returns a different mutex on every call.  But for the static 
12958 ** mutex types, the same mutex is returned on every call that has
12959 ** the same type number.
12960 */
12961 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
12962   static sqlite3_mutex staticMutexes[] = {
12963     { PTHREAD_MUTEX_INITIALIZER, },
12964     { PTHREAD_MUTEX_INITIALIZER, },
12965     { PTHREAD_MUTEX_INITIALIZER, },
12966     { PTHREAD_MUTEX_INITIALIZER, },
12967     { PTHREAD_MUTEX_INITIALIZER, },
12968   };
12969   sqlite3_mutex *p;
12970   switch( iType ){
12971     case SQLITE_MUTEX_RECURSIVE: {
12972       p = sqlite3MallocZero( sizeof(*p) );
12973       if( p ){
12974 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12975         /* If recursive mutexes are not available, we will have to
12976         ** build our own.  See below. */
12977         pthread_mutex_init(&p->mutex, 0);
12978 #else
12979         /* Use a recursive mutex if it is available */
12980         pthread_mutexattr_t recursiveAttr;
12981         pthread_mutexattr_init(&recursiveAttr);
12982         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
12983         pthread_mutex_init(&p->mutex, &recursiveAttr);
12984         pthread_mutexattr_destroy(&recursiveAttr);
12985 #endif
12986         p->id = iType;
12987       }
12988       break;
12989     }
12990     case SQLITE_MUTEX_FAST: {
12991       p = sqlite3MallocZero( sizeof(*p) );
12992       if( p ){
12993         p->id = iType;
12994         pthread_mutex_init(&p->mutex, 0);
12995       }
12996       break;
12997     }
12998     default: {
12999       assert( iType-2 >= 0 );
13000       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
13001       p = &staticMutexes[iType-2];
13002       p->id = iType;
13003       break;
13004     }
13005   }
13006   return p;
13007 }
13008
13009
13010 /*
13011 ** This routine deallocates a previously
13012 ** allocated mutex.  SQLite is careful to deallocate every
13013 ** mutex that it allocates.
13014 */
13015 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
13016   assert( p );
13017   assert( p->nRef==0 );
13018   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
13019   pthread_mutex_destroy(&p->mutex);
13020   sqlite3_free(p);
13021 }
13022
13023 /*
13024 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
13025 ** to enter a mutex.  If another thread is already within the mutex,
13026 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
13027 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
13028 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
13029 ** be entered multiple times by the same thread.  In such cases the,
13030 ** mutex must be exited an equal number of times before another thread
13031 ** can enter.  If the same thread tries to enter any other kind of mutex
13032 ** more than once, the behavior is undefined.
13033 */
13034 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
13035   assert( p );
13036   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13037
13038 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13039   /* If recursive mutexes are not available, then we have to grow
13040   ** our own.  This implementation assumes that pthread_equal()
13041   ** is atomic - that it cannot be deceived into thinking self
13042   ** and p->owner are equal if p->owner changes between two values
13043   ** that are not equal to self while the comparison is taking place.
13044   ** This implementation also assumes a coherent cache - that 
13045   ** separate processes cannot read different values from the same
13046   ** address at the same time.  If either of these two conditions
13047   ** are not met, then the mutexes will fail and problems will result.
13048   */
13049   {
13050     pthread_t self = pthread_self();
13051     if( p->nRef>0 && pthread_equal(p->owner, self) ){
13052       p->nRef++;
13053     }else{
13054       pthread_mutex_lock(&p->mutex);
13055       assert( p->nRef==0 );
13056       p->owner = self;
13057       p->nRef = 1;
13058     }
13059   }
13060 #else
13061   /* Use the built-in recursive mutexes if they are available.
13062   */
13063   pthread_mutex_lock(&p->mutex);
13064   p->owner = pthread_self();
13065   p->nRef++;
13066 #endif
13067
13068 #ifdef SQLITE_DEBUG
13069   if( p->trace ){
13070     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
13071   }
13072 #endif
13073 }
13074 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
13075   int rc;
13076   assert( p );
13077   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13078
13079 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13080   /* If recursive mutexes are not available, then we have to grow
13081   ** our own.  This implementation assumes that pthread_equal()
13082   ** is atomic - that it cannot be deceived into thinking self
13083   ** and p->owner are equal if p->owner changes between two values
13084   ** that are not equal to self while the comparison is taking place.
13085   ** This implementation also assumes a coherent cache - that 
13086   ** separate processes cannot read different values from the same
13087   ** address at the same time.  If either of these two conditions
13088   ** are not met, then the mutexes will fail and problems will result.
13089   */
13090   {
13091     pthread_t self = pthread_self();
13092     if( p->nRef>0 && pthread_equal(p->owner, self) ){
13093       p->nRef++;
13094       rc = SQLITE_OK;
13095     }else if( pthread_mutex_lock(&p->mutex)==0 ){
13096       assert( p->nRef==0 );
13097       p->owner = self;
13098       p->nRef = 1;
13099       rc = SQLITE_OK;
13100     }else{
13101       rc = SQLITE_BUSY;
13102     }
13103   }
13104 #else
13105   /* Use the built-in recursive mutexes if they are available.
13106   */
13107   if( pthread_mutex_trylock(&p->mutex)==0 ){
13108     p->owner = pthread_self();
13109     p->nRef++;
13110     rc = SQLITE_OK;
13111   }else{
13112     rc = SQLITE_BUSY;
13113   }
13114 #endif
13115
13116 #ifdef SQLITE_DEBUG
13117   if( rc==SQLITE_OK && p->trace ){
13118     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
13119   }
13120 #endif
13121   return rc;
13122 }
13123
13124 /*
13125 ** The sqlite3_mutex_leave() routine exits a mutex that was
13126 ** previously entered by the same thread.  The behavior
13127 ** is undefined if the mutex is not currently entered or
13128 ** is not currently allocated.  SQLite will never do either.
13129 */
13130 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
13131   assert( p );
13132   assert( sqlite3_mutex_held(p) );
13133   p->nRef--;
13134   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
13135
13136 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13137   if( p->nRef==0 ){
13138     pthread_mutex_unlock(&p->mutex);
13139   }
13140 #else
13141   pthread_mutex_unlock(&p->mutex);
13142 #endif
13143
13144 #ifdef SQLITE_DEBUG
13145   if( p->trace ){
13146     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
13147   }
13148 #endif
13149 }
13150
13151 /*
13152 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
13153 ** intended for use only inside assert() statements.  On some platforms,
13154 ** there might be race conditions that can cause these routines to
13155 ** deliver incorrect results.  In particular, if pthread_equal() is
13156 ** not an atomic operation, then these routines might delivery
13157 ** incorrect results.  On most platforms, pthread_equal() is a 
13158 ** comparison of two integers and is therefore atomic.  But we are
13159 ** told that HPUX is not such a platform.  If so, then these routines
13160 ** will not always work correctly on HPUX.
13161 **
13162 ** On those platforms where pthread_equal() is not atomic, SQLite
13163 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
13164 ** make sure no assert() statements are evaluated and hence these
13165 ** routines are never called.
13166 */
13167 #ifndef NDEBUG
13168 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
13169   return p==0 || (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
13170 }
13171 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
13172   return p==0 || p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
13173 }
13174 #endif
13175 #endif /* SQLITE_MUTEX_PTHREAD */
13176
13177 /************** End of mutex_unix.c ******************************************/
13178 /************** Begin file mutex_w32.c ***************************************/
13179 /*
13180 ** 2007 August 14
13181 **
13182 ** The author disclaims copyright to this source code.  In place of
13183 ** a legal notice, here is a blessing:
13184 **
13185 **    May you do good and not evil.
13186 **    May you find forgiveness for yourself and forgive others.
13187 **    May you share freely, never taking more than you give.
13188 **
13189 *************************************************************************
13190 ** This file contains the C functions that implement mutexes for win32
13191 **
13192 ** $Id: mutex_w32.c,v 1.5 2007/10/05 15:08:01 drh Exp $
13193 */
13194
13195 /*
13196 ** The code in this file is only used if we are compiling multithreaded
13197 ** on a win32 system.
13198 */
13199 #ifdef SQLITE_MUTEX_W32
13200
13201 /*
13202 ** Each recursive mutex is an instance of the following structure.
13203 */
13204 struct sqlite3_mutex {
13205   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
13206   int id;                    /* Mutex type */
13207   int nRef;                  /* Number of enterances */
13208   DWORD owner;               /* Thread holding this mutex */
13209 };
13210
13211 /*
13212 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
13213 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
13214 **
13215 ** Here is an interesting observation:  Win95, Win98, and WinME lack
13216 ** the LockFileEx() API.  But we can still statically link against that
13217 ** API as long as we don't call it win running Win95/98/ME.  A call to
13218 ** this routine is used to determine if the host is Win95/98/ME or
13219 ** WinNT/2K/XP so that we will know whether or not we can safely call
13220 ** the LockFileEx() API.
13221 */
13222 #if OS_WINCE
13223 # define mutexIsNT()  (1)
13224 #else
13225   static int mutexIsNT(void){
13226     static int osType = 0;
13227     if( osType==0 ){
13228       OSVERSIONINFO sInfo;
13229       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
13230       GetVersionEx(&sInfo);
13231       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
13232     }
13233     return osType==2;
13234   }
13235 #endif /* OS_WINCE */
13236
13237
13238 /*
13239 ** The sqlite3_mutex_alloc() routine allocates a new
13240 ** mutex and returns a pointer to it.  If it returns NULL
13241 ** that means that a mutex could not be allocated.  SQLite
13242 ** will unwind its stack and return an error.  The argument
13243 ** to sqlite3_mutex_alloc() is one of these integer constants:
13244 **
13245 ** <ul>
13246 ** <li>  SQLITE_MUTEX_FAST               0
13247 ** <li>  SQLITE_MUTEX_RECURSIVE          1
13248 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
13249 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
13250 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
13251 ** </ul>
13252 **
13253 ** The first two constants cause sqlite3_mutex_alloc() to create
13254 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
13255 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
13256 ** The mutex implementation does not need to make a distinction
13257 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
13258 ** not want to.  But SQLite will only request a recursive mutex in
13259 ** cases where it really needs one.  If a faster non-recursive mutex
13260 ** implementation is available on the host platform, the mutex subsystem
13261 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
13262 **
13263 ** The other allowed parameters to sqlite3_mutex_alloc() each return
13264 ** a pointer to a static preexisting mutex.  Three static mutexes are
13265 ** used by the current version of SQLite.  Future versions of SQLite
13266 ** may add additional static mutexes.  Static mutexes are for internal
13267 ** use by SQLite only.  Applications that use SQLite mutexes should
13268 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
13269 ** SQLITE_MUTEX_RECURSIVE.
13270 **
13271 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
13272 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
13273 ** returns a different mutex on every call.  But for the static 
13274 ** mutex types, the same mutex is returned on every call that has
13275 ** the same type number.
13276 */
13277 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
13278   sqlite3_mutex *p;
13279
13280   switch( iType ){
13281     case SQLITE_MUTEX_FAST:
13282     case SQLITE_MUTEX_RECURSIVE: {
13283       p = sqlite3MallocZero( sizeof(*p) );
13284       if( p ){
13285         p->id = iType;
13286         InitializeCriticalSection(&p->mutex);
13287       }
13288       break;
13289     }
13290     default: {
13291       static sqlite3_mutex staticMutexes[5];
13292       static int isInit = 0;
13293       while( !isInit ){
13294         static long lock = 0;
13295         if( InterlockedIncrement(&lock)==1 ){
13296           int i;
13297           for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
13298             InitializeCriticalSection(&staticMutexes[i].mutex);
13299           }
13300           isInit = 1;
13301         }else{
13302           Sleep(1);
13303         }
13304       }
13305       assert( iType-2 >= 0 );
13306       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
13307       p = &staticMutexes[iType-2];
13308       p->id = iType;
13309       break;
13310     }
13311   }
13312   return p;
13313 }
13314
13315
13316 /*
13317 ** This routine deallocates a previously
13318 ** allocated mutex.  SQLite is careful to deallocate every
13319 ** mutex that it allocates.
13320 */
13321 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
13322   assert( p );
13323   assert( p->nRef==0 );
13324   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
13325   DeleteCriticalSection(&p->mutex);
13326   sqlite3_free(p);
13327 }
13328
13329 /*
13330 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
13331 ** to enter a mutex.  If another thread is already within the mutex,
13332 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
13333 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
13334 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
13335 ** be entered multiple times by the same thread.  In such cases the,
13336 ** mutex must be exited an equal number of times before another thread
13337 ** can enter.  If the same thread tries to enter any other kind of mutex
13338 ** more than once, the behavior is undefined.
13339 */
13340 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
13341   assert( p );
13342   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13343   EnterCriticalSection(&p->mutex);
13344   p->owner = GetCurrentThreadId(); 
13345   p->nRef++;
13346 }
13347 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
13348   int rc = SQLITE_BUSY;
13349   assert( p );
13350   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13351   /*
13352   ** The sqlite3_mutex_try() routine is very rarely used, and when it
13353   ** is used it is merely an optimization.  So it is OK for it to always
13354   ** fail.  
13355   **
13356   ** The TryEnterCriticalSection() interface is only available on WinNT.
13357   ** And some windows compilers complain if you try to use it without
13358   ** first doing some #defines that prevent SQLite from building on Win98.
13359   ** For that reason, we will omit this optimization for now.  See
13360   ** ticket #2685.
13361   */
13362 #if 0
13363   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
13364     p->owner = GetCurrentThreadId();
13365     p->nRef++;
13366     rc = SQLITE_OK;
13367   }
13368 #endif
13369   return rc;
13370 }
13371
13372 /*
13373 ** The sqlite3_mutex_leave() routine exits a mutex that was
13374 ** previously entered by the same thread.  The behavior
13375 ** is undefined if the mutex is not currently entered or
13376 ** is not currently allocated.  SQLite will never do either.
13377 */
13378 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
13379   assert( p->nRef>0 );
13380   assert( p->owner==GetCurrentThreadId() );
13381   p->nRef--;
13382   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
13383   LeaveCriticalSection(&p->mutex);
13384 }
13385
13386 /*
13387 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
13388 ** intended for use only inside assert() statements.
13389 */
13390 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
13391   return p==0 || (p->nRef!=0 && p->owner==GetCurrentThreadId());
13392 }
13393 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
13394   return p==0 || p->nRef==0 || p->owner!=GetCurrentThreadId();
13395 }
13396 #endif /* SQLITE_MUTEX_W32 */
13397
13398 /************** End of mutex_w32.c *******************************************/
13399 /************** Begin file malloc.c ******************************************/
13400 /*
13401 ** 2001 September 15
13402 **
13403 ** The author disclaims copyright to this source code.  In place of
13404 ** a legal notice, here is a blessing:
13405 **
13406 **    May you do good and not evil.
13407 **    May you find forgiveness for yourself and forgive others.
13408 **    May you share freely, never taking more than you give.
13409 **
13410 *************************************************************************
13411 ** Memory allocation functions used throughout sqlite.
13412 **
13413 **
13414 ** $Id: malloc.c,v 1.14 2007/10/20 16:36:31 drh Exp $
13415 */
13416
13417 /*
13418 ** This routine runs when the memory allocator sees that the
13419 ** total memory allocation is about to exceed the soft heap
13420 ** limit.
13421 */
13422 static void softHeapLimitEnforcer(
13423   void *NotUsed, 
13424   sqlite3_int64 inUse,
13425   int allocSize
13426 ){
13427   sqlite3_release_memory(allocSize);
13428 }
13429
13430 /*
13431 ** Set the soft heap-size limit for the current thread. Passing a
13432 ** zero or negative value indicates no limit.
13433 */
13434 SQLITE_API void sqlite3_soft_heap_limit(int n){
13435   sqlite3_uint64 iLimit;
13436   int overage;
13437   if( n<0 ){
13438     iLimit = 0;
13439   }else{
13440     iLimit = n;
13441   }
13442   if( iLimit>0 ){
13443     sqlite3_memory_alarm(softHeapLimitEnforcer, 0, iLimit);
13444   }else{
13445     sqlite3_memory_alarm(0, 0, 0);
13446   }
13447   overage = sqlite3_memory_used() - n;
13448   if( overage>0 ){
13449     sqlite3_release_memory(overage);
13450   }
13451 }
13452
13453 /*
13454 ** Release memory held by SQLite instances created by the current thread.
13455 */
13456 SQLITE_API int sqlite3_release_memory(int n){
13457 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13458   return sqlite3PagerReleaseMemory(n);
13459 #else
13460   return SQLITE_OK;
13461 #endif
13462 }
13463
13464
13465 /*
13466 ** Allocate and zero memory.
13467 */ 
13468 SQLITE_PRIVATE void *sqlite3MallocZero(unsigned n){
13469   void *p = sqlite3_malloc(n);
13470   if( p ){
13471     memset(p, 0, n);
13472   }
13473   return p;
13474 }
13475
13476 /*
13477 ** Allocate and zero memory.  If the allocation fails, make
13478 ** the mallocFailed flag in the connection pointer.
13479 */
13480 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, unsigned n){
13481   void *p = sqlite3DbMallocRaw(db, n);
13482   if( p ){
13483     memset(p, 0, n);
13484   }
13485   return p;
13486 }
13487
13488 /*
13489 ** Allocate and zero memory.  If the allocation fails, make
13490 ** the mallocFailed flag in the connection pointer.
13491 */
13492 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, unsigned n){
13493   void *p = 0;
13494   if( !db || db->mallocFailed==0 ){
13495     p = sqlite3_malloc(n);
13496     if( !p && db ){
13497       db->mallocFailed = 1;
13498     }
13499   }
13500   return p;
13501 }
13502
13503 /*
13504 ** Resize the block of memory pointed to by p to n bytes. If the
13505 ** resize fails, set the mallocFailed flag inthe connection object.
13506 */
13507 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
13508   void *pNew = 0;
13509   if( db->mallocFailed==0 ){
13510     pNew = sqlite3_realloc(p, n);
13511     if( !pNew ){
13512       db->mallocFailed = 1;
13513     }
13514   }
13515   return pNew;
13516 }
13517
13518 /*
13519 ** Attempt to reallocate p.  If the reallocation fails, then free p
13520 ** and set the mallocFailed flag in the database connection.
13521 */
13522 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
13523   void *pNew;
13524   pNew = sqlite3DbRealloc(db, p, n);
13525   if( !pNew ){
13526     sqlite3_free(p);
13527   }
13528   return pNew;
13529 }
13530
13531 /*
13532 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
13533 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
13534 ** is because when memory debugging is turned on, these two functions are 
13535 ** called via macros that record the current file and line number in the
13536 ** ThreadData structure.
13537 */
13538 SQLITE_PRIVATE char *sqlite3StrDup(const char *z){
13539   char *zNew;
13540   int n;
13541   if( z==0 ) return 0;
13542   n = strlen(z)+1;
13543   zNew = sqlite3_malloc(n);
13544   if( zNew ) memcpy(zNew, z, n);
13545   return zNew;
13546 }
13547 SQLITE_PRIVATE char *sqlite3StrNDup(const char *z, int n){
13548   char *zNew;
13549   if( z==0 ) return 0;
13550   zNew = sqlite3_malloc(n+1);
13551   if( zNew ){
13552     memcpy(zNew, z, n);
13553     zNew[n] = 0;
13554   }
13555   return zNew;
13556 }
13557
13558 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
13559   char *zNew = sqlite3StrDup(z);
13560   if( z && !zNew ){
13561     db->mallocFailed = 1;
13562   }
13563   return zNew;
13564 }
13565 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
13566   char *zNew = sqlite3StrNDup(z, n);
13567   if( z && !zNew ){
13568     db->mallocFailed = 1;
13569   }
13570   return zNew;
13571 }
13572
13573 /*
13574 ** Create a string from the 2nd and subsequent arguments (up to the
13575 ** first NULL argument), store the string in memory obtained from
13576 ** sqliteMalloc() and make the pointer indicated by the 1st argument
13577 ** point to that string.  The 1st argument must either be NULL or 
13578 ** point to memory obtained from sqliteMalloc().
13579 */
13580 SQLITE_PRIVATE void sqlite3SetString(char **pz, ...){
13581   va_list ap;
13582   int nByte;
13583   const char *z;
13584   char *zResult;
13585
13586   assert( pz!=0 );
13587   nByte = 1;
13588   va_start(ap, pz);
13589   while( (z = va_arg(ap, const char*))!=0 ){
13590     nByte += strlen(z);
13591   }
13592   va_end(ap);
13593   sqlite3_free(*pz);
13594   *pz = zResult = sqlite3_malloc(nByte);
13595   if( zResult==0 ){
13596     return;
13597   }
13598   *zResult = 0;
13599   va_start(ap, pz);
13600   while( (z = va_arg(ap, const char*))!=0 ){
13601     int n = strlen(z);
13602     memcpy(zResult, z, n);
13603     zResult += n;
13604   }
13605   zResult[0] = 0;
13606   va_end(ap);
13607 }
13608
13609
13610 /*
13611 ** This function must be called before exiting any API function (i.e. 
13612 ** returning control to the user) that has called sqlite3_malloc or
13613 ** sqlite3_realloc.
13614 **
13615 ** The returned value is normally a copy of the second argument to this
13616 ** function. However, if a malloc() failure has occured since the previous
13617 ** invocation SQLITE_NOMEM is returned instead. 
13618 **
13619 ** If the first argument, db, is not NULL and a malloc() error has occured,
13620 ** then the connection error-code (the value returned by sqlite3_errcode())
13621 ** is set to SQLITE_NOMEM.
13622 */
13623 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
13624   /* If the db handle is not NULL, then we must hold the connection handle
13625   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
13626   ** is unsafe, as is the call to sqlite3Error().
13627   */
13628   assert( !db || sqlite3_mutex_held(db->mutex) );
13629   if( db && db->mallocFailed ){
13630     sqlite3Error(db, SQLITE_NOMEM, 0);
13631     db->mallocFailed = 0;
13632     rc = SQLITE_NOMEM;
13633   }
13634   return rc & (db ? db->errMask : 0xff);
13635 }
13636
13637 /************** End of malloc.c **********************************************/
13638 /************** Begin file printf.c ******************************************/
13639 /*
13640 ** The "printf" code that follows dates from the 1980's.  It is in
13641 ** the public domain.  The original comments are included here for
13642 ** completeness.  They are very out-of-date but might be useful as
13643 ** an historical reference.  Most of the "enhancements" have been backed
13644 ** out so that the functionality is now the same as standard printf().
13645 **
13646 **************************************************************************
13647 **
13648 ** The following modules is an enhanced replacement for the "printf" subroutines
13649 ** found in the standard C library.  The following enhancements are
13650 ** supported:
13651 **
13652 **      +  Additional functions.  The standard set of "printf" functions
13653 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
13654 **         vsprintf.  This module adds the following:
13655 **
13656 **           *  snprintf -- Works like sprintf, but has an extra argument
13657 **                          which is the size of the buffer written to.
13658 **
13659 **           *  mprintf --  Similar to sprintf.  Writes output to memory
13660 **                          obtained from malloc.
13661 **
13662 **           *  xprintf --  Calls a function to dispose of output.
13663 **
13664 **           *  nprintf --  No output, but returns the number of characters
13665 **                          that would have been output by printf.
13666 **
13667 **           *  A v- version (ex: vsnprintf) of every function is also
13668 **              supplied.
13669 **
13670 **      +  A few extensions to the formatting notation are supported:
13671 **
13672 **           *  The "=" flag (similar to "-") causes the output to be
13673 **              be centered in the appropriately sized field.
13674 **
13675 **           *  The %b field outputs an integer in binary notation.
13676 **
13677 **           *  The %c field now accepts a precision.  The character output
13678 **              is repeated by the number of times the precision specifies.
13679 **
13680 **           *  The %' field works like %c, but takes as its character the
13681 **              next character of the format string, instead of the next
13682 **              argument.  For example,  printf("%.78'-")  prints 78 minus
13683 **              signs, the same as  printf("%.78c",'-').
13684 **
13685 **      +  When compiled using GCC on a SPARC, this version of printf is
13686 **         faster than the library printf for SUN OS 4.1.
13687 **
13688 **      +  All functions are fully reentrant.
13689 **
13690 */
13691
13692 /*
13693 ** Conversion types fall into various categories as defined by the
13694 ** following enumeration.
13695 */
13696 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
13697 #define etFLOAT       2 /* Floating point.  %f */
13698 #define etEXP         3 /* Exponentional notation. %e and %E */
13699 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
13700 #define etSIZE        5 /* Return number of characters processed so far. %n */
13701 #define etSTRING      6 /* Strings. %s */
13702 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
13703 #define etPERCENT     8 /* Percent symbol. %% */
13704 #define etCHARX       9 /* Characters. %c */
13705 /* The rest are extensions, not normally found in printf() */
13706 #define etCHARLIT    10 /* Literal characters.  %' */
13707 #define etSQLESCAPE  11 /* Strings with '\'' doubled.  %q */
13708 #define etSQLESCAPE2 12 /* Strings with '\'' doubled and enclosed in '',
13709                           NULL pointers replaced by SQL NULL.  %Q */
13710 #define etTOKEN      13 /* a pointer to a Token structure */
13711 #define etSRCLIST    14 /* a pointer to a SrcList */
13712 #define etPOINTER    15 /* The %p conversion */
13713 #define etSQLESCAPE3 16 /* %w -> Strings with '\"' doubled */
13714 #define etORDINAL    17 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
13715
13716
13717 /*
13718 ** An "etByte" is an 8-bit unsigned value.
13719 */
13720 typedef unsigned char etByte;
13721
13722 /*
13723 ** Each builtin conversion character (ex: the 'd' in "%d") is described
13724 ** by an instance of the following structure
13725 */
13726 typedef struct et_info {   /* Information about each format field */
13727   char fmttype;            /* The format field code letter */
13728   etByte base;             /* The base for radix conversion */
13729   etByte flags;            /* One or more of FLAG_ constants below */
13730   etByte type;             /* Conversion paradigm */
13731   etByte charset;          /* Offset into aDigits[] of the digits string */
13732   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
13733 } et_info;
13734
13735 /*
13736 ** Allowed values for et_info.flags
13737 */
13738 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
13739 #define FLAG_INTERN  2     /* True if for internal use only */
13740 #define FLAG_STRING  4     /* Allow infinity precision */
13741
13742
13743 /*
13744 ** The following table is searched linearly, so it is good to put the
13745 ** most frequently used conversion types first.
13746 */
13747 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
13748 static const char aPrefix[] = "-x0\000X0";
13749 static const et_info fmtinfo[] = {
13750   {  'd', 10, 1, etRADIX,      0,  0 },
13751   {  's',  0, 4, etSTRING,     0,  0 },
13752   {  'g',  0, 1, etGENERIC,    30, 0 },
13753   {  'z',  0, 4, etDYNSTRING,  0,  0 },
13754   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
13755   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
13756   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
13757   {  'c',  0, 0, etCHARX,      0,  0 },
13758   {  'o',  8, 0, etRADIX,      0,  2 },
13759   {  'u', 10, 0, etRADIX,      0,  0 },
13760   {  'x', 16, 0, etRADIX,      16, 1 },
13761   {  'X', 16, 0, etRADIX,      0,  4 },
13762 #ifndef SQLITE_OMIT_FLOATING_POINT
13763   {  'f',  0, 1, etFLOAT,      0,  0 },
13764   {  'e',  0, 1, etEXP,        30, 0 },
13765   {  'E',  0, 1, etEXP,        14, 0 },
13766   {  'G',  0, 1, etGENERIC,    14, 0 },
13767 #endif
13768   {  'i', 10, 1, etRADIX,      0,  0 },
13769   {  'n',  0, 0, etSIZE,       0,  0 },
13770   {  '%',  0, 0, etPERCENT,    0,  0 },
13771   {  'p', 16, 0, etPOINTER,    0,  1 },
13772   {  'T',  0, 2, etTOKEN,      0,  0 },
13773   {  'S',  0, 2, etSRCLIST,    0,  0 },
13774   {  'r', 10, 3, etORDINAL,    0,  0 },
13775 };
13776 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
13777
13778 /*
13779 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
13780 ** conversions will work.
13781 */
13782 #ifndef SQLITE_OMIT_FLOATING_POINT
13783 /*
13784 ** "*val" is a double such that 0.1 <= *val < 10.0
13785 ** Return the ascii code for the leading digit of *val, then
13786 ** multiply "*val" by 10.0 to renormalize.
13787 **
13788 ** Example:
13789 **     input:     *val = 3.14159
13790 **     output:    *val = 1.4159    function return = '3'
13791 **
13792 ** The counter *cnt is incremented each time.  After counter exceeds
13793 ** 16 (the number of significant digits in a 64-bit float) '0' is
13794 ** always returned.
13795 */
13796 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
13797   int digit;
13798   LONGDOUBLE_TYPE d;
13799   if( (*cnt)++ >= 16 ) return '0';
13800   digit = (int)*val;
13801   d = digit;
13802   digit += '0';
13803   *val = (*val - d)*10.0;
13804   return digit;
13805 }
13806 #endif /* SQLITE_OMIT_FLOATING_POINT */
13807
13808 /*
13809 ** Append N space characters to the given string buffer.
13810 */
13811 static void appendSpace(StrAccum *pAccum, int N){
13812   static const char zSpaces[] = "                             ";
13813   while( N>=sizeof(zSpaces)-1 ){
13814     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
13815     N -= sizeof(zSpaces)-1;
13816   }
13817   if( N>0 ){
13818     sqlite3StrAccumAppend(pAccum, zSpaces, N);
13819   }
13820 }
13821
13822 /*
13823 ** On machines with a small stack size, you can redefine the
13824 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
13825 ** smaller values some %f conversions may go into an infinite loop.
13826 */
13827 #ifndef SQLITE_PRINT_BUF_SIZE
13828 # define SQLITE_PRINT_BUF_SIZE 350
13829 #endif
13830 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
13831
13832 /*
13833 ** The root program.  All variations call this core.
13834 **
13835 ** INPUTS:
13836 **   func   This is a pointer to a function taking three arguments
13837 **            1. A pointer to anything.  Same as the "arg" parameter.
13838 **            2. A pointer to the list of characters to be output
13839 **               (Note, this list is NOT null terminated.)
13840 **            3. An integer number of characters to be output.
13841 **               (Note: This number might be zero.)
13842 **
13843 **   arg    This is the pointer to anything which will be passed as the
13844 **          first argument to "func".  Use it for whatever you like.
13845 **
13846 **   fmt    This is the format string, as in the usual print.
13847 **
13848 **   ap     This is a pointer to a list of arguments.  Same as in
13849 **          vfprint.
13850 **
13851 ** OUTPUTS:
13852 **          The return value is the total number of characters sent to
13853 **          the function "func".  Returns -1 on a error.
13854 **
13855 ** Note that the order in which automatic variables are declared below
13856 ** seems to make a big difference in determining how fast this beast
13857 ** will run.
13858 */
13859 static void vxprintf(
13860   StrAccum *pAccum,                  /* Accumulate results here */
13861   int useExtended,                   /* Allow extended %-conversions */
13862   const char *fmt,                   /* Format string */
13863   va_list ap                         /* arguments */
13864 ){
13865   int c;                     /* Next character in the format string */
13866   char *bufpt;               /* Pointer to the conversion buffer */
13867   int precision;             /* Precision of the current field */
13868   int length;                /* Length of the field */
13869   int idx;                   /* A general purpose loop counter */
13870   int width;                 /* Width of the current field */
13871   etByte flag_leftjustify;   /* True if "-" flag is present */
13872   etByte flag_plussign;      /* True if "+" flag is present */
13873   etByte flag_blanksign;     /* True if " " flag is present */
13874   etByte flag_alternateform; /* True if "#" flag is present */
13875   etByte flag_altform2;      /* True if "!" flag is present */
13876   etByte flag_zeropad;       /* True if field width constant starts with zero */
13877   etByte flag_long;          /* True if "l" flag is present */
13878   etByte flag_longlong;      /* True if the "ll" flag is present */
13879   etByte done;               /* Loop termination flag */
13880   sqlite_uint64 longvalue;   /* Value for integer types */
13881   LONGDOUBLE_TYPE realvalue; /* Value for real types */
13882   const et_info *infop;      /* Pointer to the appropriate info structure */
13883   char buf[etBUFSIZE];       /* Conversion buffer */
13884   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
13885   etByte errorflag = 0;      /* True if an error is encountered */
13886   etByte xtype;              /* Conversion paradigm */
13887   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
13888 #ifndef SQLITE_OMIT_FLOATING_POINT
13889   int  exp, e2;              /* exponent of real numbers */
13890   double rounder;            /* Used for rounding floating point values */
13891   etByte flag_dp;            /* True if decimal point should be shown */
13892   etByte flag_rtz;           /* True if trailing zeros should be removed */
13893   etByte flag_exp;           /* True to force display of the exponent */
13894   int nsd;                   /* Number of significant digits returned */
13895 #endif
13896
13897   length = 0;
13898   bufpt = 0;
13899   for(; (c=(*fmt))!=0; ++fmt){
13900     if( c!='%' ){
13901       int amt;
13902       bufpt = (char *)fmt;
13903       amt = 1;
13904       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
13905       sqlite3StrAccumAppend(pAccum, bufpt, amt);
13906       if( c==0 ) break;
13907     }
13908     if( (c=(*++fmt))==0 ){
13909       errorflag = 1;
13910       sqlite3StrAccumAppend(pAccum, "%", 1);
13911       break;
13912     }
13913     /* Find out what flags are present */
13914     flag_leftjustify = flag_plussign = flag_blanksign = 
13915      flag_alternateform = flag_altform2 = flag_zeropad = 0;
13916     done = 0;
13917     do{
13918       switch( c ){
13919         case '-':   flag_leftjustify = 1;     break;
13920         case '+':   flag_plussign = 1;        break;
13921         case ' ':   flag_blanksign = 1;       break;
13922         case '#':   flag_alternateform = 1;   break;
13923         case '!':   flag_altform2 = 1;        break;
13924         case '0':   flag_zeropad = 1;         break;
13925         default:    done = 1;                 break;
13926       }
13927     }while( !done && (c=(*++fmt))!=0 );
13928     /* Get the field width */
13929     width = 0;
13930     if( c=='*' ){
13931       width = va_arg(ap,int);
13932       if( width<0 ){
13933         flag_leftjustify = 1;
13934         width = -width;
13935       }
13936       c = *++fmt;
13937     }else{
13938       while( c>='0' && c<='9' ){
13939         width = width*10 + c - '0';
13940         c = *++fmt;
13941       }
13942     }
13943     if( width > etBUFSIZE-10 ){
13944       width = etBUFSIZE-10;
13945     }
13946     /* Get the precision */
13947     if( c=='.' ){
13948       precision = 0;
13949       c = *++fmt;
13950       if( c=='*' ){
13951         precision = va_arg(ap,int);
13952         if( precision<0 ) precision = -precision;
13953         c = *++fmt;
13954       }else{
13955         while( c>='0' && c<='9' ){
13956           precision = precision*10 + c - '0';
13957           c = *++fmt;
13958         }
13959       }
13960     }else{
13961       precision = -1;
13962     }
13963     /* Get the conversion type modifier */
13964     if( c=='l' ){
13965       flag_long = 1;
13966       c = *++fmt;
13967       if( c=='l' ){
13968         flag_longlong = 1;
13969         c = *++fmt;
13970       }else{
13971         flag_longlong = 0;
13972       }
13973     }else{
13974       flag_long = flag_longlong = 0;
13975     }
13976     /* Fetch the info entry for the field */
13977     infop = 0;
13978     for(idx=0; idx<etNINFO; idx++){
13979       if( c==fmtinfo[idx].fmttype ){
13980         infop = &fmtinfo[idx];
13981         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
13982           xtype = infop->type;
13983         }else{
13984           return;
13985         }
13986         break;
13987       }
13988     }
13989     zExtra = 0;
13990     if( infop==0 ){
13991       return;
13992     }
13993
13994
13995     /* Limit the precision to prevent overflowing buf[] during conversion */
13996     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
13997       precision = etBUFSIZE-40;
13998     }
13999
14000     /*
14001     ** At this point, variables are initialized as follows:
14002     **
14003     **   flag_alternateform          TRUE if a '#' is present.
14004     **   flag_altform2               TRUE if a '!' is present.
14005     **   flag_plussign               TRUE if a '+' is present.
14006     **   flag_leftjustify            TRUE if a '-' is present or if the
14007     **                               field width was negative.
14008     **   flag_zeropad                TRUE if the width began with 0.
14009     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
14010     **                               the conversion character.
14011     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
14012     **                               the conversion character.
14013     **   flag_blanksign              TRUE if a ' ' is present.
14014     **   width                       The specified field width.  This is
14015     **                               always non-negative.  Zero is the default.
14016     **   precision                   The specified precision.  The default
14017     **                               is -1.
14018     **   xtype                       The class of the conversion.
14019     **   infop                       Pointer to the appropriate info struct.
14020     */
14021     switch( xtype ){
14022       case etPOINTER:
14023         flag_longlong = sizeof(char*)==sizeof(i64);
14024         flag_long = sizeof(char*)==sizeof(long int);
14025         /* Fall through into the next case */
14026       case etORDINAL:
14027       case etRADIX:
14028         if( infop->flags & FLAG_SIGNED ){
14029           i64 v;
14030           if( flag_longlong )   v = va_arg(ap,i64);
14031           else if( flag_long )  v = va_arg(ap,long int);
14032           else                  v = va_arg(ap,int);
14033           if( v<0 ){
14034             longvalue = -v;
14035             prefix = '-';
14036           }else{
14037             longvalue = v;
14038             if( flag_plussign )        prefix = '+';
14039             else if( flag_blanksign )  prefix = ' ';
14040             else                       prefix = 0;
14041           }
14042         }else{
14043           if( flag_longlong )   longvalue = va_arg(ap,u64);
14044           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
14045           else                  longvalue = va_arg(ap,unsigned int);
14046           prefix = 0;
14047         }
14048         if( longvalue==0 ) flag_alternateform = 0;
14049         if( flag_zeropad && precision<width-(prefix!=0) ){
14050           precision = width-(prefix!=0);
14051         }
14052         bufpt = &buf[etBUFSIZE-1];
14053         if( xtype==etORDINAL ){
14054           static const char zOrd[] = "thstndrd";
14055           int x = longvalue % 10;
14056           if( x>=4 || (longvalue/10)%10==1 ){
14057             x = 0;
14058           }
14059           buf[etBUFSIZE-3] = zOrd[x*2];
14060           buf[etBUFSIZE-2] = zOrd[x*2+1];
14061           bufpt -= 2;
14062         }
14063         {
14064           register const char *cset;      /* Use registers for speed */
14065           register int base;
14066           cset = &aDigits[infop->charset];
14067           base = infop->base;
14068           do{                                           /* Convert to ascii */
14069             *(--bufpt) = cset[longvalue%base];
14070             longvalue = longvalue/base;
14071           }while( longvalue>0 );
14072         }
14073         length = &buf[etBUFSIZE-1]-bufpt;
14074         for(idx=precision-length; idx>0; idx--){
14075           *(--bufpt) = '0';                             /* Zero pad */
14076         }
14077         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
14078         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
14079           const char *pre;
14080           char x;
14081           pre = &aPrefix[infop->prefix];
14082           if( *bufpt!=pre[0] ){
14083             for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
14084           }
14085         }
14086         length = &buf[etBUFSIZE-1]-bufpt;
14087         break;
14088       case etFLOAT:
14089       case etEXP:
14090       case etGENERIC:
14091         realvalue = va_arg(ap,double);
14092 #ifndef SQLITE_OMIT_FLOATING_POINT
14093         if( precision<0 ) precision = 6;         /* Set default precision */
14094         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
14095         if( realvalue<0.0 ){
14096           realvalue = -realvalue;
14097           prefix = '-';
14098         }else{
14099           if( flag_plussign )          prefix = '+';
14100           else if( flag_blanksign )    prefix = ' ';
14101           else                         prefix = 0;
14102         }
14103         if( xtype==etGENERIC && precision>0 ) precision--;
14104 #if 0
14105         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
14106         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
14107 #else
14108         /* It makes more sense to use 0.5 */
14109         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
14110 #endif
14111         if( xtype==etFLOAT ) realvalue += rounder;
14112         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
14113         exp = 0;
14114         if( sqlite3_isnan(realvalue) ){
14115           bufpt = "NaN";
14116           length = 3;
14117           break;
14118         }
14119         if( realvalue>0.0 ){
14120           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
14121           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
14122           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
14123           while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
14124           while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
14125           if( exp>350 || exp<-350 ){
14126             if( prefix=='-' ){
14127               bufpt = "-Inf";
14128             }else if( prefix=='+' ){
14129               bufpt = "+Inf";
14130             }else{
14131               bufpt = "Inf";
14132             }
14133             length = strlen(bufpt);
14134             break;
14135           }
14136         }
14137         bufpt = buf;
14138         /*
14139         ** If the field type is etGENERIC, then convert to either etEXP
14140         ** or etFLOAT, as appropriate.
14141         */
14142         flag_exp = xtype==etEXP;
14143         if( xtype!=etFLOAT ){
14144           realvalue += rounder;
14145           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
14146         }
14147         if( xtype==etGENERIC ){
14148           flag_rtz = !flag_alternateform;
14149           if( exp<-4 || exp>precision ){
14150             xtype = etEXP;
14151           }else{
14152             precision = precision - exp;
14153             xtype = etFLOAT;
14154           }
14155         }else{
14156           flag_rtz = 0;
14157         }
14158         if( xtype==etEXP ){
14159           e2 = 0;
14160         }else{
14161           e2 = exp;
14162         }
14163         nsd = 0;
14164         flag_dp = (precision>0) | flag_alternateform | flag_altform2;
14165         /* The sign in front of the number */
14166         if( prefix ){
14167           *(bufpt++) = prefix;
14168         }
14169         /* Digits prior to the decimal point */
14170         if( e2<0 ){
14171           *(bufpt++) = '0';
14172         }else{
14173           for(; e2>=0; e2--){
14174             *(bufpt++) = et_getdigit(&realvalue,&nsd);
14175           }
14176         }
14177         /* The decimal point */
14178         if( flag_dp ){
14179           *(bufpt++) = '.';
14180         }
14181         /* "0" digits after the decimal point but before the first
14182         ** significant digit of the number */
14183         for(e2++; e2<0 && precision>0; precision--, e2++){
14184           *(bufpt++) = '0';
14185         }
14186         /* Significant digits after the decimal point */
14187         while( (precision--)>0 ){
14188           *(bufpt++) = et_getdigit(&realvalue,&nsd);
14189         }
14190         /* Remove trailing zeros and the "." if no digits follow the "." */
14191         if( flag_rtz && flag_dp ){
14192           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
14193           assert( bufpt>buf );
14194           if( bufpt[-1]=='.' ){
14195             if( flag_altform2 ){
14196               *(bufpt++) = '0';
14197             }else{
14198               *(--bufpt) = 0;
14199             }
14200           }
14201         }
14202         /* Add the "eNNN" suffix */
14203         if( flag_exp || (xtype==etEXP && exp) ){
14204           *(bufpt++) = aDigits[infop->charset];
14205           if( exp<0 ){
14206             *(bufpt++) = '-'; exp = -exp;
14207           }else{
14208             *(bufpt++) = '+';
14209           }
14210           if( exp>=100 ){
14211             *(bufpt++) = (exp/100)+'0';                /* 100's digit */
14212             exp %= 100;
14213           }
14214           *(bufpt++) = exp/10+'0';                     /* 10's digit */
14215           *(bufpt++) = exp%10+'0';                     /* 1's digit */
14216         }
14217         *bufpt = 0;
14218
14219         /* The converted number is in buf[] and zero terminated. Output it.
14220         ** Note that the number is in the usual order, not reversed as with
14221         ** integer conversions. */
14222         length = bufpt-buf;
14223         bufpt = buf;
14224
14225         /* Special case:  Add leading zeros if the flag_zeropad flag is
14226         ** set and we are not left justified */
14227         if( flag_zeropad && !flag_leftjustify && length < width){
14228           int i;
14229           int nPad = width - length;
14230           for(i=width; i>=nPad; i--){
14231             bufpt[i] = bufpt[i-nPad];
14232           }
14233           i = prefix!=0;
14234           while( nPad-- ) bufpt[i++] = '0';
14235           length = width;
14236         }
14237 #endif
14238         break;
14239       case etSIZE:
14240         *(va_arg(ap,int*)) = pAccum->nChar;
14241         length = width = 0;
14242         break;
14243       case etPERCENT:
14244         buf[0] = '%';
14245         bufpt = buf;
14246         length = 1;
14247         break;
14248       case etCHARLIT:
14249       case etCHARX:
14250         c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
14251         if( precision>=0 ){
14252           for(idx=1; idx<precision; idx++) buf[idx] = c;
14253           length = precision;
14254         }else{
14255           length =1;
14256         }
14257         bufpt = buf;
14258         break;
14259       case etSTRING:
14260       case etDYNSTRING:
14261         bufpt = va_arg(ap,char*);
14262         if( bufpt==0 ){
14263           bufpt = "";
14264         }else if( xtype==etDYNSTRING ){
14265           zExtra = bufpt;
14266         }
14267         length = strlen(bufpt);
14268         if( precision>=0 && precision<length ) length = precision;
14269         break;
14270       case etSQLESCAPE:
14271       case etSQLESCAPE2:
14272       case etSQLESCAPE3: {
14273         int i, j, n, ch, isnull;
14274         int needQuote;
14275         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
14276         char *escarg = va_arg(ap,char*);
14277         isnull = escarg==0;
14278         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
14279         for(i=n=0; (ch=escarg[i])!=0; i++){
14280           if( ch==q )  n++;
14281         }
14282         needQuote = !isnull && xtype==etSQLESCAPE2;
14283         n += i + 1 + needQuote*2;
14284         if( n>etBUFSIZE ){
14285           bufpt = zExtra = sqlite3_malloc( n );
14286           if( bufpt==0 ) return;
14287         }else{
14288           bufpt = buf;
14289         }
14290         j = 0;
14291         if( needQuote ) bufpt[j++] = q;
14292         for(i=0; (ch=escarg[i])!=0; i++){
14293           bufpt[j++] = ch;
14294           if( ch==q ) bufpt[j++] = ch;
14295         }
14296         if( needQuote ) bufpt[j++] = q;
14297         bufpt[j] = 0;
14298         length = j;
14299         /* The precision is ignored on %q and %Q */
14300         /* if( precision>=0 && precision<length ) length = precision; */
14301         break;
14302       }
14303       case etTOKEN: {
14304         Token *pToken = va_arg(ap, Token*);
14305         if( pToken && pToken->z ){
14306           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
14307         }
14308         length = width = 0;
14309         break;
14310       }
14311       case etSRCLIST: {
14312         SrcList *pSrc = va_arg(ap, SrcList*);
14313         int k = va_arg(ap, int);
14314         struct SrcList_item *pItem = &pSrc->a[k];
14315         assert( k>=0 && k<pSrc->nSrc );
14316         if( pItem->zDatabase && pItem->zDatabase[0] ){
14317           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
14318           sqlite3StrAccumAppend(pAccum, ".", 1);
14319         }
14320         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
14321         length = width = 0;
14322         break;
14323       }
14324     }/* End switch over the format type */
14325     /*
14326     ** The text of the conversion is pointed to by "bufpt" and is
14327     ** "length" characters long.  The field width is "width".  Do
14328     ** the output.
14329     */
14330     if( !flag_leftjustify ){
14331       register int nspace;
14332       nspace = width-length;
14333       if( nspace>0 ){
14334         appendSpace(pAccum, nspace);
14335       }
14336     }
14337     if( length>0 ){
14338       sqlite3StrAccumAppend(pAccum, bufpt, length);
14339     }
14340     if( flag_leftjustify ){
14341       register int nspace;
14342       nspace = width-length;
14343       if( nspace>0 ){
14344         appendSpace(pAccum, nspace);
14345       }
14346     }
14347     if( zExtra ){
14348       sqlite3_free(zExtra);
14349     }
14350   }/* End for loop over the format string */
14351 } /* End of function */
14352
14353 /*
14354 ** Append N bytes of text from z to the StrAccum object.
14355 */
14356 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
14357   if( p->tooBig | p->mallocFailed ){
14358     return;
14359   }
14360   if( N<0 ){
14361     N = strlen(z);
14362   }
14363   if( N==0 ){
14364     return;
14365   }
14366   if( p->nChar+N >= p->nAlloc ){
14367     char *zNew;
14368     if( !p->useMalloc ){
14369       p->tooBig = 1;
14370       N = p->nAlloc - p->nChar - 1;
14371       if( N<=0 ){
14372         return;
14373       }
14374     }else{
14375       p->nAlloc += p->nAlloc + N + 1;
14376       if( p->nAlloc > SQLITE_MAX_LENGTH ){
14377         p->nAlloc = SQLITE_MAX_LENGTH;
14378         if( p->nChar+N >= p->nAlloc ){
14379           sqlite3StrAccumReset(p);
14380           p->tooBig = 1;
14381           return;
14382         }
14383       }
14384       zNew = sqlite3_malloc( p->nAlloc );
14385       if( zNew ){
14386         memcpy(zNew, p->zText, p->nChar);
14387         sqlite3StrAccumReset(p);
14388         p->zText = zNew;
14389       }else{
14390         p->mallocFailed = 1;
14391         sqlite3StrAccumReset(p);
14392         return;
14393       }
14394     }
14395   }
14396   memcpy(&p->zText[p->nChar], z, N);
14397   p->nChar += N;
14398 }
14399
14400 /*
14401 ** Finish off a string by making sure it is zero-terminated.
14402 ** Return a pointer to the resulting string.  Return a NULL
14403 ** pointer if any kind of error was encountered.
14404 */
14405 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
14406   if( p->zText ){
14407     p->zText[p->nChar] = 0;
14408     if( p->useMalloc && p->zText==p->zBase ){
14409       p->zText = sqlite3_malloc( p->nChar+1 );
14410       if( p->zText ){
14411         memcpy(p->zText, p->zBase, p->nChar+1);
14412       }else{
14413         p->mallocFailed = 1;
14414       }
14415     }
14416   }
14417   return p->zText;
14418 }
14419
14420 /*
14421 ** Reset an StrAccum string.  Reclaim all malloced memory.
14422 */
14423 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
14424   if( p->zText!=p->zBase ){
14425     sqlite3_free(p->zText);
14426     p->zText = 0;
14427   }
14428 }
14429
14430 /*
14431 ** Initialize a string accumulator
14432 */
14433 static void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n){
14434   p->zText = p->zBase = zBase;
14435   p->nChar = 0;
14436   p->nAlloc = n;
14437   p->useMalloc = 1;
14438   p->tooBig = 0;
14439   p->mallocFailed = 0;
14440 }
14441
14442 /*
14443 ** Print into memory obtained from sqliteMalloc().  Use the internal
14444 ** %-conversion extensions.
14445 */
14446 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
14447   char *z;
14448   char zBase[SQLITE_PRINT_BUF_SIZE];
14449   StrAccum acc;
14450   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase));
14451   vxprintf(&acc, 1, zFormat, ap);
14452   z = sqlite3StrAccumFinish(&acc);
14453   if( acc.mallocFailed && db ){
14454     db->mallocFailed = 1;
14455   }
14456   return z;
14457 }
14458
14459 /*
14460 ** Print into memory obtained from sqliteMalloc().  Use the internal
14461 ** %-conversion extensions.
14462 */
14463 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
14464   va_list ap;
14465   char *z;
14466   va_start(ap, zFormat);
14467   z = sqlite3VMPrintf(db, zFormat, ap);
14468   va_end(ap);
14469   return z;
14470 }
14471
14472 /*
14473 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
14474 ** %-conversion extensions.
14475 */
14476 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
14477   char *z;
14478   char zBase[SQLITE_PRINT_BUF_SIZE];
14479   StrAccum acc;
14480   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase));
14481   vxprintf(&acc, 0, zFormat, ap);
14482   z = sqlite3StrAccumFinish(&acc);
14483   return z;
14484 }
14485
14486 /*
14487 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
14488 ** %-conversion extensions.
14489 */
14490 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
14491   va_list ap;
14492   char *z;
14493   va_start(ap, zFormat);
14494   z = sqlite3_vmprintf(zFormat, ap);
14495   va_end(ap);
14496   return z;
14497 }
14498
14499 /*
14500 ** sqlite3_snprintf() works like snprintf() except that it ignores the
14501 ** current locale settings.  This is important for SQLite because we
14502 ** are not able to use a "," as the decimal point in place of "." as
14503 ** specified by some locales.
14504 */
14505 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
14506   char *z;
14507   va_list ap;
14508   StrAccum acc;
14509
14510   if( n<=0 ){
14511     return zBuf;
14512   }
14513   sqlite3StrAccumInit(&acc, zBuf, n);
14514   acc.useMalloc = 0;
14515   va_start(ap,zFormat);
14516   vxprintf(&acc, 0, zFormat, ap);
14517   va_end(ap);
14518   z = sqlite3StrAccumFinish(&acc);
14519   return z;
14520 }
14521
14522 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) || defined(SQLITE_MEMDEBUG)
14523 /*
14524 ** A version of printf() that understands %lld.  Used for debugging.
14525 ** The printf() built into some versions of windows does not understand %lld
14526 ** and segfaults if you give it a long long int.
14527 */
14528 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
14529   va_list ap;
14530   StrAccum acc;
14531   char zBuf[500];
14532   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf));
14533   acc.useMalloc = 0;
14534   va_start(ap,zFormat);
14535   vxprintf(&acc, 0, zFormat, ap);
14536   va_end(ap);
14537   sqlite3StrAccumFinish(&acc);
14538   fprintf(stdout,"%s", zBuf);
14539   fflush(stdout);
14540 }
14541 #endif
14542
14543 /************** End of printf.c **********************************************/
14544 /************** Begin file random.c ******************************************/
14545 /*
14546 ** 2001 September 15
14547 **
14548 ** The author disclaims copyright to this source code.  In place of
14549 ** a legal notice, here is a blessing:
14550 **
14551 **    May you do good and not evil.
14552 **    May you find forgiveness for yourself and forgive others.
14553 **    May you share freely, never taking more than you give.
14554 **
14555 *************************************************************************
14556 ** This file contains code to implement a pseudo-random number
14557 ** generator (PRNG) for SQLite.
14558 **
14559 ** Random numbers are used by some of the database backends in order
14560 ** to generate random integer keys for tables or random filenames.
14561 **
14562 ** $Id: random.c,v 1.21 2008/01/16 17:46:38 drh Exp $
14563 */
14564
14565
14566 /* All threads share a single random number generator.
14567 ** This structure is the current state of the generator.
14568 */
14569 static struct sqlite3PrngType {
14570   unsigned char isInit;          /* True if initialized */
14571   unsigned char i, j;            /* State variables */
14572   unsigned char s[256];          /* State variables */
14573 } sqlite3Prng;
14574
14575 /*
14576 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
14577 ** must be held while executing this routine.
14578 **
14579 ** Why not just use a library random generator like lrand48() for this?
14580 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
14581 ** good source of random numbers.  The lrand48() library function may
14582 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
14583 ** subtle problems on some systems that could cause problems.  It is hard
14584 ** to know.  To minimize the risk of problems due to bad lrand48()
14585 ** implementations, SQLite uses this random number generator based
14586 ** on RC4, which we know works very well.
14587 **
14588 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
14589 ** randomness any more.  But we will leave this code in all the same.
14590 */
14591 static int randomByte(void){
14592   unsigned char t;
14593
14594
14595   /* Initialize the state of the random number generator once,
14596   ** the first time this routine is called.  The seed value does
14597   ** not need to contain a lot of randomness since we are not
14598   ** trying to do secure encryption or anything like that...
14599   **
14600   ** Nothing in this file or anywhere else in SQLite does any kind of
14601   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
14602   ** number generator) not as an encryption device.
14603   */
14604   if( !sqlite3Prng.isInit ){
14605     int i;
14606     char k[256];
14607     sqlite3Prng.j = 0;
14608     sqlite3Prng.i = 0;
14609     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
14610     for(i=0; i<256; i++){
14611       sqlite3Prng.s[i] = i;
14612     }
14613     for(i=0; i<256; i++){
14614       sqlite3Prng.j += sqlite3Prng.s[i] + k[i];
14615       t = sqlite3Prng.s[sqlite3Prng.j];
14616       sqlite3Prng.s[sqlite3Prng.j] = sqlite3Prng.s[i];
14617       sqlite3Prng.s[i] = t;
14618     }
14619     sqlite3Prng.isInit = 1;
14620   }
14621
14622   /* Generate and return single random byte
14623   */
14624   sqlite3Prng.i++;
14625   t = sqlite3Prng.s[sqlite3Prng.i];
14626   sqlite3Prng.j += t;
14627   sqlite3Prng.s[sqlite3Prng.i] = sqlite3Prng.s[sqlite3Prng.j];
14628   sqlite3Prng.s[sqlite3Prng.j] = t;
14629   t += sqlite3Prng.s[sqlite3Prng.i];
14630   return sqlite3Prng.s[t];
14631 }
14632
14633 /*
14634 ** Return N random bytes.
14635 */
14636 SQLITE_PRIVATE void sqlite3Randomness(int N, void *pBuf){
14637   unsigned char *zBuf = pBuf;
14638   static sqlite3_mutex *mutex = 0;
14639   if( mutex==0 ){
14640     mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG);
14641   }
14642   sqlite3_mutex_enter(mutex);
14643   while( N-- ){
14644     *(zBuf++) = randomByte();
14645   }
14646   sqlite3_mutex_leave(mutex);
14647 }
14648
14649 #ifdef SQLITE_TEST
14650 /*
14651 ** For testing purposes, we sometimes want to preserve the state of
14652 ** PRNG and restore the PRNG to its saved state at a later time.
14653 */
14654 static struct sqlite3PrngType sqlite3SavedPrng;
14655 SQLITE_PRIVATE void sqlite3SavePrngState(void){
14656   memcpy(&sqlite3SavedPrng, &sqlite3Prng, sizeof(sqlite3Prng));
14657 }
14658 SQLITE_PRIVATE void sqlite3RestorePrngState(void){
14659   memcpy(&sqlite3Prng, &sqlite3SavedPrng, sizeof(sqlite3Prng));
14660 }
14661 SQLITE_PRIVATE void sqlite3ResetPrngState(void){
14662   sqlite3Prng.isInit = 0;
14663 }
14664 #endif /* SQLITE_TEST */
14665
14666 /************** End of random.c **********************************************/
14667 /************** Begin file utf.c *********************************************/
14668 /*
14669 ** 2004 April 13
14670 **
14671 ** The author disclaims copyright to this source code.  In place of
14672 ** a legal notice, here is a blessing:
14673 **
14674 **    May you do good and not evil.
14675 **    May you find forgiveness for yourself and forgive others.
14676 **    May you share freely, never taking more than you give.
14677 **
14678 *************************************************************************
14679 ** This file contains routines used to translate between UTF-8, 
14680 ** UTF-16, UTF-16BE, and UTF-16LE.
14681 **
14682 ** $Id: utf.c,v 1.60 2008/02/13 18:25:27 danielk1977 Exp $
14683 **
14684 ** Notes on UTF-8:
14685 **
14686 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
14687 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
14688 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
14689 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
14690 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
14691 **
14692 **
14693 ** Notes on UTF-16:  (with wwww+1==uuuuu)
14694 **
14695 **      Word-0               Word-1          Value
14696 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
14697 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
14698 **
14699 **
14700 ** BOM or Byte Order Mark:
14701 **     0xff 0xfe   little-endian utf-16 follows
14702 **     0xfe 0xff   big-endian utf-16 follows
14703 **
14704 */
14705 /************** Include vdbeInt.h in the middle of utf.c *********************/
14706 /************** Begin file vdbeInt.h *****************************************/
14707 /*
14708 ** 2003 September 6
14709 **
14710 ** The author disclaims copyright to this source code.  In place of
14711 ** a legal notice, here is a blessing:
14712 **
14713 **    May you do good and not evil.
14714 **    May you find forgiveness for yourself and forgive others.
14715 **    May you share freely, never taking more than you give.
14716 **
14717 *************************************************************************
14718 ** This is the header file for information that is private to the
14719 ** VDBE.  This information used to all be at the top of the single
14720 ** source code file "vdbe.c".  When that file became too big (over
14721 ** 6000 lines long) it was split up into several smaller files and
14722 ** this header information was factored out.
14723 */
14724 #ifndef _VDBEINT_H_
14725 #define _VDBEINT_H_
14726
14727 /*
14728 ** intToKey() and keyToInt() used to transform the rowid.  But with
14729 ** the latest versions of the design they are no-ops.
14730 */
14731 #define keyToInt(X)   (X)
14732 #define intToKey(X)   (X)
14733
14734
14735 /*
14736 ** SQL is translated into a sequence of instructions to be
14737 ** executed by a virtual machine.  Each instruction is an instance
14738 ** of the following structure.
14739 */
14740 typedef struct VdbeOp Op;
14741
14742 /*
14743 ** Boolean values
14744 */
14745 typedef unsigned char Bool;
14746
14747 /*
14748 ** A cursor is a pointer into a single BTree within a database file.
14749 ** The cursor can seek to a BTree entry with a particular key, or
14750 ** loop over all entries of the Btree.  You can also insert new BTree
14751 ** entries or retrieve the key or data from the entry that the cursor
14752 ** is currently pointing to.
14753 ** 
14754 ** Every cursor that the virtual machine has open is represented by an
14755 ** instance of the following structure.
14756 **
14757 ** If the Cursor.isTriggerRow flag is set it means that this cursor is
14758 ** really a single row that represents the NEW or OLD pseudo-table of
14759 ** a row trigger.  The data for the row is stored in Cursor.pData and
14760 ** the rowid is in Cursor.iKey.
14761 */
14762 struct Cursor {
14763   BtCursor *pCursor;    /* The cursor structure of the backend */
14764   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
14765   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
14766   i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
14767   Bool zeroed;          /* True if zeroed out and ready for reuse */
14768   Bool rowidIsValid;    /* True if lastRowid is valid */
14769   Bool atFirst;         /* True if pointing to first entry */
14770   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
14771   Bool nullRow;         /* True if pointing to a row with no data */
14772   Bool nextRowidValid;  /* True if the nextRowid field is valid */
14773   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
14774   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
14775   Bool isTable;         /* True if a table requiring integer keys */
14776   Bool isIndex;         /* True if an index containing keys only - no data */
14777   u8 bogusIncrKey;      /* Something for pIncrKey to point to if pKeyInfo==0 */
14778   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
14779   Btree *pBt;           /* Separate file holding temporary table */
14780   int nData;            /* Number of bytes in pData */
14781   char *pData;          /* Data for a NEW or OLD pseudo-table */
14782   i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
14783   u8 *pIncrKey;         /* Pointer to pKeyInfo->incrKey */
14784   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
14785   int nField;           /* Number of fields in the header */
14786   i64 seqCount;         /* Sequence counter */
14787   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
14788   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
14789
14790   /* Cached information about the header for the data record that the
14791   ** cursor is currently pointing to.  Only valid if cacheValid is true.
14792   ** aRow might point to (ephemeral) data for the current row, or it might
14793   ** be NULL.
14794   */
14795   int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
14796   int payloadSize;      /* Total number of bytes in the record */
14797   u32 *aType;           /* Type values for all entries in the record */
14798   u32 *aOffset;         /* Cached offsets to the start of each columns data */
14799   u8 *aRow;             /* Data for the current row, if all on one page */
14800 };
14801 typedef struct Cursor Cursor;
14802
14803 /*
14804 ** A value for Cursor.cacheValid that means the cache is always invalid.
14805 */
14806 #define CACHE_STALE 0
14807
14808 /*
14809 ** Internally, the vdbe manipulates nearly all SQL values as Mem
14810 ** structures. Each Mem struct may cache multiple representations (string,
14811 ** integer etc.) of the same value.  A value (and therefore Mem structure)
14812 ** has the following properties:
14813 **
14814 ** Each value has a manifest type. The manifest type of the value stored
14815 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
14816 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
14817 ** SQLITE_BLOB.
14818 */
14819 struct Mem {
14820   union {
14821     i64 i;              /* Integer value. Or FuncDef* when flags==MEM_Agg */
14822     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
14823   } u;
14824   double r;           /* Real value */
14825   sqlite3 *db;        /* The associated database connection */
14826   char *z;            /* String or BLOB value */
14827   int n;              /* Number of characters in string value, excluding '\0' */
14828   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
14829   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
14830   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
14831   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
14832 };
14833
14834 /* One or more of the following flags are set to indicate the validOK
14835 ** representations of the value stored in the Mem struct.
14836 **
14837 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
14838 ** No other flags may be set in this case.
14839 **
14840 ** If the MEM_Str flag is set then Mem.z points at a string representation.
14841 ** Usually this is encoded in the same unicode encoding as the main
14842 ** database (see below for exceptions). If the MEM_Term flag is also
14843 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
14844 ** flags may coexist with the MEM_Str flag.
14845 **
14846 ** Multiple of these values can appear in Mem.flags.  But only one
14847 ** at a time can appear in Mem.type.
14848 */
14849 #define MEM_Null      0x0001   /* Value is NULL */
14850 #define MEM_Str       0x0002   /* Value is a string */
14851 #define MEM_Int       0x0004   /* Value is an integer */
14852 #define MEM_Real      0x0008   /* Value is a real number */
14853 #define MEM_Blob      0x0010   /* Value is a BLOB */
14854
14855 #define MemSetTypeFlag(p, f) \
14856   ((p)->flags = ((p)->flags&~(MEM_Int|MEM_Real|MEM_Null|MEM_Blob|MEM_Str))|f)
14857
14858 /* Whenever Mem contains a valid string or blob representation, one of
14859 ** the following flags must be set to determine the memory management
14860 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
14861 ** string is \000 or \u0000 terminated
14862 */
14863 #define MEM_Term      0x0020   /* String rep is nul terminated */
14864 #define MEM_Dyn       0x0040   /* Need to call sqliteFree() on Mem.z */
14865 #define MEM_Static    0x0080   /* Mem.z points to a static string */
14866 #define MEM_Ephem     0x0100   /* Mem.z points to an ephemeral string */
14867 #define MEM_Agg       0x0400   /* Mem.z points to an agg function context */
14868 #define MEM_Zero      0x0800   /* Mem.i contains count of 0s appended to blob */
14869
14870 #ifdef SQLITE_OMIT_INCRBLOB
14871   #undef MEM_Zero
14872   #define MEM_Zero 0x0000
14873 #endif
14874
14875
14876 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
14877 ** additional information about auxiliary information bound to arguments
14878 ** of the function.  This is used to implement the sqlite3_get_auxdata()
14879 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
14880 ** that can be associated with a constant argument to a function.  This
14881 ** allows functions such as "regexp" to compile their constant regular
14882 ** expression argument once and reused the compiled code for multiple
14883 ** invocations.
14884 */
14885 struct VdbeFunc {
14886   FuncDef *pFunc;               /* The definition of the function */
14887   int nAux;                     /* Number of entries allocated for apAux[] */
14888   struct AuxData {
14889     void *pAux;                   /* Aux data for the i-th argument */
14890     void (*xDelete)(void *);      /* Destructor for the aux data */
14891   } apAux[1];                   /* One slot for each function argument */
14892 };
14893
14894 /*
14895 ** The "context" argument for a installable function.  A pointer to an
14896 ** instance of this structure is the first argument to the routines used
14897 ** implement the SQL functions.
14898 **
14899 ** There is a typedef for this structure in sqlite.h.  So all routines,
14900 ** even the public interface to SQLite, can use a pointer to this structure.
14901 ** But this file is the only place where the internal details of this
14902 ** structure are known.
14903 **
14904 ** This structure is defined inside of vdbeInt.h because it uses substructures
14905 ** (Mem) which are only defined there.
14906 */
14907 struct sqlite3_context {
14908   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
14909   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
14910   Mem s;                /* The return value is stored here */
14911   Mem *pMem;            /* Memory cell used to store aggregate context */
14912   int isError;          /* Error code returned by the function. */
14913   CollSeq *pColl;       /* Collating sequence */
14914 };
14915
14916 /*
14917 ** A Set structure is used for quick testing to see if a value
14918 ** is part of a small set.  Sets are used to implement code like
14919 ** this:
14920 **            x.y IN ('hi','hoo','hum')
14921 */
14922 typedef struct Set Set;
14923 struct Set {
14924   Hash hash;             /* A set is just a hash table */
14925   HashElem *prev;        /* Previously accessed hash elemen */
14926 };
14927
14928 /*
14929 ** A FifoPage structure holds a single page of valves.  Pages are arranged
14930 ** in a list.
14931 */
14932 typedef struct FifoPage FifoPage;
14933 struct FifoPage {
14934   int nSlot;         /* Number of entries aSlot[] */
14935   int iWrite;        /* Push the next value into this entry in aSlot[] */
14936   int iRead;         /* Read the next value from this entry in aSlot[] */
14937   FifoPage *pNext;   /* Next page in the fifo */
14938   i64 aSlot[1];      /* One or more slots for rowid values */
14939 };
14940
14941 /*
14942 ** The Fifo structure is typedef-ed in vdbeInt.h.  But the implementation
14943 ** of that structure is private to this file.
14944 **
14945 ** The Fifo structure describes the entire fifo.  
14946 */
14947 typedef struct Fifo Fifo;
14948 struct Fifo {
14949   int nEntry;         /* Total number of entries */
14950   FifoPage *pFirst;   /* First page on the list */
14951   FifoPage *pLast;    /* Last page on the list */
14952 };
14953
14954 /*
14955 ** A Context stores the last insert rowid, the last statement change count,
14956 ** and the current statement change count (i.e. changes since last statement).
14957 ** The current keylist is also stored in the context.
14958 ** Elements of Context structure type make up the ContextStack, which is
14959 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
14960 ** The context is pushed before executing a trigger a popped when the
14961 ** trigger finishes.
14962 */
14963 typedef struct Context Context;
14964 struct Context {
14965   i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
14966   int nChange;      /* Statement changes (Vdbe.nChanges)     */
14967   Fifo sFifo;       /* Records that will participate in a DELETE or UPDATE */
14968 };
14969
14970 /*
14971 ** An instance of the virtual machine.  This structure contains the complete
14972 ** state of the virtual machine.
14973 **
14974 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
14975 ** is really a pointer to an instance of this structure.
14976 **
14977 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
14978 ** any virtual table method invocations made by the vdbe program. It is
14979 ** set to 2 for xDestroy method calls and 1 for all other methods. This
14980 ** variable is used for two purposes: to allow xDestroy methods to execute
14981 ** "DROP TABLE" statements and to prevent some nasty side effects of
14982 ** malloc failure when SQLite is invoked recursively by a virtual table 
14983 ** method function.
14984 */
14985 struct Vdbe {
14986   sqlite3 *db;        /* The whole database */
14987   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
14988   int nOp;            /* Number of instructions in the program */
14989   int nOpAlloc;       /* Number of slots allocated for aOp[] */
14990   Op *aOp;            /* Space to hold the virtual machine's program */
14991   int nLabel;         /* Number of labels used */
14992   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
14993   int *aLabel;        /* Space to hold the labels */
14994   Mem **apArg;        /* Arguments to currently executing user function */
14995   Mem *aColName;      /* Column names to return */
14996   int nCursor;        /* Number of slots in apCsr[] */
14997   Cursor **apCsr;     /* One element of this array for each open cursor */
14998   int nVar;           /* Number of entries in aVar[] */
14999   Mem *aVar;          /* Values for the OP_Variable opcode. */
15000   char **azVar;       /* Name of variables */
15001   int okVar;          /* True if azVar[] has been initialized */
15002   int magic;              /* Magic number for sanity checking */
15003   int nMem;               /* Number of memory locations currently allocated */
15004   Mem *aMem;              /* The memory locations */
15005   int nCallback;          /* Number of callbacks invoked so far */
15006   int cacheCtr;           /* Cursor row cache generation counter */
15007   Fifo sFifo;             /* A list of ROWIDs */
15008   int contextStackTop;    /* Index of top element in the context stack */
15009   int contextStackDepth;  /* The size of the "context" stack */
15010   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
15011   int pc;                 /* The program counter */
15012   int rc;                 /* Value to return */
15013   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
15014   int errorAction;        /* Recovery action to do in case of an error */
15015   int inTempTrans;        /* True if temp database is transactioned */
15016   int returnStack[25];    /* Return address stack for OP_Gosub & OP_Return */
15017   int returnDepth;        /* Next unused element in returnStack[] */
15018   int nResColumn;         /* Number of columns in one row of the result set */
15019   char **azResColumn;     /* Values for one row of result */ 
15020   char *zErrMsg;          /* Error message written here */
15021   Mem *pResultSet;        /* Pointer to an array of results */
15022   u8 explain;             /* True if EXPLAIN present on SQL command */
15023   u8 changeCntOn;         /* True to update the change-counter */
15024   u8 aborted;             /* True if ROLLBACK in another VM causes an abort */
15025   u8 expired;             /* True if the VM needs to be recompiled */
15026   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
15027   u8 inVtabMethod;        /* See comments above */
15028   int nChange;            /* Number of db changes made since last reset */
15029   i64 startTime;          /* Time when query started - used for profiling */
15030   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
15031   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
15032   int nSql;             /* Number of bytes in zSql */
15033   char *zSql;           /* Text of the SQL statement that generated this */
15034 #ifdef SQLITE_DEBUG
15035   FILE *trace;        /* Write an execution trace here, if not NULL */
15036 #endif
15037   int openedStatement;  /* True if this VM has opened a statement journal */
15038 #ifdef SQLITE_SSE
15039   int fetchId;          /* Statement number used by sqlite3_fetch_statement */
15040   int lru;              /* Counter used for LRU cache replacement */
15041 #endif
15042 };
15043
15044 /*
15045 ** The following are allowed values for Vdbe.magic
15046 */
15047 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
15048 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
15049 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
15050 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
15051
15052 /*
15053 ** Function prototypes
15054 */
15055 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
15056 void sqliteVdbePopStack(Vdbe*,int);
15057 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor*);
15058 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
15059 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
15060 #endif
15061 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
15062 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
15063 SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
15064 SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
15065 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
15066
15067 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
15068 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(Cursor*,int,const unsigned char*,int*);
15069 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
15070 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
15071 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(void*,int,const void*,int, const void*);
15072 SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8*);
15073 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
15074 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
15075 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
15076 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
15077 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
15078 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
15079 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
15080 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
15081 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
15082 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
15083 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
15084 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
15085 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
15086 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
15087 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
15088 SQLITE_PRIVATE int sqlite3VdbeMemDynamicify(Mem*);
15089 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
15090 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
15091 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
15092 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
15093 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
15094 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
15095 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
15096 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
15097 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
15098 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
15099 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
15100 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
15101 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
15102
15103 #ifndef NDEBUG
15104 SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
15105 #endif
15106 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
15107 #ifdef SQLITE_DEBUG
15108 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
15109 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
15110 #endif
15111 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
15112 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo*);
15113 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo*, i64);
15114 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo*, i64*);
15115 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo*);
15116
15117 #ifndef SQLITE_OMIT_INCRBLOB
15118 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
15119 #else
15120   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
15121 #endif
15122
15123 #endif /* !defined(_VDBEINT_H_) */
15124
15125 /************** End of vdbeInt.h *********************************************/
15126 /************** Continuing where we left off in utf.c ************************/
15127
15128 /*
15129 ** The following constant value is used by the SQLITE_BIGENDIAN and
15130 ** SQLITE_LITTLEENDIAN macros.
15131 */
15132 SQLITE_PRIVATE const int sqlite3one = 1;
15133
15134 /*
15135 ** This lookup table is used to help decode the first byte of
15136 ** a multi-byte UTF8 character.
15137 */
15138 static const unsigned char sqlite3UtfTrans1[] = {
15139   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
15140   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
15141   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
15142   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
15143   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
15144   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
15145   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
15146   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
15147 };
15148
15149
15150 #define WRITE_UTF8(zOut, c) {                          \
15151   if( c<0x00080 ){                                     \
15152     *zOut++ = (c&0xFF);                                \
15153   }                                                    \
15154   else if( c<0x00800 ){                                \
15155     *zOut++ = 0xC0 + ((c>>6)&0x1F);                    \
15156     *zOut++ = 0x80 + (c & 0x3F);                       \
15157   }                                                    \
15158   else if( c<0x10000 ){                                \
15159     *zOut++ = 0xE0 + ((c>>12)&0x0F);                   \
15160     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
15161     *zOut++ = 0x80 + (c & 0x3F);                       \
15162   }else{                                               \
15163     *zOut++ = 0xF0 + ((c>>18) & 0x07);                 \
15164     *zOut++ = 0x80 + ((c>>12) & 0x3F);                 \
15165     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
15166     *zOut++ = 0x80 + (c & 0x3F);                       \
15167   }                                                    \
15168 }
15169
15170 #define WRITE_UTF16LE(zOut, c) {                                \
15171   if( c<=0xFFFF ){                                              \
15172     *zOut++ = (c&0x00FF);                                       \
15173     *zOut++ = ((c>>8)&0x00FF);                                  \
15174   }else{                                                        \
15175     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
15176     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
15177     *zOut++ = (c&0x00FF);                                       \
15178     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
15179   }                                                             \
15180 }
15181
15182 #define WRITE_UTF16BE(zOut, c) {                                \
15183   if( c<=0xFFFF ){                                              \
15184     *zOut++ = ((c>>8)&0x00FF);                                  \
15185     *zOut++ = (c&0x00FF);                                       \
15186   }else{                                                        \
15187     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
15188     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
15189     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
15190     *zOut++ = (c&0x00FF);                                       \
15191   }                                                             \
15192 }
15193
15194 #define READ_UTF16LE(zIn, c){                                         \
15195   c = (*zIn++);                                                       \
15196   c += ((*zIn++)<<8);                                                 \
15197   if( c>=0xD800 && c<0xE000 ){                                       \
15198     int c2 = (*zIn++);                                                \
15199     c2 += ((*zIn++)<<8);                                              \
15200     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
15201     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
15202   }                                                                   \
15203 }
15204
15205 #define READ_UTF16BE(zIn, c){                                         \
15206   c = ((*zIn++)<<8);                                                  \
15207   c += (*zIn++);                                                      \
15208   if( c>=0xD800 && c<0xE000 ){                                       \
15209     int c2 = ((*zIn++)<<8);                                           \
15210     c2 += (*zIn++);                                                   \
15211     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
15212     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
15213   }                                                                   \
15214 }
15215
15216 /*
15217 ** Translate a single UTF-8 character.  Return the unicode value.
15218 **
15219 ** During translation, assume that the byte that zTerm points
15220 ** is a 0x00.
15221 **
15222 ** Write a pointer to the next unread byte back into *pzNext.
15223 **
15224 ** Notes On Invalid UTF-8:
15225 **
15226 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
15227 **     be encoded as a multi-byte character.  Any multi-byte character that
15228 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
15229 **
15230 **  *  This routine never allows a UTF16 surrogate value to be encoded.
15231 **     If a multi-byte character attempts to encode a value between
15232 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
15233 **
15234 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
15235 **     byte of a character are interpreted as single-byte characters
15236 **     and rendered as themselves even though they are technically
15237 **     invalid characters.
15238 **
15239 **  *  This routine accepts an infinite number of different UTF8 encodings
15240 **     for unicode values 0x80 and greater.  It do not change over-length
15241 **     encodings to 0xfffd as some systems recommend.
15242 */
15243 SQLITE_PRIVATE int sqlite3Utf8Read(
15244   const unsigned char *z,         /* First byte of UTF-8 character */
15245   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
15246   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
15247 ){
15248   int c = *(z++);
15249   if( c>=0xc0 ){
15250     c = sqlite3UtfTrans1[c-0xc0];
15251     while( z!=zTerm && (*z & 0xc0)==0x80 ){
15252       c = (c<<6) + (0x3f & *(z++));
15253     }
15254     if( c<0x80
15255         || (c&0xFFFFF800)==0xD800
15256         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
15257   }
15258   *pzNext = z;
15259   return c;
15260 }
15261
15262
15263
15264 /*
15265 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
15266 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
15267 */ 
15268 /* #define TRANSLATE_TRACE 1 */
15269
15270 #ifndef SQLITE_OMIT_UTF16
15271 /*
15272 ** This routine transforms the internal text encoding used by pMem to
15273 ** desiredEnc. It is an error if the string is already of the desired
15274 ** encoding, or if *pMem does not contain a string value.
15275 */
15276 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
15277   int len;                    /* Maximum length of output string in bytes */
15278   unsigned char *zOut;                  /* Output buffer */
15279   unsigned char *zIn;                   /* Input iterator */
15280   unsigned char *zTerm;                 /* End of input */
15281   unsigned char *z;                     /* Output iterator */
15282   unsigned int c;
15283
15284   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
15285   assert( pMem->flags&MEM_Str );
15286   assert( pMem->enc!=desiredEnc );
15287   assert( pMem->enc!=0 );
15288   assert( pMem->n>=0 );
15289
15290 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
15291   {
15292     char zBuf[100];
15293     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
15294     fprintf(stderr, "INPUT:  %s\n", zBuf);
15295   }
15296 #endif
15297
15298   /* If the translation is between UTF-16 little and big endian, then 
15299   ** all that is required is to swap the byte order. This case is handled
15300   ** differently from the others.
15301   */
15302   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
15303     u8 temp;
15304     int rc;
15305     rc = sqlite3VdbeMemMakeWriteable(pMem);
15306     if( rc!=SQLITE_OK ){
15307       assert( rc==SQLITE_NOMEM );
15308       return SQLITE_NOMEM;
15309     }
15310     zIn = (u8*)pMem->z;
15311     zTerm = &zIn[pMem->n];
15312     while( zIn<zTerm ){
15313       temp = *zIn;
15314       *zIn = *(zIn+1);
15315       zIn++;
15316       *zIn++ = temp;
15317     }
15318     pMem->enc = desiredEnc;
15319     goto translate_out;
15320   }
15321
15322   /* Set len to the maximum number of bytes required in the output buffer. */
15323   if( desiredEnc==SQLITE_UTF8 ){
15324     /* When converting from UTF-16, the maximum growth results from
15325     ** translating a 2-byte character to a 4-byte UTF-8 character.
15326     ** A single byte is required for the output string
15327     ** nul-terminator.
15328     */
15329     len = pMem->n * 2 + 1;
15330   }else{
15331     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
15332     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
15333     ** character. Two bytes are required in the output buffer for the
15334     ** nul-terminator.
15335     */
15336     len = pMem->n * 2 + 2;
15337   }
15338
15339   /* Set zIn to point at the start of the input buffer and zTerm to point 1
15340   ** byte past the end.
15341   **
15342   ** Variable zOut is set to point at the output buffer, space obtained
15343   ** from sqlite3_malloc().
15344   */
15345   zIn = (u8*)pMem->z;
15346   zTerm = &zIn[pMem->n];
15347   zOut = sqlite3DbMallocRaw(pMem->db, len);
15348   if( !zOut ){
15349     return SQLITE_NOMEM;
15350   }
15351   z = zOut;
15352
15353   if( pMem->enc==SQLITE_UTF8 ){
15354     if( desiredEnc==SQLITE_UTF16LE ){
15355       /* UTF-8 -> UTF-16 Little-endian */
15356       while( zIn<zTerm ){
15357         c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
15358         WRITE_UTF16LE(z, c);
15359       }
15360     }else{
15361       assert( desiredEnc==SQLITE_UTF16BE );
15362       /* UTF-8 -> UTF-16 Big-endian */
15363       while( zIn<zTerm ){
15364         c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
15365         WRITE_UTF16BE(z, c);
15366       }
15367     }
15368     pMem->n = z - zOut;
15369     *z++ = 0;
15370   }else{
15371     assert( desiredEnc==SQLITE_UTF8 );
15372     if( pMem->enc==SQLITE_UTF16LE ){
15373       /* UTF-16 Little-endian -> UTF-8 */
15374       while( zIn<zTerm ){
15375         READ_UTF16LE(zIn, c); 
15376         WRITE_UTF8(z, c);
15377       }
15378     }else{
15379       /* UTF-16 Little-endian -> UTF-8 */
15380       while( zIn<zTerm ){
15381         READ_UTF16BE(zIn, c); 
15382         WRITE_UTF8(z, c);
15383       }
15384     }
15385     pMem->n = z - zOut;
15386   }
15387   *z = 0;
15388   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
15389
15390   sqlite3VdbeMemRelease(pMem);
15391   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
15392   pMem->enc = desiredEnc;
15393   pMem->flags |= (MEM_Term|MEM_Dyn);
15394   pMem->z = (char*)zOut;
15395
15396 translate_out:
15397 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
15398   {
15399     char zBuf[100];
15400     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
15401     fprintf(stderr, "OUTPUT: %s\n", zBuf);
15402   }
15403 #endif
15404   return SQLITE_OK;
15405 }
15406
15407 /*
15408 ** This routine checks for a byte-order mark at the beginning of the 
15409 ** UTF-16 string stored in *pMem. If one is present, it is removed and
15410 ** the encoding of the Mem adjusted. This routine does not do any
15411 ** byte-swapping, it just sets Mem.enc appropriately.
15412 **
15413 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
15414 ** changed by this function.
15415 */
15416 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
15417   int rc = SQLITE_OK;
15418   u8 bom = 0;
15419
15420   if( pMem->n<0 || pMem->n>1 ){
15421     u8 b1 = *(u8 *)pMem->z;
15422     u8 b2 = *(((u8 *)pMem->z) + 1);
15423     if( b1==0xFE && b2==0xFF ){
15424       bom = SQLITE_UTF16BE;
15425     }
15426     if( b1==0xFF && b2==0xFE ){
15427       bom = SQLITE_UTF16LE;
15428     }
15429   }
15430   
15431   if( bom ){
15432     rc = sqlite3VdbeMemMakeWriteable(pMem);
15433     if( rc==SQLITE_OK ){
15434       pMem->n -= 2;
15435       memmove(pMem->z, &pMem->z[2], pMem->n);
15436       pMem->z[pMem->n] = '\0';
15437       pMem->z[pMem->n+1] = '\0';
15438       pMem->flags |= MEM_Term;
15439       pMem->enc = bom;
15440     }
15441   }
15442   return rc;
15443 }
15444 #endif /* SQLITE_OMIT_UTF16 */
15445
15446 /*
15447 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
15448 ** return the number of unicode characters in pZ up to (but not including)
15449 ** the first 0x00 byte. If nByte is not less than zero, return the
15450 ** number of unicode characters in the first nByte of pZ (or up to 
15451 ** the first 0x00, whichever comes first).
15452 */
15453 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
15454   int r = 0;
15455   const u8 *z = (const u8*)zIn;
15456   const u8 *zTerm;
15457   if( nByte>=0 ){
15458     zTerm = &z[nByte];
15459   }else{
15460     zTerm = (const u8*)(-1);
15461   }
15462   assert( z<=zTerm );
15463   while( *z!=0 && z<zTerm ){
15464     SQLITE_SKIP_UTF8(z);
15465     r++;
15466   }
15467   return r;
15468 }
15469
15470 /* This test function is not currently used by the automated test-suite. 
15471 ** Hence it is only available in debug builds.
15472 */
15473 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
15474 /*
15475 ** Translate UTF-8 to UTF-8.
15476 **
15477 ** This has the effect of making sure that the string is well-formed
15478 ** UTF-8.  Miscoded characters are removed.
15479 **
15480 ** The translation is done in-place (since it is impossible for the
15481 ** correct UTF-8 encoding to be longer than a malformed encoding).
15482 */
15483 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
15484   unsigned char *zOut = zIn;
15485   unsigned char *zStart = zIn;
15486   unsigned char *zTerm;
15487   u32 c;
15488
15489   while( zIn[0] ){
15490     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
15491     if( c!=0xfffd ){
15492       WRITE_UTF8(zOut, c);
15493     }
15494   }
15495   *zOut = 0;
15496   return zOut - zStart;
15497 }
15498 #endif
15499
15500 #ifndef SQLITE_OMIT_UTF16
15501 /*
15502 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
15503 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
15504 ** be freed by the calling function.
15505 **
15506 ** NULL is returned if there is an allocation error.
15507 */
15508 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
15509   Mem m;
15510   memset(&m, 0, sizeof(m));
15511   m.db = db;
15512   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
15513   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
15514   if( db->mallocFailed ){
15515     sqlite3VdbeMemRelease(&m);
15516     m.z = 0;
15517   }
15518   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
15519   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
15520   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
15521 }
15522
15523 /*
15524 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
15525 ** return the number of bytes up to (but not including), the first pair
15526 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
15527 ** then return the number of bytes in the first nChar unicode characters
15528 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
15529 */
15530 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
15531   unsigned int c = 1;
15532   char const *z = zIn;
15533   int n = 0;
15534   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
15535     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
15536     ** and in other parts of this file means that at one branch will
15537     ** not be covered by coverage testing on any single host. But coverage
15538     ** will be complete if the tests are run on both a little-endian and 
15539     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
15540     ** macros are constant at compile time the compiler can determine
15541     ** which branch will be followed. It is therefore assumed that no runtime
15542     ** penalty is paid for this "if" statement.
15543     */
15544     while( c && ((nChar<0) || n<nChar) ){
15545       READ_UTF16BE(z, c);
15546       n++;
15547     }
15548   }else{
15549     while( c && ((nChar<0) || n<nChar) ){
15550       READ_UTF16LE(z, c);
15551       n++;
15552     }
15553   }
15554   return (z-(char const *)zIn)-((c==0)?2:0);
15555 }
15556
15557 #if defined(SQLITE_TEST)
15558 /*
15559 ** This routine is called from the TCL test function "translate_selftest".
15560 ** It checks that the primitives for serializing and deserializing
15561 ** characters in each encoding are inverses of each other.
15562 */
15563 SQLITE_PRIVATE void sqlite3UtfSelfTest(){
15564   unsigned int i, t;
15565   unsigned char zBuf[20];
15566   unsigned char *z;
15567   unsigned char *zTerm;
15568   int n;
15569   unsigned int c;
15570
15571   for(i=0; i<0x00110000; i++){
15572     z = zBuf;
15573     WRITE_UTF8(z, i);
15574     n = z-zBuf;
15575     z[0] = 0;
15576     zTerm = z;
15577     z = zBuf;
15578     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
15579     t = i;
15580     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
15581     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
15582     assert( c==t );
15583     assert( (z-zBuf)==n );
15584   }
15585   for(i=0; i<0x00110000; i++){
15586     if( i>=0xD800 && i<0xE000 ) continue;
15587     z = zBuf;
15588     WRITE_UTF16LE(z, i);
15589     n = z-zBuf;
15590     z[0] = 0;
15591     z = zBuf;
15592     READ_UTF16LE(z, c);
15593     assert( c==i );
15594     assert( (z-zBuf)==n );
15595   }
15596   for(i=0; i<0x00110000; i++){
15597     if( i>=0xD800 && i<0xE000 ) continue;
15598     z = zBuf;
15599     WRITE_UTF16BE(z, i);
15600     n = z-zBuf;
15601     z[0] = 0;
15602     z = zBuf;
15603     READ_UTF16BE(z, c);
15604     assert( c==i );
15605     assert( (z-zBuf)==n );
15606   }
15607 }
15608 #endif /* SQLITE_TEST */
15609 #endif /* SQLITE_OMIT_UTF16 */
15610
15611 /************** End of utf.c *************************************************/
15612 /************** Begin file util.c ********************************************/
15613 /*
15614 ** 2001 September 15
15615 **
15616 ** The author disclaims copyright to this source code.  In place of
15617 ** a legal notice, here is a blessing:
15618 **
15619 **    May you do good and not evil.
15620 **    May you find forgiveness for yourself and forgive others.
15621 **    May you share freely, never taking more than you give.
15622 **
15623 *************************************************************************
15624 ** Utility functions used throughout sqlite.
15625 **
15626 ** This file contains functions for allocating memory, comparing
15627 ** strings, and stuff like that.
15628 **
15629 ** $Id: util.c,v 1.216 2008/01/23 03:03:05 drh Exp $
15630 */
15631
15632
15633 /*
15634 ** Set the most recent error code and error string for the sqlite
15635 ** handle "db". The error code is set to "err_code".
15636 **
15637 ** If it is not NULL, string zFormat specifies the format of the
15638 ** error string in the style of the printf functions: The following
15639 ** format characters are allowed:
15640 **
15641 **      %s      Insert a string
15642 **      %z      A string that should be freed after use
15643 **      %d      Insert an integer
15644 **      %T      Insert a token
15645 **      %S      Insert the first element of a SrcList
15646 **
15647 ** zFormat and any string tokens that follow it are assumed to be
15648 ** encoded in UTF-8.
15649 **
15650 ** To clear the most recent error for sqlite handle "db", sqlite3Error
15651 ** should be called with err_code set to SQLITE_OK and zFormat set
15652 ** to NULL.
15653 */
15654 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
15655   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
15656     db->errCode = err_code;
15657     if( zFormat ){
15658       char *z;
15659       va_list ap;
15660       va_start(ap, zFormat);
15661       z = sqlite3VMPrintf(db, zFormat, ap);
15662       va_end(ap);
15663       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3_free);
15664     }else{
15665       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
15666     }
15667   }
15668 }
15669
15670 /*
15671 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
15672 ** The following formatting characters are allowed:
15673 **
15674 **      %s      Insert a string
15675 **      %z      A string that should be freed after use
15676 **      %d      Insert an integer
15677 **      %T      Insert a token
15678 **      %S      Insert the first element of a SrcList
15679 **
15680 ** This function should be used to report any error that occurs whilst
15681 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
15682 ** last thing the sqlite3_prepare() function does is copy the error
15683 ** stored by this function into the database handle using sqlite3Error().
15684 ** Function sqlite3Error() should be used during statement execution
15685 ** (sqlite3_step() etc.).
15686 */
15687 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
15688   va_list ap;
15689   pParse->nErr++;
15690   sqlite3_free(pParse->zErrMsg);
15691   va_start(ap, zFormat);
15692   pParse->zErrMsg = sqlite3VMPrintf(pParse->db, zFormat, ap);
15693   va_end(ap);
15694   if( pParse->rc==SQLITE_OK ){
15695     pParse->rc = SQLITE_ERROR;
15696   }
15697 }
15698
15699 /*
15700 ** Clear the error message in pParse, if any
15701 */
15702 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
15703   sqlite3_free(pParse->zErrMsg);
15704   pParse->zErrMsg = 0;
15705   pParse->nErr = 0;
15706 }
15707
15708 /*
15709 ** Convert an SQL-style quoted string into a normal string by removing
15710 ** the quote characters.  The conversion is done in-place.  If the
15711 ** input does not begin with a quote character, then this routine
15712 ** is a no-op.
15713 **
15714 ** 2002-Feb-14: This routine is extended to remove MS-Access style
15715 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
15716 ** "a-b-c".
15717 */
15718 SQLITE_PRIVATE void sqlite3Dequote(char *z){
15719   int quote;
15720   int i, j;
15721   if( z==0 ) return;
15722   quote = z[0];
15723   switch( quote ){
15724     case '\'':  break;
15725     case '"':   break;
15726     case '`':   break;                /* For MySQL compatibility */
15727     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
15728     default:    return;
15729   }
15730   for(i=1, j=0; z[i]; i++){
15731     if( z[i]==quote ){
15732       if( z[i+1]==quote ){
15733         z[j++] = quote;
15734         i++;
15735       }else{
15736         z[j++] = 0;
15737         break;
15738       }
15739     }else{
15740       z[j++] = z[i];
15741     }
15742   }
15743 }
15744
15745 /* An array to map all upper-case characters into their corresponding
15746 ** lower-case character. 
15747 */
15748 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
15749 #ifdef SQLITE_ASCII
15750       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
15751      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
15752      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
15753      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
15754     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
15755     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
15756     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
15757     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
15758     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
15759     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
15760     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
15761     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
15762     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
15763     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
15764     252,253,254,255
15765 #endif
15766 #ifdef SQLITE_EBCDIC
15767       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
15768      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
15769      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
15770      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
15771      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
15772      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
15773      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
15774     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
15775     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
15776     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
15777     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
15778     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
15779     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
15780     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
15781     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
15782     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
15783 #endif
15784 };
15785 #define UpperToLower sqlite3UpperToLower
15786
15787 /*
15788 ** Some systems have stricmp().  Others have strcasecmp().  Because
15789 ** there is no consistency, we will define our own.
15790 */
15791 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
15792   register unsigned char *a, *b;
15793   a = (unsigned char *)zLeft;
15794   b = (unsigned char *)zRight;
15795   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
15796   return UpperToLower[*a] - UpperToLower[*b];
15797 }
15798 SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
15799   register unsigned char *a, *b;
15800   a = (unsigned char *)zLeft;
15801   b = (unsigned char *)zRight;
15802   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
15803   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
15804 }
15805
15806 /*
15807 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
15808 ** string contains any character which is not part of a number. If
15809 ** the string is numeric and contains the '.' character, set *realnum
15810 ** to TRUE (otherwise FALSE).
15811 **
15812 ** An empty string is considered non-numeric.
15813 */
15814 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
15815   int incr = (enc==SQLITE_UTF8?1:2);
15816   if( enc==SQLITE_UTF16BE ) z++;
15817   if( *z=='-' || *z=='+' ) z += incr;
15818   if( !isdigit(*(u8*)z) ){
15819     return 0;
15820   }
15821   z += incr;
15822   if( realnum ) *realnum = 0;
15823   while( isdigit(*(u8*)z) ){ z += incr; }
15824   if( *z=='.' ){
15825     z += incr;
15826     if( !isdigit(*(u8*)z) ) return 0;
15827     while( isdigit(*(u8*)z) ){ z += incr; }
15828     if( realnum ) *realnum = 1;
15829   }
15830   if( *z=='e' || *z=='E' ){
15831     z += incr;
15832     if( *z=='+' || *z=='-' ) z += incr;
15833     if( !isdigit(*(u8*)z) ) return 0;
15834     while( isdigit(*(u8*)z) ){ z += incr; }
15835     if( realnum ) *realnum = 1;
15836   }
15837   return *z==0;
15838 }
15839
15840 /*
15841 ** The string z[] is an ascii representation of a real number.
15842 ** Convert this string to a double.
15843 **
15844 ** This routine assumes that z[] really is a valid number.  If it
15845 ** is not, the result is undefined.
15846 **
15847 ** This routine is used instead of the library atof() function because
15848 ** the library atof() might want to use "," as the decimal point instead
15849 ** of "." depending on how locale is set.  But that would cause problems
15850 ** for SQL.  So this routine always uses "." regardless of locale.
15851 */
15852 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
15853 #ifndef SQLITE_OMIT_FLOATING_POINT
15854   int sign = 1;
15855   const char *zBegin = z;
15856   LONGDOUBLE_TYPE v1 = 0.0;
15857   while( isspace(*(u8*)z) ) z++;
15858   if( *z=='-' ){
15859     sign = -1;
15860     z++;
15861   }else if( *z=='+' ){
15862     z++;
15863   }
15864   while( isdigit(*(u8*)z) ){
15865     v1 = v1*10.0 + (*z - '0');
15866     z++;
15867   }
15868   if( *z=='.' ){
15869     LONGDOUBLE_TYPE divisor = 1.0;
15870     z++;
15871     while( isdigit(*(u8*)z) ){
15872       v1 = v1*10.0 + (*z - '0');
15873       divisor *= 10.0;
15874       z++;
15875     }
15876     v1 /= divisor;
15877   }
15878   if( *z=='e' || *z=='E' ){
15879     int esign = 1;
15880     int eval = 0;
15881     LONGDOUBLE_TYPE scale = 1.0;
15882     z++;
15883     if( *z=='-' ){
15884       esign = -1;
15885       z++;
15886     }else if( *z=='+' ){
15887       z++;
15888     }
15889     while( isdigit(*(u8*)z) ){
15890       eval = eval*10 + *z - '0';
15891       z++;
15892     }
15893     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
15894     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
15895     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
15896     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
15897     if( esign<0 ){
15898       v1 /= scale;
15899     }else{
15900       v1 *= scale;
15901     }
15902   }
15903   *pResult = sign<0 ? -v1 : v1;
15904   return z - zBegin;
15905 #else
15906   return sqlite3Atoi64(z, pResult);
15907 #endif /* SQLITE_OMIT_FLOATING_POINT */
15908 }
15909
15910 /*
15911 ** Compare the 19-character string zNum against the text representation
15912 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
15913 ** if zNum is less than, equal to, or greater than the string.
15914 **
15915 ** Unlike memcmp() this routine is guaranteed to return the difference
15916 ** in the values of the last digit if the only difference is in the
15917 ** last digit.  So, for example,
15918 **
15919 **      compare2pow63("9223372036854775800")
15920 **
15921 ** will return -8.
15922 */
15923 static int compare2pow63(const char *zNum){
15924   int c;
15925   c = memcmp(zNum,"922337203685477580",18);
15926   if( c==0 ){
15927     c = zNum[18] - '8';
15928   }
15929   return c;
15930 }
15931
15932
15933 /*
15934 ** Return TRUE if zNum is a 64-bit signed integer and write
15935 ** the value of the integer into *pNum.  If zNum is not an integer
15936 ** or is an integer that is too large to be expressed with 64 bits,
15937 ** then return false.
15938 **
15939 ** When this routine was originally written it dealt with only
15940 ** 32-bit numbers.  At that time, it was much faster than the
15941 ** atoi() library routine in RedHat 7.2.
15942 */
15943 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
15944   i64 v = 0;
15945   int neg;
15946   int i, c;
15947   while( isspace(*(u8*)zNum) ) zNum++;
15948   if( *zNum=='-' ){
15949     neg = 1;
15950     zNum++;
15951   }else if( *zNum=='+' ){
15952     neg = 0;
15953     zNum++;
15954   }else{
15955     neg = 0;
15956   }
15957   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
15958   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
15959     v = v*10 + c - '0';
15960   }
15961   *pNum = neg ? -v : v;
15962   if( c!=0 || i==0 || i>19 ){
15963     /* zNum is empty or contains non-numeric text or is longer
15964     ** than 19 digits (thus guaranting that it is too large) */
15965     return 0;
15966   }else if( i<19 ){
15967     /* Less than 19 digits, so we know that it fits in 64 bits */
15968     return 1;
15969   }else{
15970     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
15971     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
15972     ** is 2^63. */
15973     return compare2pow63(zNum)<neg;
15974   }
15975 }
15976
15977 /*
15978 ** The string zNum represents an integer.  There might be some other
15979 ** information following the integer too, but that part is ignored.
15980 ** If the integer that the prefix of zNum represents will fit in a
15981 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
15982 **
15983 ** This routine returns FALSE for the string -9223372036854775808 even that
15984 ** that number will, in theory fit in a 64-bit integer.  Positive
15985 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
15986 ** false.
15987 */
15988 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
15989   int i, c;
15990   int neg = 0;
15991   if( *zNum=='-' ){
15992     neg = 1;
15993     zNum++;
15994   }else if( *zNum=='+' ){
15995     zNum++;
15996   }
15997   if( negFlag ) neg = 1-neg;
15998   while( *zNum=='0' ){
15999     zNum++;   /* Skip leading zeros.  Ticket #2454 */
16000   }
16001   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
16002   if( i<19 ){
16003     /* Guaranteed to fit if less than 19 digits */
16004     return 1;
16005   }else if( i>19 ){
16006     /* Guaranteed to be too big if greater than 19 digits */
16007     return 0;
16008   }else{
16009     /* Compare against 2^63. */
16010     return compare2pow63(zNum)<neg;
16011   }
16012 }
16013
16014 /*
16015 ** If zNum represents an integer that will fit in 32-bits, then set
16016 ** *pValue to that integer and return true.  Otherwise return false.
16017 **
16018 ** Any non-numeric characters that following zNum are ignored.
16019 ** This is different from sqlite3Atoi64() which requires the
16020 ** input number to be zero-terminated.
16021 */
16022 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
16023   sqlite_int64 v = 0;
16024   int i, c;
16025   int neg = 0;
16026   if( zNum[0]=='-' ){
16027     neg = 1;
16028     zNum++;
16029   }else if( zNum[0]=='+' ){
16030     zNum++;
16031   }
16032   while( zNum[0]=='0' ) zNum++;
16033   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
16034     v = v*10 + c;
16035   }
16036
16037   /* The longest decimal representation of a 32 bit integer is 10 digits:
16038   **
16039   **             1234567890
16040   **     2^31 -> 2147483648
16041   */
16042   if( i>10 ){
16043     return 0;
16044   }
16045   if( v-neg>2147483647 ){
16046     return 0;
16047   }
16048   if( neg ){
16049     v = -v;
16050   }
16051   *pValue = (int)v;
16052   return 1;
16053 }
16054
16055 /*
16056 ** The variable-length integer encoding is as follows:
16057 **
16058 ** KEY:
16059 **         A = 0xxxxxxx    7 bits of data and one flag bit
16060 **         B = 1xxxxxxx    7 bits of data and one flag bit
16061 **         C = xxxxxxxx    8 bits of data
16062 **
16063 **  7 bits - A
16064 ** 14 bits - BA
16065 ** 21 bits - BBA
16066 ** 28 bits - BBBA
16067 ** 35 bits - BBBBA
16068 ** 42 bits - BBBBBA
16069 ** 49 bits - BBBBBBA
16070 ** 56 bits - BBBBBBBA
16071 ** 64 bits - BBBBBBBBC
16072 */
16073
16074 /*
16075 ** Write a 64-bit variable-length integer to memory starting at p[0].
16076 ** The length of data write will be between 1 and 9 bytes.  The number
16077 ** of bytes written is returned.
16078 **
16079 ** A variable-length integer consists of the lower 7 bits of each byte
16080 ** for all bytes that have the 8th bit set and one byte with the 8th
16081 ** bit clear.  Except, if we get to the 9th byte, it stores the full
16082 ** 8 bits and is the last byte.
16083 */
16084 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
16085   int i, j, n;
16086   u8 buf[10];
16087   if( v & (((u64)0xff000000)<<32) ){
16088     p[8] = v;
16089     v >>= 8;
16090     for(i=7; i>=0; i--){
16091       p[i] = (v & 0x7f) | 0x80;
16092       v >>= 7;
16093     }
16094     return 9;
16095   }    
16096   n = 0;
16097   do{
16098     buf[n++] = (v & 0x7f) | 0x80;
16099     v >>= 7;
16100   }while( v!=0 );
16101   buf[0] &= 0x7f;
16102   assert( n<=9 );
16103   for(i=0, j=n-1; j>=0; j--, i++){
16104     p[i] = buf[j];
16105   }
16106   return n;
16107 }
16108
16109 /*
16110 ** Read a 64-bit variable-length integer from memory starting at p[0].
16111 ** Return the number of bytes read.  The value is stored in *v.
16112 */
16113 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *p, u64 *v){
16114   u32 x;
16115   u64 x64;
16116   int n;
16117   unsigned char c;
16118   if( ((c = p[0]) & 0x80)==0 ){
16119     *v = c;
16120     return 1;
16121   }
16122   x = c & 0x7f;
16123   if( ((c = p[1]) & 0x80)==0 ){
16124     *v = (x<<7) | c;
16125     return 2;
16126   }
16127   x = (x<<7) | (c&0x7f);
16128   if( ((c = p[2]) & 0x80)==0 ){
16129     *v = (x<<7) | c;
16130     return 3;
16131   }
16132   x = (x<<7) | (c&0x7f);
16133   if( ((c = p[3]) & 0x80)==0 ){
16134     *v = (x<<7) | c;
16135     return 4;
16136   }
16137   x64 = (x<<7) | (c&0x7f);
16138   n = 4;
16139   do{
16140     c = p[n++];
16141     if( n==9 ){
16142       x64 = (x64<<8) | c;
16143       break;
16144     }
16145     x64 = (x64<<7) | (c&0x7f);
16146   }while( (c & 0x80)!=0 );
16147   *v = x64;
16148   return n;
16149 }
16150
16151 /*
16152 ** Read a 32-bit variable-length integer from memory starting at p[0].
16153 ** Return the number of bytes read.  The value is stored in *v.
16154 */
16155 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *p, u32 *v){
16156   u32 x;
16157   int n;
16158   unsigned char c;
16159   if( ((signed char*)p)[0]>=0 ){
16160     *v = p[0];
16161     return 1;
16162   }
16163   x = p[0] & 0x7f;
16164   if( ((signed char*)p)[1]>=0 ){
16165     *v = (x<<7) | p[1];
16166     return 2;
16167   }
16168   x = (x<<7) | (p[1] & 0x7f);
16169   n = 2;
16170   do{
16171     x = (x<<7) | ((c = p[n++])&0x7f);
16172   }while( (c & 0x80)!=0 && n<9 );
16173   *v = x;
16174   return n;
16175 }
16176
16177 /*
16178 ** Return the number of bytes that will be needed to store the given
16179 ** 64-bit integer.
16180 */
16181 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
16182   int i = 0;
16183   do{
16184     i++;
16185     v >>= 7;
16186   }while( v!=0 && i<9 );
16187   return i;
16188 }
16189
16190
16191 /*
16192 ** Read or write a four-byte big-endian integer value.
16193 */
16194 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
16195   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
16196 }
16197 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
16198   p[0] = v>>24;
16199   p[1] = v>>16;
16200   p[2] = v>>8;
16201   p[3] = v;
16202 }
16203
16204
16205
16206 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) \
16207     || defined(SQLITE_TEST)
16208 /*
16209 ** Translate a single byte of Hex into an integer.
16210 */
16211 static int hexToInt(int h){
16212   if( h>='0' && h<='9' ){
16213     return h - '0';
16214   }else if( h>='a' && h<='f' ){
16215     return h - 'a' + 10;
16216   }else{
16217     assert( h>='A' && h<='F' );
16218     return h - 'A' + 10;
16219   }
16220 }
16221 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC || SQLITE_TEST */
16222
16223 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
16224 /*
16225 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
16226 ** value.  Return a pointer to its binary value.  Space to hold the
16227 ** binary value has been obtained from malloc and must be freed by
16228 ** the calling routine.
16229 */
16230 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
16231   char *zBlob;
16232   int i;
16233
16234   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
16235   n--;
16236   if( zBlob ){
16237     for(i=0; i<n; i+=2){
16238       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
16239     }
16240     zBlob[i/2] = 0;
16241   }
16242   return zBlob;
16243 }
16244 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
16245
16246
16247 /*
16248 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
16249 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
16250 ** when this routine is called.
16251 **
16252 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
16253 ** value indicates that the database connection passed into the API is
16254 ** open and is not being used by another thread.  By changing the value
16255 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
16256 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
16257 ** when the API exits. 
16258 **
16259 ** This routine is a attempt to detect if two threads use the
16260 ** same sqlite* pointer at the same time.  There is a race 
16261 ** condition so it is possible that the error is not detected.
16262 ** But usually the problem will be seen.  The result will be an
16263 ** error which can be used to debug the application that is
16264 ** using SQLite incorrectly.
16265 **
16266 ** Ticket #202:  If db->magic is not a valid open value, take care not
16267 ** to modify the db structure at all.  It could be that db is a stale
16268 ** pointer.  In other words, it could be that there has been a prior
16269 ** call to sqlite3_close(db) and db has been deallocated.  And we do
16270 ** not want to write into deallocated memory.
16271 */
16272 #ifdef SQLITE_DEBUG
16273 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
16274   if( db->magic==SQLITE_MAGIC_OPEN ){
16275     db->magic = SQLITE_MAGIC_BUSY;
16276     return 0;
16277   }else if( db->magic==SQLITE_MAGIC_BUSY ){
16278     db->magic = SQLITE_MAGIC_ERROR;
16279     db->u1.isInterrupted = 1;
16280   }
16281   return 1;
16282 }
16283 #endif
16284
16285 /*
16286 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
16287 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
16288 ** when this routine is called.
16289 */
16290 #ifdef SQLITE_DEBUG
16291 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
16292   if( db->magic==SQLITE_MAGIC_BUSY ){
16293     db->magic = SQLITE_MAGIC_OPEN;
16294     return 0;
16295   }else{
16296     db->magic = SQLITE_MAGIC_ERROR;
16297     db->u1.isInterrupted = 1;
16298     return 1;
16299   }
16300 }
16301 #endif
16302
16303 /*
16304 ** Check to make sure we have a valid db pointer.  This test is not
16305 ** foolproof but it does provide some measure of protection against
16306 ** misuse of the interface such as passing in db pointers that are
16307 ** NULL or which have been previously closed.  If this routine returns
16308 ** 1 it means that the db pointer is valid and 0 if it should not be
16309 ** dereferenced for any reason.  The calling function should invoke
16310 ** SQLITE_MISUSE immediately.
16311 **
16312 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
16313 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
16314 ** open properly and is not fit for general use but which can be
16315 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
16316 */
16317 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
16318   int magic;
16319   if( db==0 ) return 0;
16320   magic = db->magic;
16321   if( magic!=SQLITE_MAGIC_OPEN &&
16322       magic!=SQLITE_MAGIC_BUSY ) return 0;
16323   return 1;
16324 }
16325 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
16326   int magic;
16327   if( db==0 ) return 0;
16328   magic = db->magic;
16329   if( magic!=SQLITE_MAGIC_SICK &&
16330       magic!=SQLITE_MAGIC_OPEN &&
16331       magic!=SQLITE_MAGIC_BUSY ) return 0;
16332   return 1;
16333 }
16334
16335 /************** End of util.c ************************************************/
16336 /************** Begin file hash.c ********************************************/
16337 /*
16338 ** 2001 September 22
16339 **
16340 ** The author disclaims copyright to this source code.  In place of
16341 ** a legal notice, here is a blessing:
16342 **
16343 **    May you do good and not evil.
16344 **    May you find forgiveness for yourself and forgive others.
16345 **    May you share freely, never taking more than you give.
16346 **
16347 *************************************************************************
16348 ** This is the implementation of generic hash-tables
16349 ** used in SQLite.
16350 **
16351 ** $Id: hash.c,v 1.26 2008/02/18 22:24:58 drh Exp $
16352 */
16353
16354 /* Turn bulk memory into a hash table object by initializing the
16355 ** fields of the Hash structure.
16356 **
16357 ** "pNew" is a pointer to the hash table that is to be initialized.
16358 ** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
16359 ** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING.  The value of keyClass 
16360 ** determines what kind of key the hash table will use.  "copyKey" is
16361 ** true if the hash table should make its own private copy of keys and
16362 ** false if it should just use the supplied pointer.  CopyKey only makes
16363 ** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
16364 ** for other key classes.
16365 */
16366 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
16367   assert( pNew!=0 );
16368   assert( keyClass>=SQLITE_HASH_STRING && keyClass<=SQLITE_HASH_BINARY );
16369   pNew->keyClass = keyClass;
16370 #if 0
16371   if( keyClass==SQLITE_HASH_POINTER || keyClass==SQLITE_HASH_INT ) copyKey = 0;
16372 #endif
16373   pNew->copyKey = copyKey;
16374   pNew->first = 0;
16375   pNew->count = 0;
16376   pNew->htsize = 0;
16377   pNew->ht = 0;
16378 }
16379
16380 /* Remove all entries from a hash table.  Reclaim all memory.
16381 ** Call this routine to delete a hash table or to reset a hash table
16382 ** to the empty state.
16383 */
16384 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
16385   HashElem *elem;         /* For looping over all elements of the table */
16386
16387   assert( pH!=0 );
16388   elem = pH->first;
16389   pH->first = 0;
16390   if( pH->ht ) sqlite3_free(pH->ht);
16391   pH->ht = 0;
16392   pH->htsize = 0;
16393   while( elem ){
16394     HashElem *next_elem = elem->next;
16395     if( pH->copyKey && elem->pKey ){
16396       sqlite3_free(elem->pKey);
16397     }
16398     sqlite3_free(elem);
16399     elem = next_elem;
16400   }
16401   pH->count = 0;
16402 }
16403
16404 #if 0 /* NOT USED */
16405 /*
16406 ** Hash and comparison functions when the mode is SQLITE_HASH_INT
16407 */
16408 static int intHash(const void *pKey, int nKey){
16409   return nKey ^ (nKey<<8) ^ (nKey>>8);
16410 }
16411 static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
16412   return n2 - n1;
16413 }
16414 #endif
16415
16416 #if 0 /* NOT USED */
16417 /*
16418 ** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
16419 */
16420 static int ptrHash(const void *pKey, int nKey){
16421   uptr x = Addr(pKey);
16422   return x ^ (x<<8) ^ (x>>8);
16423 }
16424 static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
16425   if( pKey1==pKey2 ) return 0;
16426   if( pKey1<pKey2 ) return -1;
16427   return 1;
16428 }
16429 #endif
16430
16431 /*
16432 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
16433 */
16434 static int strHash(const void *pKey, int nKey){
16435   const char *z = (const char *)pKey;
16436   int h = 0;
16437   if( nKey<=0 ) nKey = strlen(z);
16438   while( nKey > 0  ){
16439     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
16440     nKey--;
16441   }
16442   return h & 0x7fffffff;
16443 }
16444 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
16445   if( n1!=n2 ) return 1;
16446   return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
16447 }
16448
16449 /*
16450 ** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
16451 */
16452 static int binHash(const void *pKey, int nKey){
16453   int h = 0;
16454   const char *z = (const char *)pKey;
16455   while( nKey-- > 0 ){
16456     h = (h<<3) ^ h ^ *(z++);
16457   }
16458   return h & 0x7fffffff;
16459 }
16460 static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
16461   if( n1!=n2 ) return 1;
16462   return memcmp(pKey1,pKey2,n1);
16463 }
16464
16465 /*
16466 ** Return a pointer to the appropriate hash function given the key class.
16467 **
16468 ** The C syntax in this function definition may be unfamilar to some 
16469 ** programmers, so we provide the following additional explanation:
16470 **
16471 ** The name of the function is "hashFunction".  The function takes a
16472 ** single parameter "keyClass".  The return value of hashFunction()
16473 ** is a pointer to another function.  Specifically, the return value
16474 ** of hashFunction() is a pointer to a function that takes two parameters
16475 ** with types "const void*" and "int" and returns an "int".
16476 */
16477 static int (*hashFunction(int keyClass))(const void*,int){
16478 #if 0  /* HASH_INT and HASH_POINTER are never used */
16479   switch( keyClass ){
16480     case SQLITE_HASH_INT:     return &intHash;
16481     case SQLITE_HASH_POINTER: return &ptrHash;
16482     case SQLITE_HASH_STRING:  return &strHash;
16483     case SQLITE_HASH_BINARY:  return &binHash;;
16484     default: break;
16485   }
16486   return 0;
16487 #else
16488   if( keyClass==SQLITE_HASH_STRING ){
16489     return &strHash;
16490   }else{
16491     assert( keyClass==SQLITE_HASH_BINARY );
16492     return &binHash;
16493   }
16494 #endif
16495 }
16496
16497 /*
16498 ** Return a pointer to the appropriate hash function given the key class.
16499 **
16500 ** For help in interpreted the obscure C code in the function definition,
16501 ** see the header comment on the previous function.
16502 */
16503 static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
16504 #if 0 /* HASH_INT and HASH_POINTER are never used */
16505   switch( keyClass ){
16506     case SQLITE_HASH_INT:     return &intCompare;
16507     case SQLITE_HASH_POINTER: return &ptrCompare;
16508     case SQLITE_HASH_STRING:  return &strCompare;
16509     case SQLITE_HASH_BINARY:  return &binCompare;
16510     default: break;
16511   }
16512   return 0;
16513 #else
16514   if( keyClass==SQLITE_HASH_STRING ){
16515     return &strCompare;
16516   }else{
16517     assert( keyClass==SQLITE_HASH_BINARY );
16518     return &binCompare;
16519   }
16520 #endif
16521 }
16522
16523 /* Link an element into the hash table
16524 */
16525 static void insertElement(
16526   Hash *pH,              /* The complete hash table */
16527   struct _ht *pEntry,    /* The entry into which pNew is inserted */
16528   HashElem *pNew         /* The element to be inserted */
16529 ){
16530   HashElem *pHead;       /* First element already in pEntry */
16531   pHead = pEntry->chain;
16532   if( pHead ){
16533     pNew->next = pHead;
16534     pNew->prev = pHead->prev;
16535     if( pHead->prev ){ pHead->prev->next = pNew; }
16536     else             { pH->first = pNew; }
16537     pHead->prev = pNew;
16538   }else{
16539     pNew->next = pH->first;
16540     if( pH->first ){ pH->first->prev = pNew; }
16541     pNew->prev = 0;
16542     pH->first = pNew;
16543   }
16544   pEntry->count++;
16545   pEntry->chain = pNew;
16546 }
16547
16548
16549 /* Resize the hash table so that it cantains "new_size" buckets.
16550 ** "new_size" must be a power of 2.  The hash table might fail 
16551 ** to resize if sqlite3_malloc() fails.
16552 */
16553 static void rehash(Hash *pH, int new_size){
16554   struct _ht *new_ht;            /* The new hash table */
16555   HashElem *elem, *next_elem;    /* For looping over existing elements */
16556   int (*xHash)(const void*,int); /* The hash function */
16557
16558 #ifdef SQLITE_MALLOC_SOFT_LIMIT
16559   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
16560     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
16561   }
16562   if( new_size==pH->htsize ) return;
16563 #endif
16564
16565   /* There is a call to sqlite3_malloc() inside rehash(). If there is
16566   ** already an allocation at pH->ht, then if this malloc() fails it
16567   ** is benign (since failing to resize a hash table is a performance
16568   ** hit only, not a fatal error).
16569   */
16570   sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, pH->htsize>0);
16571   new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
16572   sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 0);
16573
16574   if( new_ht==0 ) return;
16575   if( pH->ht ) sqlite3_free(pH->ht);
16576   pH->ht = new_ht;
16577   pH->htsize = new_size;
16578   xHash = hashFunction(pH->keyClass);
16579   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
16580     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
16581     next_elem = elem->next;
16582     insertElement(pH, &new_ht[h], elem);
16583   }
16584 }
16585
16586 /* This function (for internal use only) locates an element in an
16587 ** hash table that matches the given key.  The hash for this key has
16588 ** already been computed and is passed as the 4th parameter.
16589 */
16590 static HashElem *findElementGivenHash(
16591   const Hash *pH,     /* The pH to be searched */
16592   const void *pKey,   /* The key we are searching for */
16593   int nKey,
16594   int h               /* The hash for this key. */
16595 ){
16596   HashElem *elem;                /* Used to loop thru the element list */
16597   int count;                     /* Number of elements left to test */
16598   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
16599
16600   if( pH->ht ){
16601     struct _ht *pEntry = &pH->ht[h];
16602     elem = pEntry->chain;
16603     count = pEntry->count;
16604     xCompare = compareFunction(pH->keyClass);
16605     while( count-- && elem ){
16606       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
16607         return elem;
16608       }
16609       elem = elem->next;
16610     }
16611   }
16612   return 0;
16613 }
16614
16615 /* Remove a single entry from the hash table given a pointer to that
16616 ** element and a hash on the element's key.
16617 */
16618 static void removeElementGivenHash(
16619   Hash *pH,         /* The pH containing "elem" */
16620   HashElem* elem,   /* The element to be removed from the pH */
16621   int h             /* Hash value for the element */
16622 ){
16623   struct _ht *pEntry;
16624   if( elem->prev ){
16625     elem->prev->next = elem->next; 
16626   }else{
16627     pH->first = elem->next;
16628   }
16629   if( elem->next ){
16630     elem->next->prev = elem->prev;
16631   }
16632   pEntry = &pH->ht[h];
16633   if( pEntry->chain==elem ){
16634     pEntry->chain = elem->next;
16635   }
16636   pEntry->count--;
16637   if( pEntry->count<=0 ){
16638     pEntry->chain = 0;
16639   }
16640   if( pH->copyKey ){
16641     sqlite3_free(elem->pKey);
16642   }
16643   sqlite3_free( elem );
16644   pH->count--;
16645   if( pH->count<=0 ){
16646     assert( pH->first==0 );
16647     assert( pH->count==0 );
16648     sqlite3HashClear(pH);
16649   }
16650 }
16651
16652 /* Attempt to locate an element of the hash table pH with a key
16653 ** that matches pKey,nKey.  Return a pointer to the corresponding 
16654 ** HashElem structure for this element if it is found, or NULL
16655 ** otherwise.
16656 */
16657 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
16658   int h;             /* A hash on key */
16659   HashElem *elem;    /* The element that matches key */
16660   int (*xHash)(const void*,int);  /* The hash function */
16661
16662   if( pH==0 || pH->ht==0 ) return 0;
16663   xHash = hashFunction(pH->keyClass);
16664   assert( xHash!=0 );
16665   h = (*xHash)(pKey,nKey);
16666   elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
16667   return elem;
16668 }
16669
16670 /* Attempt to locate an element of the hash table pH with a key
16671 ** that matches pKey,nKey.  Return the data for this element if it is
16672 ** found, or NULL if there is no match.
16673 */
16674 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
16675   HashElem *elem;    /* The element that matches key */
16676   elem = sqlite3HashFindElem(pH, pKey, nKey);
16677   return elem ? elem->data : 0;
16678 }
16679
16680 /* Insert an element into the hash table pH.  The key is pKey,nKey
16681 ** and the data is "data".
16682 **
16683 ** If no element exists with a matching key, then a new
16684 ** element is created.  A copy of the key is made if the copyKey
16685 ** flag is set.  NULL is returned.
16686 **
16687 ** If another element already exists with the same key, then the
16688 ** new data replaces the old data and the old data is returned.
16689 ** The key is not copied in this instance.  If a malloc fails, then
16690 ** the new data is returned and the hash table is unchanged.
16691 **
16692 ** If the "data" parameter to this function is NULL, then the
16693 ** element corresponding to "key" is removed from the hash table.
16694 */
16695 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
16696   int hraw;             /* Raw hash value of the key */
16697   int h;                /* the hash of the key modulo hash table size */
16698   HashElem *elem;       /* Used to loop thru the element list */
16699   HashElem *new_elem;   /* New element added to the pH */
16700   int (*xHash)(const void*,int);  /* The hash function */
16701
16702   assert( pH!=0 );
16703   xHash = hashFunction(pH->keyClass);
16704   assert( xHash!=0 );
16705   hraw = (*xHash)(pKey, nKey);
16706   if( pH->htsize ){
16707     h = hraw % pH->htsize;
16708     elem = findElementGivenHash(pH,pKey,nKey,h);
16709     if( elem ){
16710       void *old_data = elem->data;
16711       if( data==0 ){
16712         removeElementGivenHash(pH,elem,h);
16713       }else{
16714         elem->data = data;
16715         if( !pH->copyKey ){
16716           elem->pKey = (void *)pKey;
16717         }
16718         assert(nKey==elem->nKey);
16719       }
16720       return old_data;
16721     }
16722   }
16723   if( data==0 ) return 0;
16724   new_elem = (HashElem*)sqlite3_malloc( sizeof(HashElem) );
16725   if( new_elem==0 ) return data;
16726   if( pH->copyKey && pKey!=0 ){
16727     new_elem->pKey = sqlite3_malloc( nKey );
16728     if( new_elem->pKey==0 ){
16729       sqlite3_free(new_elem);
16730       return data;
16731     }
16732     memcpy((void*)new_elem->pKey, pKey, nKey);
16733   }else{
16734     new_elem->pKey = (void*)pKey;
16735   }
16736   new_elem->nKey = nKey;
16737   pH->count++;
16738   if( pH->htsize==0 ){
16739     rehash(pH, 128/sizeof(pH->ht[0]));
16740     if( pH->htsize==0 ){
16741       pH->count = 0;
16742       if( pH->copyKey ){
16743         sqlite3_free(new_elem->pKey);
16744       }
16745       sqlite3_free(new_elem);
16746       return data;
16747     }
16748   }
16749   if( pH->count > pH->htsize ){
16750     rehash(pH,pH->htsize*2);
16751   }
16752   assert( pH->htsize>0 );
16753   h = hraw % pH->htsize;
16754   insertElement(pH, &pH->ht[h], new_elem);
16755   new_elem->data = data;
16756   return 0;
16757 }
16758
16759 /************** End of hash.c ************************************************/
16760 /************** Begin file opcodes.c *****************************************/
16761 /* Automatically generated.  Do not edit */
16762 /* See the mkopcodec.awk script for details. */
16763 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
16764 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
16765  static const char *const azName[] = { "?",
16766      /*   1 */ "VNext",
16767      /*   2 */ "Column",
16768      /*   3 */ "SetCookie",
16769      /*   4 */ "Sequence",
16770      /*   5 */ "MoveGt",
16771      /*   6 */ "RowKey",
16772      /*   7 */ "SCopy",
16773      /*   8 */ "OpenWrite",
16774      /*   9 */ "If",
16775      /*  10 */ "VRowid",
16776      /*  11 */ "CollSeq",
16777      /*  12 */ "OpenRead",
16778      /*  13 */ "Expire",
16779      /*  14 */ "AutoCommit",
16780      /*  15 */ "IntegrityCk",
16781      /*  16 */ "Not",
16782      /*  17 */ "Sort",
16783      /*  18 */ "Copy",
16784      /*  19 */ "Trace",
16785      /*  20 */ "Function",
16786      /*  21 */ "IfNeg",
16787      /*  22 */ "Noop",
16788      /*  23 */ "Return",
16789      /*  24 */ "NewRowid",
16790      /*  25 */ "Variable",
16791      /*  26 */ "String",
16792      /*  27 */ "RealAffinity",
16793      /*  28 */ "VRename",
16794      /*  29 */ "ParseSchema",
16795      /*  30 */ "VOpen",
16796      /*  31 */ "Close",
16797      /*  32 */ "CreateIndex",
16798      /*  33 */ "IsUnique",
16799      /*  34 */ "NotFound",
16800      /*  35 */ "Int64",
16801      /*  36 */ "MustBeInt",
16802      /*  37 */ "Halt",
16803      /*  38 */ "Rowid",
16804      /*  39 */ "IdxLT",
16805      /*  40 */ "AddImm",
16806      /*  41 */ "Statement",
16807      /*  42 */ "RowData",
16808      /*  43 */ "MemMax",
16809      /*  44 */ "NotExists",
16810      /*  45 */ "Gosub",
16811      /*  46 */ "Integer",
16812      /*  47 */ "Prev",
16813      /*  48 */ "VColumn",
16814      /*  49 */ "CreateTable",
16815      /*  50 */ "Last",
16816      /*  51 */ "IncrVacuum",
16817      /*  52 */ "IdxRowid",
16818      /*  53 */ "ResetCount",
16819      /*  54 */ "FifoWrite",
16820      /*  55 */ "ContextPush",
16821      /*  56 */ "DropTrigger",
16822      /*  57 */ "DropIndex",
16823      /*  58 */ "IdxGE",
16824      /*  59 */ "IdxDelete",
16825      /*  60 */ "Or",
16826      /*  61 */ "And",
16827      /*  62 */ "Vacuum",
16828      /*  63 */ "MoveLe",
16829      /*  64 */ "IfNot",
16830      /*  65 */ "IsNull",
16831      /*  66 */ "NotNull",
16832      /*  67 */ "Ne",
16833      /*  68 */ "Eq",
16834      /*  69 */ "Gt",
16835      /*  70 */ "Le",
16836      /*  71 */ "Lt",
16837      /*  72 */ "Ge",
16838      /*  73 */ "DropTable",
16839      /*  74 */ "BitAnd",
16840      /*  75 */ "BitOr",
16841      /*  76 */ "ShiftLeft",
16842      /*  77 */ "ShiftRight",
16843      /*  78 */ "Add",
16844      /*  79 */ "Subtract",
16845      /*  80 */ "Multiply",
16846      /*  81 */ "Divide",
16847      /*  82 */ "Remainder",
16848      /*  83 */ "Concat",
16849      /*  84 */ "MakeRecord",
16850      /*  85 */ "ResultRow",
16851      /*  86 */ "Delete",
16852      /*  87 */ "BitNot",
16853      /*  88 */ "String8",
16854      /*  89 */ "AggFinal",
16855      /*  90 */ "Goto",
16856      /*  91 */ "TableLock",
16857      /*  92 */ "FifoRead",
16858      /*  93 */ "Clear",
16859      /*  94 */ "MoveLt",
16860      /*  95 */ "VerifyCookie",
16861      /*  96 */ "AggStep",
16862      /*  97 */ "SetNumColumns",
16863      /*  98 */ "Transaction",
16864      /*  99 */ "VFilter",
16865      /* 100 */ "VDestroy",
16866      /* 101 */ "ContextPop",
16867      /* 102 */ "Next",
16868      /* 103 */ "IdxInsert",
16869      /* 104 */ "Insert",
16870      /* 105 */ "Destroy",
16871      /* 106 */ "ReadCookie",
16872      /* 107 */ "ForceInt",
16873      /* 108 */ "LoadAnalysis",
16874      /* 109 */ "Explain",
16875      /* 110 */ "OpenPseudo",
16876      /* 111 */ "OpenEphemeral",
16877      /* 112 */ "Null",
16878      /* 113 */ "Move",
16879      /* 114 */ "Blob",
16880      /* 115 */ "Rewind",
16881      /* 116 */ "MoveGe",
16882      /* 117 */ "VBegin",
16883      /* 118 */ "VUpdate",
16884      /* 119 */ "IfZero",
16885      /* 120 */ "VCreate",
16886      /* 121 */ "Found",
16887      /* 122 */ "IfPos",
16888      /* 123 */ "NullRow",
16889      /* 124 */ "NotUsed_124",
16890      /* 125 */ "Real",
16891      /* 126 */ "NotUsed_126",
16892      /* 127 */ "NotUsed_127",
16893      /* 128 */ "NotUsed_128",
16894      /* 129 */ "NotUsed_129",
16895      /* 130 */ "NotUsed_130",
16896      /* 131 */ "NotUsed_131",
16897      /* 132 */ "NotUsed_132",
16898      /* 133 */ "NotUsed_133",
16899      /* 134 */ "NotUsed_134",
16900      /* 135 */ "NotUsed_135",
16901      /* 136 */ "NotUsed_136",
16902      /* 137 */ "NotUsed_137",
16903      /* 138 */ "ToText",
16904      /* 139 */ "ToBlob",
16905      /* 140 */ "ToNumeric",
16906      /* 141 */ "ToInt",
16907      /* 142 */ "ToReal",
16908   };
16909   return azName[i];
16910 }
16911 #endif
16912
16913 /************** End of opcodes.c *********************************************/
16914 /************** Begin file os_os2.c ******************************************/
16915 /*
16916 ** 2006 Feb 14
16917 **
16918 ** The author disclaims copyright to this source code.  In place of
16919 ** a legal notice, here is a blessing:
16920 **
16921 **    May you do good and not evil.
16922 **    May you find forgiveness for yourself and forgive others.
16923 **    May you share freely, never taking more than you give.
16924 **
16925 ******************************************************************************
16926 **
16927 ** This file contains code that is specific to OS/2.
16928 */
16929
16930
16931 #if OS_OS2
16932
16933 /*
16934 ** A Note About Memory Allocation:
16935 **
16936 ** This driver uses malloc()/free() directly rather than going through
16937 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
16938 ** are designed for use on embedded systems where memory is scarce and
16939 ** malloc failures happen frequently.  OS/2 does not typically run on
16940 ** embedded systems, and when it does the developers normally have bigger
16941 ** problems to worry about than running out of memory.  So there is not
16942 ** a compelling need to use the wrappers.
16943 **
16944 ** But there is a good reason to not use the wrappers.  If we use the
16945 ** wrappers then we will get simulated malloc() failures within this
16946 ** driver.  And that causes all kinds of problems for our tests.  We
16947 ** could enhance SQLite to deal with simulated malloc failures within
16948 ** the OS driver, but the code to deal with those failure would not
16949 ** be exercised on Linux (which does not need to malloc() in the driver)
16950 ** and so we would have difficulty writing coverage tests for that
16951 ** code.  Better to leave the code out, we think.
16952 **
16953 ** The point of this discussion is as follows:  When creating a new
16954 ** OS layer for an embedded system, if you use this file as an example,
16955 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
16956 ** desktops but not so well in embedded systems.
16957 */
16958
16959 /*
16960 ** Macros used to determine whether or not to use threads.
16961 */
16962 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
16963 # define SQLITE_OS2_THREADS 1
16964 #endif
16965
16966 /*
16967 ** Include code that is common to all os_*.c files
16968 */
16969 /************** Include os_common.h in the middle of os_os2.c ****************/
16970 /************** Begin file os_common.h ***************************************/
16971 /*
16972 ** 2004 May 22
16973 **
16974 ** The author disclaims copyright to this source code.  In place of
16975 ** a legal notice, here is a blessing:
16976 **
16977 **    May you do good and not evil.
16978 **    May you find forgiveness for yourself and forgive others.
16979 **    May you share freely, never taking more than you give.
16980 **
16981 ******************************************************************************
16982 **
16983 ** This file contains macros and a little bit of code that is common to
16984 ** all of the platform-specific files (os_*.c) and is #included into those
16985 ** files.
16986 **
16987 ** This file should be #included by the os_*.c files only.  It is not a
16988 ** general purpose header file.
16989 */
16990
16991 /*
16992 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
16993 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
16994 ** switch.  The following code should catch this problem at compile-time.
16995 */
16996 #ifdef MEMORY_DEBUG
16997 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
16998 #endif
16999
17000
17001 /*
17002  * When testing, this global variable stores the location of the
17003  * pending-byte in the database file.
17004  */
17005 #ifdef SQLITE_TEST
17006 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
17007 #endif
17008
17009 #ifdef SQLITE_DEBUG
17010 SQLITE_PRIVATE int sqlite3OSTrace = 0;
17011 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
17012 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
17013 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
17014 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
17015 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
17016 #define OSTRACE6(X,Y,Z,A,B,C) \
17017     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
17018 #define OSTRACE7(X,Y,Z,A,B,C,D) \
17019     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
17020 #else
17021 #define OSTRACE1(X)
17022 #define OSTRACE2(X,Y)
17023 #define OSTRACE3(X,Y,Z)
17024 #define OSTRACE4(X,Y,Z,A)
17025 #define OSTRACE5(X,Y,Z,A,B)
17026 #define OSTRACE6(X,Y,Z,A,B,C)
17027 #define OSTRACE7(X,Y,Z,A,B,C,D)
17028 #endif
17029
17030 /*
17031 ** Macros for performance tracing.  Normally turned off.  Only works
17032 ** on i486 hardware.
17033 */
17034 #ifdef SQLITE_PERFORMANCE_TRACE
17035 __inline__ unsigned long long int hwtime(void){
17036   unsigned long long int x;
17037   __asm__("rdtsc\n\t"
17038           "mov %%edx, %%ecx\n\t"
17039           :"=A" (x));
17040   return x;
17041 }
17042 static unsigned long long int g_start;
17043 static unsigned int elapse;
17044 #define TIMER_START       g_start=hwtime()
17045 #define TIMER_END         elapse=hwtime()-g_start
17046 #define TIMER_ELAPSED     elapse
17047 #else
17048 #define TIMER_START
17049 #define TIMER_END
17050 #define TIMER_ELAPSED     0
17051 #endif
17052
17053 /*
17054 ** If we compile with the SQLITE_TEST macro set, then the following block
17055 ** of code will give us the ability to simulate a disk I/O error.  This
17056 ** is used for testing the I/O recovery logic.
17057 */
17058 #ifdef SQLITE_TEST
17059 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
17060 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
17061 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
17062 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
17063 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
17064 SQLITE_API int sqlite3_diskfull_pending = 0;
17065 SQLITE_API int sqlite3_diskfull = 0;
17066 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
17067 #define SimulateIOError(CODE)  \
17068   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
17069        || sqlite3_io_error_pending-- == 1 )  \
17070               { local_ioerr(); CODE; }
17071 static void local_ioerr(){
17072   IOTRACE(("IOERR\n"));
17073   sqlite3_io_error_hit++;
17074   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
17075 }
17076 #define SimulateDiskfullError(CODE) \
17077    if( sqlite3_diskfull_pending ){ \
17078      if( sqlite3_diskfull_pending == 1 ){ \
17079        local_ioerr(); \
17080        sqlite3_diskfull = 1; \
17081        sqlite3_io_error_hit = 1; \
17082        CODE; \
17083      }else{ \
17084        sqlite3_diskfull_pending--; \
17085      } \
17086    }
17087 #else
17088 #define SimulateIOErrorBenign(X)
17089 #define SimulateIOError(A)
17090 #define SimulateDiskfullError(A)
17091 #endif
17092
17093 /*
17094 ** When testing, keep a count of the number of open files.
17095 */
17096 #ifdef SQLITE_TEST
17097 SQLITE_API int sqlite3_open_file_count = 0;
17098 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
17099 #else
17100 #define OpenCounter(X)
17101 #endif
17102
17103 /************** End of os_common.h *******************************************/
17104 /************** Continuing where we left off in os_os2.c *********************/
17105
17106 /*
17107 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
17108 ** protability layer.
17109 */
17110 typedef struct os2File os2File;
17111 struct os2File {
17112   const sqlite3_io_methods *pMethod;  /* Always the first entry */
17113   HFILE h;                  /* Handle for accessing the file */
17114   int delOnClose;           /* True if file is to be deleted on close */
17115   char* pathToDel;          /* Name of file to delete on close */
17116   unsigned char locktype;   /* Type of lock currently held on this file */
17117 };
17118
17119 /*****************************************************************************
17120 ** The next group of routines implement the I/O methods specified
17121 ** by the sqlite3_io_methods object.
17122 ******************************************************************************/
17123
17124 /*
17125 ** Close a file.
17126 */
17127 int os2Close( sqlite3_file *id ){
17128   APIRET rc = NO_ERROR;
17129   os2File *pFile;
17130   if( id && (pFile = (os2File*)id) != 0 ){
17131     OSTRACE2( "CLOSE %d\n", pFile->h );
17132     rc = DosClose( pFile->h );
17133     pFile->locktype = NO_LOCK;
17134     if( pFile->delOnClose != 0 ){
17135       rc = DosForceDelete( (PSZ)pFile->pathToDel );
17136     }
17137     if( pFile->pathToDel ){
17138       free( pFile->pathToDel );
17139     }
17140     id = 0;
17141     OpenCounter( -1 );
17142   }
17143
17144   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
17145 }
17146
17147 /*
17148 ** Read data from a file into a buffer.  Return SQLITE_OK if all
17149 ** bytes were read successfully and SQLITE_IOERR if anything goes
17150 ** wrong.
17151 */
17152 int os2Read(
17153   sqlite3_file *id,               /* File to read from */
17154   void *pBuf,                     /* Write content into this buffer */
17155   int amt,                        /* Number of bytes to read */
17156   sqlite3_int64 offset            /* Begin reading at this offset */
17157 ){
17158   ULONG fileLocation = 0L;
17159   ULONG got;
17160   os2File *pFile = (os2File*)id;
17161   assert( id!=0 );
17162   SimulateIOError( return SQLITE_IOERR_READ );
17163   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
17164   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
17165     return SQLITE_IOERR;
17166   }
17167   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
17168     return SQLITE_IOERR_READ;
17169   }
17170   if( got == (ULONG)amt )
17171     return SQLITE_OK;
17172   else {
17173     memset(&((char*)pBuf)[got], 0, amt-got);
17174     return SQLITE_IOERR_SHORT_READ;
17175   }
17176 }
17177
17178 /*
17179 ** Write data from a buffer into a file.  Return SQLITE_OK on success
17180 ** or some other error code on failure.
17181 */
17182 int os2Write(
17183   sqlite3_file *id,               /* File to write into */
17184   const void *pBuf,               /* The bytes to be written */
17185   int amt,                        /* Number of bytes to write */
17186   sqlite3_int64 offset            /* Offset into the file to begin writing at */
17187 ){
17188   ULONG fileLocation = 0L;
17189   APIRET rc = NO_ERROR;
17190   ULONG wrote;
17191   os2File *pFile = (os2File*)id;
17192   assert( id!=0 );
17193   SimulateIOError( return SQLITE_IOERR_WRITE );
17194   SimulateDiskfullError( return SQLITE_FULL );
17195   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
17196   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
17197     return SQLITE_IOERR;
17198   }
17199   assert( amt>0 );
17200   while( amt > 0 &&
17201          (rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote )) &&
17202          wrote > 0
17203   ){
17204     amt -= wrote;
17205     pBuf = &((char*)pBuf)[wrote];
17206   }
17207
17208   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
17209 }
17210
17211 /*
17212 ** Truncate an open file to a specified size
17213 */
17214 int os2Truncate( sqlite3_file *id, i64 nByte ){
17215   APIRET rc = NO_ERROR;
17216   os2File *pFile = (os2File*)id;
17217   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
17218   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
17219   rc = DosSetFileSize( pFile->h, nByte );
17220   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
17221 }
17222
17223 #ifdef SQLITE_TEST
17224 /*
17225 ** Count the number of fullsyncs and normal syncs.  This is used to test
17226 ** that syncs and fullsyncs are occuring at the right times.
17227 */
17228 SQLITE_API int sqlite3_sync_count = 0;
17229 SQLITE_API int sqlite3_fullsync_count = 0;
17230 #endif
17231
17232 /*
17233 ** Make sure all writes to a particular file are committed to disk.
17234 */
17235 int os2Sync( sqlite3_file *id, int flags ){
17236   os2File *pFile = (os2File*)id;
17237   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
17238 #ifdef SQLITE_TEST
17239   if( flags & SQLITE_SYNC_FULL){
17240     sqlite3_fullsync_count++;
17241   }
17242   sqlite3_sync_count++;
17243 #endif
17244   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
17245 }
17246
17247 /*
17248 ** Determine the current size of a file in bytes
17249 */
17250 int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
17251   APIRET rc = NO_ERROR;
17252   FILESTATUS3 fsts3FileInfo;
17253   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
17254   assert( id!=0 );
17255   SimulateIOError( return SQLITE_IOERR );
17256   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
17257   if( rc == NO_ERROR ){
17258     *pSize = fsts3FileInfo.cbFile;
17259     return SQLITE_OK;
17260   }else{
17261     return SQLITE_IOERR;
17262   }
17263 }
17264
17265 /*
17266 ** Acquire a reader lock.
17267 */
17268 static int getReadLock( os2File *pFile ){
17269   FILELOCK  LockArea,
17270             UnlockArea;
17271   APIRET res;
17272   memset(&LockArea, 0, sizeof(LockArea));
17273   memset(&UnlockArea, 0, sizeof(UnlockArea));
17274   LockArea.lOffset = SHARED_FIRST;
17275   LockArea.lRange = SHARED_SIZE;
17276   UnlockArea.lOffset = 0L;
17277   UnlockArea.lRange = 0L;
17278   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17279   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
17280   return res;
17281 }
17282
17283 /*
17284 ** Undo a readlock
17285 */
17286 static int unlockReadLock( os2File *id ){
17287   FILELOCK  LockArea,
17288             UnlockArea;
17289   APIRET res;
17290   memset(&LockArea, 0, sizeof(LockArea));
17291   memset(&UnlockArea, 0, sizeof(UnlockArea));
17292   LockArea.lOffset = 0L;
17293   LockArea.lRange = 0L;
17294   UnlockArea.lOffset = SHARED_FIRST;
17295   UnlockArea.lRange = SHARED_SIZE;
17296   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, 2000L, 1L );
17297   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
17298   return res;
17299 }
17300
17301 /*
17302 ** Lock the file with the lock specified by parameter locktype - one
17303 ** of the following:
17304 **
17305 **     (1) SHARED_LOCK
17306 **     (2) RESERVED_LOCK
17307 **     (3) PENDING_LOCK
17308 **     (4) EXCLUSIVE_LOCK
17309 **
17310 ** Sometimes when requesting one lock state, additional lock states
17311 ** are inserted in between.  The locking might fail on one of the later
17312 ** transitions leaving the lock state different from what it started but
17313 ** still short of its goal.  The following chart shows the allowed
17314 ** transitions and the inserted intermediate states:
17315 **
17316 **    UNLOCKED -> SHARED
17317 **    SHARED -> RESERVED
17318 **    SHARED -> (PENDING) -> EXCLUSIVE
17319 **    RESERVED -> (PENDING) -> EXCLUSIVE
17320 **    PENDING -> EXCLUSIVE
17321 **
17322 ** This routine will only increase a lock.  The os2Unlock() routine
17323 ** erases all locks at once and returns us immediately to locking level 0.
17324 ** It is not possible to lower the locking level one step at a time.  You
17325 ** must go straight to locking level 0.
17326 */
17327 int os2Lock( sqlite3_file *id, int locktype ){
17328   int rc = SQLITE_OK;       /* Return code from subroutines */
17329   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
17330   int newLocktype;       /* Set pFile->locktype to this value before exiting */
17331   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
17332   FILELOCK  LockArea,
17333             UnlockArea;
17334   os2File *pFile = (os2File*)id;
17335   memset(&LockArea, 0, sizeof(LockArea));
17336   memset(&UnlockArea, 0, sizeof(UnlockArea));
17337   assert( pFile!=0 );
17338   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
17339
17340   /* If there is already a lock of this type or more restrictive on the
17341   ** os2File, do nothing. Don't use the end_lock: exit path, as
17342   ** sqlite3OsEnterMutex() hasn't been called yet.
17343   */
17344   if( pFile->locktype>=locktype ){
17345     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
17346     return SQLITE_OK;
17347   }
17348
17349   /* Make sure the locking sequence is correct
17350   */
17351   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
17352   assert( locktype!=PENDING_LOCK );
17353   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
17354
17355   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
17356   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
17357   ** the PENDING_LOCK byte is temporary.
17358   */
17359   newLocktype = pFile->locktype;
17360   if( pFile->locktype==NO_LOCK
17361       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
17362   ){
17363     int cnt = 3;
17364
17365     LockArea.lOffset = PENDING_BYTE;
17366     LockArea.lRange = 1L;
17367     UnlockArea.lOffset = 0L;
17368     UnlockArea.lRange = 0L;
17369
17370     while( cnt-->0 && ( res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L) )
17371                       != NO_ERROR
17372     ){
17373       /* Try 3 times to get the pending lock.  The pending lock might be
17374       ** held by another reader process who will release it momentarily.
17375       */
17376       OSTRACE2( "LOCK could not get a PENDING lock. cnt=%d\n", cnt );
17377       DosSleep(1);
17378     }
17379     if( res == NO_ERROR){
17380       gotPendingLock = 1;
17381       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
17382     }
17383   }
17384
17385   /* Acquire a shared lock
17386   */
17387   if( locktype==SHARED_LOCK && res == NO_ERROR ){
17388     assert( pFile->locktype==NO_LOCK );
17389     res = getReadLock(pFile);
17390     if( res == NO_ERROR ){
17391       newLocktype = SHARED_LOCK;
17392     }
17393     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
17394   }
17395
17396   /* Acquire a RESERVED lock
17397   */
17398   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
17399     assert( pFile->locktype==SHARED_LOCK );
17400     LockArea.lOffset = RESERVED_BYTE;
17401     LockArea.lRange = 1L;
17402     UnlockArea.lOffset = 0L;
17403     UnlockArea.lRange = 0L;
17404     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17405     if( res == NO_ERROR ){
17406       newLocktype = RESERVED_LOCK;
17407     }
17408     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
17409   }
17410
17411   /* Acquire a PENDING lock
17412   */
17413   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
17414     newLocktype = PENDING_LOCK;
17415     gotPendingLock = 0;
17416     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
17417   }
17418
17419   /* Acquire an EXCLUSIVE lock
17420   */
17421   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
17422     assert( pFile->locktype>=SHARED_LOCK );
17423     res = unlockReadLock(pFile);
17424     OSTRACE2( "unreadlock = %d\n", res );
17425     LockArea.lOffset = SHARED_FIRST;
17426     LockArea.lRange = SHARED_SIZE;
17427     UnlockArea.lOffset = 0L;
17428     UnlockArea.lRange = 0L;
17429     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17430     if( res == NO_ERROR ){
17431       newLocktype = EXCLUSIVE_LOCK;
17432     }else{
17433       OSTRACE2( "OS/2 error-code = %d\n", res );
17434       getReadLock(pFile);
17435     }
17436     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
17437   }
17438
17439   /* If we are holding a PENDING lock that ought to be released, then
17440   ** release it now.
17441   */
17442   if( gotPendingLock && locktype==SHARED_LOCK ){
17443     int r;
17444     LockArea.lOffset = 0L;
17445     LockArea.lRange = 0L;
17446     UnlockArea.lOffset = PENDING_BYTE;
17447     UnlockArea.lRange = 1L;
17448     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17449     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
17450   }
17451
17452   /* Update the state of the lock has held in the file descriptor then
17453   ** return the appropriate result code.
17454   */
17455   if( res == NO_ERROR ){
17456     rc = SQLITE_OK;
17457   }else{
17458     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
17459               locktype, newLocktype );
17460     rc = SQLITE_BUSY;
17461   }
17462   pFile->locktype = newLocktype;
17463   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
17464   return rc;
17465 }
17466
17467 /*
17468 ** This routine checks if there is a RESERVED lock held on the specified
17469 ** file by this or any other process. If such a lock is held, return
17470 ** non-zero, otherwise zero.
17471 */
17472 int os2CheckReservedLock( sqlite3_file *id ){
17473   int r = 0;
17474   os2File *pFile = (os2File*)id;
17475   assert( pFile!=0 );
17476   if( pFile->locktype>=RESERVED_LOCK ){
17477     r = 1;
17478     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
17479   }else{
17480     FILELOCK  LockArea,
17481               UnlockArea;
17482     APIRET rc = NO_ERROR;
17483     memset(&LockArea, 0, sizeof(LockArea));
17484     memset(&UnlockArea, 0, sizeof(UnlockArea));
17485     LockArea.lOffset = RESERVED_BYTE;
17486     LockArea.lRange = 1L;
17487     UnlockArea.lOffset = 0L;
17488     UnlockArea.lRange = 0L;
17489     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17490     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
17491     if( rc == NO_ERROR ){
17492       APIRET rcu = NO_ERROR; /* return code for unlocking */
17493       LockArea.lOffset = 0L;
17494       LockArea.lRange = 0L;
17495       UnlockArea.lOffset = RESERVED_BYTE;
17496       UnlockArea.lRange = 1L;
17497       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17498       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
17499     }
17500     r = !(rc == NO_ERROR);
17501     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
17502   }
17503   return r;
17504 }
17505
17506 /*
17507 ** Lower the locking level on file descriptor id to locktype.  locktype
17508 ** must be either NO_LOCK or SHARED_LOCK.
17509 **
17510 ** If the locking level of the file descriptor is already at or below
17511 ** the requested locking level, this routine is a no-op.
17512 **
17513 ** It is not possible for this routine to fail if the second argument
17514 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
17515 ** might return SQLITE_IOERR;
17516 */
17517 int os2Unlock( sqlite3_file *id, int locktype ){
17518   int type;
17519   os2File *pFile = (os2File*)id;
17520   APIRET rc = SQLITE_OK;
17521   APIRET res = NO_ERROR;
17522   FILELOCK  LockArea,
17523             UnlockArea;
17524   memset(&LockArea, 0, sizeof(LockArea));
17525   memset(&UnlockArea, 0, sizeof(UnlockArea));
17526   assert( pFile!=0 );
17527   assert( locktype<=SHARED_LOCK );
17528   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
17529   type = pFile->locktype;
17530   if( type>=EXCLUSIVE_LOCK ){
17531     LockArea.lOffset = 0L;
17532     LockArea.lRange = 0L;
17533     UnlockArea.lOffset = SHARED_FIRST;
17534     UnlockArea.lRange = SHARED_SIZE;
17535     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17536     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
17537     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
17538       /* This should never happen.  We should always be able to
17539       ** reacquire the read lock */
17540       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
17541       rc = SQLITE_IOERR_UNLOCK;
17542     }
17543   }
17544   if( type>=RESERVED_LOCK ){
17545     LockArea.lOffset = 0L;
17546     LockArea.lRange = 0L;
17547     UnlockArea.lOffset = RESERVED_BYTE;
17548     UnlockArea.lRange = 1L;
17549     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17550     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
17551   }
17552   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
17553     res = unlockReadLock(pFile);
17554     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
17555   }
17556   if( type>=PENDING_LOCK ){
17557     LockArea.lOffset = 0L;
17558     LockArea.lRange = 0L;
17559     UnlockArea.lOffset = PENDING_BYTE;
17560     UnlockArea.lRange = 1L;
17561     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
17562     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
17563   }
17564   pFile->locktype = locktype;
17565   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
17566   return rc;
17567 }
17568
17569 /*
17570 ** Control and query of the open file handle.
17571 */
17572 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
17573   switch( op ){
17574     case SQLITE_FCNTL_LOCKSTATE: {
17575       *(int*)pArg = ((os2File*)id)->locktype;
17576       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
17577       return SQLITE_OK;
17578     }
17579   }
17580   return SQLITE_ERROR;
17581 }
17582
17583 /*
17584 ** Return the sector size in bytes of the underlying block device for
17585 ** the specified file. This is almost always 512 bytes, but may be
17586 ** larger for some devices.
17587 **
17588 ** SQLite code assumes this function cannot fail. It also assumes that
17589 ** if two files are created in the same file-system directory (i.e.
17590 ** a database and its journal file) that the sector size will be the
17591 ** same for both.
17592 */
17593 static int os2SectorSize(sqlite3_file *id){
17594   return SQLITE_DEFAULT_SECTOR_SIZE;
17595 }
17596
17597 /*
17598 ** Return a vector of device characteristics.
17599 */
17600 static int os2DeviceCharacteristics(sqlite3_file *id){
17601   return 0;
17602 }
17603
17604 /*
17605 ** This vector defines all the methods that can operate on an
17606 ** sqlite3_file for os2.
17607 */
17608 static const sqlite3_io_methods os2IoMethod = {
17609   1,                        /* iVersion */
17610   os2Close,
17611   os2Read,
17612   os2Write,
17613   os2Truncate,
17614   os2Sync,
17615   os2FileSize,
17616   os2Lock,
17617   os2Unlock,
17618   os2CheckReservedLock,
17619   os2FileControl,
17620   os2SectorSize,
17621   os2DeviceCharacteristics
17622 };
17623
17624 /***************************************************************************
17625 ** Here ends the I/O methods that form the sqlite3_io_methods object.
17626 **
17627 ** The next block of code implements the VFS methods.
17628 ****************************************************************************/
17629
17630 /*
17631 ** Open a file.
17632 */
17633 static int os2Open(
17634   sqlite3_vfs *pVfs,            /* Not used */
17635   const char *zName,            /* Name of the file */
17636   sqlite3_file *id,             /* Write the SQLite file handle here */
17637   int flags,                    /* Open mode flags */
17638   int *pOutFlags                /* Status return flags */
17639 ){
17640   HFILE h;
17641   ULONG ulFileAttribute = 0;
17642   ULONG ulOpenFlags = 0;
17643   ULONG ulOpenMode = 0;
17644   os2File *pFile = (os2File*)id;
17645   APIRET rc = NO_ERROR;
17646   ULONG ulAction;
17647
17648   memset(pFile, 0, sizeof(*pFile));
17649
17650   OSTRACE2( "OPEN want %d\n", flags );
17651
17652   //ulOpenMode = flags & SQLITE_OPEN_READWRITE ? OPEN_ACCESS_READWRITE : OPEN_ACCESS_READONLY;
17653   if( flags & SQLITE_OPEN_READWRITE ){
17654     ulOpenMode |= OPEN_ACCESS_READWRITE;
17655     OSTRACE1( "OPEN read/write\n" );
17656   }else{
17657     ulOpenMode |= OPEN_ACCESS_READONLY;
17658     OSTRACE1( "OPEN read only\n" );
17659   }
17660
17661   //ulOpenFlags = flags & SQLITE_OPEN_CREATE ? OPEN_ACTION_CREATE_IF_NEW : OPEN_ACTION_FAIL_IF_NEW;
17662   if( flags & SQLITE_OPEN_CREATE ){
17663     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
17664     OSTRACE1( "OPEN open new/create\n" );
17665   }else{
17666     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
17667     OSTRACE1( "OPEN open existing\n" );
17668   }
17669
17670   //ulOpenMode |= flags & SQLITE_OPEN_MAIN_DB ? OPEN_SHARE_DENYNONE : OPEN_SHARE_DENYWRITE;
17671   if( flags & SQLITE_OPEN_MAIN_DB ){
17672     ulOpenMode |= OPEN_SHARE_DENYNONE;
17673     OSTRACE1( "OPEN share read/write\n" );
17674   }else{
17675     ulOpenMode |= OPEN_SHARE_DENYWRITE;
17676     OSTRACE1( "OPEN share read only\n" );
17677   }
17678
17679   if( flags & (SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_TEMP_JOURNAL
17680                | SQLITE_OPEN_SUBJOURNAL) ){
17681     //ulFileAttribute = FILE_HIDDEN;  //for debugging, we want to make sure it is deleted
17682     ulFileAttribute = FILE_NORMAL;
17683     pFile->delOnClose = 1;
17684     pFile->pathToDel = (char*)malloc(sizeof(char) * pVfs->mxPathname);
17685     sqlite3OsFullPathname(pVfs, zName, pVfs->mxPathname, pFile->pathToDel);
17686     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
17687   }else{
17688     ulFileAttribute = FILE_ARCHIVED | FILE_NORMAL;
17689     pFile->delOnClose = 0;
17690     pFile->pathToDel = NULL;
17691     OSTRACE1( "OPEN normal file attribute\n" );
17692   }
17693
17694   /* always open in random access mode for possibly better speed */
17695   ulOpenMode |= OPEN_FLAGS_RANDOM;
17696   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
17697
17698   rc = DosOpen( (PSZ)zName,
17699                 &h,
17700                 &ulAction,
17701                 0L,
17702                 ulFileAttribute,
17703                 ulOpenFlags,
17704                 ulOpenMode,
17705                 (PEAOP2)NULL );
17706   if( rc != NO_ERROR ){
17707     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
17708               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
17709     if( flags & SQLITE_OPEN_READWRITE ){
17710       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
17711       return os2Open( 0, zName, id,
17712                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
17713                       pOutFlags );
17714     }else{
17715       return SQLITE_CANTOPEN;
17716     }
17717   }
17718
17719   if( pOutFlags ){
17720     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
17721   }
17722
17723   pFile->pMethod = &os2IoMethod;
17724   pFile->h = h;
17725   OpenCounter(+1);
17726   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
17727   return SQLITE_OK;
17728 }
17729
17730 /*
17731 ** Delete the named file.
17732 */
17733 int os2Delete(
17734   sqlite3_vfs *pVfs,                     /* Not used on os2 */
17735   const char *zFilename,                 /* Name of file to delete */
17736   int syncDir                            /* Not used on os2 */
17737 ){
17738   APIRET rc = NO_ERROR;
17739   SimulateIOError(return SQLITE_IOERR_DELETE);
17740   rc = DosDelete( (PSZ)zFilename );
17741   OSTRACE2( "DELETE \"%s\"\n", zFilename );
17742   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
17743 }
17744
17745 /*
17746 ** Check the existance and status of a file.
17747 */
17748 static int os2Access(
17749   sqlite3_vfs *pVfs,        /* Not used on os2 */
17750   const char *zFilename,    /* Name of file to check */
17751   int flags                 /* Type of test to make on this file */
17752 ){
17753   FILESTATUS3 fsts3ConfigInfo;
17754   APIRET rc = NO_ERROR;
17755
17756   memset(&fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo));
17757   rc = DosQueryPathInfo( (PSZ)zFilename, FIL_STANDARD,
17758                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
17759   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
17760             fsts3ConfigInfo.attrFile, flags, rc );
17761   switch( flags ){
17762     case SQLITE_ACCESS_READ:
17763     case SQLITE_ACCESS_EXISTS:
17764       rc = (rc == NO_ERROR);
17765       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
17766       break;
17767     case SQLITE_ACCESS_READWRITE:
17768       rc = (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0;
17769       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
17770       break;
17771     default:
17772       assert( !"Invalid flags argument" );
17773   }
17774   return rc;
17775 }
17776
17777
17778 /*
17779 ** Create a temporary file name in zBuf.  zBuf must be big enough to
17780 ** hold at pVfs->mxPathname characters.
17781 */
17782 static int os2GetTempname( sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
17783   static const unsigned char zChars[] =
17784     "abcdefghijklmnopqrstuvwxyz"
17785     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
17786     "0123456789";
17787   int i, j;
17788   char zTempPathBuf[3];
17789   PSZ zTempPath = (PSZ)&zTempPathBuf;
17790   if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
17791     if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
17792       if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
17793            ULONG ulDriveNum = 0, ulDriveMap = 0;
17794            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
17795            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
17796       }
17797     }
17798   }
17799   /* strip off a trailing slashes or backslashes, otherwise we would get *
17800    * multiple (back)slashes which causes DosOpen() to fail               */
17801   j = strlen(zTempPath);
17802   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ) ){
17803     j--;
17804   }
17805   zTempPath[j] = '\0';
17806   sqlite3_snprintf( nBuf-30, zBuf,
17807                     "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
17808   j = strlen( zBuf );
17809   sqlite3Randomness( 20, &zBuf[j] );
17810   for( i = 0; i < 20; i++, j++ ){
17811     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
17812   }
17813   zBuf[j] = 0;
17814   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
17815   return SQLITE_OK;
17816 }
17817
17818
17819 /*
17820 ** Turn a relative pathname into a full pathname.  Write the full
17821 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
17822 ** bytes in size.
17823 */
17824 static int os2FullPathname(
17825   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
17826   const char *zRelative,      /* Possibly relative input path */
17827   int nFull,                  /* Size of output buffer in bytes */
17828   char *zFull                 /* Output buffer */
17829 ){
17830   APIRET rc = DosQueryPathInfo( zRelative, FIL_QUERYFULLNAME, zFull, nFull );
17831   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
17832 }
17833
17834 #ifndef SQLITE_OMIT_LOAD_EXTENSION
17835 /*
17836 ** Interfaces for opening a shared library, finding entry points
17837 ** within the shared library, and closing the shared library.
17838 */
17839 /*
17840 ** Interfaces for opening a shared library, finding entry points
17841 ** within the shared library, and closing the shared library.
17842 */
17843 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
17844   UCHAR loadErr[256];
17845   HMODULE hmod;
17846   APIRET rc;
17847   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilename, &hmod);
17848   return rc != NO_ERROR ? 0 : (void*)hmod;
17849 }
17850 /*
17851 ** A no-op since the error code is returned on the DosLoadModule call.
17852 ** os2Dlopen returns zero if DosLoadModule is not successful.
17853 */
17854 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
17855 /* no-op */
17856 }
17857 void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
17858   PFN pfn;
17859   APIRET rc;
17860   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
17861   if( rc != NO_ERROR ){
17862     /* if the symbol itself was not found, search again for the same
17863      * symbol with an extra underscore, that might be needed depending
17864      * on the calling convention */
17865     char _zSymbol[256] = "_";
17866     strncat(_zSymbol, zSymbol, 255);
17867     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
17868   }
17869   return rc != NO_ERROR ? 0 : (void*)pfn;
17870 }
17871 void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
17872   DosFreeModule((HMODULE)pHandle);
17873 }
17874 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
17875   #define os2DlOpen 0
17876   #define os2DlError 0
17877   #define os2DlSym 0
17878   #define os2DlClose 0
17879 #endif
17880
17881
17882 /*
17883 ** Write up to nBuf bytes of randomness into zBuf.
17884 */
17885 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
17886   ULONG sizeofULong = sizeof(ULONG);
17887   int n = 0;
17888   if( sizeof(DATETIME) <= nBuf - n ){
17889     DATETIME x;
17890     DosGetDateTime(&x);
17891     memcpy(&zBuf[n], &x, sizeof(x));
17892     n += sizeof(x);
17893   }
17894
17895   if( sizeofULong <= nBuf - n ){
17896     PPIB ppib;
17897     DosGetInfoBlocks(NULL, &ppib);
17898     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
17899     n += sizeofULong;
17900   }
17901
17902   if( sizeofULong <= nBuf - n ){
17903     PTIB ptib;
17904     DosGetInfoBlocks(&ptib, NULL);
17905     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
17906     n += sizeofULong;
17907   }
17908
17909   /* if we still haven't filled the buffer yet the following will */
17910   /* grab everything once instead of making several calls for a single item */
17911   if( sizeofULong <= nBuf - n ){
17912     ULONG ulSysInfo[QSV_MAX];
17913     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
17914
17915     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
17916     n += sizeofULong;
17917
17918     if( sizeofULong <= nBuf - n ){
17919       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
17920       n += sizeofULong;
17921     }
17922     if( sizeofULong <= nBuf - n ){
17923       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
17924       n += sizeofULong;
17925     }
17926     if( sizeofULong <= nBuf - n ){
17927       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
17928       n += sizeofULong;
17929     }
17930     if( sizeofULong <= nBuf - n ){
17931       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
17932       n += sizeofULong;
17933     }
17934   }
17935
17936   return n;
17937 }
17938
17939 /*
17940 ** Sleep for a little while.  Return the amount of time slept.
17941 ** The argument is the number of microseconds we want to sleep.
17942 ** The return value is the number of microseconds of sleep actually
17943 ** requested from the underlying operating system, a number which
17944 ** might be greater than or equal to the argument, but not less
17945 ** than the argument.
17946 */
17947 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
17948   DosSleep( (microsec/1000) );
17949   return microsec;
17950 }
17951
17952 /*
17953 ** The following variable, if set to a non-zero value, becomes the result
17954 ** returned from sqlite3OsCurrentTime().  This is used for testing.
17955 */
17956 #ifdef SQLITE_TEST
17957 SQLITE_API int sqlite3_current_time = 0;
17958 #endif
17959
17960 /*
17961 ** Find the current time (in Universal Coordinated Time).  Write the
17962 ** current time and date as a Julian Day number into *prNow and
17963 ** return 0.  Return 1 if the time and date cannot be found.
17964 */
17965 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
17966   double now;
17967   SHORT minute; /* needs to be able to cope with negative timezone offset */
17968   USHORT second, hour,
17969          day, month, year;
17970   DATETIME dt;
17971   DosGetDateTime( &dt );
17972   second = (USHORT)dt.seconds;
17973   minute = (SHORT)dt.minutes + dt.timezone;
17974   hour = (USHORT)dt.hours;
17975   day = (USHORT)dt.day;
17976   month = (USHORT)dt.month;
17977   year = (USHORT)dt.year;
17978
17979   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
17980      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
17981   /* Calculate the Julian days */
17982   now = day - 32076 +
17983     1461*(year + 4800 + (month - 14)/12)/4 +
17984     367*(month - 2 - (month - 14)/12*12)/12 -
17985     3*((year + 4900 + (month - 14)/12)/100)/4;
17986
17987   /* Add the fractional hours, mins and seconds */
17988   now += (hour + 12.0)/24.0;
17989   now += minute/1440.0;
17990   now += second/86400.0;
17991   *prNow = now;
17992 #ifdef SQLITE_TEST
17993   if( sqlite3_current_time ){
17994     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
17995   }
17996 #endif
17997   return 0;
17998 }
17999
18000 /*
18001 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
18002 ** a function rather than give the structure global scope because
18003 ** some compilers (MSVC) do not allow forward declarations of
18004 ** initialized structures.
18005 */
18006 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
18007   static sqlite3_vfs os2Vfs = {
18008     1,                 /* iVersion */
18009     sizeof(os2File),   /* szOsFile */
18010     CCHMAXPATH,        /* mxPathname */
18011     0,                 /* pNext */
18012     "os2",             /* zName */
18013     0,                 /* pAppData */
18014
18015     os2Open,           /* xOpen */
18016     os2Delete,         /* xDelete */
18017     os2Access,         /* xAccess */
18018     os2GetTempname,    /* xGetTempname */
18019     os2FullPathname,   /* xFullPathname */
18020     os2DlOpen,         /* xDlOpen */
18021     os2DlError,        /* xDlError */
18022     os2DlSym,          /* xDlSym */
18023     os2DlClose,        /* xDlClose */
18024     os2Randomness,     /* xRandomness */
18025     os2Sleep,          /* xSleep */
18026     os2CurrentTime     /* xCurrentTime */
18027   };
18028
18029   return &os2Vfs;
18030 }
18031
18032 #endif /* OS_OS2 */
18033
18034 /************** End of os_os2.c **********************************************/
18035 /************** Begin file os_unix.c *****************************************/
18036 /*
18037 ** 2004 May 22
18038 **
18039 ** The author disclaims copyright to this source code.  In place of
18040 ** a legal notice, here is a blessing:
18041 **
18042 **    May you do good and not evil.
18043 **    May you find forgiveness for yourself and forgive others.
18044 **    May you share freely, never taking more than you give.
18045 **
18046 ******************************************************************************
18047 **
18048 ** This file contains code that is specific to Unix systems.
18049 */
18050 #if OS_UNIX              /* This file is used on unix only */
18051
18052 /* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
18053
18054 /*
18055 ** These #defines should enable >2GB file support on Posix if the
18056 ** underlying operating system supports it.  If the OS lacks
18057 ** large file support, these should be no-ops.
18058 **
18059 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
18060 ** on the compiler command line.  This is necessary if you are compiling
18061 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
18062 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
18063 ** without this option, LFS is enable.  But LFS does not exist in the kernel
18064 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
18065 ** portability you should omit LFS.
18066 */
18067 #ifndef SQLITE_DISABLE_LFS
18068 # define _LARGE_FILE       1
18069 # ifndef _FILE_OFFSET_BITS
18070 #   define _FILE_OFFSET_BITS 64
18071 # endif
18072 # define _LARGEFILE_SOURCE 1
18073 #endif
18074
18075 /*
18076 ** standard include files.
18077 */
18078 #include <sys/types.h>
18079 #include <sys/stat.h>
18080 #include <fcntl.h>
18081 #include <unistd.h>
18082 #include <sys/time.h>
18083 #include <errno.h>
18084 #ifdef SQLITE_ENABLE_LOCKING_STYLE
18085 #include <sys/ioctl.h>
18086 #include <sys/param.h>
18087 #include <sys/mount.h>
18088 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
18089
18090 /*
18091 ** If we are to be thread-safe, include the pthreads header and define
18092 ** the SQLITE_UNIX_THREADS macro.
18093 */
18094 #if SQLITE_THREADSAFE
18095 # define SQLITE_UNIX_THREADS 1
18096 #endif
18097
18098 /*
18099 ** Default permissions when creating a new file
18100 */
18101 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
18102 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
18103 #endif
18104
18105 /*
18106 ** Maximum supported path-length.
18107 */
18108 #define MAX_PATHNAME 512
18109
18110
18111 /*
18112 ** The unixFile structure is subclass of sqlite3_file specific for the unix
18113 ** protability layer.
18114 */
18115 typedef struct unixFile unixFile;
18116 struct unixFile {
18117   sqlite3_io_methods const *pMethod;  /* Always the first entry */
18118 #ifdef SQLITE_TEST
18119   /* In test mode, increase the size of this structure a bit so that 
18120   ** it is larger than the struct CrashFile defined in test6.c.
18121   */
18122   char aPadding[32];
18123 #endif
18124   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
18125   struct lockInfo *pLock;   /* Info about locks on this inode */
18126 #ifdef SQLITE_ENABLE_LOCKING_STYLE
18127   void *lockingContext;     /* Locking style specific state */
18128 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
18129   int h;                    /* The file descriptor */
18130   unsigned char locktype;   /* The type of lock held on this fd */
18131   int dirfd;                /* File descriptor for the directory */
18132 #if SQLITE_THREADSAFE
18133   pthread_t tid;            /* The thread that "owns" this unixFile */
18134 #endif
18135 };
18136
18137 /*
18138 ** Include code that is common to all os_*.c files
18139 */
18140 /************** Include os_common.h in the middle of os_unix.c ***************/
18141 /************** Begin file os_common.h ***************************************/
18142 /*
18143 ** 2004 May 22
18144 **
18145 ** The author disclaims copyright to this source code.  In place of
18146 ** a legal notice, here is a blessing:
18147 **
18148 **    May you do good and not evil.
18149 **    May you find forgiveness for yourself and forgive others.
18150 **    May you share freely, never taking more than you give.
18151 **
18152 ******************************************************************************
18153 **
18154 ** This file contains macros and a little bit of code that is common to
18155 ** all of the platform-specific files (os_*.c) and is #included into those
18156 ** files.
18157 **
18158 ** This file should be #included by the os_*.c files only.  It is not a
18159 ** general purpose header file.
18160 */
18161
18162 /*
18163 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
18164 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
18165 ** switch.  The following code should catch this problem at compile-time.
18166 */
18167 #ifdef MEMORY_DEBUG
18168 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
18169 #endif
18170
18171
18172 /*
18173  * When testing, this global variable stores the location of the
18174  * pending-byte in the database file.
18175  */
18176 #ifdef SQLITE_TEST
18177 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
18178 #endif
18179
18180 #ifdef SQLITE_DEBUG
18181 SQLITE_PRIVATE int sqlite3OSTrace = 0;
18182 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
18183 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
18184 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
18185 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
18186 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
18187 #define OSTRACE6(X,Y,Z,A,B,C) \
18188     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
18189 #define OSTRACE7(X,Y,Z,A,B,C,D) \
18190     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
18191 #else
18192 #define OSTRACE1(X)
18193 #define OSTRACE2(X,Y)
18194 #define OSTRACE3(X,Y,Z)
18195 #define OSTRACE4(X,Y,Z,A)
18196 #define OSTRACE5(X,Y,Z,A,B)
18197 #define OSTRACE6(X,Y,Z,A,B,C)
18198 #define OSTRACE7(X,Y,Z,A,B,C,D)
18199 #endif
18200
18201 /*
18202 ** Macros for performance tracing.  Normally turned off.  Only works
18203 ** on i486 hardware.
18204 */
18205 #ifdef SQLITE_PERFORMANCE_TRACE
18206 __inline__ unsigned long long int hwtime(void){
18207   unsigned long long int x;
18208   __asm__("rdtsc\n\t"
18209           "mov %%edx, %%ecx\n\t"
18210           :"=A" (x));
18211   return x;
18212 }
18213 static unsigned long long int g_start;
18214 static unsigned int elapse;
18215 #define TIMER_START       g_start=hwtime()
18216 #define TIMER_END         elapse=hwtime()-g_start
18217 #define TIMER_ELAPSED     elapse
18218 #else
18219 #define TIMER_START
18220 #define TIMER_END
18221 #define TIMER_ELAPSED     0
18222 #endif
18223
18224 /*
18225 ** If we compile with the SQLITE_TEST macro set, then the following block
18226 ** of code will give us the ability to simulate a disk I/O error.  This
18227 ** is used for testing the I/O recovery logic.
18228 */
18229 #ifdef SQLITE_TEST
18230 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
18231 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
18232 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
18233 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
18234 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
18235 SQLITE_API int sqlite3_diskfull_pending = 0;
18236 SQLITE_API int sqlite3_diskfull = 0;
18237 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
18238 #define SimulateIOError(CODE)  \
18239   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
18240        || sqlite3_io_error_pending-- == 1 )  \
18241               { local_ioerr(); CODE; }
18242 static void local_ioerr(){
18243   IOTRACE(("IOERR\n"));
18244   sqlite3_io_error_hit++;
18245   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
18246 }
18247 #define SimulateDiskfullError(CODE) \
18248    if( sqlite3_diskfull_pending ){ \
18249      if( sqlite3_diskfull_pending == 1 ){ \
18250        local_ioerr(); \
18251        sqlite3_diskfull = 1; \
18252        sqlite3_io_error_hit = 1; \
18253        CODE; \
18254      }else{ \
18255        sqlite3_diskfull_pending--; \
18256      } \
18257    }
18258 #else
18259 #define SimulateIOErrorBenign(X)
18260 #define SimulateIOError(A)
18261 #define SimulateDiskfullError(A)
18262 #endif
18263
18264 /*
18265 ** When testing, keep a count of the number of open files.
18266 */
18267 #ifdef SQLITE_TEST
18268 SQLITE_API int sqlite3_open_file_count = 0;
18269 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
18270 #else
18271 #define OpenCounter(X)
18272 #endif
18273
18274 /************** End of os_common.h *******************************************/
18275 /************** Continuing where we left off in os_unix.c ********************/
18276
18277 /*
18278 ** Define various macros that are missing from some systems.
18279 */
18280 #ifndef O_LARGEFILE
18281 # define O_LARGEFILE 0
18282 #endif
18283 #ifdef SQLITE_DISABLE_LFS
18284 # undef O_LARGEFILE
18285 # define O_LARGEFILE 0
18286 #endif
18287 #ifndef O_NOFOLLOW
18288 # define O_NOFOLLOW 0
18289 #endif
18290 #ifndef O_BINARY
18291 # define O_BINARY 0
18292 #endif
18293
18294 /*
18295 ** The DJGPP compiler environment looks mostly like Unix, but it
18296 ** lacks the fcntl() system call.  So redefine fcntl() to be something
18297 ** that always succeeds.  This means that locking does not occur under
18298 ** DJGPP.  But it is DOS - what did you expect?
18299 */
18300 #ifdef __DJGPP__
18301 # define fcntl(A,B,C) 0
18302 #endif
18303
18304 /*
18305 ** The threadid macro resolves to the thread-id or to 0.  Used for
18306 ** testing and debugging only.
18307 */
18308 #if SQLITE_THREADSAFE
18309 #define threadid pthread_self()
18310 #else
18311 #define threadid 0
18312 #endif
18313
18314 /*
18315 ** Set or check the unixFile.tid field.  This field is set when an unixFile
18316 ** is first opened.  All subsequent uses of the unixFile verify that the
18317 ** same thread is operating on the unixFile.  Some operating systems do
18318 ** not allow locks to be overridden by other threads and that restriction
18319 ** means that sqlite3* database handles cannot be moved from one thread
18320 ** to another.  This logic makes sure a user does not try to do that
18321 ** by mistake.
18322 **
18323 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
18324 ** another as long as we are running on a system that supports threads
18325 ** overriding each others locks (which now the most common behavior)
18326 ** or if no locks are held.  But the unixFile.pLock field needs to be
18327 ** recomputed because its key includes the thread-id.  See the 
18328 ** transferOwnership() function below for additional information
18329 */
18330 #if SQLITE_THREADSAFE
18331 # define SET_THREADID(X)   (X)->tid = pthread_self()
18332 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
18333                             !pthread_equal((X)->tid, pthread_self()))
18334 #else
18335 # define SET_THREADID(X)
18336 # define CHECK_THREADID(X) 0
18337 #endif
18338
18339 /*
18340 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
18341 ** section 6.5.2.2 lines 483 through 490 specify that when a process
18342 ** sets or clears a lock, that operation overrides any prior locks set
18343 ** by the same process.  It does not explicitly say so, but this implies
18344 ** that it overrides locks set by the same process using a different
18345 ** file descriptor.  Consider this test case:
18346 **
18347 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
18348 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
18349 **
18350 ** Suppose ./file1 and ./file2 are really the same file (because
18351 ** one is a hard or symbolic link to the other) then if you set
18352 ** an exclusive lock on fd1, then try to get an exclusive lock
18353 ** on fd2, it works.  I would have expected the second lock to
18354 ** fail since there was already a lock on the file due to fd1.
18355 ** But not so.  Since both locks came from the same process, the
18356 ** second overrides the first, even though they were on different
18357 ** file descriptors opened on different file names.
18358 **
18359 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
18360 ** that we cannot use POSIX locks to synchronize file access among
18361 ** competing threads of the same process.  POSIX locks will work fine
18362 ** to synchronize access for threads in separate processes, but not
18363 ** threads within the same process.
18364 **
18365 ** To work around the problem, SQLite has to manage file locks internally
18366 ** on its own.  Whenever a new database is opened, we have to find the
18367 ** specific inode of the database file (the inode is determined by the
18368 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
18369 ** and check for locks already existing on that inode.  When locks are
18370 ** created or removed, we have to look at our own internal record of the
18371 ** locks to see if another thread has previously set a lock on that same
18372 ** inode.
18373 **
18374 ** The sqlite3_file structure for POSIX is no longer just an integer file
18375 ** descriptor.  It is now a structure that holds the integer file
18376 ** descriptor and a pointer to a structure that describes the internal
18377 ** locks on the corresponding inode.  There is one locking structure
18378 ** per inode, so if the same inode is opened twice, both unixFile structures
18379 ** point to the same locking structure.  The locking structure keeps
18380 ** a reference count (so we will know when to delete it) and a "cnt"
18381 ** field that tells us its internal lock status.  cnt==0 means the
18382 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
18383 ** cnt>0 means there are cnt shared locks on the file.
18384 **
18385 ** Any attempt to lock or unlock a file first checks the locking
18386 ** structure.  The fcntl() system call is only invoked to set a 
18387 ** POSIX lock if the internal lock structure transitions between
18388 ** a locked and an unlocked state.
18389 **
18390 ** 2004-Jan-11:
18391 ** More recent discoveries about POSIX advisory locks.  (The more
18392 ** I discover, the more I realize the a POSIX advisory locks are
18393 ** an abomination.)
18394 **
18395 ** If you close a file descriptor that points to a file that has locks,
18396 ** all locks on that file that are owned by the current process are
18397 ** released.  To work around this problem, each unixFile structure contains
18398 ** a pointer to an openCnt structure.  There is one openCnt structure
18399 ** per open inode, which means that multiple unixFile can point to a single
18400 ** openCnt.  When an attempt is made to close an unixFile, if there are
18401 ** other unixFile open on the same inode that are holding locks, the call
18402 ** to close() the file descriptor is deferred until all of the locks clear.
18403 ** The openCnt structure keeps a list of file descriptors that need to
18404 ** be closed and that list is walked (and cleared) when the last lock
18405 ** clears.
18406 **
18407 ** First, under Linux threads, because each thread has a separate
18408 ** process ID, lock operations in one thread do not override locks
18409 ** to the same file in other threads.  Linux threads behave like
18410 ** separate processes in this respect.  But, if you close a file
18411 ** descriptor in linux threads, all locks are cleared, even locks
18412 ** on other threads and even though the other threads have different
18413 ** process IDs.  Linux threads is inconsistent in this respect.
18414 ** (I'm beginning to think that linux threads is an abomination too.)
18415 ** The consequence of this all is that the hash table for the lockInfo
18416 ** structure has to include the process id as part of its key because
18417 ** locks in different threads are treated as distinct.  But the 
18418 ** openCnt structure should not include the process id in its
18419 ** key because close() clears lock on all threads, not just the current
18420 ** thread.  Were it not for this goofiness in linux threads, we could
18421 ** combine the lockInfo and openCnt structures into a single structure.
18422 **
18423 ** 2004-Jun-28:
18424 ** On some versions of linux, threads can override each others locks.
18425 ** On others not.  Sometimes you can change the behavior on the same
18426 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
18427 ** POSIX standard is silent as to which behavior is correct, as far
18428 ** as I can tell, so other versions of unix might show the same
18429 ** inconsistency.  There is no little doubt in my mind that posix
18430 ** advisory locks and linux threads are profoundly broken.
18431 **
18432 ** To work around the inconsistencies, we have to test at runtime 
18433 ** whether or not threads can override each others locks.  This test
18434 ** is run once, the first time any lock is attempted.  A static 
18435 ** variable is set to record the results of this test for future
18436 ** use.
18437 */
18438
18439 /*
18440 ** An instance of the following structure serves as the key used
18441 ** to locate a particular lockInfo structure given its inode.
18442 **
18443 ** If threads cannot override each others locks, then we set the
18444 ** lockKey.tid field to the thread ID.  If threads can override
18445 ** each others locks then tid is always set to zero.  tid is omitted
18446 ** if we compile without threading support.
18447 */
18448 struct lockKey {
18449   dev_t dev;       /* Device number */
18450   ino_t ino;       /* Inode number */
18451 #if SQLITE_THREADSAFE
18452   pthread_t tid;   /* Thread ID or zero if threads can override each other */
18453 #endif
18454 };
18455
18456 /*
18457 ** An instance of the following structure is allocated for each open
18458 ** inode on each thread with a different process ID.  (Threads have
18459 ** different process IDs on linux, but not on most other unixes.)
18460 **
18461 ** A single inode can have multiple file descriptors, so each unixFile
18462 ** structure contains a pointer to an instance of this object and this
18463 ** object keeps a count of the number of unixFile pointing to it.
18464 */
18465 struct lockInfo {
18466   struct lockKey key;  /* The lookup key */
18467   int cnt;             /* Number of SHARED locks held */
18468   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
18469   int nRef;            /* Number of pointers to this structure */
18470 };
18471
18472 /*
18473 ** An instance of the following structure serves as the key used
18474 ** to locate a particular openCnt structure given its inode.  This
18475 ** is the same as the lockKey except that the thread ID is omitted.
18476 */
18477 struct openKey {
18478   dev_t dev;   /* Device number */
18479   ino_t ino;   /* Inode number */
18480 };
18481
18482 /*
18483 ** An instance of the following structure is allocated for each open
18484 ** inode.  This structure keeps track of the number of locks on that
18485 ** inode.  If a close is attempted against an inode that is holding
18486 ** locks, the close is deferred until all locks clear by adding the
18487 ** file descriptor to be closed to the pending list.
18488 */
18489 struct openCnt {
18490   struct openKey key;   /* The lookup key */
18491   int nRef;             /* Number of pointers to this structure */
18492   int nLock;            /* Number of outstanding locks */
18493   int nPending;         /* Number of pending close() operations */
18494   int *aPending;        /* Malloced space holding fd's awaiting a close() */
18495 };
18496
18497 /* 
18498 ** These hash tables map inodes and file descriptors (really, lockKey and
18499 ** openKey structures) into lockInfo and openCnt structures.  Access to 
18500 ** these hash tables must be protected by a mutex.
18501 */
18502 static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
18503 static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
18504
18505 #ifdef SQLITE_ENABLE_LOCKING_STYLE
18506 /*
18507 ** The locking styles are associated with the different file locking
18508 ** capabilities supported by different file systems.  
18509 **
18510 ** POSIX locking style fully supports shared and exclusive byte-range locks 
18511 ** ADP locking only supports exclusive byte-range locks
18512 ** FLOCK only supports a single file-global exclusive lock
18513 ** DOTLOCK isn't a true locking style, it refers to the use of a special
18514 **   file named the same as the database file with a '.lock' extension, this
18515 **   can be used on file systems that do not offer any reliable file locking
18516 ** NO locking means that no locking will be attempted, this is only used for
18517 **   read-only file systems currently
18518 ** UNSUPPORTED means that no locking will be attempted, this is only used for
18519 **   file systems that are known to be unsupported
18520 */
18521 typedef enum {
18522   posixLockingStyle = 0,       /* standard posix-advisory locks */
18523   afpLockingStyle,             /* use afp locks */
18524   flockLockingStyle,           /* use flock() */
18525   dotlockLockingStyle,         /* use <file>.lock files */
18526   noLockingStyle,              /* useful for read-only file system */
18527   unsupportedLockingStyle      /* indicates unsupported file system */
18528 } sqlite3LockingStyle;
18529 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
18530
18531 /*
18532 ** Helper functions to obtain and relinquish the global mutex.
18533 */
18534 static void enterMutex(){
18535   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
18536 }
18537 static void leaveMutex(){
18538   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
18539 }
18540
18541 #if SQLITE_THREADSAFE
18542 /*
18543 ** This variable records whether or not threads can override each others
18544 ** locks.
18545 **
18546 **    0:  No.  Threads cannot override each others locks.
18547 **    1:  Yes.  Threads can override each others locks.
18548 **   -1:  We don't know yet.
18549 **
18550 ** On some systems, we know at compile-time if threads can override each
18551 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
18552 ** will be set appropriately.  On other systems, we have to check at
18553 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
18554 ** undefined.
18555 **
18556 ** This variable normally has file scope only.  But during testing, we make
18557 ** it a global so that the test code can change its value in order to verify
18558 ** that the right stuff happens in either case.
18559 */
18560 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
18561 # define SQLITE_THREAD_OVERRIDE_LOCK -1
18562 #endif
18563 #ifdef SQLITE_TEST
18564 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
18565 #else
18566 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
18567 #endif
18568
18569 /*
18570 ** This structure holds information passed into individual test
18571 ** threads by the testThreadLockingBehavior() routine.
18572 */
18573 struct threadTestData {
18574   int fd;                /* File to be locked */
18575   struct flock lock;     /* The locking operation */
18576   int result;            /* Result of the locking operation */
18577 };
18578
18579 #ifdef SQLITE_LOCK_TRACE
18580 /*
18581 ** Print out information about all locking operations.
18582 **
18583 ** This routine is used for troubleshooting locks on multithreaded
18584 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
18585 ** command-line option on the compiler.  This code is normally
18586 ** turned off.
18587 */
18588 static int lockTrace(int fd, int op, struct flock *p){
18589   char *zOpName, *zType;
18590   int s;
18591   int savedErrno;
18592   if( op==F_GETLK ){
18593     zOpName = "GETLK";
18594   }else if( op==F_SETLK ){
18595     zOpName = "SETLK";
18596   }else{
18597     s = fcntl(fd, op, p);
18598     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
18599     return s;
18600   }
18601   if( p->l_type==F_RDLCK ){
18602     zType = "RDLCK";
18603   }else if( p->l_type==F_WRLCK ){
18604     zType = "WRLCK";
18605   }else if( p->l_type==F_UNLCK ){
18606     zType = "UNLCK";
18607   }else{
18608     assert( 0 );
18609   }
18610   assert( p->l_whence==SEEK_SET );
18611   s = fcntl(fd, op, p);
18612   savedErrno = errno;
18613   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
18614      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
18615      (int)p->l_pid, s);
18616   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
18617     struct flock l2;
18618     l2 = *p;
18619     fcntl(fd, F_GETLK, &l2);
18620     if( l2.l_type==F_RDLCK ){
18621       zType = "RDLCK";
18622     }else if( l2.l_type==F_WRLCK ){
18623       zType = "WRLCK";
18624     }else if( l2.l_type==F_UNLCK ){
18625       zType = "UNLCK";
18626     }else{
18627       assert( 0 );
18628     }
18629     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
18630        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
18631   }
18632   errno = savedErrno;
18633   return s;
18634 }
18635 #define fcntl lockTrace
18636 #endif /* SQLITE_LOCK_TRACE */
18637
18638 /*
18639 ** The testThreadLockingBehavior() routine launches two separate
18640 ** threads on this routine.  This routine attempts to lock a file
18641 ** descriptor then returns.  The success or failure of that attempt
18642 ** allows the testThreadLockingBehavior() procedure to determine
18643 ** whether or not threads can override each others locks.
18644 */
18645 static void *threadLockingTest(void *pArg){
18646   struct threadTestData *pData = (struct threadTestData*)pArg;
18647   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
18648   return pArg;
18649 }
18650
18651 /*
18652 ** This procedure attempts to determine whether or not threads
18653 ** can override each others locks then sets the 
18654 ** threadsOverrideEachOthersLocks variable appropriately.
18655 */
18656 static void testThreadLockingBehavior(int fd_orig){
18657   int fd;
18658   struct threadTestData d[2];
18659   pthread_t t[2];
18660
18661   fd = dup(fd_orig);
18662   if( fd<0 ) return;
18663   memset(d, 0, sizeof(d));
18664   d[0].fd = fd;
18665   d[0].lock.l_type = F_RDLCK;
18666   d[0].lock.l_len = 1;
18667   d[0].lock.l_start = 0;
18668   d[0].lock.l_whence = SEEK_SET;
18669   d[1] = d[0];
18670   d[1].lock.l_type = F_WRLCK;
18671   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
18672   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
18673   pthread_join(t[0], 0);
18674   pthread_join(t[1], 0);
18675   close(fd);
18676   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
18677 }
18678 #endif /* SQLITE_THREADSAFE */
18679
18680 /*
18681 ** Release a lockInfo structure previously allocated by findLockInfo().
18682 */
18683 static void releaseLockInfo(struct lockInfo *pLock){
18684   if (pLock == NULL)
18685     return;
18686   pLock->nRef--;
18687   if( pLock->nRef==0 ){
18688     sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
18689     sqlite3_free(pLock);
18690   }
18691 }
18692
18693 /*
18694 ** Release a openCnt structure previously allocated by findLockInfo().
18695 */
18696 static void releaseOpenCnt(struct openCnt *pOpen){
18697   if (pOpen == NULL)
18698     return;
18699   pOpen->nRef--;
18700   if( pOpen->nRef==0 ){
18701     sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
18702     free(pOpen->aPending);
18703     sqlite3_free(pOpen);
18704   }
18705 }
18706
18707 #ifdef SQLITE_ENABLE_LOCKING_STYLE
18708 /*
18709 ** Tests a byte-range locking query to see if byte range locks are 
18710 ** supported, if not we fall back to dotlockLockingStyle.
18711 */
18712 static sqlite3LockingStyle sqlite3TestLockingStyle(
18713   const char *filePath, 
18714   int fd
18715 ){
18716   /* test byte-range lock using fcntl */
18717   struct flock lockInfo;
18718   
18719   lockInfo.l_len = 1;
18720   lockInfo.l_start = 0;
18721   lockInfo.l_whence = SEEK_SET;
18722   lockInfo.l_type = F_RDLCK;
18723   
18724   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
18725     return posixLockingStyle;
18726   } 
18727   
18728   /* testing for flock can give false positives.  So if if the above test
18729   ** fails, then we fall back to using dot-lock style locking.
18730   */  
18731   return dotlockLockingStyle;
18732 }
18733
18734 /* 
18735 ** Examines the f_fstypename entry in the statfs structure as returned by 
18736 ** stat() for the file system hosting the database file, assigns the 
18737 ** appropriate locking style based on its value.  These values and 
18738 ** assignments are based on Darwin/OSX behavior and have not been tested on 
18739 ** other systems.
18740 */
18741 static sqlite3LockingStyle sqlite3DetectLockingStyle(
18742   const char *filePath, 
18743   int fd
18744 ){
18745
18746 #ifdef SQLITE_FIXED_LOCKING_STYLE
18747   return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
18748 #else
18749   struct statfs fsInfo;
18750
18751   if( statfs(filePath, &fsInfo) == -1 ){
18752     return sqlite3TestLockingStyle(filePath, fd);
18753   }
18754   if( fsInfo.f_flags & MNT_RDONLY ){
18755     return noLockingStyle;
18756   }
18757   if( strcmp(fsInfo.f_fstypename, "hfs")==0 ||
18758       strcmp(fsInfo.f_fstypename, "ufs")==0 ){
18759     return posixLockingStyle;
18760   }
18761   if( strcmp(fsInfo.f_fstypename, "afpfs")==0 ){
18762     return afpLockingStyle;
18763   }
18764   if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
18765     return sqlite3TestLockingStyle(filePath, fd);
18766   }
18767   if( strcmp(fsInfo.f_fstypename, "smbfs")==0 ){
18768     return flockLockingStyle;
18769   }
18770   if( strcmp(fsInfo.f_fstypename, "msdos")==0 ){
18771     return dotlockLockingStyle;
18772   }
18773   if( strcmp(fsInfo.f_fstypename, "webdav")==0 ){
18774     return unsupportedLockingStyle;
18775   }
18776   return sqlite3TestLockingStyle(filePath, fd);  
18777 #endif /* SQLITE_FIXED_LOCKING_STYLE */
18778 }
18779
18780 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
18781
18782 /*
18783 ** Given a file descriptor, locate lockInfo and openCnt structures that
18784 ** describes that file descriptor.  Create new ones if necessary.  The
18785 ** return values might be uninitialized if an error occurs.
18786 **
18787 ** Return the number of errors.
18788 */
18789 static int findLockInfo(
18790   int fd,                      /* The file descriptor used in the key */
18791   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
18792   struct openCnt **ppOpen      /* Return the openCnt structure here */
18793 ){
18794   int rc;
18795   struct lockKey key1;
18796   struct openKey key2;
18797   struct stat statbuf;
18798   struct lockInfo *pLock;
18799   struct openCnt *pOpen;
18800   rc = fstat(fd, &statbuf);
18801   if( rc!=0 ) return 1;
18802
18803   memset(&key1, 0, sizeof(key1));
18804   key1.dev = statbuf.st_dev;
18805   key1.ino = statbuf.st_ino;
18806 #if SQLITE_THREADSAFE
18807   if( threadsOverrideEachOthersLocks<0 ){
18808     testThreadLockingBehavior(fd);
18809   }
18810   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
18811 #endif
18812   memset(&key2, 0, sizeof(key2));
18813   key2.dev = statbuf.st_dev;
18814   key2.ino = statbuf.st_ino;
18815   pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
18816   if( pLock==0 ){
18817     struct lockInfo *pOld;
18818     pLock = sqlite3_malloc( sizeof(*pLock) );
18819     if( pLock==0 ){
18820       rc = 1;
18821       goto exit_findlockinfo;
18822     }
18823     pLock->key = key1;
18824     pLock->nRef = 1;
18825     pLock->cnt = 0;
18826     pLock->locktype = 0;
18827     pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
18828     if( pOld!=0 ){
18829       assert( pOld==pLock );
18830       sqlite3_free(pLock);
18831       rc = 1;
18832       goto exit_findlockinfo;
18833     }
18834   }else{
18835     pLock->nRef++;
18836   }
18837   *ppLock = pLock;
18838   if( ppOpen!=0 ){
18839     pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
18840     if( pOpen==0 ){
18841       struct openCnt *pOld;
18842       pOpen = sqlite3_malloc( sizeof(*pOpen) );
18843       if( pOpen==0 ){
18844         releaseLockInfo(pLock);
18845         rc = 1;
18846         goto exit_findlockinfo;
18847       }
18848       pOpen->key = key2;
18849       pOpen->nRef = 1;
18850       pOpen->nLock = 0;
18851       pOpen->nPending = 0;
18852       pOpen->aPending = 0;
18853       pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
18854       if( pOld!=0 ){
18855         assert( pOld==pOpen );
18856         sqlite3_free(pOpen);
18857         releaseLockInfo(pLock);
18858         rc = 1;
18859         goto exit_findlockinfo;
18860       }
18861     }else{
18862       pOpen->nRef++;
18863     }
18864     *ppOpen = pOpen;
18865   }
18866
18867 exit_findlockinfo:
18868   return rc;
18869 }
18870
18871 #ifdef SQLITE_DEBUG
18872 /*
18873 ** Helper function for printing out trace information from debugging
18874 ** binaries. This returns the string represetation of the supplied
18875 ** integer lock-type.
18876 */
18877 static const char *locktypeName(int locktype){
18878   switch( locktype ){
18879   case NO_LOCK: return "NONE";
18880   case SHARED_LOCK: return "SHARED";
18881   case RESERVED_LOCK: return "RESERVED";
18882   case PENDING_LOCK: return "PENDING";
18883   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
18884   }
18885   return "ERROR";
18886 }
18887 #endif
18888
18889 /*
18890 ** If we are currently in a different thread than the thread that the
18891 ** unixFile argument belongs to, then transfer ownership of the unixFile
18892 ** over to the current thread.
18893 **
18894 ** A unixFile is only owned by a thread on systems where one thread is
18895 ** unable to override locks created by a different thread.  RedHat9 is
18896 ** an example of such a system.
18897 **
18898 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
18899 ** If the unixFile is locked and an ownership is wrong, then return
18900 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
18901 */
18902 #if SQLITE_THREADSAFE
18903 static int transferOwnership(unixFile *pFile){
18904   int rc;
18905   pthread_t hSelf;
18906   if( threadsOverrideEachOthersLocks ){
18907     /* Ownership transfers not needed on this system */
18908     return SQLITE_OK;
18909   }
18910   hSelf = pthread_self();
18911   if( pthread_equal(pFile->tid, hSelf) ){
18912     /* We are still in the same thread */
18913     OSTRACE1("No-transfer, same thread\n");
18914     return SQLITE_OK;
18915   }
18916   if( pFile->locktype!=NO_LOCK ){
18917     /* We cannot change ownership while we are holding a lock! */
18918     return SQLITE_MISUSE;
18919   }
18920   OSTRACE4("Transfer ownership of %d from %d to %d\n",
18921             pFile->h, pFile->tid, hSelf);
18922   pFile->tid = hSelf;
18923   if (pFile->pLock != NULL) {
18924     releaseLockInfo(pFile->pLock);
18925     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
18926     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
18927            locktypeName(pFile->locktype),
18928            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
18929     return rc;
18930   } else {
18931     return SQLITE_OK;
18932   }
18933 }
18934 #else
18935   /* On single-threaded builds, ownership transfer is a no-op */
18936 # define transferOwnership(X) SQLITE_OK
18937 #endif
18938
18939 /*
18940 ** Seek to the offset passed as the second argument, then read cnt 
18941 ** bytes into pBuf. Return the number of bytes actually read.
18942 **
18943 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
18944 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
18945 ** one system to another.  Since SQLite does not define USE_PREAD
18946 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
18947 ** See tickets #2741 and #2681.
18948 */
18949 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
18950   int got;
18951   i64 newOffset;
18952   TIMER_START;
18953 #if defined(USE_PREAD)
18954   got = pread(id->h, pBuf, cnt, offset);
18955   SimulateIOError( got = -1 );
18956 #elif defined(USE_PREAD64)
18957   got = pread64(id->h, pBuf, cnt, offset);
18958   SimulateIOError( got = -1 );
18959 #else
18960   newOffset = lseek(id->h, offset, SEEK_SET);
18961   SimulateIOError( newOffset-- );
18962   if( newOffset!=offset ){
18963     return -1;
18964   }
18965   got = read(id->h, pBuf, cnt);
18966 #endif
18967   TIMER_END;
18968   OSTRACE5("READ    %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
18969   return got;
18970 }
18971
18972 /*
18973 ** Read data from a file into a buffer.  Return SQLITE_OK if all
18974 ** bytes were read successfully and SQLITE_IOERR if anything goes
18975 ** wrong.
18976 */
18977 static int unixRead(
18978   sqlite3_file *id, 
18979   void *pBuf, 
18980   int amt,
18981   sqlite3_int64 offset
18982 ){
18983   int got;
18984   assert( id );
18985   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
18986   if( got==amt ){
18987     return SQLITE_OK;
18988   }else if( got<0 ){
18989     return SQLITE_IOERR_READ;
18990   }else{
18991     memset(&((char*)pBuf)[got], 0, amt-got);
18992     return SQLITE_IOERR_SHORT_READ;
18993   }
18994 }
18995
18996 /*
18997 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
18998 ** Return the number of bytes actually read.  Update the offset.
18999 */
19000 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
19001   int got;
19002   i64 newOffset;
19003   TIMER_START;
19004 #if defined(USE_PREAD)
19005   got = pwrite(id->h, pBuf, cnt, offset);
19006 #elif defined(USE_PREAD64)
19007   got = pwrite64(id->h, pBuf, cnt, offset);
19008 #else
19009   newOffset = lseek(id->h, offset, SEEK_SET);
19010   if( newOffset!=offset ){
19011     return -1;
19012   }
19013   got = write(id->h, pBuf, cnt);
19014 #endif
19015   TIMER_END;
19016   OSTRACE5("WRITE   %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
19017   return got;
19018 }
19019
19020
19021 /*
19022 ** Write data from a buffer into a file.  Return SQLITE_OK on success
19023 ** or some other error code on failure.
19024 */
19025 static int unixWrite(
19026   sqlite3_file *id, 
19027   const void *pBuf, 
19028   int amt,
19029   sqlite3_int64 offset 
19030 ){
19031   int wrote = 0;
19032   assert( id );
19033   assert( amt>0 );
19034   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
19035     amt -= wrote;
19036     offset += wrote;
19037     pBuf = &((char*)pBuf)[wrote];
19038   }
19039   SimulateIOError(( wrote=(-1), amt=1 ));
19040   SimulateDiskfullError(( wrote=0, amt=1 ));
19041   if( amt>0 ){
19042     if( wrote<0 ){
19043       return SQLITE_IOERR_WRITE;
19044     }else{
19045       return SQLITE_FULL;
19046     }
19047   }
19048   return SQLITE_OK;
19049 }
19050
19051 #ifdef SQLITE_TEST
19052 /*
19053 ** Count the number of fullsyncs and normal syncs.  This is used to test
19054 ** that syncs and fullsyncs are occuring at the right times.
19055 */
19056 SQLITE_API int sqlite3_sync_count = 0;
19057 SQLITE_API int sqlite3_fullsync_count = 0;
19058 #endif
19059
19060 /*
19061 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
19062 ** Otherwise use fsync() in its place.
19063 */
19064 #ifndef HAVE_FDATASYNC
19065 # define fdatasync fsync
19066 #endif
19067
19068 /*
19069 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
19070 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
19071 ** only available on Mac OS X.  But that could change.
19072 */
19073 #ifdef F_FULLFSYNC
19074 # define HAVE_FULLFSYNC 1
19075 #else
19076 # define HAVE_FULLFSYNC 0
19077 #endif
19078
19079
19080 /*
19081 ** The fsync() system call does not work as advertised on many
19082 ** unix systems.  The following procedure is an attempt to make
19083 ** it work better.
19084 **
19085 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
19086 ** for testing when we want to run through the test suite quickly.
19087 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
19088 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
19089 ** or power failure will likely corrupt the database file.
19090 */
19091 static int full_fsync(int fd, int fullSync, int dataOnly){
19092   int rc;
19093
19094   /* Record the number of times that we do a normal fsync() and 
19095   ** FULLSYNC.  This is used during testing to verify that this procedure
19096   ** gets called with the correct arguments.
19097   */
19098 #ifdef SQLITE_TEST
19099   if( fullSync ) sqlite3_fullsync_count++;
19100   sqlite3_sync_count++;
19101 #endif
19102
19103   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
19104   ** no-op
19105   */
19106 #ifdef SQLITE_NO_SYNC
19107   rc = SQLITE_OK;
19108 #else
19109
19110 #if HAVE_FULLFSYNC
19111   if( fullSync ){
19112     rc = fcntl(fd, F_FULLFSYNC, 0);
19113   }else{
19114     rc = 1;
19115   }
19116   /* If the FULLFSYNC failed, fall back to attempting an fsync().
19117    * It shouldn't be possible for fullfsync to fail on the local 
19118    * file system (on OSX), so failure indicates that FULLFSYNC
19119    * isn't supported for this file system. So, attempt an fsync 
19120    * and (for now) ignore the overhead of a superfluous fcntl call.  
19121    * It'd be better to detect fullfsync support once and avoid 
19122    * the fcntl call every time sync is called.
19123    */
19124   if( rc ) rc = fsync(fd);
19125
19126 #else 
19127   if( dataOnly ){
19128     rc = fdatasync(fd);
19129   }else{
19130     rc = fsync(fd);
19131   }
19132 #endif /* HAVE_FULLFSYNC */
19133 #endif /* defined(SQLITE_NO_SYNC) */
19134
19135   return rc;
19136 }
19137
19138 /*
19139 ** Make sure all writes to a particular file are committed to disk.
19140 **
19141 ** If dataOnly==0 then both the file itself and its metadata (file
19142 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
19143 ** file data is synced.
19144 **
19145 ** Under Unix, also make sure that the directory entry for the file
19146 ** has been created by fsync-ing the directory that contains the file.
19147 ** If we do not do this and we encounter a power failure, the directory
19148 ** entry for the journal might not exist after we reboot.  The next
19149 ** SQLite to access the file will not know that the journal exists (because
19150 ** the directory entry for the journal was never created) and the transaction
19151 ** will not roll back - possibly leading to database corruption.
19152 */
19153 static int unixSync(sqlite3_file *id, int flags){
19154   int rc;
19155   unixFile *pFile = (unixFile*)id;
19156
19157   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
19158   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
19159
19160   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
19161   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
19162       || (flags&0x0F)==SQLITE_SYNC_FULL
19163   );
19164
19165   assert( pFile );
19166   OSTRACE2("SYNC    %-3d\n", pFile->h);
19167   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
19168   SimulateIOError( rc=1 );
19169   if( rc ){
19170     return SQLITE_IOERR_FSYNC;
19171   }
19172   if( pFile->dirfd>=0 ){
19173     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
19174             HAVE_FULLFSYNC, isFullsync);
19175 #ifndef SQLITE_DISABLE_DIRSYNC
19176     /* The directory sync is only attempted if full_fsync is
19177     ** turned off or unavailable.  If a full_fsync occurred above,
19178     ** then the directory sync is superfluous.
19179     */
19180     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
19181        /*
19182        ** We have received multiple reports of fsync() returning
19183        ** errors when applied to directories on certain file systems.
19184        ** A failed directory sync is not a big deal.  So it seems
19185        ** better to ignore the error.  Ticket #1657
19186        */
19187        /* return SQLITE_IOERR; */
19188     }
19189 #endif
19190     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
19191     pFile->dirfd = -1;    /* when we are done. */
19192   }
19193   return SQLITE_OK;
19194 }
19195
19196 /*
19197 ** Truncate an open file to a specified size
19198 */
19199 static int unixTruncate(sqlite3_file *id, i64 nByte){
19200   int rc;
19201   assert( id );
19202   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
19203   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
19204   if( rc ){
19205     return SQLITE_IOERR_TRUNCATE;
19206   }else{
19207     return SQLITE_OK;
19208   }
19209 }
19210
19211 /*
19212 ** Determine the current size of a file in bytes
19213 */
19214 static int unixFileSize(sqlite3_file *id, i64 *pSize){
19215   int rc;
19216   struct stat buf;
19217   assert( id );
19218   rc = fstat(((unixFile*)id)->h, &buf);
19219   SimulateIOError( rc=1 );
19220   if( rc!=0 ){
19221     return SQLITE_IOERR_FSTAT;
19222   }
19223   *pSize = buf.st_size;
19224   return SQLITE_OK;
19225 }
19226
19227 /*
19228 ** This routine checks if there is a RESERVED lock held on the specified
19229 ** file by this or any other process. If such a lock is held, return
19230 ** non-zero.  If the file is unlocked or holds only SHARED locks, then
19231 ** return zero.
19232 */
19233 static int unixCheckReservedLock(sqlite3_file *id){
19234   int r = 0;
19235   unixFile *pFile = (unixFile*)id;
19236
19237   assert( pFile );
19238   enterMutex(); /* Because pFile->pLock is shared across threads */
19239
19240   /* Check if a thread in this process holds such a lock */
19241   if( pFile->pLock->locktype>SHARED_LOCK ){
19242     r = 1;
19243   }
19244
19245   /* Otherwise see if some other process holds it.
19246   */
19247   if( !r ){
19248     struct flock lock;
19249     lock.l_whence = SEEK_SET;
19250     lock.l_start = RESERVED_BYTE;
19251     lock.l_len = 1;
19252     lock.l_type = F_WRLCK;
19253     fcntl(pFile->h, F_GETLK, &lock);
19254     if( lock.l_type!=F_UNLCK ){
19255       r = 1;
19256     }
19257   }
19258   
19259   leaveMutex();
19260   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
19261
19262   return r;
19263 }
19264
19265 /*
19266 ** Lock the file with the lock specified by parameter locktype - one
19267 ** of the following:
19268 **
19269 **     (1) SHARED_LOCK
19270 **     (2) RESERVED_LOCK
19271 **     (3) PENDING_LOCK
19272 **     (4) EXCLUSIVE_LOCK
19273 **
19274 ** Sometimes when requesting one lock state, additional lock states
19275 ** are inserted in between.  The locking might fail on one of the later
19276 ** transitions leaving the lock state different from what it started but
19277 ** still short of its goal.  The following chart shows the allowed
19278 ** transitions and the inserted intermediate states:
19279 **
19280 **    UNLOCKED -> SHARED
19281 **    SHARED -> RESERVED
19282 **    SHARED -> (PENDING) -> EXCLUSIVE
19283 **    RESERVED -> (PENDING) -> EXCLUSIVE
19284 **    PENDING -> EXCLUSIVE
19285 **
19286 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
19287 ** routine to lower a locking level.
19288 */
19289 static int unixLock(sqlite3_file *id, int locktype){
19290   /* The following describes the implementation of the various locks and
19291   ** lock transitions in terms of the POSIX advisory shared and exclusive
19292   ** lock primitives (called read-locks and write-locks below, to avoid
19293   ** confusion with SQLite lock names). The algorithms are complicated
19294   ** slightly in order to be compatible with windows systems simultaneously
19295   ** accessing the same database file, in case that is ever required.
19296   **
19297   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
19298   ** byte', each single bytes at well known offsets, and the 'shared byte
19299   ** range', a range of 510 bytes at a well known offset.
19300   **
19301   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
19302   ** byte'.  If this is successful, a random byte from the 'shared byte
19303   ** range' is read-locked and the lock on the 'pending byte' released.
19304   **
19305   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
19306   ** A RESERVED lock is implemented by grabbing a write-lock on the
19307   ** 'reserved byte'. 
19308   **
19309   ** A process may only obtain a PENDING lock after it has obtained a
19310   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
19311   ** on the 'pending byte'. This ensures that no new SHARED locks can be
19312   ** obtained, but existing SHARED locks are allowed to persist. A process
19313   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
19314   ** This property is used by the algorithm for rolling back a journal file
19315   ** after a crash.
19316   **
19317   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
19318   ** implemented by obtaining a write-lock on the entire 'shared byte
19319   ** range'. Since all other locks require a read-lock on one of the bytes
19320   ** within this range, this ensures that no other locks are held on the
19321   ** database. 
19322   **
19323   ** The reason a single byte cannot be used instead of the 'shared byte
19324   ** range' is that some versions of windows do not support read-locks. By
19325   ** locking a random byte from a range, concurrent SHARED locks may exist
19326   ** even if the locking primitive used is always a write-lock.
19327   */
19328   int rc = SQLITE_OK;
19329   unixFile *pFile = (unixFile*)id;
19330   struct lockInfo *pLock = pFile->pLock;
19331   struct flock lock;
19332   int s;
19333
19334   assert( pFile );
19335   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
19336       locktypeName(locktype), locktypeName(pFile->locktype),
19337       locktypeName(pLock->locktype), pLock->cnt , getpid());
19338
19339   /* If there is already a lock of this type or more restrictive on the
19340   ** unixFile, do nothing. Don't use the end_lock: exit path, as
19341   ** enterMutex() hasn't been called yet.
19342   */
19343   if( pFile->locktype>=locktype ){
19344     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
19345             locktypeName(locktype));
19346     return SQLITE_OK;
19347   }
19348
19349   /* Make sure the locking sequence is correct
19350   */
19351   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
19352   assert( locktype!=PENDING_LOCK );
19353   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
19354
19355   /* This mutex is needed because pFile->pLock is shared across threads
19356   */
19357   enterMutex();
19358
19359   /* Make sure the current thread owns the pFile.
19360   */
19361   rc = transferOwnership(pFile);
19362   if( rc!=SQLITE_OK ){
19363     leaveMutex();
19364     return rc;
19365   }
19366   pLock = pFile->pLock;
19367
19368   /* If some thread using this PID has a lock via a different unixFile*
19369   ** handle that precludes the requested lock, return BUSY.
19370   */
19371   if( (pFile->locktype!=pLock->locktype && 
19372           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
19373   ){
19374     rc = SQLITE_BUSY;
19375     goto end_lock;
19376   }
19377
19378   /* If a SHARED lock is requested, and some thread using this PID already
19379   ** has a SHARED or RESERVED lock, then increment reference counts and
19380   ** return SQLITE_OK.
19381   */
19382   if( locktype==SHARED_LOCK && 
19383       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
19384     assert( locktype==SHARED_LOCK );
19385     assert( pFile->locktype==0 );
19386     assert( pLock->cnt>0 );
19387     pFile->locktype = SHARED_LOCK;
19388     pLock->cnt++;
19389     pFile->pOpen->nLock++;
19390     goto end_lock;
19391   }
19392
19393   lock.l_len = 1L;
19394
19395   lock.l_whence = SEEK_SET;
19396
19397   /* A PENDING lock is needed before acquiring a SHARED lock and before
19398   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
19399   ** be released.
19400   */
19401   if( locktype==SHARED_LOCK 
19402       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
19403   ){
19404     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
19405     lock.l_start = PENDING_BYTE;
19406     s = fcntl(pFile->h, F_SETLK, &lock);
19407     if( s==(-1) ){
19408       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
19409       goto end_lock;
19410     }
19411   }
19412
19413
19414   /* If control gets to this point, then actually go ahead and make
19415   ** operating system calls for the specified lock.
19416   */
19417   if( locktype==SHARED_LOCK ){
19418     assert( pLock->cnt==0 );
19419     assert( pLock->locktype==0 );
19420
19421     /* Now get the read-lock */
19422     lock.l_start = SHARED_FIRST;
19423     lock.l_len = SHARED_SIZE;
19424     s = fcntl(pFile->h, F_SETLK, &lock);
19425
19426     /* Drop the temporary PENDING lock */
19427     lock.l_start = PENDING_BYTE;
19428     lock.l_len = 1L;
19429     lock.l_type = F_UNLCK;
19430     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
19431       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
19432       goto end_lock;
19433     }
19434     if( s==(-1) ){
19435       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
19436     }else{
19437       pFile->locktype = SHARED_LOCK;
19438       pFile->pOpen->nLock++;
19439       pLock->cnt = 1;
19440     }
19441   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
19442     /* We are trying for an exclusive lock but another thread in this
19443     ** same process is still holding a shared lock. */
19444     rc = SQLITE_BUSY;
19445   }else{
19446     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
19447     ** assumed that there is a SHARED or greater lock on the file
19448     ** already.
19449     */
19450     assert( 0!=pFile->locktype );
19451     lock.l_type = F_WRLCK;
19452     switch( locktype ){
19453       case RESERVED_LOCK:
19454         lock.l_start = RESERVED_BYTE;
19455         break;
19456       case EXCLUSIVE_LOCK:
19457         lock.l_start = SHARED_FIRST;
19458         lock.l_len = SHARED_SIZE;
19459         break;
19460       default:
19461         assert(0);
19462     }
19463     s = fcntl(pFile->h, F_SETLK, &lock);
19464     if( s==(-1) ){
19465       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
19466     }
19467   }
19468   
19469   if( rc==SQLITE_OK ){
19470     pFile->locktype = locktype;
19471     pLock->locktype = locktype;
19472   }else if( locktype==EXCLUSIVE_LOCK ){
19473     pFile->locktype = PENDING_LOCK;
19474     pLock->locktype = PENDING_LOCK;
19475   }
19476
19477 end_lock:
19478   leaveMutex();
19479   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
19480       rc==SQLITE_OK ? "ok" : "failed");
19481   return rc;
19482 }
19483
19484 /*
19485 ** Lower the locking level on file descriptor pFile to locktype.  locktype
19486 ** must be either NO_LOCK or SHARED_LOCK.
19487 **
19488 ** If the locking level of the file descriptor is already at or below
19489 ** the requested locking level, this routine is a no-op.
19490 */
19491 static int unixUnlock(sqlite3_file *id, int locktype){
19492   struct lockInfo *pLock;
19493   struct flock lock;
19494   int rc = SQLITE_OK;
19495   unixFile *pFile = (unixFile*)id;
19496   int h;
19497
19498   assert( pFile );
19499   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
19500       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
19501
19502   assert( locktype<=SHARED_LOCK );
19503   if( pFile->locktype<=locktype ){
19504     return SQLITE_OK;
19505   }
19506   if( CHECK_THREADID(pFile) ){
19507     return SQLITE_MISUSE;
19508   }
19509   enterMutex();
19510   h = pFile->h;
19511   pLock = pFile->pLock;
19512   assert( pLock->cnt!=0 );
19513   if( pFile->locktype>SHARED_LOCK ){
19514     assert( pLock->locktype==pFile->locktype );
19515     SimulateIOErrorBenign(1);
19516     SimulateIOError( h=(-1) )
19517     SimulateIOErrorBenign(0);
19518     if( locktype==SHARED_LOCK ){
19519       lock.l_type = F_RDLCK;
19520       lock.l_whence = SEEK_SET;
19521       lock.l_start = SHARED_FIRST;
19522       lock.l_len = SHARED_SIZE;
19523       if( fcntl(h, F_SETLK, &lock)==(-1) ){
19524         rc = SQLITE_IOERR_RDLOCK;
19525       }
19526     }
19527     lock.l_type = F_UNLCK;
19528     lock.l_whence = SEEK_SET;
19529     lock.l_start = PENDING_BYTE;
19530     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
19531     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
19532       pLock->locktype = SHARED_LOCK;
19533     }else{
19534       rc = SQLITE_IOERR_UNLOCK;
19535     }
19536   }
19537   if( locktype==NO_LOCK ){
19538     struct openCnt *pOpen;
19539
19540     /* Decrement the shared lock counter.  Release the lock using an
19541     ** OS call only when all threads in this same process have released
19542     ** the lock.
19543     */
19544     pLock->cnt--;
19545     if( pLock->cnt==0 ){
19546       lock.l_type = F_UNLCK;
19547       lock.l_whence = SEEK_SET;
19548       lock.l_start = lock.l_len = 0L;
19549       SimulateIOErrorBenign(1);
19550       SimulateIOError( h=(-1) )
19551       SimulateIOErrorBenign(0);
19552       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
19553         pLock->locktype = NO_LOCK;
19554       }else{
19555         rc = SQLITE_IOERR_UNLOCK;
19556         pLock->cnt = 1;
19557       }
19558     }
19559
19560     /* Decrement the count of locks against this same file.  When the
19561     ** count reaches zero, close any other file descriptors whose close
19562     ** was deferred because of outstanding locks.
19563     */
19564     if( rc==SQLITE_OK ){
19565       pOpen = pFile->pOpen;
19566       pOpen->nLock--;
19567       assert( pOpen->nLock>=0 );
19568       if( pOpen->nLock==0 && pOpen->nPending>0 ){
19569         int i;
19570         for(i=0; i<pOpen->nPending; i++){
19571           close(pOpen->aPending[i]);
19572         }
19573         free(pOpen->aPending);
19574         pOpen->nPending = 0;
19575         pOpen->aPending = 0;
19576       }
19577     }
19578   }
19579   leaveMutex();
19580   if( rc==SQLITE_OK ) pFile->locktype = locktype;
19581   return rc;
19582 }
19583
19584 /*
19585 ** Close a file.
19586 */
19587 static int unixClose(sqlite3_file *id){
19588   unixFile *pFile = (unixFile *)id;
19589   if( !pFile ) return SQLITE_OK;
19590   unixUnlock(id, NO_LOCK);
19591   if( pFile->dirfd>=0 ) close(pFile->dirfd);
19592   pFile->dirfd = -1;
19593   enterMutex();
19594
19595   if( pFile->pOpen->nLock ){
19596     /* If there are outstanding locks, do not actually close the file just
19597     ** yet because that would clear those locks.  Instead, add the file
19598     ** descriptor to pOpen->aPending.  It will be automatically closed when
19599     ** the last lock is cleared.
19600     */
19601     int *aNew;
19602     struct openCnt *pOpen = pFile->pOpen;
19603     aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
19604     if( aNew==0 ){
19605       /* If a malloc fails, just leak the file descriptor */
19606     }else{
19607       pOpen->aPending = aNew;
19608       pOpen->aPending[pOpen->nPending] = pFile->h;
19609       pOpen->nPending++;
19610     }
19611   }else{
19612     /* There are no outstanding locks so we can close the file immediately */
19613     close(pFile->h);
19614   }
19615   releaseLockInfo(pFile->pLock);
19616   releaseOpenCnt(pFile->pOpen);
19617
19618   leaveMutex();
19619   OSTRACE2("CLOSE   %-3d\n", pFile->h);
19620   OpenCounter(-1);
19621   memset(pFile, 0, sizeof(unixFile));
19622   return SQLITE_OK;
19623 }
19624
19625
19626 #ifdef SQLITE_ENABLE_LOCKING_STYLE
19627 #pragma mark AFP Support
19628
19629 /*
19630  ** The afpLockingContext structure contains all afp lock specific state
19631  */
19632 typedef struct afpLockingContext afpLockingContext;
19633 struct afpLockingContext {
19634   unsigned long long sharedLockByte;
19635   const char *filePath;
19636 };
19637
19638 struct ByteRangeLockPB2
19639 {
19640   unsigned long long offset;        /* offset to first byte to lock */
19641   unsigned long long length;        /* nbr of bytes to lock */
19642   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
19643   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
19644   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
19645   int fd;                           /* file desc to assoc this lock with */
19646 };
19647
19648 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
19649
19650 /* 
19651 ** Return 0 on success, 1 on failure.  To match the behavior of the 
19652 ** normal posix file locking (used in unixLock for example), we should 
19653 ** provide 'richer' return codes - specifically to differentiate between
19654 ** 'file busy' and 'file system error' results.
19655 */
19656 static int _AFPFSSetLock(
19657   const char *path, 
19658   int fd, 
19659   unsigned long long offset, 
19660   unsigned long long length, 
19661   int setLockFlag
19662 ){
19663   struct ByteRangeLockPB2       pb;
19664   int                     err;
19665   
19666   pb.unLockFlag = setLockFlag ? 0 : 1;
19667   pb.startEndFlag = 0;
19668   pb.offset = offset;
19669   pb.length = length; 
19670   pb.fd = fd;
19671   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
19672     (setLockFlag?"ON":"OFF"), fd, offset, length);
19673   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
19674   if ( err==-1 ) {
19675     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
19676       strerror(errno));
19677     return 1; /* error */
19678   } else {
19679     return 0;
19680   }
19681 }
19682
19683 /*
19684  ** This routine checks if there is a RESERVED lock held on the specified
19685  ** file by this or any other process. If such a lock is held, return
19686  ** non-zero.  If the file is unlocked or holds only SHARED locks, then
19687  ** return zero.
19688  */
19689 static int afpUnixCheckReservedLock(sqlite3_file *id){
19690   int r = 0;
19691   unixFile *pFile = (unixFile*)id;
19692   
19693   assert( pFile ); 
19694   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
19695   
19696   /* Check if a thread in this process holds such a lock */
19697   if( pFile->locktype>SHARED_LOCK ){
19698     r = 1;
19699   }
19700   
19701   /* Otherwise see if some other process holds it.
19702    */
19703   if ( !r ) {
19704     /* lock the byte */
19705     int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
19706     if (failed) {
19707       /* if we failed to get the lock then someone else must have it */
19708       r = 1;
19709     } else {
19710       /* if we succeeded in taking the reserved lock, unlock it to restore
19711       ** the original state */
19712       _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
19713     }
19714   }
19715   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
19716   
19717   return r;
19718 }
19719
19720 /* AFP-style locking following the behavior of unixLock, see the unixLock 
19721 ** function comments for details of lock management. */
19722 static int afpUnixLock(sqlite3_file *id, int locktype){
19723   int rc = SQLITE_OK;
19724   unixFile *pFile = (unixFile*)id;
19725   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
19726   int gotPendingLock = 0;
19727   
19728   assert( pFile );
19729   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
19730          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
19731
19732   /* If there is already a lock of this type or more restrictive on the
19733   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
19734   ** enterMutex() hasn't been called yet.
19735   */
19736   if( pFile->locktype>=locktype ){
19737     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
19738            locktypeName(locktype));
19739     return SQLITE_OK;
19740   }
19741
19742   /* Make sure the locking sequence is correct
19743   */
19744   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
19745   assert( locktype!=PENDING_LOCK );
19746   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
19747   
19748   /* This mutex is needed because pFile->pLock is shared across threads
19749   */
19750   enterMutex();
19751
19752   /* Make sure the current thread owns the pFile.
19753   */
19754   rc = transferOwnership(pFile);
19755   if( rc!=SQLITE_OK ){
19756     leaveMutex();
19757     return rc;
19758   }
19759     
19760   /* A PENDING lock is needed before acquiring a SHARED lock and before
19761   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
19762   ** be released.
19763   */
19764   if( locktype==SHARED_LOCK 
19765       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
19766   ){
19767     int failed;
19768     failed = _AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 1);
19769     if (failed) {
19770       rc = SQLITE_BUSY;
19771       goto afp_end_lock;
19772     }
19773   }
19774   
19775   /* If control gets to this point, then actually go ahead and make
19776   ** operating system calls for the specified lock.
19777   */
19778   if( locktype==SHARED_LOCK ){
19779     int lk, failed;
19780     int tries = 0;
19781     
19782     /* Now get the read-lock */
19783     /* note that the quality of the randomness doesn't matter that much */
19784     lk = random(); 
19785     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
19786     failed = _AFPFSSetLock(context->filePath, pFile->h, 
19787       SHARED_FIRST+context->sharedLockByte, 1, 1);
19788     
19789     /* Drop the temporary PENDING lock */
19790     if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
19791       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
19792       goto afp_end_lock;
19793     }
19794     
19795     if( failed ){
19796       rc = SQLITE_BUSY;
19797     } else {
19798       pFile->locktype = SHARED_LOCK;
19799     }
19800   }else{
19801     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
19802     ** assumed that there is a SHARED or greater lock on the file
19803     ** already.
19804     */
19805     int failed = 0;
19806     assert( 0!=pFile->locktype );
19807     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
19808         /* Acquire a RESERVED lock */
19809         failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
19810     }
19811     if (!failed && locktype == EXCLUSIVE_LOCK) {
19812       /* Acquire an EXCLUSIVE lock */
19813         
19814       /* Remove the shared lock before trying the range.  we'll need to 
19815       ** reestablish the shared lock if we can't get the  afpUnixUnlock
19816       */
19817       if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
19818                          context->sharedLockByte, 1, 0)) {
19819         /* now attemmpt to get the exclusive lock range */
19820         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
19821                                SHARED_SIZE, 1);
19822         if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
19823                                     context->sharedLockByte, 1, 1)) {
19824           rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
19825         }
19826       } else {
19827         /* */
19828         rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
19829       }
19830     }
19831     if( failed && rc == SQLITE_OK){
19832       rc = SQLITE_BUSY;
19833     }
19834   }
19835   
19836   if( rc==SQLITE_OK ){
19837     pFile->locktype = locktype;
19838   }else if( locktype==EXCLUSIVE_LOCK ){
19839     pFile->locktype = PENDING_LOCK;
19840   }
19841   
19842 afp_end_lock:
19843   leaveMutex();
19844   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
19845          rc==SQLITE_OK ? "ok" : "failed");
19846   return rc;
19847 }
19848
19849 /*
19850 ** Lower the locking level on file descriptor pFile to locktype.  locktype
19851 ** must be either NO_LOCK or SHARED_LOCK.
19852 **
19853 ** If the locking level of the file descriptor is already at or below
19854 ** the requested locking level, this routine is a no-op.
19855 */
19856 static int afpUnixUnlock(sqlite3_file *id, int locktype) {
19857   struct flock lock;
19858   int rc = SQLITE_OK;
19859   unixFile *pFile = (unixFile*)id;
19860   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
19861
19862   assert( pFile );
19863   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
19864          pFile->locktype, getpid());
19865   
19866   assert( locktype<=SHARED_LOCK );
19867   if( pFile->locktype<=locktype ){
19868     return SQLITE_OK;
19869   }
19870   if( CHECK_THREADID(pFile) ){
19871     return SQLITE_MISUSE;
19872   }
19873   enterMutex();
19874   if( pFile->locktype>SHARED_LOCK ){
19875     if( locktype==SHARED_LOCK ){
19876       int failed = 0;
19877
19878       /* unlock the exclusive range - then re-establish the shared lock */
19879       if (pFile->locktype==EXCLUSIVE_LOCK) {
19880         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
19881                                  SHARED_SIZE, 0);
19882         if (!failed) {
19883           /* successfully removed the exclusive lock */
19884           if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
19885                             context->sharedLockByte, 1, 1)) {
19886             /* failed to re-establish our shared lock */
19887             rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
19888           }
19889         } else {
19890           /* This should never happen - failed to unlock the exclusive range */
19891           rc = SQLITE_IOERR_UNLOCK;
19892         } 
19893       }
19894     }
19895     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
19896       if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
19897         /* failed to release the pending lock */
19898         rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
19899       }
19900     } 
19901     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
19902       if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
19903         /* failed to release the reserved lock */
19904         rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
19905       }
19906     } 
19907   }
19908   if( locktype==NO_LOCK ){
19909     int failed = _AFPFSSetLock(context->filePath, pFile->h, 
19910                                SHARED_FIRST + context->sharedLockByte, 1, 0);
19911     if (failed) {
19912       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
19913     }
19914   }
19915   if (rc == SQLITE_OK)
19916     pFile->locktype = locktype;
19917   leaveMutex();
19918   return rc;
19919 }
19920
19921 /*
19922 ** Close a file & cleanup AFP specific locking context 
19923 */
19924 static int afpUnixClose(sqlite3_file *id) {
19925   unixFile *pFile = (unixFile*)id;
19926
19927   if( !pFile ) return SQLITE_OK;
19928   afpUnixUnlock(id, NO_LOCK);
19929   sqlite3_free(pFile->lockingContext);
19930   if( pFile->dirfd>=0 ) close(pFile->dirfd);
19931   pFile->dirfd = -1;
19932   enterMutex();
19933   close(pFile->h);
19934   leaveMutex();
19935   OSTRACE2("CLOSE   %-3d\n", pFile->h);
19936   OpenCounter(-1);
19937   memset(pFile, 0, sizeof(unixFile));
19938   return SQLITE_OK;
19939 }
19940
19941
19942 #pragma mark flock() style locking
19943
19944 /*
19945 ** The flockLockingContext is not used
19946 */
19947 typedef void flockLockingContext;
19948
19949 static int flockUnixCheckReservedLock(sqlite3_file *id){
19950   unixFile *pFile = (unixFile*)id;
19951   
19952   if (pFile->locktype == RESERVED_LOCK) {
19953     return 1; /* already have a reserved lock */
19954   } else {
19955     /* attempt to get the lock */
19956     int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
19957     if (!rc) {
19958       /* got the lock, unlock it */
19959       flock(pFile->h, LOCK_UN);
19960       return 0;  /* no one has it reserved */
19961     }
19962     return 1; /* someone else might have it reserved */
19963   }
19964 }
19965
19966 static int flockUnixLock(sqlite3_file *id, int locktype) {
19967   unixFile *pFile = (unixFile*)id;
19968   
19969   /* if we already have a lock, it is exclusive.  
19970   ** Just adjust level and punt on outta here. */
19971   if (pFile->locktype > NO_LOCK) {
19972     pFile->locktype = locktype;
19973     return SQLITE_OK;
19974   }
19975   
19976   /* grab an exclusive lock */
19977   int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
19978   if (rc) {
19979     /* didn't get, must be busy */
19980     return SQLITE_BUSY;
19981   } else {
19982     /* got it, set the type and return ok */
19983     pFile->locktype = locktype;
19984     return SQLITE_OK;
19985   }
19986 }
19987
19988 static int flockUnixUnlock(sqlite3_file *id, int locktype) {
19989   unixFile *pFile = (unixFile*)id;
19990   
19991   assert( locktype<=SHARED_LOCK );
19992   
19993   /* no-op if possible */
19994   if( pFile->locktype==locktype ){
19995     return SQLITE_OK;
19996   }
19997   
19998   /* shared can just be set because we always have an exclusive */
19999   if (locktype==SHARED_LOCK) {
20000     pFile->locktype = locktype;
20001     return SQLITE_OK;
20002   }
20003   
20004   /* no, really, unlock. */
20005   int rc = flock(pFile->h, LOCK_UN);
20006   if (rc)
20007     return SQLITE_IOERR_UNLOCK;
20008   else {
20009     pFile->locktype = NO_LOCK;
20010     return SQLITE_OK;
20011   }
20012 }
20013
20014 /*
20015 ** Close a file.
20016 */
20017 static int flockUnixClose(sqlite3_file *id) {
20018   unixFile *pFile = (unixFile*)id;
20019   
20020   if( !pFile ) return SQLITE_OK;
20021   flockUnixUnlock(id, NO_LOCK);
20022   
20023   if( pFile->dirfd>=0 ) close(pFile->dirfd);
20024   pFile->dirfd = -1;
20025
20026   enterMutex();
20027   close(pFile->h);  
20028   leaveMutex();
20029   OSTRACE2("CLOSE   %-3d\n", pFile->h);
20030   OpenCounter(-1);
20031   memset(pFile, 0, sizeof(unixFile));
20032   return SQLITE_OK;
20033 }
20034
20035 #pragma mark Old-School .lock file based locking
20036
20037 /*
20038 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
20039 ** specific state
20040 */
20041 typedef struct dotlockLockingContext dotlockLockingContext;
20042 struct dotlockLockingContext {
20043   char *lockPath;
20044 };
20045
20046
20047 static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
20048   unixFile *pFile = (unixFile*)id;
20049   dotlockLockingContext *context;
20050
20051   context = (dotlockLockingContext*)pFile->lockingContext;
20052   if (pFile->locktype == RESERVED_LOCK) {
20053     return 1; /* already have a reserved lock */
20054   } else {
20055     struct stat statBuf;
20056     if (lstat(context->lockPath,&statBuf) == 0){
20057       /* file exists, someone else has the lock */
20058       return 1;
20059     }else{
20060       /* file does not exist, we could have it if we want it */
20061       return 0;
20062     }
20063   }
20064 }
20065
20066 static int dotlockUnixLock(sqlite3_file *id, int locktype) {
20067   unixFile *pFile = (unixFile*)id;
20068   dotlockLockingContext *context;
20069   int fd;
20070
20071   context = (dotlockLockingContext*)pFile->lockingContext;
20072   
20073   /* if we already have a lock, it is exclusive.  
20074   ** Just adjust level and punt on outta here. */
20075   if (pFile->locktype > NO_LOCK) {
20076     pFile->locktype = locktype;
20077     
20078     /* Always update the timestamp on the old file */
20079     utimes(context->lockPath,NULL);
20080     return SQLITE_OK;
20081   }
20082   
20083   /* check to see if lock file already exists */
20084   struct stat statBuf;
20085   if (lstat(context->lockPath,&statBuf) == 0){
20086     return SQLITE_BUSY; /* it does, busy */
20087   }
20088   
20089   /* grab an exclusive lock */
20090   fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
20091   if( fd<0 ){
20092     /* failed to open/create the file, someone else may have stolen the lock */
20093     return SQLITE_BUSY; 
20094   }
20095   close(fd);
20096   
20097   /* got it, set the type and return ok */
20098   pFile->locktype = locktype;
20099   return SQLITE_OK;
20100 }
20101
20102 static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
20103   unixFile *pFile = (unixFile*)id;
20104   dotlockLockingContext *context;
20105
20106   context = (dotlockLockingContext*)pFile->lockingContext;
20107   
20108   assert( locktype<=SHARED_LOCK );
20109   
20110   /* no-op if possible */
20111   if( pFile->locktype==locktype ){
20112     return SQLITE_OK;
20113   }
20114   
20115   /* shared can just be set because we always have an exclusive */
20116   if (locktype==SHARED_LOCK) {
20117     pFile->locktype = locktype;
20118     return SQLITE_OK;
20119   }
20120   
20121   /* no, really, unlock. */
20122   unlink(context->lockPath);
20123   pFile->locktype = NO_LOCK;
20124   return SQLITE_OK;
20125 }
20126
20127 /*
20128  ** Close a file.
20129  */
20130 static int dotlockUnixClose(sqlite3_file *id) {
20131   unixFile *pFile = (unixFile*)id;
20132   
20133   if( !pFile ) return SQLITE_OK;
20134   dotlockUnixUnlock(id, NO_LOCK);
20135   sqlite3_free(pFile->lockingContext);
20136   if( pFile->dirfd>=0 ) close(pFile->dirfd);
20137   pFile->dirfd = -1;
20138   enterMutex();  
20139   close(pFile->h);
20140   leaveMutex();
20141   OSTRACE2("CLOSE   %-3d\n", pFile->h);
20142   OpenCounter(-1);
20143   memset(pFile, 0, sizeof(unixFile));
20144   return SQLITE_OK;
20145 }
20146
20147
20148 #pragma mark No locking
20149
20150 /*
20151 ** The nolockLockingContext is void
20152 */
20153 typedef void nolockLockingContext;
20154
20155 static int nolockUnixCheckReservedLock(sqlite3_file *id) {
20156   return 0;
20157 }
20158
20159 static int nolockUnixLock(sqlite3_file *id, int locktype) {
20160   return SQLITE_OK;
20161 }
20162
20163 static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
20164   return SQLITE_OK;
20165 }
20166
20167 /*
20168 ** Close a file.
20169 */
20170 static int nolockUnixClose(sqlite3_file *id) {
20171   unixFile *pFile = (unixFile*)id;
20172   
20173   if( !pFile ) return SQLITE_OK;
20174   if( pFile->dirfd>=0 ) close(pFile->dirfd);
20175   pFile->dirfd = -1;
20176   enterMutex();
20177   close(pFile->h);
20178   leaveMutex();
20179   OSTRACE2("CLOSE   %-3d\n", pFile->h);
20180   OpenCounter(-1);
20181   memset(pFile, 0, sizeof(unixFile));
20182   return SQLITE_OK;
20183 }
20184
20185 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
20186
20187
20188 /*
20189 ** Information and control of an open file handle.
20190 */
20191 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
20192   switch( op ){
20193     case SQLITE_FCNTL_LOCKSTATE: {
20194       *(int*)pArg = ((unixFile*)id)->locktype;
20195       return SQLITE_OK;
20196     }
20197   }
20198   return SQLITE_ERROR;
20199 }
20200
20201 /*
20202 ** Return the sector size in bytes of the underlying block device for
20203 ** the specified file. This is almost always 512 bytes, but may be
20204 ** larger for some devices.
20205 **
20206 ** SQLite code assumes this function cannot fail. It also assumes that
20207 ** if two files are created in the same file-system directory (i.e.
20208 ** a database and its journal file) that the sector size will be the
20209 ** same for both.
20210 */
20211 static int unixSectorSize(sqlite3_file *id){
20212   return SQLITE_DEFAULT_SECTOR_SIZE;
20213 }
20214
20215 /*
20216 ** Return the device characteristics for the file. This is always 0.
20217 */
20218 static int unixDeviceCharacteristics(sqlite3_file *id){
20219   return 0;
20220 }
20221
20222 /*
20223 ** This vector defines all the methods that can operate on an sqlite3_file
20224 ** for unix.
20225 */
20226 static const sqlite3_io_methods sqlite3UnixIoMethod = {
20227   1,                        /* iVersion */
20228   unixClose,
20229   unixRead,
20230   unixWrite,
20231   unixTruncate,
20232   unixSync,
20233   unixFileSize,
20234   unixLock,
20235   unixUnlock,
20236   unixCheckReservedLock,
20237   unixFileControl,
20238   unixSectorSize,
20239   unixDeviceCharacteristics
20240 };
20241
20242 #ifdef SQLITE_ENABLE_LOCKING_STYLE
20243 /*
20244 ** This vector defines all the methods that can operate on an sqlite3_file
20245 ** for unix with AFP style file locking.
20246 */
20247 static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
20248   1,                        /* iVersion */
20249   afpUnixClose,
20250   unixRead,
20251   unixWrite,
20252   unixTruncate,
20253   unixSync,
20254   unixFileSize,
20255   afpUnixLock,
20256   afpUnixUnlock,
20257   afpUnixCheckReservedLock,
20258   unixFileControl,
20259   unixSectorSize,
20260   unixDeviceCharacteristics
20261 };
20262
20263 /*
20264 ** This vector defines all the methods that can operate on an sqlite3_file
20265 ** for unix with flock() style file locking.
20266 */
20267 static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
20268   1,                        /* iVersion */
20269   flockUnixClose,
20270   unixRead,
20271   unixWrite,
20272   unixTruncate,
20273   unixSync,
20274   unixFileSize,
20275   flockUnixLock,
20276   flockUnixUnlock,
20277   flockUnixCheckReservedLock,
20278   unixFileControl,
20279   unixSectorSize,
20280   unixDeviceCharacteristics
20281 };
20282
20283 /*
20284 ** This vector defines all the methods that can operate on an sqlite3_file
20285 ** for unix with dotlock style file locking.
20286 */
20287 static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
20288   1,                        /* iVersion */
20289   dotlockUnixClose,
20290   unixRead,
20291   unixWrite,
20292   unixTruncate,
20293   unixSync,
20294   unixFileSize,
20295   dotlockUnixLock,
20296   dotlockUnixUnlock,
20297   dotlockUnixCheckReservedLock,
20298   unixFileControl,
20299   unixSectorSize,
20300   unixDeviceCharacteristics
20301 };
20302
20303 /*
20304 ** This vector defines all the methods that can operate on an sqlite3_file
20305 ** for unix with nolock style file locking.
20306 */
20307 static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
20308   1,                        /* iVersion */
20309   nolockUnixClose,
20310   unixRead,
20311   unixWrite,
20312   unixTruncate,
20313   unixSync,
20314   unixFileSize,
20315   nolockUnixLock,
20316   nolockUnixUnlock,
20317   nolockUnixCheckReservedLock,
20318   unixFileControl,
20319   unixSectorSize,
20320   unixDeviceCharacteristics
20321 };
20322
20323 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
20324
20325 /*
20326 ** Allocate memory for a new unixFile and initialize that unixFile.
20327 ** Write a pointer to the new unixFile into *pId.
20328 ** If we run out of memory, close the file and return an error.
20329 */
20330 #ifdef SQLITE_ENABLE_LOCKING_STYLE
20331 /* 
20332 ** When locking extensions are enabled, the filepath and locking style 
20333 ** are needed to determine the unixFile pMethod to use for locking operations.
20334 ** The locking-style specific lockingContext data structure is created 
20335 ** and assigned here also.
20336 */
20337 static int fillInUnixFile(
20338   int h,                  /* Open file descriptor of file being opened */
20339   int dirfd,              /* Directory file descriptor */
20340   sqlite3_file *pId,      /* Write to the unixFile structure here */
20341   const char *zFilename   /* Name of the file being opened */
20342 ){
20343   sqlite3LockingStyle lockingStyle;
20344   unixFile *pNew = (unixFile *)pId;
20345   int rc;
20346
20347 #ifdef FD_CLOEXEC
20348   fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
20349 #endif
20350
20351   lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
20352   if ( lockingStyle==posixLockingStyle ){
20353     enterMutex();
20354     rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
20355     leaveMutex();
20356     if( rc ){
20357       if( dirfd>=0 ) close(dirfd);
20358       close(h);
20359       return SQLITE_NOMEM;
20360     }
20361   } else {
20362     /*  pLock and pOpen are only used for posix advisory locking */
20363     pNew->pLock = NULL;
20364     pNew->pOpen = NULL;
20365   }
20366
20367   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
20368   pNew->dirfd = -1;
20369   pNew->h = h;
20370   pNew->dirfd = dirfd;
20371   SET_THREADID(pNew);
20372     
20373   switch(lockingStyle) {
20374     case afpLockingStyle: {
20375       /* afp locking uses the file path so it needs to be included in
20376       ** the afpLockingContext */
20377       afpLockingContext *context;
20378       pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
20379       pNew->lockingContext = context = sqlite3_malloc( sizeof(*context) );
20380       if( context==0 ){
20381         close(h);
20382         if( dirfd>=0 ) close(dirfd);
20383         return SQLITE_NOMEM;
20384       }
20385
20386       /* NB: zFilename exists and remains valid until the file is closed
20387       ** according to requirement F11141.  So we do not need to make a
20388       ** copy of the filename. */
20389       context->filePath = zFilename;
20390       srandomdev();
20391       break;
20392     }
20393     case flockLockingStyle:
20394       /* flock locking doesn't need additional lockingContext information */
20395       pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
20396       break;
20397     case dotlockLockingStyle: {
20398       /* dotlock locking uses the file path so it needs to be included in
20399       ** the dotlockLockingContext */
20400       dotlockLockingContext *context;
20401       int nFilename;
20402       nFilename = strlen(zFilename);
20403       pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
20404       pNew->lockingContext = context = 
20405          sqlite3_malloc( sizeof(*context) + nFilename + 6 );
20406       if( context==0 ){
20407         close(h);
20408         if( dirfd>=0 ) close(dirfd);
20409         return SQLITE_NOMEM;
20410       }
20411       context->lockPath = (char*)&context[1];
20412       sqlite3_snprintf(nFilename, context->lockPath,
20413                        "%s.lock", zFilename);
20414       break;
20415     }
20416     case posixLockingStyle:
20417       /* posix locking doesn't need additional lockingContext information */
20418       pNew->pMethod = &sqlite3UnixIoMethod;
20419       break;
20420     case noLockingStyle:
20421     case unsupportedLockingStyle:
20422     default: 
20423       pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
20424   }
20425   OpenCounter(+1);
20426   return SQLITE_OK;
20427 }
20428 #else /* SQLITE_ENABLE_LOCKING_STYLE */
20429 static int fillInUnixFile(
20430   int h,                 /* Open file descriptor on file being opened */
20431   int dirfd,
20432   sqlite3_file *pId,     /* Write to the unixFile structure here */
20433   const char *zFilename  /* Name of the file being opened */
20434 ){
20435   unixFile *pNew = (unixFile *)pId;
20436   int rc;
20437
20438 #ifdef FD_CLOEXEC
20439   fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
20440 #endif
20441
20442   enterMutex();
20443   rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
20444   leaveMutex();
20445   if( rc ){
20446     if( dirfd>=0 ) close(dirfd);
20447     close(h);
20448     return SQLITE_NOMEM;
20449   }
20450
20451   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
20452   pNew->dirfd = -1;
20453   pNew->h = h;
20454   pNew->dirfd = dirfd;
20455   SET_THREADID(pNew);
20456
20457   pNew->pMethod = &sqlite3UnixIoMethod;
20458   OpenCounter(+1);
20459   return SQLITE_OK;
20460 }
20461 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
20462
20463 /*
20464 ** Open a file descriptor to the directory containing file zFilename.
20465 ** If successful, *pFd is set to the opened file descriptor and
20466 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
20467 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
20468 ** value.
20469 **
20470 ** If SQLITE_OK is returned, the caller is responsible for closing
20471 ** the file descriptor *pFd using close().
20472 */
20473 static int openDirectory(const char *zFilename, int *pFd){
20474   int ii;
20475   int fd = -1;
20476   char zDirname[MAX_PATHNAME+1];
20477
20478   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
20479   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
20480   if( ii>0 ){
20481     zDirname[ii] = '\0';
20482     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
20483     if( fd>=0 ){
20484 #ifdef FD_CLOEXEC
20485       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
20486 #endif
20487       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
20488     }
20489   }
20490   *pFd = fd;
20491   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
20492 }
20493
20494 /*
20495 ** Open the file zPath.
20496 ** 
20497 ** Previously, the SQLite OS layer used three functions in place of this
20498 ** one:
20499 **
20500 **     sqlite3OsOpenReadWrite();
20501 **     sqlite3OsOpenReadOnly();
20502 **     sqlite3OsOpenExclusive();
20503 **
20504 ** These calls correspond to the following combinations of flags:
20505 **
20506 **     ReadWrite() ->     (READWRITE | CREATE)
20507 **     ReadOnly()  ->     (READONLY) 
20508 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
20509 **
20510 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
20511 ** true, the file was configured to be automatically deleted when the
20512 ** file handle closed. To achieve the same effect using this new 
20513 ** interface, add the DELETEONCLOSE flag to those specified above for 
20514 ** OpenExclusive().
20515 */
20516 static int unixOpen(
20517   sqlite3_vfs *pVfs, 
20518   const char *zPath, 
20519   sqlite3_file *pFile,
20520   int flags,
20521   int *pOutFlags
20522 ){
20523   int fd = 0;                    /* File descriptor returned by open() */
20524   int dirfd = -1;                /* Directory file descriptor */
20525   int oflags = 0;                /* Flags to pass to open() */
20526   int eType = flags&0xFFFFFF00;  /* Type of file to open */
20527
20528   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
20529   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
20530   int isCreate     = (flags & SQLITE_OPEN_CREATE);
20531   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
20532   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
20533
20534   /* If creating a master or main-file journal, this function will open
20535   ** a file-descriptor on the directory too. The first time unixSync()
20536   ** is called the directory file descriptor will be fsync()ed and close()d.
20537   */
20538   int isOpenDirectory = (isCreate && 
20539       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
20540   );
20541
20542   /* Check the following statements are true: 
20543   **
20544   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
20545   **   (b) if CREATE is set, then READWRITE must also be set, and
20546   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
20547   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
20548   */
20549   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
20550   assert(isCreate==0 || isReadWrite);
20551   assert(isExclusive==0 || isCreate);
20552   assert(isDelete==0 || isCreate);
20553
20554
20555   /* The main DB, main journal, and master journal are never automatically
20556   ** deleted
20557   */
20558   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
20559   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
20560   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
20561
20562   /* Assert that the upper layer has set one of the "file-type" flags. */
20563   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
20564        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
20565        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
20566        || eType==SQLITE_OPEN_TRANSIENT_DB
20567   );
20568
20569   if( isReadonly )  oflags |= O_RDONLY;
20570   if( isReadWrite ) oflags |= O_RDWR;
20571   if( isCreate )    oflags |= O_CREAT;
20572   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
20573   oflags |= (O_LARGEFILE|O_BINARY);
20574
20575   memset(pFile, 0, sizeof(unixFile));
20576   fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
20577   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
20578     /* Failed to open the file for read/write access. Try read-only. */
20579     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
20580     flags |= SQLITE_OPEN_READONLY;
20581     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
20582   }
20583   if( fd<0 ){
20584     return SQLITE_CANTOPEN;
20585   }
20586   if( isDelete ){
20587     unlink(zPath);
20588   }
20589   if( pOutFlags ){
20590     *pOutFlags = flags;
20591   }
20592
20593   assert(fd!=0);
20594   if( isOpenDirectory ){
20595     int rc = openDirectory(zPath, &dirfd);
20596     if( rc!=SQLITE_OK ){
20597       close(fd);
20598       return rc;
20599     }
20600   }
20601   return fillInUnixFile(fd, dirfd, pFile, zPath);
20602 }
20603
20604 /*
20605 ** Delete the file at zPath. If the dirSync argument is true, fsync()
20606 ** the directory after deleting the file.
20607 */
20608 static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
20609   int rc = SQLITE_OK;
20610   SimulateIOError(return SQLITE_IOERR_DELETE);
20611   unlink(zPath);
20612   if( dirSync ){
20613     int fd;
20614     rc = openDirectory(zPath, &fd);
20615     if( rc==SQLITE_OK ){
20616       if( fsync(fd) ){
20617         rc = SQLITE_IOERR_DIR_FSYNC;
20618       }
20619       close(fd);
20620     }
20621   }
20622   return rc;
20623 }
20624
20625 /*
20626 ** Test the existance of or access permissions of file zPath. The
20627 ** test performed depends on the value of flags:
20628 **
20629 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
20630 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
20631 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
20632 **
20633 ** Otherwise return 0.
20634 */
20635 static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
20636   int amode = 0;
20637   switch( flags ){
20638     case SQLITE_ACCESS_EXISTS:
20639       amode = F_OK;
20640       break;
20641     case SQLITE_ACCESS_READWRITE:
20642       amode = W_OK|R_OK;
20643       break;
20644     case SQLITE_ACCESS_READ:
20645       amode = R_OK;
20646       break;
20647
20648     default:
20649       assert(!"Invalid flags argument");
20650   }
20651   return (access(zPath, amode)==0);
20652 }
20653
20654 /*
20655 ** Create a temporary file name in zBuf.  zBuf must be allocated
20656 ** by the calling process and must be big enough to hold at least
20657 ** pVfs->mxPathname bytes.
20658 */
20659 static int unixGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
20660   static const char *azDirs[] = {
20661      0,
20662      "/var/tmp",
20663      "/usr/tmp",
20664      "/tmp",
20665      ".",
20666   };
20667   static const unsigned char zChars[] =
20668     "abcdefghijklmnopqrstuvwxyz"
20669     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20670     "0123456789";
20671   int i, j;
20672   struct stat buf;
20673   const char *zDir = ".";
20674
20675   /* It's odd to simulate an io-error here, but really this is just
20676   ** using the io-error infrastructure to test that SQLite handles this
20677   ** function failing. 
20678   */
20679   SimulateIOError( return SQLITE_ERROR );
20680
20681   azDirs[0] = sqlite3_temp_directory;
20682   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
20683     if( azDirs[i]==0 ) continue;
20684     if( stat(azDirs[i], &buf) ) continue;
20685     if( !S_ISDIR(buf.st_mode) ) continue;
20686     if( access(azDirs[i], 07) ) continue;
20687     zDir = azDirs[i];
20688     break;
20689   }
20690   if( strlen(zDir) - sizeof(SQLITE_TEMP_FILE_PREFIX) - 17 <=0 ){
20691     return SQLITE_ERROR;
20692   }
20693   do{
20694     assert( pVfs->mxPathname==MAX_PATHNAME );
20695     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
20696     j = strlen(zBuf);
20697     sqlite3Randomness(15, &zBuf[j]);
20698     for(i=0; i<15; i++, j++){
20699       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20700     }
20701     zBuf[j] = 0;
20702   }while( access(zBuf,0)==0 );
20703   return SQLITE_OK;
20704 }
20705
20706
20707 /*
20708 ** Turn a relative pathname into a full pathname. The relative path
20709 ** is stored as a nul-terminated string in the buffer pointed to by
20710 ** zPath. 
20711 **
20712 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
20713 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
20714 ** this buffer before returning.
20715 */
20716 static int unixFullPathname(
20717   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
20718   const char *zPath,            /* Possibly relative input path */
20719   int nOut,                     /* Size of output buffer in bytes */
20720   char *zOut                    /* Output buffer */
20721 ){
20722
20723   /* It's odd to simulate an io-error here, but really this is just
20724   ** using the io-error infrastructure to test that SQLite handles this
20725   ** function failing. This function could fail if, for example, the
20726   ** current working directly has been unlinked.
20727   */
20728   SimulateIOError( return SQLITE_ERROR );
20729
20730   assert( pVfs->mxPathname==MAX_PATHNAME );
20731   zOut[nOut-1] = '\0';
20732   if( zPath[0]=='/' ){
20733     sqlite3_snprintf(nOut, zOut, "%s", zPath);
20734   }else{
20735     int nCwd;
20736     if( getcwd(zOut, nOut-1)==0 ){
20737       return SQLITE_CANTOPEN;
20738     }
20739     nCwd = strlen(zOut);
20740     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
20741   }
20742   return SQLITE_OK;
20743
20744 #if 0
20745   /*
20746   ** Remove "/./" path elements and convert "/A/./" path elements
20747   ** to just "/".
20748   */
20749   if( zFull ){
20750     int i, j;
20751     for(i=j=0; zFull[i]; i++){
20752       if( zFull[i]=='/' ){
20753         if( zFull[i+1]=='/' ) continue;
20754         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
20755           i += 1;
20756           continue;
20757         }
20758         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
20759           while( j>0 && zFull[j-1]!='/' ){ j--; }
20760           i += 3;
20761           continue;
20762         }
20763       }
20764       zFull[j++] = zFull[i];
20765     }
20766     zFull[j] = 0;
20767   }
20768 #endif
20769 }
20770
20771
20772 #ifndef SQLITE_OMIT_LOAD_EXTENSION
20773 /*
20774 ** Interfaces for opening a shared library, finding entry points
20775 ** within the shared library, and closing the shared library.
20776 */
20777 #include <dlfcn.h>
20778 static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
20779   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
20780 }
20781
20782 /*
20783 ** SQLite calls this function immediately after a call to unixDlSym() or
20784 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
20785 ** message is available, it is written to zBufOut. If no error message
20786 ** is available, zBufOut is left unmodified and SQLite uses a default
20787 ** error message.
20788 */
20789 static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
20790   char *zErr;
20791   enterMutex();
20792   zErr = dlerror();
20793   if( zErr ){
20794     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
20795   }
20796   leaveMutex();
20797 }
20798 static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
20799   return dlsym(pHandle, zSymbol);
20800 }
20801 static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
20802   dlclose(pHandle);
20803 }
20804 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
20805   #define unixDlOpen  0
20806   #define unixDlError 0
20807   #define unixDlSym   0
20808   #define unixDlClose 0
20809 #endif
20810
20811 /*
20812 ** Write nBuf bytes of random data to the supplied buffer zBuf.
20813 */
20814 static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
20815
20816   assert(nBuf>=(sizeof(time_t)+sizeof(int)));
20817
20818   /* We have to initialize zBuf to prevent valgrind from reporting
20819   ** errors.  The reports issued by valgrind are incorrect - we would
20820   ** prefer that the randomness be increased by making use of the
20821   ** uninitialized space in zBuf - but valgrind errors tend to worry
20822   ** some users.  Rather than argue, it seems easier just to initialize
20823   ** the whole array and silence valgrind, even if that means less randomness
20824   ** in the random seed.
20825   **
20826   ** When testing, initializing zBuf[] to zero is all we do.  That means
20827   ** that we always use the same random number sequence.  This makes the
20828   ** tests repeatable.
20829   */
20830   memset(zBuf, 0, nBuf);
20831 #if !defined(SQLITE_TEST)
20832   {
20833     int pid, fd;
20834     fd = open("/dev/urandom", O_RDONLY);
20835     if( fd<0 ){
20836       time_t t;
20837       time(&t);
20838       memcpy(zBuf, &t, sizeof(t));
20839       pid = getpid();
20840       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
20841     }else{
20842       read(fd, zBuf, nBuf);
20843       close(fd);
20844     }
20845   }
20846 #endif
20847   return SQLITE_OK;
20848 }
20849
20850
20851 /*
20852 ** Sleep for a little while.  Return the amount of time slept.
20853 ** The argument is the number of microseconds we want to sleep.
20854 ** The return value is the number of microseconds of sleep actually
20855 ** requested from the underlying operating system, a number which
20856 ** might be greater than or equal to the argument, but not less
20857 ** than the argument.
20858 */
20859 static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
20860 #if defined(HAVE_USLEEP) && HAVE_USLEEP
20861   usleep(microseconds);
20862   return microseconds;
20863 #else
20864   int seconds = (microseconds+999999)/1000000;
20865   sleep(seconds);
20866   return seconds*1000000;
20867 #endif
20868 }
20869
20870 /*
20871 ** The following variable, if set to a non-zero value, becomes the result
20872 ** returned from sqlite3OsCurrentTime().  This is used for testing.
20873 */
20874 #ifdef SQLITE_TEST
20875 SQLITE_API int sqlite3_current_time = 0;
20876 #endif
20877
20878 /*
20879 ** Find the current time (in Universal Coordinated Time).  Write the
20880 ** current time and date as a Julian Day number into *prNow and
20881 ** return 0.  Return 1 if the time and date cannot be found.
20882 */
20883 static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
20884 #ifdef NO_GETTOD
20885   time_t t;
20886   time(&t);
20887   *prNow = t/86400.0 + 2440587.5;
20888 #else
20889   struct timeval sNow;
20890   gettimeofday(&sNow, 0);
20891   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
20892 #endif
20893 #ifdef SQLITE_TEST
20894   if( sqlite3_current_time ){
20895     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
20896   }
20897 #endif
20898   return 0;
20899 }
20900
20901 /*
20902 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
20903 ** a function rather than give the structure global scope because
20904 ** some compilers (MSVC) do not allow forward declarations of
20905 ** initialized structures.
20906 */
20907 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
20908   static sqlite3_vfs unixVfs = {
20909     1,                  /* iVersion */
20910     sizeof(unixFile),   /* szOsFile */
20911     MAX_PATHNAME,       /* mxPathname */
20912     0,                  /* pNext */
20913     "unix",             /* zName */
20914     0,                  /* pAppData */
20915   
20916     unixOpen,           /* xOpen */
20917     unixDelete,         /* xDelete */
20918     unixAccess,         /* xAccess */
20919     unixGetTempname,    /* xGetTempName */
20920     unixFullPathname,   /* xFullPathname */
20921     unixDlOpen,         /* xDlOpen */
20922     unixDlError,        /* xDlError */
20923     unixDlSym,          /* xDlSym */
20924     unixDlClose,        /* xDlClose */
20925     unixRandomness,     /* xRandomness */
20926     unixSleep,          /* xSleep */
20927     unixCurrentTime     /* xCurrentTime */
20928   };
20929   
20930   return &unixVfs;
20931 }
20932  
20933 #endif /* OS_UNIX */
20934
20935 /************** End of os_unix.c *********************************************/
20936 /************** Begin file os_win.c ******************************************/
20937 /*
20938 ** 2004 May 22
20939 **
20940 ** The author disclaims copyright to this source code.  In place of
20941 ** a legal notice, here is a blessing:
20942 **
20943 **    May you do good and not evil.
20944 **    May you find forgiveness for yourself and forgive others.
20945 **    May you share freely, never taking more than you give.
20946 **
20947 ******************************************************************************
20948 **
20949 ** This file contains code that is specific to windows.
20950 */
20951 #if OS_WIN               /* This file is used for windows only */
20952
20953
20954 /*
20955 ** A Note About Memory Allocation:
20956 **
20957 ** This driver uses malloc()/free() directly rather than going through
20958 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20959 ** are designed for use on embedded systems where memory is scarce and
20960 ** malloc failures happen frequently.  Win32 does not typically run on
20961 ** embedded systems, and when it does the developers normally have bigger
20962 ** problems to worry about than running out of memory.  So there is not
20963 ** a compelling need to use the wrappers.
20964 **
20965 ** But there is a good reason to not use the wrappers.  If we use the
20966 ** wrappers then we will get simulated malloc() failures within this
20967 ** driver.  And that causes all kinds of problems for our tests.  We
20968 ** could enhance SQLite to deal with simulated malloc failures within
20969 ** the OS driver, but the code to deal with those failure would not
20970 ** be exercised on Linux (which does not need to malloc() in the driver)
20971 ** and so we would have difficulty writing coverage tests for that
20972 ** code.  Better to leave the code out, we think.
20973 **
20974 ** The point of this discussion is as follows:  When creating a new
20975 ** OS layer for an embedded system, if you use this file as an example,
20976 ** avoid the use of malloc()/free().  Those routines work ok on windows
20977 ** desktops but not so well in embedded systems.
20978 */
20979
20980 #include <winbase.h>
20981
20982 #ifdef __CYGWIN__
20983 # include <sys/cygwin.h>
20984 #endif
20985
20986 /*
20987 ** Macros used to determine whether or not to use threads.
20988 */
20989 #if defined(THREADSAFE) && THREADSAFE
20990 # define SQLITE_W32_THREADS 1
20991 #endif
20992
20993 /*
20994 ** Include code that is common to all os_*.c files
20995 */
20996 /************** Include os_common.h in the middle of os_win.c ****************/
20997 /************** Begin file os_common.h ***************************************/
20998 /*
20999 ** 2004 May 22
21000 **
21001 ** The author disclaims copyright to this source code.  In place of
21002 ** a legal notice, here is a blessing:
21003 **
21004 **    May you do good and not evil.
21005 **    May you find forgiveness for yourself and forgive others.
21006 **    May you share freely, never taking more than you give.
21007 **
21008 ******************************************************************************
21009 **
21010 ** This file contains macros and a little bit of code that is common to
21011 ** all of the platform-specific files (os_*.c) and is #included into those
21012 ** files.
21013 **
21014 ** This file should be #included by the os_*.c files only.  It is not a
21015 ** general purpose header file.
21016 */
21017
21018 /*
21019 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21020 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21021 ** switch.  The following code should catch this problem at compile-time.
21022 */
21023 #ifdef MEMORY_DEBUG
21024 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21025 #endif
21026
21027
21028 /*
21029  * When testing, this global variable stores the location of the
21030  * pending-byte in the database file.
21031  */
21032 #ifdef SQLITE_TEST
21033 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
21034 #endif
21035
21036 #ifdef SQLITE_DEBUG
21037 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21038 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21039 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21040 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21041 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21042 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21043 #define OSTRACE6(X,Y,Z,A,B,C) \
21044     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21045 #define OSTRACE7(X,Y,Z,A,B,C,D) \
21046     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21047 #else
21048 #define OSTRACE1(X)
21049 #define OSTRACE2(X,Y)
21050 #define OSTRACE3(X,Y,Z)
21051 #define OSTRACE4(X,Y,Z,A)
21052 #define OSTRACE5(X,Y,Z,A,B)
21053 #define OSTRACE6(X,Y,Z,A,B,C)
21054 #define OSTRACE7(X,Y,Z,A,B,C,D)
21055 #endif
21056
21057 /*
21058 ** Macros for performance tracing.  Normally turned off.  Only works
21059 ** on i486 hardware.
21060 */
21061 #ifdef SQLITE_PERFORMANCE_TRACE
21062 __inline__ unsigned long long int hwtime(void){
21063   unsigned long long int x;
21064   __asm__("rdtsc\n\t"
21065           "mov %%edx, %%ecx\n\t"
21066           :"=A" (x));
21067   return x;
21068 }
21069 static unsigned long long int g_start;
21070 static unsigned int elapse;
21071 #define TIMER_START       g_start=hwtime()
21072 #define TIMER_END         elapse=hwtime()-g_start
21073 #define TIMER_ELAPSED     elapse
21074 #else
21075 #define TIMER_START
21076 #define TIMER_END
21077 #define TIMER_ELAPSED     0
21078 #endif
21079
21080 /*
21081 ** If we compile with the SQLITE_TEST macro set, then the following block
21082 ** of code will give us the ability to simulate a disk I/O error.  This
21083 ** is used for testing the I/O recovery logic.
21084 */
21085 #ifdef SQLITE_TEST
21086 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21087 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21088 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21089 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21090 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21091 SQLITE_API int sqlite3_diskfull_pending = 0;
21092 SQLITE_API int sqlite3_diskfull = 0;
21093 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21094 #define SimulateIOError(CODE)  \
21095   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21096        || sqlite3_io_error_pending-- == 1 )  \
21097               { local_ioerr(); CODE; }
21098 static void local_ioerr(){
21099   IOTRACE(("IOERR\n"));
21100   sqlite3_io_error_hit++;
21101   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21102 }
21103 #define SimulateDiskfullError(CODE) \
21104    if( sqlite3_diskfull_pending ){ \
21105      if( sqlite3_diskfull_pending == 1 ){ \
21106        local_ioerr(); \
21107        sqlite3_diskfull = 1; \
21108        sqlite3_io_error_hit = 1; \
21109        CODE; \
21110      }else{ \
21111        sqlite3_diskfull_pending--; \
21112      } \
21113    }
21114 #else
21115 #define SimulateIOErrorBenign(X)
21116 #define SimulateIOError(A)
21117 #define SimulateDiskfullError(A)
21118 #endif
21119
21120 /*
21121 ** When testing, keep a count of the number of open files.
21122 */
21123 #ifdef SQLITE_TEST
21124 SQLITE_API int sqlite3_open_file_count = 0;
21125 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21126 #else
21127 #define OpenCounter(X)
21128 #endif
21129
21130 /************** End of os_common.h *******************************************/
21131 /************** Continuing where we left off in os_win.c *********************/
21132
21133 /*
21134 ** Determine if we are dealing with WindowsCE - which has a much
21135 ** reduced API.
21136 */
21137 #if defined(_WIN32_WCE)
21138 # define OS_WINCE 1
21139 # define AreFileApisANSI() 1
21140 #else
21141 # define OS_WINCE 0
21142 #endif
21143
21144 /*
21145 ** WinCE lacks native support for file locking so we have to fake it
21146 ** with some code of our own.
21147 */
21148 #if OS_WINCE
21149 typedef struct winceLock {
21150   int nReaders;       /* Number of reader locks obtained */
21151   BOOL bPending;      /* Indicates a pending lock has been obtained */
21152   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
21153   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
21154 } winceLock;
21155 #endif
21156
21157 /*
21158 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
21159 ** portability layer.
21160 */
21161 typedef struct winFile winFile;
21162 struct winFile {
21163   const sqlite3_io_methods *pMethod;/* Must be first */
21164   HANDLE h;               /* Handle for accessing the file */
21165   unsigned char locktype; /* Type of lock currently held on this file */
21166   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
21167 #if OS_WINCE
21168   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
21169   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
21170   HANDLE hShared;         /* Shared memory segment used for locking */
21171   winceLock local;        /* Locks obtained by this instance of winFile */
21172   winceLock *shared;      /* Global shared lock memory for the file  */
21173 #endif
21174 };
21175
21176
21177 /*
21178 ** The following variable is (normally) set once and never changes
21179 ** thereafter.  It records whether the operating system is Win95
21180 ** or WinNT.
21181 **
21182 ** 0:   Operating system unknown.
21183 ** 1:   Operating system is Win95.
21184 ** 2:   Operating system is WinNT.
21185 **
21186 ** In order to facilitate testing on a WinNT system, the test fixture
21187 ** can manually set this value to 1 to emulate Win98 behavior.
21188 */
21189 #ifdef SQLITE_TEST
21190 SQLITE_API int sqlite3_os_type = 0;
21191 #else
21192 static int sqlite3_os_type = 0;
21193 #endif
21194
21195 /*
21196 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
21197 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
21198 **
21199 ** Here is an interesting observation:  Win95, Win98, and WinME lack
21200 ** the LockFileEx() API.  But we can still statically link against that
21201 ** API as long as we don't call it win running Win95/98/ME.  A call to
21202 ** this routine is used to determine if the host is Win95/98/ME or
21203 ** WinNT/2K/XP so that we will know whether or not we can safely call
21204 ** the LockFileEx() API.
21205 */
21206 #if OS_WINCE
21207 # define isNT()  (1)
21208 #else
21209   static int isNT(void){
21210     if( sqlite3_os_type==0 ){
21211       OSVERSIONINFO sInfo;
21212       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
21213       GetVersionEx(&sInfo);
21214       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
21215     }
21216     return sqlite3_os_type==2;
21217   }
21218 #endif /* OS_WINCE */
21219
21220 /*
21221 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
21222 **
21223 ** Space to hold the returned string is obtained from malloc.
21224 */
21225 static WCHAR *utf8ToUnicode(const char *zFilename){
21226   int nChar;
21227   WCHAR *zWideFilename;
21228
21229   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
21230   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
21231   if( zWideFilename==0 ){
21232     return 0;
21233   }
21234   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
21235   if( nChar==0 ){
21236     free(zWideFilename);
21237     zWideFilename = 0;
21238   }
21239   return zWideFilename;
21240 }
21241
21242 /*
21243 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
21244 ** obtained from malloc().
21245 */
21246 static char *unicodeToUtf8(const WCHAR *zWideFilename){
21247   int nByte;
21248   char *zFilename;
21249
21250   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
21251   zFilename = malloc( nByte );
21252   if( zFilename==0 ){
21253     return 0;
21254   }
21255   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
21256                               0, 0);
21257   if( nByte == 0 ){
21258     free(zFilename);
21259     zFilename = 0;
21260   }
21261   return zFilename;
21262 }
21263
21264 /*
21265 ** Convert an ansi string to microsoft unicode, based on the
21266 ** current codepage settings for file apis.
21267 ** 
21268 ** Space to hold the returned string is obtained
21269 ** from malloc.
21270 */
21271 static WCHAR *mbcsToUnicode(const char *zFilename){
21272   int nByte;
21273   WCHAR *zMbcsFilename;
21274   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
21275
21276   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
21277   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
21278   if( zMbcsFilename==0 ){
21279     return 0;
21280   }
21281   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
21282   if( nByte==0 ){
21283     free(zMbcsFilename);
21284     zMbcsFilename = 0;
21285   }
21286   return zMbcsFilename;
21287 }
21288
21289 /*
21290 ** Convert microsoft unicode to multibyte character string, based on the
21291 ** user's Ansi codepage.
21292 **
21293 ** Space to hold the returned string is obtained from
21294 ** malloc().
21295 */
21296 static char *unicodeToMbcs(const WCHAR *zWideFilename){
21297   int nByte;
21298   char *zFilename;
21299   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
21300
21301   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
21302   zFilename = malloc( nByte );
21303   if( zFilename==0 ){
21304     return 0;
21305   }
21306   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
21307                               0, 0);
21308   if( nByte == 0 ){
21309     free(zFilename);
21310     zFilename = 0;
21311   }
21312   return zFilename;
21313 }
21314
21315 /*
21316 ** Convert multibyte character string to UTF-8.  Space to hold the
21317 ** returned string is obtained from malloc().
21318 */
21319 static char *mbcsToUtf8(const char *zFilename){
21320   char *zFilenameUtf8;
21321   WCHAR *zTmpWide;
21322
21323   zTmpWide = mbcsToUnicode(zFilename);
21324   if( zTmpWide==0 ){
21325     return 0;
21326   }
21327   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
21328   free(zTmpWide);
21329   return zFilenameUtf8;
21330 }
21331
21332 /*
21333 ** Convert UTF-8 to multibyte character string.  Space to hold the 
21334 ** returned string is obtained from malloc().
21335 */
21336 static char *utf8ToMbcs(const char *zFilename){
21337   char *zFilenameMbcs;
21338   WCHAR *zTmpWide;
21339
21340   zTmpWide = utf8ToUnicode(zFilename);
21341   if( zTmpWide==0 ){
21342     return 0;
21343   }
21344   zFilenameMbcs = unicodeToMbcs(zTmpWide);
21345   free(zTmpWide);
21346   return zFilenameMbcs;
21347 }
21348
21349 #if OS_WINCE
21350 /*************************************************************************
21351 ** This section contains code for WinCE only.
21352 */
21353 /*
21354 ** WindowsCE does not have a localtime() function.  So create a
21355 ** substitute.
21356 */
21357 struct tm *__cdecl localtime(const time_t *t)
21358 {
21359   static struct tm y;
21360   FILETIME uTm, lTm;
21361   SYSTEMTIME pTm;
21362   sqlite3_int64 t64;
21363   t64 = *t;
21364   t64 = (t64 + 11644473600)*10000000;
21365   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
21366   uTm.dwHighDateTime= t64 >> 32;
21367   FileTimeToLocalFileTime(&uTm,&lTm);
21368   FileTimeToSystemTime(&lTm,&pTm);
21369   y.tm_year = pTm.wYear - 1900;
21370   y.tm_mon = pTm.wMonth - 1;
21371   y.tm_wday = pTm.wDayOfWeek;
21372   y.tm_mday = pTm.wDay;
21373   y.tm_hour = pTm.wHour;
21374   y.tm_min = pTm.wMinute;
21375   y.tm_sec = pTm.wSecond;
21376   return &y;
21377 }
21378
21379 /* This will never be called, but defined to make the code compile */
21380 #define GetTempPathA(a,b)
21381
21382 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
21383 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
21384 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
21385
21386 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
21387
21388 /*
21389 ** Acquire a lock on the handle h
21390 */
21391 static void winceMutexAcquire(HANDLE h){
21392    DWORD dwErr;
21393    do {
21394      dwErr = WaitForSingleObject(h, INFINITE);
21395    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
21396 }
21397 /*
21398 ** Release a lock acquired by winceMutexAcquire()
21399 */
21400 #define winceMutexRelease(h) ReleaseMutex(h)
21401
21402 /*
21403 ** Create the mutex and shared memory used for locking in the file
21404 ** descriptor pFile
21405 */
21406 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
21407   WCHAR *zTok;
21408   WCHAR *zName = utf8ToUnicode(zFilename);
21409   BOOL bInit = TRUE;
21410
21411   /* Initialize the local lockdata */
21412   ZeroMemory(&pFile->local, sizeof(pFile->local));
21413
21414   /* Replace the backslashes from the filename and lowercase it
21415   ** to derive a mutex name. */
21416   zTok = CharLowerW(zName);
21417   for (;*zTok;zTok++){
21418     if (*zTok == '\\') *zTok = '_';
21419   }
21420
21421   /* Create/open the named mutex */
21422   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
21423   if (!pFile->hMutex){
21424     free(zName);
21425     return FALSE;
21426   }
21427
21428   /* Acquire the mutex before continuing */
21429   winceMutexAcquire(pFile->hMutex);
21430   
21431   /* Since the names of named mutexes, semaphores, file mappings etc are 
21432   ** case-sensitive, take advantage of that by uppercasing the mutex name
21433   ** and using that as the shared filemapping name.
21434   */
21435   CharUpperW(zName);
21436   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
21437                                        PAGE_READWRITE, 0, sizeof(winceLock),
21438                                        zName);  
21439
21440   /* Set a flag that indicates we're the first to create the memory so it 
21441   ** must be zero-initialized */
21442   if (GetLastError() == ERROR_ALREADY_EXISTS){
21443     bInit = FALSE;
21444   }
21445
21446   free(zName);
21447
21448   /* If we succeeded in making the shared memory handle, map it. */
21449   if (pFile->hShared){
21450     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
21451              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
21452     /* If mapping failed, close the shared memory handle and erase it */
21453     if (!pFile->shared){
21454       CloseHandle(pFile->hShared);
21455       pFile->hShared = NULL;
21456     }
21457   }
21458
21459   /* If shared memory could not be created, then close the mutex and fail */
21460   if (pFile->hShared == NULL){
21461     winceMutexRelease(pFile->hMutex);
21462     CloseHandle(pFile->hMutex);
21463     pFile->hMutex = NULL;
21464     return FALSE;
21465   }
21466   
21467   /* Initialize the shared memory if we're supposed to */
21468   if (bInit) {
21469     ZeroMemory(pFile->shared, sizeof(winceLock));
21470   }
21471
21472   winceMutexRelease(pFile->hMutex);
21473   return TRUE;
21474 }
21475
21476 /*
21477 ** Destroy the part of winFile that deals with wince locks
21478 */
21479 static void winceDestroyLock(winFile *pFile){
21480   if (pFile->hMutex){
21481     /* Acquire the mutex */
21482     winceMutexAcquire(pFile->hMutex);
21483
21484     /* The following blocks should probably assert in debug mode, but they
21485        are to cleanup in case any locks remained open */
21486     if (pFile->local.nReaders){
21487       pFile->shared->nReaders --;
21488     }
21489     if (pFile->local.bReserved){
21490       pFile->shared->bReserved = FALSE;
21491     }
21492     if (pFile->local.bPending){
21493       pFile->shared->bPending = FALSE;
21494     }
21495     if (pFile->local.bExclusive){
21496       pFile->shared->bExclusive = FALSE;
21497     }
21498
21499     /* De-reference and close our copy of the shared memory handle */
21500     UnmapViewOfFile(pFile->shared);
21501     CloseHandle(pFile->hShared);
21502
21503     /* Done with the mutex */
21504     winceMutexRelease(pFile->hMutex);    
21505     CloseHandle(pFile->hMutex);
21506     pFile->hMutex = NULL;
21507   }
21508 }
21509
21510 /* 
21511 ** An implementation of the LockFile() API of windows for wince
21512 */
21513 static BOOL winceLockFile(
21514   HANDLE *phFile,
21515   DWORD dwFileOffsetLow,
21516   DWORD dwFileOffsetHigh,
21517   DWORD nNumberOfBytesToLockLow,
21518   DWORD nNumberOfBytesToLockHigh
21519 ){
21520   winFile *pFile = HANDLE_TO_WINFILE(phFile);
21521   BOOL bReturn = FALSE;
21522
21523   if (!pFile->hMutex) return TRUE;
21524   winceMutexAcquire(pFile->hMutex);
21525
21526   /* Wanting an exclusive lock? */
21527   if (dwFileOffsetLow == SHARED_FIRST
21528        && nNumberOfBytesToLockLow == SHARED_SIZE){
21529     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
21530        pFile->shared->bExclusive = TRUE;
21531        pFile->local.bExclusive = TRUE;
21532        bReturn = TRUE;
21533     }
21534   }
21535
21536   /* Want a read-only lock? */
21537   else if ((dwFileOffsetLow >= SHARED_FIRST &&
21538             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
21539             nNumberOfBytesToLockLow == 1){
21540     if (pFile->shared->bExclusive == 0){
21541       pFile->local.nReaders ++;
21542       if (pFile->local.nReaders == 1){
21543         pFile->shared->nReaders ++;
21544       }
21545       bReturn = TRUE;
21546     }
21547   }
21548
21549   /* Want a pending lock? */
21550   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
21551     /* If no pending lock has been acquired, then acquire it */
21552     if (pFile->shared->bPending == 0) {
21553       pFile->shared->bPending = TRUE;
21554       pFile->local.bPending = TRUE;
21555       bReturn = TRUE;
21556     }
21557   }
21558   /* Want a reserved lock? */
21559   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
21560     if (pFile->shared->bReserved == 0) {
21561       pFile->shared->bReserved = TRUE;
21562       pFile->local.bReserved = TRUE;
21563       bReturn = TRUE;
21564     }
21565   }
21566
21567   winceMutexRelease(pFile->hMutex);
21568   return bReturn;
21569 }
21570
21571 /*
21572 ** An implementation of the UnlockFile API of windows for wince
21573 */
21574 static BOOL winceUnlockFile(
21575   HANDLE *phFile,
21576   DWORD dwFileOffsetLow,
21577   DWORD dwFileOffsetHigh,
21578   DWORD nNumberOfBytesToUnlockLow,
21579   DWORD nNumberOfBytesToUnlockHigh
21580 ){
21581   winFile *pFile = HANDLE_TO_WINFILE(phFile);
21582   BOOL bReturn = FALSE;
21583
21584   if (!pFile->hMutex) return TRUE;
21585   winceMutexAcquire(pFile->hMutex);
21586
21587   /* Releasing a reader lock or an exclusive lock */
21588   if (dwFileOffsetLow >= SHARED_FIRST &&
21589        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
21590     /* Did we have an exclusive lock? */
21591     if (pFile->local.bExclusive){
21592       pFile->local.bExclusive = FALSE;
21593       pFile->shared->bExclusive = FALSE;
21594       bReturn = TRUE;
21595     }
21596
21597     /* Did we just have a reader lock? */
21598     else if (pFile->local.nReaders){
21599       pFile->local.nReaders --;
21600       if (pFile->local.nReaders == 0)
21601       {
21602         pFile->shared->nReaders --;
21603       }
21604       bReturn = TRUE;
21605     }
21606   }
21607
21608   /* Releasing a pending lock */
21609   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
21610     if (pFile->local.bPending){
21611       pFile->local.bPending = FALSE;
21612       pFile->shared->bPending = FALSE;
21613       bReturn = TRUE;
21614     }
21615   }
21616   /* Releasing a reserved lock */
21617   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
21618     if (pFile->local.bReserved) {
21619       pFile->local.bReserved = FALSE;
21620       pFile->shared->bReserved = FALSE;
21621       bReturn = TRUE;
21622     }
21623   }
21624
21625   winceMutexRelease(pFile->hMutex);
21626   return bReturn;
21627 }
21628
21629 /*
21630 ** An implementation of the LockFileEx() API of windows for wince
21631 */
21632 static BOOL winceLockFileEx(
21633   HANDLE *phFile,
21634   DWORD dwFlags,
21635   DWORD dwReserved,
21636   DWORD nNumberOfBytesToLockLow,
21637   DWORD nNumberOfBytesToLockHigh,
21638   LPOVERLAPPED lpOverlapped
21639 ){
21640   /* If the caller wants a shared read lock, forward this call
21641   ** to winceLockFile */
21642   if (lpOverlapped->Offset == SHARED_FIRST &&
21643       dwFlags == 1 &&
21644       nNumberOfBytesToLockLow == SHARED_SIZE){
21645     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
21646   }
21647   return FALSE;
21648 }
21649 /*
21650 ** End of the special code for wince
21651 *****************************************************************************/
21652 #endif /* OS_WINCE */
21653
21654 /*****************************************************************************
21655 ** The next group of routines implement the I/O methods specified
21656 ** by the sqlite3_io_methods object.
21657 ******************************************************************************/
21658
21659 /*
21660 ** Close a file.
21661 **
21662 ** It is reported that an attempt to close a handle might sometimes
21663 ** fail.  This is a very unreasonable result, but windows is notorious
21664 ** for being unreasonable so I do not doubt that it might happen.  If
21665 ** the close fails, we pause for 100 milliseconds and try again.  As
21666 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
21667 ** giving up and returning an error.
21668 */
21669 #define MX_CLOSE_ATTEMPT 3
21670 static int winClose(sqlite3_file *id){
21671   int rc, cnt = 0;
21672   winFile *pFile = (winFile*)id;
21673   OSTRACE2("CLOSE %d\n", pFile->h);
21674   do{
21675     rc = CloseHandle(pFile->h);
21676   }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
21677 #if OS_WINCE
21678 #define WINCE_DELETION_ATTEMPTS 3
21679   winceDestroyLock(pFile);
21680   if( pFile->zDeleteOnClose ){
21681     int cnt = 0;
21682     while(
21683            DeleteFileW(pFile->zDeleteOnClose)==0
21684         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
21685         && cnt++ < WINCE_DELETION_ATTEMPTS
21686     ){
21687        Sleep(100);  /* Wait a little before trying again */
21688     }
21689     free(pFile->zDeleteOnClose);
21690   }
21691 #endif
21692   OpenCounter(-1);
21693   return rc ? SQLITE_OK : SQLITE_IOERR;
21694 }
21695
21696 /*
21697 ** Some microsoft compilers lack this definition.
21698 */
21699 #ifndef INVALID_SET_FILE_POINTER
21700 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
21701 #endif
21702
21703 /*
21704 ** Read data from a file into a buffer.  Return SQLITE_OK if all
21705 ** bytes were read successfully and SQLITE_IOERR if anything goes
21706 ** wrong.
21707 */
21708 static int winRead(
21709   sqlite3_file *id,          /* File to read from */
21710   void *pBuf,                /* Write content into this buffer */
21711   int amt,                   /* Number of bytes to read */
21712   sqlite3_int64 offset       /* Begin reading at this offset */
21713 ){
21714   LONG upperBits = (offset>>32) & 0x7fffffff;
21715   LONG lowerBits = offset & 0xffffffff;
21716   DWORD rc;
21717   DWORD got;
21718   winFile *pFile = (winFile*)id;
21719   assert( id!=0 );
21720   SimulateIOError(return SQLITE_IOERR_READ);
21721   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
21722   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
21723   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
21724     return SQLITE_FULL;
21725   }
21726   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
21727     return SQLITE_IOERR_READ;
21728   }
21729   if( got==(DWORD)amt ){
21730     return SQLITE_OK;
21731   }else{
21732     memset(&((char*)pBuf)[got], 0, amt-got);
21733     return SQLITE_IOERR_SHORT_READ;
21734   }
21735 }
21736
21737 /*
21738 ** Write data from a buffer into a file.  Return SQLITE_OK on success
21739 ** or some other error code on failure.
21740 */
21741 static int winWrite(
21742   sqlite3_file *id,         /* File to write into */
21743   const void *pBuf,         /* The bytes to be written */
21744   int amt,                  /* Number of bytes to write */
21745   sqlite3_int64 offset      /* Offset into the file to begin writing at */
21746 ){
21747   LONG upperBits = (offset>>32) & 0x7fffffff;
21748   LONG lowerBits = offset & 0xffffffff;
21749   DWORD rc;
21750   DWORD wrote;
21751   winFile *pFile = (winFile*)id;
21752   assert( id!=0 );
21753   SimulateIOError(return SQLITE_IOERR_WRITE);
21754   SimulateDiskfullError(return SQLITE_FULL);
21755   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
21756   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
21757   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
21758     return SQLITE_FULL;
21759   }
21760   assert( amt>0 );
21761   while(
21762      amt>0
21763      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
21764      && wrote>0
21765   ){
21766     amt -= wrote;
21767     pBuf = &((char*)pBuf)[wrote];
21768   }
21769   if( !rc || amt>(int)wrote ){
21770     return SQLITE_FULL;
21771   }
21772   return SQLITE_OK;
21773 }
21774
21775 /*
21776 ** Truncate an open file to a specified size
21777 */
21778 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
21779   LONG upperBits = (nByte>>32) & 0x7fffffff;
21780   LONG lowerBits = nByte & 0xffffffff;
21781   winFile *pFile = (winFile*)id;
21782   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
21783   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
21784   SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
21785   SetEndOfFile(pFile->h);
21786   return SQLITE_OK;
21787 }
21788
21789 #ifdef SQLITE_TEST
21790 /*
21791 ** Count the number of fullsyncs and normal syncs.  This is used to test
21792 ** that syncs and fullsyncs are occuring at the right times.
21793 */
21794 SQLITE_API int sqlite3_sync_count = 0;
21795 SQLITE_API int sqlite3_fullsync_count = 0;
21796 #endif
21797
21798 /*
21799 ** Make sure all writes to a particular file are committed to disk.
21800 */
21801 static int winSync(sqlite3_file *id, int flags){
21802   winFile *pFile = (winFile*)id;
21803   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
21804 #ifdef SQLITE_TEST
21805   if( flags & SQLITE_SYNC_FULL ){
21806     sqlite3_fullsync_count++;
21807   }
21808   sqlite3_sync_count++;
21809 #endif
21810   if( FlushFileBuffers(pFile->h) ){
21811     return SQLITE_OK;
21812   }else{
21813     return SQLITE_IOERR;
21814   }
21815 }
21816
21817 /*
21818 ** Determine the current size of a file in bytes
21819 */
21820 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
21821   winFile *pFile = (winFile*)id;
21822   DWORD upperBits, lowerBits;
21823   SimulateIOError(return SQLITE_IOERR_FSTAT);
21824   lowerBits = GetFileSize(pFile->h, &upperBits);
21825   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
21826   return SQLITE_OK;
21827 }
21828
21829 /*
21830 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
21831 */
21832 #ifndef LOCKFILE_FAIL_IMMEDIATELY
21833 # define LOCKFILE_FAIL_IMMEDIATELY 1
21834 #endif
21835
21836 /*
21837 ** Acquire a reader lock.
21838 ** Different API routines are called depending on whether or not this
21839 ** is Win95 or WinNT.
21840 */
21841 static int getReadLock(winFile *pFile){
21842   int res;
21843   if( isNT() ){
21844     OVERLAPPED ovlp;
21845     ovlp.Offset = SHARED_FIRST;
21846     ovlp.OffsetHigh = 0;
21847     ovlp.hEvent = 0;
21848     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
21849                      0, SHARED_SIZE, 0, &ovlp);
21850   }else{
21851     int lk;
21852     sqlite3Randomness(sizeof(lk), &lk);
21853     pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
21854     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
21855   }
21856   return res;
21857 }
21858
21859 /*
21860 ** Undo a readlock
21861 */
21862 static int unlockReadLock(winFile *pFile){
21863   int res;
21864   if( isNT() ){
21865     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
21866   }else{
21867     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
21868   }
21869   return res;
21870 }
21871
21872 /*
21873 ** Lock the file with the lock specified by parameter locktype - one
21874 ** of the following:
21875 **
21876 **     (1) SHARED_LOCK
21877 **     (2) RESERVED_LOCK
21878 **     (3) PENDING_LOCK
21879 **     (4) EXCLUSIVE_LOCK
21880 **
21881 ** Sometimes when requesting one lock state, additional lock states
21882 ** are inserted in between.  The locking might fail on one of the later
21883 ** transitions leaving the lock state different from what it started but
21884 ** still short of its goal.  The following chart shows the allowed
21885 ** transitions and the inserted intermediate states:
21886 **
21887 **    UNLOCKED -> SHARED
21888 **    SHARED -> RESERVED
21889 **    SHARED -> (PENDING) -> EXCLUSIVE
21890 **    RESERVED -> (PENDING) -> EXCLUSIVE
21891 **    PENDING -> EXCLUSIVE
21892 **
21893 ** This routine will only increase a lock.  The winUnlock() routine
21894 ** erases all locks at once and returns us immediately to locking level 0.
21895 ** It is not possible to lower the locking level one step at a time.  You
21896 ** must go straight to locking level 0.
21897 */
21898 static int winLock(sqlite3_file *id, int locktype){
21899   int rc = SQLITE_OK;    /* Return code from subroutines */
21900   int res = 1;           /* Result of a windows lock call */
21901   int newLocktype;       /* Set pFile->locktype to this value before exiting */
21902   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
21903   winFile *pFile = (winFile*)id;
21904
21905   assert( pFile!=0 );
21906   OSTRACE5("LOCK %d %d was %d(%d)\n",
21907           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
21908
21909   /* If there is already a lock of this type or more restrictive on the
21910   ** OsFile, do nothing. Don't use the end_lock: exit path, as
21911   ** sqlite3OsEnterMutex() hasn't been called yet.
21912   */
21913   if( pFile->locktype>=locktype ){
21914     return SQLITE_OK;
21915   }
21916
21917   /* Make sure the locking sequence is correct
21918   */
21919   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
21920   assert( locktype!=PENDING_LOCK );
21921   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
21922
21923   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
21924   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
21925   ** the PENDING_LOCK byte is temporary.
21926   */
21927   newLocktype = pFile->locktype;
21928   if( pFile->locktype==NO_LOCK
21929    || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21930   ){
21931     int cnt = 3;
21932     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
21933       /* Try 3 times to get the pending lock.  The pending lock might be
21934       ** held by another reader process who will release it momentarily.
21935       */
21936       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
21937       Sleep(1);
21938     }
21939     gotPendingLock = res;
21940   }
21941
21942   /* Acquire a shared lock
21943   */
21944   if( locktype==SHARED_LOCK && res ){
21945     assert( pFile->locktype==NO_LOCK );
21946     res = getReadLock(pFile);
21947     if( res ){
21948       newLocktype = SHARED_LOCK;
21949     }
21950   }
21951
21952   /* Acquire a RESERVED lock
21953   */
21954   if( locktype==RESERVED_LOCK && res ){
21955     assert( pFile->locktype==SHARED_LOCK );
21956     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
21957     if( res ){
21958       newLocktype = RESERVED_LOCK;
21959     }
21960   }
21961
21962   /* Acquire a PENDING lock
21963   */
21964   if( locktype==EXCLUSIVE_LOCK && res ){
21965     newLocktype = PENDING_LOCK;
21966     gotPendingLock = 0;
21967   }
21968
21969   /* Acquire an EXCLUSIVE lock
21970   */
21971   if( locktype==EXCLUSIVE_LOCK && res ){
21972     assert( pFile->locktype>=SHARED_LOCK );
21973     res = unlockReadLock(pFile);
21974     OSTRACE2("unreadlock = %d\n", res);
21975     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
21976     if( res ){
21977       newLocktype = EXCLUSIVE_LOCK;
21978     }else{
21979       OSTRACE2("error-code = %d\n", GetLastError());
21980       getReadLock(pFile);
21981     }
21982   }
21983
21984   /* If we are holding a PENDING lock that ought to be released, then
21985   ** release it now.
21986   */
21987   if( gotPendingLock && locktype==SHARED_LOCK ){
21988     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
21989   }
21990
21991   /* Update the state of the lock has held in the file descriptor then
21992   ** return the appropriate result code.
21993   */
21994   if( res ){
21995     rc = SQLITE_OK;
21996   }else{
21997     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21998            locktype, newLocktype);
21999     rc = SQLITE_BUSY;
22000   }
22001   pFile->locktype = newLocktype;
22002   return rc;
22003 }
22004
22005 /*
22006 ** This routine checks if there is a RESERVED lock held on the specified
22007 ** file by this or any other process. If such a lock is held, return
22008 ** non-zero, otherwise zero.
22009 */
22010 static int winCheckReservedLock(sqlite3_file *id){
22011   int rc;
22012   winFile *pFile = (winFile*)id;
22013   assert( pFile!=0 );
22014   if( pFile->locktype>=RESERVED_LOCK ){
22015     rc = 1;
22016     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
22017   }else{
22018     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
22019     if( rc ){
22020       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
22021     }
22022     rc = !rc;
22023     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
22024   }
22025   return rc;
22026 }
22027
22028 /*
22029 ** Lower the locking level on file descriptor id to locktype.  locktype
22030 ** must be either NO_LOCK or SHARED_LOCK.
22031 **
22032 ** If the locking level of the file descriptor is already at or below
22033 ** the requested locking level, this routine is a no-op.
22034 **
22035 ** It is not possible for this routine to fail if the second argument
22036 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22037 ** might return SQLITE_IOERR;
22038 */
22039 static int winUnlock(sqlite3_file *id, int locktype){
22040   int type;
22041   winFile *pFile = (winFile*)id;
22042   int rc = SQLITE_OK;
22043   assert( pFile!=0 );
22044   assert( locktype<=SHARED_LOCK );
22045   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
22046           pFile->locktype, pFile->sharedLockByte);
22047   type = pFile->locktype;
22048   if( type>=EXCLUSIVE_LOCK ){
22049     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
22050     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
22051       /* This should never happen.  We should always be able to
22052       ** reacquire the read lock */
22053       rc = SQLITE_IOERR_UNLOCK;
22054     }
22055   }
22056   if( type>=RESERVED_LOCK ){
22057     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
22058   }
22059   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22060     unlockReadLock(pFile);
22061   }
22062   if( type>=PENDING_LOCK ){
22063     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
22064   }
22065   pFile->locktype = locktype;
22066   return rc;
22067 }
22068
22069 /*
22070 ** Control and query of the open file handle.
22071 */
22072 static int winFileControl(sqlite3_file *id, int op, void *pArg){
22073   switch( op ){
22074     case SQLITE_FCNTL_LOCKSTATE: {
22075       *(int*)pArg = ((winFile*)id)->locktype;
22076       return SQLITE_OK;
22077     }
22078   }
22079   return SQLITE_ERROR;
22080 }
22081
22082 /*
22083 ** Return the sector size in bytes of the underlying block device for
22084 ** the specified file. This is almost always 512 bytes, but may be
22085 ** larger for some devices.
22086 **
22087 ** SQLite code assumes this function cannot fail. It also assumes that
22088 ** if two files are created in the same file-system directory (i.e.
22089 ** a database and its journal file) that the sector size will be the
22090 ** same for both.
22091 */
22092 static int winSectorSize(sqlite3_file *id){
22093   return SQLITE_DEFAULT_SECTOR_SIZE;
22094 }
22095
22096 /*
22097 ** Return a vector of device characteristics.
22098 */
22099 static int winDeviceCharacteristics(sqlite3_file *id){
22100   return 0;
22101 }
22102
22103 /*
22104 ** This vector defines all the methods that can operate on an
22105 ** sqlite3_file for win32.
22106 */
22107 static const sqlite3_io_methods winIoMethod = {
22108   1,                        /* iVersion */
22109   winClose,
22110   winRead,
22111   winWrite,
22112   winTruncate,
22113   winSync,
22114   winFileSize,
22115   winLock,
22116   winUnlock,
22117   winCheckReservedLock,
22118   winFileControl,
22119   winSectorSize,
22120   winDeviceCharacteristics
22121 };
22122
22123 /***************************************************************************
22124 ** Here ends the I/O methods that form the sqlite3_io_methods object.
22125 **
22126 ** The next block of code implements the VFS methods.
22127 ****************************************************************************/
22128
22129 /*
22130 ** Convert a UTF-8 filename into whatever form the underlying
22131 ** operating system wants filenames in.  Space to hold the result
22132 ** is obtained from malloc and must be freed by the calling
22133 ** function.
22134 */
22135 static void *convertUtf8Filename(const char *zFilename){
22136   void *zConverted = 0;
22137   if( isNT() ){
22138     zConverted = utf8ToUnicode(zFilename);
22139   }else{
22140     zConverted = utf8ToMbcs(zFilename);
22141   }
22142   /* caller will handle out of memory */
22143   return zConverted;
22144 }
22145
22146 /*
22147 ** Open a file.
22148 */
22149 static int winOpen(
22150   sqlite3_vfs *pVfs,        /* Not used */
22151   const char *zName,        /* Name of the file (UTF-8) */
22152   sqlite3_file *id,         /* Write the SQLite file handle here */
22153   int flags,                /* Open mode flags */
22154   int *pOutFlags            /* Status return flags */
22155 ){
22156   HANDLE h;
22157   DWORD dwDesiredAccess;
22158   DWORD dwShareMode;
22159   DWORD dwCreationDisposition;
22160   DWORD dwFlagsAndAttributes = 0;
22161   int isTemp;
22162   winFile *pFile = (winFile*)id;
22163   void *zConverted = convertUtf8Filename(zName);
22164   if( zConverted==0 ){
22165     return SQLITE_NOMEM;
22166   }
22167
22168   if( flags & SQLITE_OPEN_READWRITE ){
22169     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
22170   }else{
22171     dwDesiredAccess = GENERIC_READ;
22172   }
22173   if( flags & SQLITE_OPEN_CREATE ){
22174     dwCreationDisposition = OPEN_ALWAYS;
22175   }else{
22176     dwCreationDisposition = OPEN_EXISTING;
22177   }
22178   if( flags & SQLITE_OPEN_MAIN_DB ){
22179     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
22180   }else{
22181     dwShareMode = 0;
22182   }
22183   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
22184 #if OS_WINCE
22185     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
22186 #else
22187     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
22188                                | FILE_ATTRIBUTE_HIDDEN
22189                                | FILE_FLAG_DELETE_ON_CLOSE;
22190 #endif
22191     isTemp = 1;
22192   }else{
22193     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
22194     isTemp = 0;
22195   }
22196   /* Reports from the internet are that performance is always
22197   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
22198   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
22199   if( isNT() ){
22200     h = CreateFileW((WCHAR*)zConverted,
22201        dwDesiredAccess,
22202        dwShareMode,
22203        NULL,
22204        dwCreationDisposition,
22205        dwFlagsAndAttributes,
22206        NULL
22207     );
22208   }else{
22209 #if OS_WINCE
22210     return SQLITE_NOMEM;
22211 #else
22212     h = CreateFileA((char*)zConverted,
22213        dwDesiredAccess,
22214        dwShareMode,
22215        NULL,
22216        dwCreationDisposition,
22217        dwFlagsAndAttributes,
22218        NULL
22219     );
22220 #endif
22221   }
22222   if( h==INVALID_HANDLE_VALUE ){
22223     free(zConverted);
22224     if( flags & SQLITE_OPEN_READWRITE ){
22225       return winOpen(0, zName, id, 
22226              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
22227     }else{
22228       return SQLITE_CANTOPEN;
22229     }
22230   }
22231   if( pOutFlags ){
22232     if( flags & SQLITE_OPEN_READWRITE ){
22233       *pOutFlags = SQLITE_OPEN_READWRITE;
22234     }else{
22235       *pOutFlags = SQLITE_OPEN_READONLY;
22236     }
22237   }
22238   memset(pFile, 0, sizeof(*pFile));
22239   pFile->pMethod = &winIoMethod;
22240   pFile->h = h;
22241 #if OS_WINCE
22242   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
22243                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
22244        && !winceCreateLock(zName, pFile)
22245   ){
22246     CloseHandle(h);
22247     free(zConverted);
22248     return SQLITE_CANTOPEN;
22249   }
22250   if( isTemp ){
22251     pFile->zDeleteOnClose = zConverted;
22252   }else
22253 #endif
22254   {
22255     free(zConverted);
22256   }
22257   OpenCounter(+1);
22258   return SQLITE_OK;
22259 }
22260
22261 /*
22262 ** Delete the named file.
22263 **
22264 ** Note that windows does not allow a file to be deleted if some other
22265 ** process has it open.  Sometimes a virus scanner or indexing program
22266 ** will open a journal file shortly after it is created in order to do
22267 ** whatever does.  While this other process is holding the
22268 ** file open, we will be unable to delete it.  To work around this
22269 ** problem, we delay 100 milliseconds and try to delete again.  Up
22270 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
22271 ** up and returning an error.
22272 */
22273 #define MX_DELETION_ATTEMPTS 5
22274 static int winDelete(
22275   sqlite3_vfs *pVfs,          /* Not used on win32 */
22276   const char *zFilename,      /* Name of file to delete */
22277   int syncDir                 /* Not used on win32 */
22278 ){
22279   int cnt = 0;
22280   int rc;
22281   void *zConverted = convertUtf8Filename(zFilename);
22282   if( zConverted==0 ){
22283     return SQLITE_NOMEM;
22284   }
22285   SimulateIOError(return SQLITE_IOERR_DELETE);
22286   if( isNT() ){
22287     do{
22288       DeleteFileW(zConverted);
22289     }while( (rc = GetFileAttributesW(zConverted))!=0xffffffff 
22290             && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
22291   }else{
22292 #if OS_WINCE
22293     return SQLITE_NOMEM;
22294 #else
22295     do{
22296       DeleteFileA(zConverted);
22297     }while( (rc = GetFileAttributesA(zConverted))!=0xffffffff
22298             && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
22299 #endif
22300   }
22301   free(zConverted);
22302   OSTRACE2("DELETE \"%s\"\n", zFilename);
22303   return rc==0xffffffff ? SQLITE_OK : SQLITE_IOERR_DELETE;
22304 }
22305
22306 /*
22307 ** Check the existance and status of a file.
22308 */
22309 static int winAccess(
22310   sqlite3_vfs *pVfs,         /* Not used on win32 */
22311   const char *zFilename,     /* Name of file to check */
22312   int flags                  /* Type of test to make on this file */
22313 ){
22314   DWORD attr;
22315   int rc;
22316   void *zConverted = convertUtf8Filename(zFilename);
22317   if( zConverted==0 ){
22318     return SQLITE_NOMEM;
22319   }
22320   if( isNT() ){
22321     attr = GetFileAttributesW((WCHAR*)zConverted);
22322   }else{
22323 #if OS_WINCE
22324     return SQLITE_NOMEM;
22325 #else
22326     attr = GetFileAttributesA((char*)zConverted);
22327 #endif
22328   }
22329   free(zConverted);
22330   switch( flags ){
22331     case SQLITE_ACCESS_READ:
22332     case SQLITE_ACCESS_EXISTS:
22333       rc = attr!=0xffffffff;
22334       break;
22335     case SQLITE_ACCESS_READWRITE:
22336       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
22337       break;
22338     default:
22339       assert(!"Invalid flags argument");
22340   }
22341   return rc;
22342 }
22343
22344
22345 /*
22346 ** Create a temporary file name in zBuf.  zBuf must be big enough to
22347 ** hold at pVfs->mxPathname characters.
22348 */
22349 static int winGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22350   static char zChars[] =
22351     "abcdefghijklmnopqrstuvwxyz"
22352     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
22353     "0123456789";
22354   int i, j;
22355   char zTempPath[MAX_PATH+1];
22356   if( sqlite3_temp_directory ){
22357     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
22358   }else if( isNT() ){
22359     char *zMulti;
22360     WCHAR zWidePath[MAX_PATH];
22361     GetTempPathW(MAX_PATH-30, zWidePath);
22362     zMulti = unicodeToUtf8(zWidePath);
22363     if( zMulti ){
22364       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
22365       free(zMulti);
22366     }else{
22367       return SQLITE_NOMEM;
22368     }
22369   }else{
22370     char *zUtf8;
22371     char zMbcsPath[MAX_PATH];
22372     GetTempPathA(MAX_PATH-30, zMbcsPath);
22373     zUtf8 = mbcsToUtf8(zMbcsPath);
22374     if( zUtf8 ){
22375       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
22376       free(zUtf8);
22377     }else{
22378       return SQLITE_NOMEM;
22379     }
22380   }
22381   for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
22382   zTempPath[i] = 0;
22383   sqlite3_snprintf(nBuf-30, zBuf,
22384                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
22385   j = strlen(zBuf);
22386   sqlite3Randomness(20, &zBuf[j]);
22387   for(i=0; i<20; i++, j++){
22388     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
22389   }
22390   zBuf[j] = 0;
22391   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
22392   return SQLITE_OK; 
22393 }
22394
22395 /*
22396 ** Turn a relative pathname into a full pathname.  Write the full
22397 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
22398 ** bytes in size.
22399 */
22400 static int winFullPathname(
22401   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
22402   const char *zRelative,        /* Possibly relative input path */
22403   int nFull,                    /* Size of output buffer in bytes */
22404   char *zFull                   /* Output buffer */
22405 ){
22406
22407 #if defined(__CYGWIN__)
22408   cygwin_conv_to_full_win32_path(zRelative, zFull);
22409   return SQLITE_OK;
22410 #endif
22411
22412 #if OS_WINCE
22413   /* WinCE has no concept of a relative pathname, or so I am told. */
22414   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
22415   return SQLITE_OK;
22416 #endif
22417
22418 #if !OS_WINCE && !defined(__CYGWIN__)
22419   int nByte;
22420   void *zConverted;
22421   char *zOut;
22422   zConverted = convertUtf8Filename(zRelative);
22423   if( isNT() ){
22424     WCHAR *zTemp;
22425     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
22426     zTemp = malloc( nByte*sizeof(zTemp[0]) );
22427     if( zTemp==0 ){
22428       free(zConverted);
22429       return SQLITE_NOMEM;
22430     }
22431     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
22432     free(zConverted);
22433     zOut = unicodeToUtf8(zTemp);
22434     free(zTemp);
22435   }else{
22436     char *zTemp;
22437     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
22438     zTemp = malloc( nByte*sizeof(zTemp[0]) );
22439     if( zTemp==0 ){
22440       free(zConverted);
22441       return SQLITE_NOMEM;
22442     }
22443     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
22444     free(zConverted);
22445     zOut = mbcsToUtf8(zTemp);
22446     free(zTemp);
22447   }
22448   if( zOut ){
22449     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
22450     free(zOut);
22451     return SQLITE_OK;
22452   }else{
22453     return SQLITE_NOMEM;
22454   }
22455 #endif
22456 }
22457
22458 #ifndef SQLITE_OMIT_LOAD_EXTENSION
22459 /*
22460 ** Interfaces for opening a shared library, finding entry points
22461 ** within the shared library, and closing the shared library.
22462 */
22463 /*
22464 ** Interfaces for opening a shared library, finding entry points
22465 ** within the shared library, and closing the shared library.
22466 */
22467 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
22468   HANDLE h;
22469   void *zConverted = convertUtf8Filename(zFilename);
22470   if( zConverted==0 ){
22471     return 0;
22472   }
22473   if( isNT() ){
22474     h = LoadLibraryW((WCHAR*)zConverted);
22475   }else{
22476 #if OS_WINCE
22477     return 0;
22478 #else
22479     h = LoadLibraryA((char*)zConverted);
22480 #endif
22481   }
22482   free(zConverted);
22483   return (void*)h;
22484 }
22485 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
22486 #if OS_WINCE
22487   int error = GetLastError();
22488   if( error>0x7FFFFFF ){
22489     sqlite3_snprintf(nBuf, zBufOut, "OsError 0x%x", error);
22490   }else{
22491     sqlite3_snprintf(nBuf, zBufOut, "OsError %d", error);
22492   }
22493 #else
22494   FormatMessageA(
22495     FORMAT_MESSAGE_FROM_SYSTEM,
22496     NULL,
22497     GetLastError(),
22498     0,
22499     zBufOut,
22500     nBuf-1,
22501     0
22502   );
22503 #endif
22504 }
22505 void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
22506 #if OS_WINCE
22507   /* The GetProcAddressA() routine is only available on wince. */
22508   return GetProcAddressA((HANDLE)pHandle, zSymbol);
22509 #else
22510   /* All other windows platforms expect GetProcAddress() to take
22511   ** an Ansi string regardless of the _UNICODE setting */
22512   return GetProcAddress((HANDLE)pHandle, zSymbol);
22513 #endif
22514 }
22515 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
22516   FreeLibrary((HANDLE)pHandle);
22517 }
22518 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
22519   #define winDlOpen  0
22520   #define winDlError 0
22521   #define winDlSym   0
22522   #define winDlClose 0
22523 #endif
22524
22525
22526 /*
22527 ** Write up to nBuf bytes of randomness into zBuf.
22528 */
22529 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22530   int n = 0;
22531   if( sizeof(SYSTEMTIME)<=nBuf-n ){
22532     SYSTEMTIME x;
22533     GetSystemTime(&x);
22534     memcpy(&zBuf[n], &x, sizeof(x));
22535     n += sizeof(x);
22536   }
22537   if( sizeof(DWORD)<=nBuf-n ){
22538     DWORD pid = GetCurrentProcessId();
22539     memcpy(&zBuf[n], &pid, sizeof(pid));
22540     n += sizeof(pid);
22541   }
22542   if( sizeof(DWORD)<=nBuf-n ){
22543     DWORD cnt = GetTickCount();
22544     memcpy(&zBuf[n], &cnt, sizeof(cnt));
22545     n += sizeof(cnt);
22546   }
22547   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
22548     LARGE_INTEGER i;
22549     QueryPerformanceCounter(&i);
22550     memcpy(&zBuf[n], &i, sizeof(i));
22551     n += sizeof(i);
22552   }
22553   return n;
22554 }
22555
22556
22557 /*
22558 ** Sleep for a little while.  Return the amount of time slept.
22559 */
22560 static int winSleep(sqlite3_vfs *pVfs, int microsec){
22561   Sleep((microsec+999)/1000);
22562   return ((microsec+999)/1000)*1000;
22563 }
22564
22565 /*
22566 ** The following variable, if set to a non-zero value, becomes the result
22567 ** returned from sqlite3OsCurrentTime().  This is used for testing.
22568 */
22569 #ifdef SQLITE_TEST
22570 SQLITE_API int sqlite3_current_time = 0;
22571 #endif
22572
22573 /*
22574 ** Find the current time (in Universal Coordinated Time).  Write the
22575 ** current time and date as a Julian Day number into *prNow and
22576 ** return 0.  Return 1 if the time and date cannot be found.
22577 */
22578 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
22579   FILETIME ft;
22580   /* FILETIME structure is a 64-bit value representing the number of 
22581      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
22582   */
22583   double now;
22584 #if OS_WINCE
22585   SYSTEMTIME time;
22586   GetSystemTime(&time);
22587   SystemTimeToFileTime(&time,&ft);
22588 #else
22589   GetSystemTimeAsFileTime( &ft );
22590 #endif
22591   now = ((double)ft.dwHighDateTime) * 4294967296.0; 
22592   *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
22593 #ifdef SQLITE_TEST
22594   if( sqlite3_current_time ){
22595     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
22596   }
22597 #endif
22598   return 0;
22599 }
22600
22601
22602 /*
22603 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
22604 ** a function rather than give the structure global scope because
22605 ** some compilers (MSVC) do not allow forward declarations of
22606 ** initialized structures.
22607 */
22608 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
22609   static sqlite3_vfs winVfs = {
22610     1,                 /* iVersion */
22611     sizeof(winFile),   /* szOsFile */
22612     MAX_PATH,          /* mxPathname */
22613     0,                 /* pNext */
22614     "win32",           /* zName */
22615     0,                 /* pAppData */
22616   
22617     winOpen,           /* xOpen */
22618     winDelete,         /* xDelete */
22619     winAccess,         /* xAccess */
22620     winGetTempname,    /* xGetTempName */
22621     winFullPathname,   /* xFullPathname */
22622     winDlOpen,         /* xDlOpen */
22623     winDlError,        /* xDlError */
22624     winDlSym,          /* xDlSym */
22625     winDlClose,        /* xDlClose */
22626     winRandomness,     /* xRandomness */
22627     winSleep,          /* xSleep */
22628     winCurrentTime     /* xCurrentTime */
22629   };
22630   
22631   return &winVfs;
22632 }
22633
22634 #endif /* OS_WIN */
22635
22636 /************** End of os_win.c **********************************************/
22637 /************** Begin file bitvec.c ******************************************/
22638 /*
22639 ** 2008 February 16
22640 **
22641 ** The author disclaims copyright to this source code.  In place of
22642 ** a legal notice, here is a blessing:
22643 **
22644 **    May you do good and not evil.
22645 **    May you find forgiveness for yourself and forgive others.
22646 **    May you share freely, never taking more than you give.
22647 **
22648 *************************************************************************
22649 ** This file implements an object that represents a fixed-length
22650 ** bitmap.  Bits are numbered starting with 1.
22651 **
22652 ** A bitmap is used to record what pages a database file have been
22653 ** journalled during a transaction.  Usually only a few pages are
22654 ** journalled.  So the bitmap is usually sparse and has low cardinality.
22655 ** But sometimes (for example when during a DROP of a large table) most
22656 ** or all of the pages get journalled.  In those cases, the bitmap becomes
22657 ** dense.  The algorithm needs to handle both cases well.
22658 **
22659 ** The size of the bitmap is fixed when the object is created.
22660 **
22661 ** All bits are clear when the bitmap is created.  Individual bits
22662 ** may be set or cleared one at a time.
22663 **
22664 ** Test operations are about 100 times more common that set operations.
22665 ** Clear operations are exceedingly rare.  There are usually between
22666 ** 5 and 500 set operations per Bitvec object, though the number of sets can
22667 ** sometimes grow into tens of thousands or larger.  The size of the
22668 ** Bitvec object is the number of pages in the database file at the
22669 ** start of a transaction, and is thus usually less than a few thousand,
22670 ** but can be as large as 2 billion for a really big database.
22671 **
22672 ** @(#) $Id: bitvec.c,v 1.2 2008/03/14 13:02:08 mlcreech Exp $
22673 */
22674
22675 #define BITVEC_SZ        512
22676 /* Round the union size down to the nearest pointer boundary, since that's how 
22677 ** it will be aligned within the Bitvec struct. */
22678 #define BITVEC_USIZE     (((BITVEC_SZ-12)/sizeof(Bitvec *))*sizeof(Bitvec *))
22679 #define BITVEC_NCHAR     BITVEC_USIZE
22680 #define BITVEC_NBIT      (BITVEC_NCHAR*8)
22681 #define BITVEC_NINT      (BITVEC_USIZE/4)
22682 #define BITVEC_MXHASH    (BITVEC_NINT/2)
22683 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
22684
22685 #define BITVEC_HASH(X)   (((X)*37)%BITVEC_NINT)
22686
22687 /*
22688 ** A bitmap is an instance of the following structure.
22689 **
22690 ** This bitmap records the existance of zero or more bits
22691 ** with values between 1 and iSize, inclusive.
22692 **
22693 ** There are three possible representations of the bitmap.
22694 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
22695 ** bitmap.  The least significant bit is bit 1.
22696 **
22697 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
22698 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
22699 **
22700 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
22701 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
22702 ** handles up to iDivisor separate values of i.  apSub[0] holds
22703 ** values between 1 and iDivisor.  apSub[1] holds values between
22704 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
22705 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
22706 ** to hold deal with values between 1 and iDivisor.
22707 */
22708 struct Bitvec {
22709   u32 iSize;      /* Maximum bit index */
22710   u32 nSet;       /* Number of bits that are set */
22711   u32 iDivisor;   /* Number of bits handled by each apSub[] entry */
22712   union {
22713     u8 aBitmap[BITVEC_NCHAR];    /* Bitmap representation */
22714     u32 aHash[BITVEC_NINT];      /* Hash table representation */
22715     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
22716   } u;
22717 };
22718
22719 /*
22720 ** Create a new bitmap object able to handle bits between 0 and iSize,
22721 ** inclusive.  Return a pointer to the new object.  Return NULL if 
22722 ** malloc fails.
22723 */
22724 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
22725   Bitvec *p;
22726   assert( sizeof(*p)==BITVEC_SZ );
22727   p = sqlite3MallocZero( sizeof(*p) );
22728   if( p ){
22729     p->iSize = iSize;
22730   }
22731   return p;
22732 }
22733
22734 /*
22735 ** Check to see if the i-th bit is set.  Return true or false.
22736 ** If p is NULL (if the bitmap has not been created) or if
22737 ** i is out of range, then return false.
22738 */
22739 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
22740   assert( i>0 );
22741   if( p==0 ) return 0;
22742   if( i>p->iSize ) return 0;
22743   if( p->iSize<=BITVEC_NBIT ){
22744     i--;
22745     return (p->u.aBitmap[i/8] & (1<<(i&7)))!=0;
22746   }
22747   if( p->iDivisor>0 ){
22748     u32 bin = (i-1)/p->iDivisor;
22749     i = (i-1)%p->iDivisor + 1;
22750     return sqlite3BitvecTest(p->u.apSub[bin], i);
22751   }else{
22752     u32 h = BITVEC_HASH(i);
22753     while( p->u.aHash[h] ){
22754       if( p->u.aHash[h]==i ) return 1;
22755       h++;
22756       if( h>=BITVEC_NINT ) h = 0;
22757     }
22758     return 0;
22759   }
22760 }
22761
22762 /*
22763 ** Set the i-th bit.  Return 0 on success and an error code if
22764 ** anything goes wrong.
22765 */
22766 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
22767   u32 h;
22768   assert( p!=0 );
22769   if( p->iSize<=BITVEC_NBIT ){
22770     i--;
22771     p->u.aBitmap[i/8] |= 1 << (i&7);
22772     return SQLITE_OK;
22773   }
22774   if( p->iDivisor ){
22775     u32 bin = (i-1)/p->iDivisor;
22776     i = (i-1)%p->iDivisor + 1;
22777     if( p->u.apSub[bin]==0 ){
22778       sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 1);
22779       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
22780       sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 0);
22781       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
22782     }
22783     return sqlite3BitvecSet(p->u.apSub[bin], i);
22784   }
22785   h = BITVEC_HASH(i);
22786   while( p->u.aHash[h] ){
22787     if( p->u.aHash[h]==i ) return SQLITE_OK;
22788     h++;
22789     if( h==BITVEC_NINT ) h = 0;
22790   }
22791   p->nSet++;
22792   if( p->nSet>=BITVEC_MXHASH ){
22793     int j, rc;
22794     u32 aiValues[BITVEC_NINT];
22795     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
22796     memset(p->u.apSub, 0, sizeof(p->u.apSub[0])*BITVEC_NPTR);
22797     p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
22798     sqlite3BitvecSet(p, i);
22799     for(rc=j=0; j<BITVEC_NINT; j++){
22800       if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
22801     }
22802     return rc;
22803   }
22804   p->u.aHash[h] = i;
22805   return SQLITE_OK;
22806 }
22807
22808 /*
22809 ** Clear the i-th bit.  Return 0 on success and an error code if
22810 ** anything goes wrong.
22811 */
22812 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
22813   assert( p!=0 );
22814   if( p->iSize<=BITVEC_NBIT ){
22815     i--;
22816     p->u.aBitmap[i/8] &= ~(1 << (i&7));
22817   }else if( p->iDivisor ){
22818     u32 bin = (i-1)/p->iDivisor;
22819     i = (i-1)%p->iDivisor + 1;
22820     if( p->u.apSub[bin] ){
22821       sqlite3BitvecClear(p->u.apSub[bin], i);
22822     }
22823   }else{
22824     int j;
22825     u32 aiValues[BITVEC_NINT];
22826     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
22827     memset(p->u.aHash, 0, sizeof(p->u.aHash[0])*BITVEC_NINT);
22828     p->nSet = 0;
22829     for(j=0; j<BITVEC_NINT; j++){
22830       if( aiValues[j] && aiValues[j]!=i ) sqlite3BitvecSet(p, aiValues[j]);
22831     }
22832   }
22833 }
22834
22835 /*
22836 ** Destroy a bitmap object.  Reclaim all memory used.
22837 */
22838 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
22839   if( p==0 ) return;
22840   if( p->iDivisor ){
22841     int i;
22842     for(i=0; i<BITVEC_NPTR; i++){
22843       sqlite3BitvecDestroy(p->u.apSub[i]);
22844     }
22845   }
22846   sqlite3_free(p);
22847 }
22848
22849 /************** End of bitvec.c **********************************************/
22850 /************** Begin file pager.c *******************************************/
22851 /*
22852 ** 2001 September 15
22853 **
22854 ** The author disclaims copyright to this source code.  In place of
22855 ** a legal notice, here is a blessing:
22856 **
22857 **    May you do good and not evil.
22858 **    May you find forgiveness for yourself and forgive others.
22859 **    May you share freely, never taking more than you give.
22860 **
22861 *************************************************************************
22862 ** This is the implementation of the page cache subsystem or "pager".
22863 ** 
22864 ** The pager is used to access a database disk file.  It implements
22865 ** atomic commit and rollback through the use of a journal file that
22866 ** is separate from the database file.  The pager also implements file
22867 ** locking to prevent two processes from writing the same database
22868 ** file simultaneously, or one process from reading the database while
22869 ** another is writing.
22870 **
22871 ** @(#) $Id: pager.c,v 1.417 2008/03/17 13:50:58 drh Exp $
22872 */
22873 #ifndef SQLITE_OMIT_DISKIO
22874
22875 /*
22876 ** Macros for troubleshooting.  Normally turned off
22877 */
22878 #if 0
22879 #define sqlite3DebugPrintf printf
22880 #define PAGERTRACE1(X)       sqlite3DebugPrintf(X)
22881 #define PAGERTRACE2(X,Y)     sqlite3DebugPrintf(X,Y)
22882 #define PAGERTRACE3(X,Y,Z)   sqlite3DebugPrintf(X,Y,Z)
22883 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
22884 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
22885 #else
22886 #define PAGERTRACE1(X)
22887 #define PAGERTRACE2(X,Y)
22888 #define PAGERTRACE3(X,Y,Z)
22889 #define PAGERTRACE4(X,Y,Z,W)
22890 #define PAGERTRACE5(X,Y,Z,W,V)
22891 #endif
22892
22893 /*
22894 ** The following two macros are used within the PAGERTRACEX() macros above
22895 ** to print out file-descriptors. 
22896 **
22897 ** PAGERID() takes a pointer to a Pager struct as its argument. The
22898 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
22899 ** struct as its argument.
22900 */
22901 #define PAGERID(p) ((int)(p->fd))
22902 #define FILEHANDLEID(fd) ((int)fd)
22903
22904 /*
22905 ** The page cache as a whole is always in one of the following
22906 ** states:
22907 **
22908 **   PAGER_UNLOCK        The page cache is not currently reading or 
22909 **                       writing the database file.  There is no
22910 **                       data held in memory.  This is the initial
22911 **                       state.
22912 **
22913 **   PAGER_SHARED        The page cache is reading the database.
22914 **                       Writing is not permitted.  There can be
22915 **                       multiple readers accessing the same database
22916 **                       file at the same time.
22917 **
22918 **   PAGER_RESERVED      This process has reserved the database for writing
22919 **                       but has not yet made any changes.  Only one process
22920 **                       at a time can reserve the database.  The original
22921 **                       database file has not been modified so other
22922 **                       processes may still be reading the on-disk
22923 **                       database file.
22924 **
22925 **   PAGER_EXCLUSIVE     The page cache is writing the database.
22926 **                       Access is exclusive.  No other processes or
22927 **                       threads can be reading or writing while one
22928 **                       process is writing.
22929 **
22930 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
22931 **                       after all dirty pages have been written to the
22932 **                       database file and the file has been synced to
22933 **                       disk. All that remains to do is to remove or
22934 **                       truncate the journal file and the transaction 
22935 **                       will be committed.
22936 **
22937 ** The page cache comes up in PAGER_UNLOCK.  The first time a
22938 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
22939 ** After all pages have been released using sqlite_page_unref(),
22940 ** the state transitions back to PAGER_UNLOCK.  The first time
22941 ** that sqlite3PagerWrite() is called, the state transitions to
22942 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
22943 ** called on an outstanding page which means that the pager must
22944 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
22945 ** PAGER_RESERVED means that there is an open rollback journal.
22946 ** The transition to PAGER_EXCLUSIVE occurs before any changes
22947 ** are made to the database file, though writes to the rollback
22948 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
22949 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
22950 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
22951 */
22952 #define PAGER_UNLOCK      0
22953 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
22954 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
22955 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
22956 #define PAGER_SYNCED      5
22957
22958 /*
22959 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
22960 ** then failed attempts to get a reserved lock will invoke the busy callback.
22961 ** This is off by default.  To see why, consider the following scenario:
22962 ** 
22963 ** Suppose thread A already has a shared lock and wants a reserved lock.
22964 ** Thread B already has a reserved lock and wants an exclusive lock.  If
22965 ** both threads are using their busy callbacks, it might be a long time
22966 ** be for one of the threads give up and allows the other to proceed.
22967 ** But if the thread trying to get the reserved lock gives up quickly
22968 ** (if it never invokes its busy callback) then the contention will be
22969 ** resolved quickly.
22970 */
22971 #ifndef SQLITE_BUSY_RESERVED_LOCK
22972 # define SQLITE_BUSY_RESERVED_LOCK 0
22973 #endif
22974
22975 /*
22976 ** This macro rounds values up so that if the value is an address it
22977 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
22978 */
22979 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
22980
22981 typedef struct PgHdr PgHdr;
22982
22983 /*
22984 ** Each pager stores all currently unreferenced pages in a list sorted
22985 ** in least-recently-used (LRU) order (i.e. the first item on the list has 
22986 ** not been referenced in a long time, the last item has been recently
22987 ** used). An instance of this structure is included as part of each
22988 ** pager structure for this purpose (variable Pager.lru).
22989 **
22990 ** Additionally, if memory-management is enabled, all unreferenced pages 
22991 ** are stored in a global LRU list (global variable sqlite3LruPageList).
22992 **
22993 ** In both cases, the PagerLruList.pFirstSynced variable points to
22994 ** the first page in the corresponding list that does not require an
22995 ** fsync() operation before its memory can be reclaimed. If no such
22996 ** page exists, PagerLruList.pFirstSynced is set to NULL.
22997 */
22998 typedef struct PagerLruList PagerLruList;
22999 struct PagerLruList {
23000   PgHdr *pFirst;         /* First page in LRU list */
23001   PgHdr *pLast;          /* Last page in LRU list (the most recently used) */
23002   PgHdr *pFirstSynced;   /* First page in list with PgHdr.needSync==0 */
23003 };
23004
23005 /*
23006 ** The following structure contains the next and previous pointers used
23007 ** to link a PgHdr structure into a PagerLruList linked list. 
23008 */
23009 typedef struct PagerLruLink PagerLruLink;
23010 struct PagerLruLink {
23011   PgHdr *pNext;
23012   PgHdr *pPrev;
23013 };
23014
23015 /*
23016 ** Each in-memory image of a page begins with the following header.
23017 ** This header is only visible to this pager module.  The client
23018 ** code that calls pager sees only the data that follows the header.
23019 **
23020 ** Client code should call sqlite3PagerWrite() on a page prior to making
23021 ** any modifications to that page.  The first time sqlite3PagerWrite()
23022 ** is called, the original page contents are written into the rollback
23023 ** journal and PgHdr.inJournal and PgHdr.needSync are set.  Later, once
23024 ** the journal page has made it onto the disk surface, PgHdr.needSync
23025 ** is cleared.  The modified page cannot be written back into the original
23026 ** database file until the journal pages has been synced to disk and the
23027 ** PgHdr.needSync has been cleared.
23028 **
23029 ** The PgHdr.dirty flag is set when sqlite3PagerWrite() is called and
23030 ** is cleared again when the page content is written back to the original
23031 ** database file.
23032 **
23033 ** Details of important structure elements:
23034 **
23035 ** needSync
23036 **
23037 **     If this is true, this means that it is not safe to write the page
23038 **     content to the database because the original content needed
23039 **     for rollback has not by synced to the main rollback journal.
23040 **     The original content may have been written to the rollback journal
23041 **     but it has not yet been synced.  So we cannot write to the database
23042 **     file because power failure might cause the page in the journal file
23043 **     to never reach the disk.  It is as if the write to the journal file
23044 **     does not occur until the journal file is synced.
23045 **     
23046 **     This flag is false if the page content exactly matches what
23047 **     currently exists in the database file.  The needSync flag is also
23048 **     false if the original content has been written to the main rollback
23049 **     journal and synced.  If the page represents a new page that has
23050 **     been added onto the end of the database during the current
23051 **     transaction, the needSync flag is true until the original database
23052 **     size in the journal header has been synced to disk.
23053 **
23054 ** inJournal
23055 **
23056 **     This is true if the original page has been written into the main
23057 **     rollback journal.  This is always false for new pages added to
23058 **     the end of the database file during the current transaction.
23059 **     And this flag says nothing about whether or not the journal
23060 **     has been synced to disk.  For pages that are in the original
23061 **     database file, the following expression should always be true:
23062 **
23063 **       inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno)
23064 **
23065 **     The pPager->pInJournal object is only valid for the original
23066 **     pages of the database, not new pages that are added to the end
23067 **     of the database, so obviously the above expression cannot be
23068 **     valid for new pages.  For new pages inJournal is always 0.
23069 **
23070 ** dirty
23071 **
23072 **     When true, this means that the content of the page has been
23073 **     modified and needs to be written back to the database file.
23074 **     If false, it means that either the content of the page is
23075 **     unchanged or else the content is unimportant and we do not
23076 **     care whether or not it is preserved.
23077 **
23078 ** alwaysRollback
23079 **
23080 **     This means that the sqlite3PagerDontRollback() API should be
23081 **     ignored for this page.  The DontRollback() API attempts to say
23082 **     that the content of the page on disk is unimportant (it is an
23083 **     unused page on the freelist) so that it is unnecessary to 
23084 **     rollback changes to this page because the content of the page
23085 **     can change without changing the meaning of the database.  This
23086 **     flag overrides any DontRollback() attempt.  This flag is set
23087 **     when a page that originally contained valid data is added to
23088 **     the freelist.  Later in the same transaction, this page might
23089 **     be pulled from the freelist and reused for something different
23090 **     and at that point the DontRollback() API will be called because
23091 **     pages taken from the freelist do not need to be protected by
23092 **     the rollback journal.  But this flag says that the page was
23093 **     not originally part of the freelist so that it still needs to
23094 **     be rolled back in spite of any subsequent DontRollback() calls.
23095 **
23096 ** needRead 
23097 **
23098 **     This flag means (when true) that the content of the page has
23099 **     not yet been loaded from disk.  The in-memory content is just
23100 **     garbage.  (Actually, we zero the content, but you should not
23101 **     make any assumptions about the content nevertheless.)  If the
23102 **     content is needed in the future, it should be read from the
23103 **     original database file.
23104 */
23105 struct PgHdr {
23106   Pager *pPager;                 /* The pager to which this page belongs */
23107   Pgno pgno;                     /* The page number for this page */
23108   PgHdr *pNextHash, *pPrevHash;  /* Hash collision chain for PgHdr.pgno */
23109   PagerLruLink free;             /* Next and previous free pages */
23110   PgHdr *pNextAll;               /* A list of all pages */
23111   u8 inJournal;                  /* TRUE if has been written to journal */
23112   u8 dirty;                      /* TRUE if we need to write back changes */
23113   u8 needSync;                   /* Sync journal before writing this page */
23114   u8 alwaysRollback;             /* Disable DontRollback() for this page */
23115   u8 needRead;                   /* Read content if PagerWrite() is called */
23116   short int nRef;                /* Number of users of this page */
23117   PgHdr *pDirty, *pPrevDirty;    /* Dirty pages */
23118 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23119   PagerLruLink gfree;            /* Global list of nRef==0 pages */
23120 #endif
23121 #ifdef SQLITE_CHECK_PAGES
23122   u32 pageHash;
23123 #endif
23124   void *pData;                   /* Page data */
23125   /* Pager.nExtra bytes of local data appended to this header */
23126 };
23127
23128 /*
23129 ** For an in-memory only database, some extra information is recorded about
23130 ** each page so that changes can be rolled back.  (Journal files are not
23131 ** used for in-memory databases.)  The following information is added to
23132 ** the end of every EXTRA block for in-memory databases.
23133 **
23134 ** This information could have been added directly to the PgHdr structure.
23135 ** But then it would take up an extra 8 bytes of storage on every PgHdr
23136 ** even for disk-based databases.  Splitting it out saves 8 bytes.  This
23137 ** is only a savings of 0.8% but those percentages add up.
23138 */
23139 typedef struct PgHistory PgHistory;
23140 struct PgHistory {
23141   u8 *pOrig;     /* Original page text.  Restore to this on a full rollback */
23142   u8 *pStmt;     /* Text as it was at the beginning of the current statement */
23143   PgHdr *pNextStmt, *pPrevStmt;  /* List of pages in the statement journal */
23144   u8 inStmt;                     /* TRUE if in the statement subjournal */
23145 };
23146
23147 /*
23148 ** A macro used for invoking the codec if there is one
23149 */
23150 #ifdef SQLITE_HAS_CODEC
23151 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
23152 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
23153 #else
23154 # define CODEC1(P,D,N,X) /* NO-OP */
23155 # define CODEC2(P,D,N,X) ((char*)D)
23156 #endif
23157
23158 /*
23159 ** Convert a pointer to a PgHdr into a pointer to its data
23160 ** and back again.
23161 */
23162 #define PGHDR_TO_DATA(P)    ((P)->pData)
23163 #define PGHDR_TO_EXTRA(G,P) ((void*)&((G)[1]))
23164 #define PGHDR_TO_HIST(P,PGR)  \
23165             ((PgHistory*)&((char*)(&(P)[1]))[(PGR)->nExtra])
23166
23167 /*
23168 ** A open page cache is an instance of the following structure.
23169 **
23170 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
23171 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
23172 ** and is returned as the result of every major pager API call.  The
23173 ** SQLITE_FULL return code is slightly different. It persists only until the
23174 ** next successful rollback is performed on the pager cache. Also,
23175 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
23176 ** APIs, they may still be used successfully.
23177 */
23178 struct Pager {
23179   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
23180   u8 journalOpen;             /* True if journal file descriptors is valid */
23181   u8 journalStarted;          /* True if header of journal is synced */
23182   u8 useJournal;              /* Use a rollback journal on this file */
23183   u8 noReadlock;              /* Do not bother to obtain readlocks */
23184   u8 stmtOpen;                /* True if the statement subjournal is open */
23185   u8 stmtInUse;               /* True we are in a statement subtransaction */
23186   u8 stmtAutoopen;            /* Open stmt journal when main journal is opened*/
23187   u8 noSync;                  /* Do not sync the journal if true */
23188   u8 fullSync;                /* Do extra syncs of the journal for robustness */
23189   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
23190   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
23191   u8 tempFile;                /* zFilename is a temporary file */
23192   u8 readOnly;                /* True for a read-only database */
23193   u8 needSync;                /* True if an fsync() is needed on the journal */
23194   u8 dirtyCache;              /* True if cached pages have changed */
23195   u8 alwaysRollback;          /* Disable DontRollback() for all pages */
23196   u8 memDb;                   /* True to inhibit all file I/O */
23197   u8 setMaster;               /* True if a m-j name has been written to jrnl */
23198   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
23199   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
23200   u8 changeCountDone;         /* Set after incrementing the change-counter */
23201   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
23202   int errCode;                /* One of several kinds of errors */
23203   int dbSize;                 /* Number of pages in the file */
23204   int origDbSize;             /* dbSize before the current change */
23205   int stmtSize;               /* Size of database (in pages) at stmt_begin() */
23206   int nRec;                   /* Number of pages written to the journal */
23207   u32 cksumInit;              /* Quasi-random value added to every checksum */
23208   int stmtNRec;               /* Number of records in stmt subjournal */
23209   int nExtra;                 /* Add this many bytes to each in-memory page */
23210   int pageSize;               /* Number of bytes in a page */
23211   int nPage;                  /* Total number of in-memory pages */
23212   int nRef;                   /* Number of in-memory pages with PgHdr.nRef>0 */
23213   int mxPage;                 /* Maximum number of pages to hold in cache */
23214   Pgno mxPgno;                /* Maximum allowed size of the database */
23215   Bitvec *pInJournal;         /* One bit for each page in the database file */
23216   Bitvec *pInStmt;            /* One bit for each page in the database */
23217   char *zFilename;            /* Name of the database file */
23218   char *zJournal;             /* Name of the journal file */
23219   char *zDirectory;           /* Directory hold database and journal files */
23220   char *zStmtJrnl;            /* Name of the statement journal file */
23221   sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
23222   sqlite3_file *stfd;         /* File descriptor for the statement subjournal*/
23223   BusyHandler *pBusyHandler;  /* Pointer to sqlite.busyHandler */
23224   PagerLruList lru;           /* LRU list of free pages */
23225   PgHdr *pAll;                /* List of all pages */
23226   PgHdr *pStmt;               /* List of pages in the statement subjournal */
23227   PgHdr *pDirty;              /* List of all dirty pages */
23228   i64 journalOff;             /* Current byte offset in the journal file */
23229   i64 journalHdr;             /* Byte offset to previous journal header */
23230   i64 stmtHdrOff;             /* First journal header written this statement */
23231   i64 stmtCksum;              /* cksumInit when statement was started */
23232   i64 stmtJSize;              /* Size of journal at stmt_begin() */
23233   int sectorSize;             /* Assumed sector size during rollback */
23234 #ifdef SQLITE_TEST
23235   int nHit, nMiss;            /* Cache hits and missing */
23236   int nRead, nWrite;          /* Database pages read/written */
23237 #endif
23238   void (*xDestructor)(DbPage*,int); /* Call this routine when freeing pages */
23239   void (*xReiniter)(DbPage*,int);   /* Call this routine when reloading pages */
23240 #ifdef SQLITE_HAS_CODEC
23241   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
23242   void *pCodecArg;            /* First argument to xCodec() */
23243 #endif
23244   int nHash;                  /* Size of the pager hash table */
23245   PgHdr **aHash;              /* Hash table to map page number to PgHdr */
23246 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23247   Pager *pNext;               /* Doubly linked list of pagers on which */
23248   Pager *pPrev;               /* sqlite3_release_memory() will work */
23249   int iInUseMM;               /* Non-zero if unavailable to MM */
23250   int iInUseDB;               /* Non-zero if in sqlite3_release_memory() */
23251 #endif
23252   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
23253   char dbFileVers[16];        /* Changes whenever database file changes */
23254 };
23255
23256 /*
23257 ** The following global variables hold counters used for
23258 ** testing purposes only.  These variables do not exist in
23259 ** a non-testing build.  These variables are not thread-safe.
23260 */
23261 #ifdef SQLITE_TEST
23262 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
23263 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
23264 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
23265 SQLITE_API int sqlite3_pager_pgfree_count = 0;    /* Number of cache pages freed */
23266 # define PAGER_INCR(v)  v++
23267 #else
23268 # define PAGER_INCR(v)
23269 #endif
23270
23271 /*
23272 ** The following variable points to the head of a double-linked list
23273 ** of all pagers that are eligible for page stealing by the
23274 ** sqlite3_release_memory() interface.  Access to this list is
23275 ** protected by the SQLITE_MUTEX_STATIC_MEM2 mutex.
23276 */
23277 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23278 static Pager *sqlite3PagerList = 0;
23279 static PagerLruList sqlite3LruPageList = {0, 0, 0};
23280 #endif
23281
23282
23283 /*
23284 ** Journal files begin with the following magic string.  The data
23285 ** was obtained from /dev/random.  It is used only as a sanity check.
23286 **
23287 ** Since version 2.8.0, the journal format contains additional sanity
23288 ** checking information.  If the power fails while the journal is begin
23289 ** written, semi-random garbage data might appear in the journal
23290 ** file after power is restored.  If an attempt is then made
23291 ** to roll the journal back, the database could be corrupted.  The additional
23292 ** sanity checking data is an attempt to discover the garbage in the
23293 ** journal and ignore it.
23294 **
23295 ** The sanity checking information for the new journal format consists
23296 ** of a 32-bit checksum on each page of data.  The checksum covers both
23297 ** the page number and the pPager->pageSize bytes of data for the page.
23298 ** This cksum is initialized to a 32-bit random value that appears in the
23299 ** journal file right after the header.  The random initializer is important,
23300 ** because garbage data that appears at the end of a journal is likely
23301 ** data that was once in other files that have now been deleted.  If the
23302 ** garbage data came from an obsolete journal file, the checksums might
23303 ** be correct.  But by initializing the checksum to random value which
23304 ** is different for every journal, we minimize that risk.
23305 */
23306 static const unsigned char aJournalMagic[] = {
23307   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
23308 };
23309
23310 /*
23311 ** The size of the header and of each page in the journal is determined
23312 ** by the following macros.
23313 */
23314 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
23315
23316 /*
23317 ** The journal header size for this pager. In the future, this could be
23318 ** set to some value read from the disk controller. The important
23319 ** characteristic is that it is the same size as a disk sector.
23320 */
23321 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
23322
23323 /*
23324 ** The macro MEMDB is true if we are dealing with an in-memory database.
23325 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
23326 ** the value of MEMDB will be a constant and the compiler will optimize
23327 ** out code that would never execute.
23328 */
23329 #ifdef SQLITE_OMIT_MEMORYDB
23330 # define MEMDB 0
23331 #else
23332 # define MEMDB pPager->memDb
23333 #endif
23334
23335 /*
23336 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
23337 ** reserved for working around a windows/posix incompatibility). It is
23338 ** used in the journal to signify that the remainder of the journal file 
23339 ** is devoted to storing a master journal name - there are no more pages to
23340 ** roll back. See comments for function writeMasterJournal() for details.
23341 */
23342 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
23343 #define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
23344
23345 /*
23346 ** The maximum legal page number is (2^31 - 1).
23347 */
23348 #define PAGER_MAX_PGNO 2147483647
23349
23350 /*
23351 ** The pagerEnter() and pagerLeave() routines acquire and release
23352 ** a mutex on each pager.  The mutex is recursive.
23353 **
23354 ** This is a special-purpose mutex.  It only provides mutual exclusion
23355 ** between the Btree and the Memory Management sqlite3_release_memory()
23356 ** function.  It does not prevent, for example, two Btrees from accessing
23357 ** the same pager at the same time.  Other general-purpose mutexes in
23358 ** the btree layer handle that chore.
23359 */
23360 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23361   static void pagerEnter(Pager *p){
23362     p->iInUseDB++;
23363     if( p->iInUseMM && p->iInUseDB==1 ){
23364       sqlite3_mutex *mutex;
23365       mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
23366       p->iInUseDB = 0;
23367       sqlite3_mutex_enter(mutex);
23368       p->iInUseDB = 1;
23369       sqlite3_mutex_leave(mutex);
23370     }
23371     assert( p->iInUseMM==0 );
23372   }
23373   static void pagerLeave(Pager *p){
23374     p->iInUseDB--;
23375     assert( p->iInUseDB>=0 );
23376   }
23377 #else
23378 # define pagerEnter(X)
23379 # define pagerLeave(X)
23380 #endif
23381
23382 /*
23383 ** Add page pPg to the end of the linked list managed by structure
23384 ** pList (pPg becomes the last entry in the list - the most recently 
23385 ** used). Argument pLink should point to either pPg->free or pPg->gfree,
23386 ** depending on whether pPg is being added to the pager-specific or
23387 ** global LRU list.
23388 */
23389 static void listAdd(PagerLruList *pList, PagerLruLink *pLink, PgHdr *pPg){
23390   pLink->pNext = 0;
23391   pLink->pPrev = pList->pLast;
23392
23393 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23394   assert(pLink==&pPg->free || pLink==&pPg->gfree);
23395   assert(pLink==&pPg->gfree || pList!=&sqlite3LruPageList);
23396 #endif
23397
23398   if( pList->pLast ){
23399     int iOff = (char *)pLink - (char *)pPg;
23400     PagerLruLink *pLastLink = (PagerLruLink *)(&((u8 *)pList->pLast)[iOff]);
23401     pLastLink->pNext = pPg;
23402   }else{
23403     assert(!pList->pFirst);
23404     pList->pFirst = pPg;
23405   }
23406
23407   pList->pLast = pPg;
23408   if( !pList->pFirstSynced && pPg->needSync==0 ){
23409     pList->pFirstSynced = pPg;
23410   }
23411 }
23412
23413 /*
23414 ** Remove pPg from the list managed by the structure pointed to by pList.
23415 **
23416 ** Argument pLink should point to either pPg->free or pPg->gfree, depending 
23417 ** on whether pPg is being added to the pager-specific or global LRU list.
23418 */
23419 static void listRemove(PagerLruList *pList, PagerLruLink *pLink, PgHdr *pPg){
23420   int iOff = (char *)pLink - (char *)pPg;
23421
23422 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23423   assert(pLink==&pPg->free || pLink==&pPg->gfree);
23424   assert(pLink==&pPg->gfree || pList!=&sqlite3LruPageList);
23425 #endif
23426
23427   if( pPg==pList->pFirst ){
23428     pList->pFirst = pLink->pNext;
23429   }
23430   if( pPg==pList->pLast ){
23431     pList->pLast = pLink->pPrev;
23432   }
23433   if( pLink->pPrev ){
23434     PagerLruLink *pPrevLink = (PagerLruLink *)(&((u8 *)pLink->pPrev)[iOff]);
23435     pPrevLink->pNext = pLink->pNext;
23436   }
23437   if( pLink->pNext ){
23438     PagerLruLink *pNextLink = (PagerLruLink *)(&((u8 *)pLink->pNext)[iOff]);
23439     pNextLink->pPrev = pLink->pPrev;
23440   }
23441   if( pPg==pList->pFirstSynced ){
23442     PgHdr *p = pLink->pNext;
23443     while( p && p->needSync ){
23444       PagerLruLink *pL = (PagerLruLink *)(&((u8 *)p)[iOff]);
23445       p = pL->pNext;
23446     }
23447     pList->pFirstSynced = p;
23448   }
23449
23450   pLink->pNext = pLink->pPrev = 0;
23451 }
23452
23453 /* 
23454 ** Add page pPg to the list of free pages for the pager. If 
23455 ** memory-management is enabled, also add the page to the global 
23456 ** list of free pages.
23457 */
23458 static void lruListAdd(PgHdr *pPg){
23459   listAdd(&pPg->pPager->lru, &pPg->free, pPg);
23460 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23461   if( !pPg->pPager->memDb ){
23462     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
23463     listAdd(&sqlite3LruPageList, &pPg->gfree, pPg);
23464     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
23465   }
23466 #endif
23467 }
23468
23469 /* 
23470 ** Remove page pPg from the list of free pages for the associated pager.
23471 ** If memory-management is enabled, also remove pPg from the global list
23472 ** of free pages.
23473 */
23474 static void lruListRemove(PgHdr *pPg){
23475   listRemove(&pPg->pPager->lru, &pPg->free, pPg);
23476 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23477   if( !pPg->pPager->memDb ){
23478     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
23479     listRemove(&sqlite3LruPageList, &pPg->gfree, pPg);
23480     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
23481   }
23482 #endif
23483 }
23484
23485 /* 
23486 ** This function is called just after the needSync flag has been cleared
23487 ** from all pages managed by pPager (usually because the journal file
23488 ** has just been synced). It updates the pPager->lru.pFirstSynced variable
23489 ** and, if memory-management is enabled, the sqlite3LruPageList.pFirstSynced
23490 ** variable also.
23491 */
23492 static void lruListSetFirstSynced(Pager *pPager){
23493   pPager->lru.pFirstSynced = pPager->lru.pFirst;
23494 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23495   if( !pPager->memDb ){
23496     PgHdr *p;
23497     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
23498     for(p=sqlite3LruPageList.pFirst; p && p->needSync; p=p->gfree.pNext);
23499     assert(p==pPager->lru.pFirstSynced || p==sqlite3LruPageList.pFirstSynced);
23500     sqlite3LruPageList.pFirstSynced = p;
23501     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
23502   }
23503 #endif
23504 }
23505
23506 /*
23507 ** Return true if page *pPg has already been written to the statement
23508 ** journal (or statement snapshot has been created, if *pPg is part
23509 ** of an in-memory database).
23510 */
23511 static int pageInStatement(PgHdr *pPg){
23512   Pager *pPager = pPg->pPager;
23513   if( MEMDB ){
23514     return PGHDR_TO_HIST(pPg, pPager)->inStmt;
23515   }else{
23516     return sqlite3BitvecTest(pPager->pInStmt, pPg->pgno);
23517   }
23518 }
23519
23520 /*
23521 ** Change the size of the pager hash table to N.  N must be a power
23522 ** of two.
23523 */
23524 static void pager_resize_hash_table(Pager *pPager, int N){
23525   PgHdr **aHash, *pPg;
23526   assert( N>0 && (N&(N-1))==0 );
23527 #ifdef SQLITE_MALLOC_SOFT_LIMIT
23528   if( N*sizeof(aHash[0])>SQLITE_MALLOC_SOFT_LIMIT ){
23529     N = SQLITE_MALLOC_SOFT_LIMIT/sizeof(aHash[0]);
23530   }
23531   if( N==pPager->nHash ) return;
23532 #endif
23533   pagerLeave(pPager);
23534   sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, pPager->aHash!=0);
23535   aHash = sqlite3MallocZero( sizeof(aHash[0])*N );
23536   sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 0);
23537   pagerEnter(pPager);
23538   if( aHash==0 ){
23539     /* Failure to rehash is not an error.  It is only a performance hit. */
23540     return;
23541   }
23542   sqlite3_free(pPager->aHash);
23543   pPager->nHash = N;
23544   pPager->aHash = aHash;
23545   for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
23546     int h;
23547     if( pPg->pgno==0 ){
23548       assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
23549       continue;
23550     }
23551     h = pPg->pgno & (N-1);
23552     pPg->pNextHash = aHash[h];
23553     if( aHash[h] ){
23554       aHash[h]->pPrevHash = pPg;
23555     }
23556     aHash[h] = pPg;
23557     pPg->pPrevHash = 0;
23558   }
23559 }
23560
23561 /*
23562 ** Read a 32-bit integer from the given file descriptor.  Store the integer
23563 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
23564 ** error code is something goes wrong.
23565 **
23566 ** All values are stored on disk as big-endian.
23567 */
23568 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
23569   unsigned char ac[4];
23570   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
23571   if( rc==SQLITE_OK ){
23572     *pRes = sqlite3Get4byte(ac);
23573   }
23574   return rc;
23575 }
23576
23577 /*
23578 ** Write a 32-bit integer into a string buffer in big-endian byte order.
23579 */
23580 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
23581
23582 /*
23583 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
23584 ** on success or an error code is something goes wrong.
23585 */
23586 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
23587   char ac[4];
23588   put32bits(ac, val);
23589   return sqlite3OsWrite(fd, ac, 4, offset);
23590 }
23591
23592 /*
23593 ** If file pFd is open, call sqlite3OsUnlock() on it.
23594 */
23595 static int osUnlock(sqlite3_file *pFd, int eLock){
23596   if( !pFd->pMethods ){
23597     return SQLITE_OK;
23598   }
23599   return sqlite3OsUnlock(pFd, eLock);
23600 }
23601
23602 /*
23603 ** This function determines whether or not the atomic-write optimization
23604 ** can be used with this pager. The optimization can be used if:
23605 **
23606 **  (a) the value returned by OsDeviceCharacteristics() indicates that
23607 **      a database page may be written atomically, and
23608 **  (b) the value returned by OsSectorSize() is less than or equal
23609 **      to the page size.
23610 **
23611 ** If the optimization cannot be used, 0 is returned. If it can be used,
23612 ** then the value returned is the size of the journal file when it
23613 ** contains rollback data for exactly one page.
23614 */
23615 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
23616 static int jrnlBufferSize(Pager *pPager){
23617   int dc;           /* Device characteristics */
23618   int nSector;      /* Sector size */
23619   int nPage;        /* Page size */
23620   sqlite3_file *fd = pPager->fd;
23621
23622   if( fd->pMethods ){
23623     dc = sqlite3OsDeviceCharacteristics(fd);
23624     nSector = sqlite3OsSectorSize(fd);
23625     nPage = pPager->pageSize;
23626   }
23627
23628   assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
23629   assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
23630
23631   if( !fd->pMethods || (dc&(SQLITE_IOCAP_ATOMIC|(nPage>>8))&&nSector<=nPage) ){
23632     return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
23633   }
23634   return 0;
23635 }
23636 #endif
23637
23638 /*
23639 ** This function should be called when an error occurs within the pager
23640 ** code. The first argument is a pointer to the pager structure, the
23641 ** second the error-code about to be returned by a pager API function. 
23642 ** The value returned is a copy of the second argument to this function. 
23643 **
23644 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
23645 ** the error becomes persistent. Until the persisten error is cleared,
23646 ** subsequent API calls on this Pager will immediately return the same 
23647 ** error code.
23648 **
23649 ** A persistent error indicates that the contents of the pager-cache 
23650 ** cannot be trusted. This state can be cleared by completely discarding 
23651 ** the contents of the pager-cache. If a transaction was active when
23652 ** the persistent error occured, then the rollback journal may need
23653 ** to be replayed.
23654 */
23655 static void pager_unlock(Pager *pPager);
23656 static int pager_error(Pager *pPager, int rc){
23657   int rc2 = rc & 0xff;
23658   assert(
23659        pPager->errCode==SQLITE_FULL ||
23660        pPager->errCode==SQLITE_OK ||
23661        (pPager->errCode & 0xff)==SQLITE_IOERR
23662   );
23663   if(
23664     rc2==SQLITE_FULL ||
23665     rc2==SQLITE_IOERR ||
23666     rc2==SQLITE_CORRUPT
23667   ){
23668     pPager->errCode = rc;
23669     if( pPager->state==PAGER_UNLOCK && pPager->nRef==0 ){
23670       /* If the pager is already unlocked, call pager_unlock() now to
23671       ** clear the error state and ensure that the pager-cache is 
23672       ** completely empty.
23673       */
23674       pager_unlock(pPager);
23675     }
23676   }
23677   return rc;
23678 }
23679
23680 /*
23681 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
23682 ** on the cache using a hash function.  This is used for testing
23683 ** and debugging only.
23684 */
23685 #ifdef SQLITE_CHECK_PAGES
23686 /*
23687 ** Return a 32-bit hash of the page data for pPage.
23688 */
23689 static u32 pager_datahash(int nByte, unsigned char *pData){
23690   u32 hash = 0;
23691   int i;
23692   for(i=0; i<nByte; i++){
23693     hash = (hash*1039) + pData[i];
23694   }
23695   return hash;
23696 }
23697 static u32 pager_pagehash(PgHdr *pPage){
23698   return pager_datahash(pPage->pPager->pageSize, 
23699                         (unsigned char *)PGHDR_TO_DATA(pPage));
23700 }
23701
23702 /*
23703 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
23704 ** is defined, and NDEBUG is not defined, an assert() statement checks
23705 ** that the page is either dirty or still matches the calculated page-hash.
23706 */
23707 #define CHECK_PAGE(x) checkPage(x)
23708 static void checkPage(PgHdr *pPg){
23709   Pager *pPager = pPg->pPager;
23710   assert( !pPg->pageHash || pPager->errCode || MEMDB || pPg->dirty || 
23711       pPg->pageHash==pager_pagehash(pPg) );
23712 }
23713
23714 #else
23715 #define pager_datahash(X,Y)  0
23716 #define pager_pagehash(X)  0
23717 #define CHECK_PAGE(x)
23718 #endif
23719
23720 /*
23721 ** When this is called the journal file for pager pPager must be open.
23722 ** The master journal file name is read from the end of the file and 
23723 ** written into memory supplied by the caller. 
23724 **
23725 ** zMaster must point to a buffer of at least nMaster bytes allocated by
23726 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
23727 ** enough space to write the master journal name). If the master journal
23728 ** name in the journal is longer than nMaster bytes (including a
23729 ** nul-terminator), then this is handled as if no master journal name
23730 ** were present in the journal.
23731 **
23732 ** If no master journal file name is present zMaster[0] is set to 0 and
23733 ** SQLITE_OK returned.
23734 */
23735 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, int nMaster){
23736   int rc;
23737   u32 len;
23738   i64 szJ;
23739   u32 cksum;
23740   int i;
23741   unsigned char aMagic[8]; /* A buffer to hold the magic header */
23742
23743   zMaster[0] = '\0';
23744
23745   rc = sqlite3OsFileSize(pJrnl, &szJ);
23746   if( rc!=SQLITE_OK || szJ<16 ) return rc;
23747
23748   rc = read32bits(pJrnl, szJ-16, &len);
23749   if( rc!=SQLITE_OK ) return rc;
23750
23751   if( len>=nMaster ){
23752     return SQLITE_OK;
23753   }
23754
23755   rc = read32bits(pJrnl, szJ-12, &cksum);
23756   if( rc!=SQLITE_OK ) return rc;
23757
23758   rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
23759   if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
23760
23761   rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
23762   if( rc!=SQLITE_OK ){
23763     return rc;
23764   }
23765   zMaster[len] = '\0';
23766
23767   /* See if the checksum matches the master journal name */
23768   for(i=0; i<len; i++){
23769     cksum -= zMaster[i];
23770    }
23771   if( cksum ){
23772     /* If the checksum doesn't add up, then one or more of the disk sectors
23773     ** containing the master journal filename is corrupted. This means
23774     ** definitely roll back, so just return SQLITE_OK and report a (nul)
23775     ** master-journal filename.
23776     */
23777     zMaster[0] = '\0';
23778   }
23779    
23780   return SQLITE_OK;
23781 }
23782
23783 /*
23784 ** Seek the journal file descriptor to the next sector boundary where a
23785 ** journal header may be read or written. Pager.journalOff is updated with
23786 ** the new seek offset.
23787 **
23788 ** i.e for a sector size of 512:
23789 **
23790 ** Input Offset              Output Offset
23791 ** ---------------------------------------
23792 ** 0                         0
23793 ** 512                       512
23794 ** 100                       512
23795 ** 2000                      2048
23796 ** 
23797 */
23798 static void seekJournalHdr(Pager *pPager){
23799   i64 offset = 0;
23800   i64 c = pPager->journalOff;
23801   if( c ){
23802     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
23803   }
23804   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
23805   assert( offset>=c );
23806   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
23807   pPager->journalOff = offset;
23808 }
23809
23810 /*
23811 ** The journal file must be open when this routine is called. A journal
23812 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
23813 ** current location.
23814 **
23815 ** The format for the journal header is as follows:
23816 ** - 8 bytes: Magic identifying journal format.
23817 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
23818 ** - 4 bytes: Random number used for page hash.
23819 ** - 4 bytes: Initial database page count.
23820 ** - 4 bytes: Sector size used by the process that wrote this journal.
23821 ** 
23822 ** Followed by (JOURNAL_HDR_SZ - 24) bytes of unused space.
23823 */
23824 static int writeJournalHdr(Pager *pPager){
23825   char zHeader[sizeof(aJournalMagic)+16];
23826   int rc;
23827
23828   if( pPager->stmtHdrOff==0 ){
23829     pPager->stmtHdrOff = pPager->journalOff;
23830   }
23831
23832   seekJournalHdr(pPager);
23833   pPager->journalHdr = pPager->journalOff;
23834
23835   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
23836
23837   /* 
23838   ** Write the nRec Field - the number of page records that follow this
23839   ** journal header. Normally, zero is written to this value at this time.
23840   ** After the records are added to the journal (and the journal synced, 
23841   ** if in full-sync mode), the zero is overwritten with the true number
23842   ** of records (see syncJournal()).
23843   **
23844   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
23845   ** reading the journal this value tells SQLite to assume that the
23846   ** rest of the journal file contains valid page records. This assumption
23847   ** is dangerous, as if a failure occured whilst writing to the journal
23848   ** file it may contain some garbage data. There are two scenarios
23849   ** where this risk can be ignored:
23850   **
23851   **   * When the pager is in no-sync mode. Corruption can follow a
23852   **     power failure in this case anyway.
23853   **
23854   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
23855   **     that garbage data is never appended to the journal file.
23856   */
23857   assert(pPager->fd->pMethods||pPager->noSync);
23858   if( (pPager->noSync) 
23859    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
23860   ){
23861     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
23862   }else{
23863     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
23864   }
23865
23866   /* The random check-hash initialiser */ 
23867   sqlite3Randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
23868   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
23869   /* The initial database size */
23870   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
23871   /* The assumed sector size for this process */
23872   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
23873   IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, sizeof(zHeader)))
23874   rc = sqlite3OsWrite(pPager->jfd, zHeader, sizeof(zHeader),pPager->journalOff);
23875   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
23876
23877   /* The journal header has been written successfully. Seek the journal
23878   ** file descriptor to the end of the journal header sector.
23879   */
23880   if( rc==SQLITE_OK ){
23881     IOTRACE(("JTAIL %p %lld\n", pPager, pPager->journalOff-1))
23882     rc = sqlite3OsWrite(pPager->jfd, "\000", 1, pPager->journalOff-1);
23883   }
23884   return rc;
23885 }
23886
23887 /*
23888 ** The journal file must be open when this is called. A journal header file
23889 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
23890 ** file. See comments above function writeJournalHdr() for a description of
23891 ** the journal header format.
23892 **
23893 ** If the header is read successfully, *nRec is set to the number of
23894 ** page records following this header and *dbSize is set to the size of the
23895 ** database before the transaction began, in pages. Also, pPager->cksumInit
23896 ** is set to the value read from the journal header. SQLITE_OK is returned
23897 ** in this case.
23898 **
23899 ** If the journal header file appears to be corrupted, SQLITE_DONE is
23900 ** returned and *nRec and *dbSize are not set.  If JOURNAL_HDR_SZ bytes
23901 ** cannot be read from the journal file an error code is returned.
23902 */
23903 static int readJournalHdr(
23904   Pager *pPager, 
23905   i64 journalSize,
23906   u32 *pNRec, 
23907   u32 *pDbSize
23908 ){
23909   int rc;
23910   unsigned char aMagic[8]; /* A buffer to hold the magic header */
23911   i64 jrnlOff;
23912
23913   seekJournalHdr(pPager);
23914   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
23915     return SQLITE_DONE;
23916   }
23917   jrnlOff = pPager->journalOff;
23918
23919   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
23920   if( rc ) return rc;
23921   jrnlOff += sizeof(aMagic);
23922
23923   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
23924     return SQLITE_DONE;
23925   }
23926
23927   rc = read32bits(pPager->jfd, jrnlOff, pNRec);
23928   if( rc ) return rc;
23929
23930   rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
23931   if( rc ) return rc;
23932
23933   rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
23934   if( rc ) return rc;
23935
23936   /* Update the assumed sector-size to match the value used by 
23937   ** the process that created this journal. If this journal was
23938   ** created by a process other than this one, then this routine
23939   ** is being called from within pager_playback(). The local value
23940   ** of Pager.sectorSize is restored at the end of that routine.
23941   */
23942   rc = read32bits(pPager->jfd, jrnlOff+12, (u32 *)&pPager->sectorSize);
23943   if( rc ) return rc;
23944
23945   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
23946   return SQLITE_OK;
23947 }
23948
23949
23950 /*
23951 ** Write the supplied master journal name into the journal file for pager
23952 ** pPager at the current location. The master journal name must be the last
23953 ** thing written to a journal file. If the pager is in full-sync mode, the
23954 ** journal file descriptor is advanced to the next sector boundary before
23955 ** anything is written. The format is:
23956 **
23957 ** + 4 bytes: PAGER_MJ_PGNO.
23958 ** + N bytes: length of master journal name.
23959 ** + 4 bytes: N
23960 ** + 4 bytes: Master journal name checksum.
23961 ** + 8 bytes: aJournalMagic[].
23962 **
23963 ** The master journal page checksum is the sum of the bytes in the master
23964 ** journal name.
23965 **
23966 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
23967 ** this call is a no-op.
23968 */
23969 static int writeMasterJournal(Pager *pPager, const char *zMaster){
23970   int rc;
23971   int len; 
23972   int i; 
23973   i64 jrnlOff;
23974   u32 cksum = 0;
23975   char zBuf[sizeof(aJournalMagic)+2*4];
23976
23977   if( !zMaster || pPager->setMaster) return SQLITE_OK;
23978   pPager->setMaster = 1;
23979
23980   len = strlen(zMaster);
23981   for(i=0; i<len; i++){
23982     cksum += zMaster[i];
23983   }
23984
23985   /* If in full-sync mode, advance to the next disk sector before writing
23986   ** the master journal name. This is in case the previous page written to
23987   ** the journal has already been synced.
23988   */
23989   if( pPager->fullSync ){
23990     seekJournalHdr(pPager);
23991   }
23992   jrnlOff = pPager->journalOff;
23993   pPager->journalOff += (len+20);
23994
23995   rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
23996   if( rc!=SQLITE_OK ) return rc;
23997   jrnlOff += 4;
23998
23999   rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
24000   if( rc!=SQLITE_OK ) return rc;
24001   jrnlOff += len;
24002
24003   put32bits(zBuf, len);
24004   put32bits(&zBuf[4], cksum);
24005   memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
24006   rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
24007   pPager->needSync = !pPager->noSync;
24008   return rc;
24009 }
24010
24011 /*
24012 ** Add or remove a page from the list of all pages that are in the
24013 ** statement journal.
24014 **
24015 ** The Pager keeps a separate list of pages that are currently in
24016 ** the statement journal.  This helps the sqlite3PagerStmtCommit()
24017 ** routine run MUCH faster for the common case where there are many
24018 ** pages in memory but only a few are in the statement journal.
24019 */
24020 static void page_add_to_stmt_list(PgHdr *pPg){
24021   Pager *pPager = pPg->pPager;
24022   PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
24023   assert( MEMDB );
24024   if( !pHist->inStmt ){
24025     assert( pHist->pPrevStmt==0 && pHist->pNextStmt==0 );
24026     if( pPager->pStmt ){
24027       PGHDR_TO_HIST(pPager->pStmt, pPager)->pPrevStmt = pPg;
24028     }
24029     pHist->pNextStmt = pPager->pStmt;
24030     pPager->pStmt = pPg;
24031     pHist->inStmt = 1;
24032   }
24033 }
24034
24035 /*
24036 ** Find a page in the hash table given its page number.  Return
24037 ** a pointer to the page or NULL if not found.
24038 */
24039 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
24040   PgHdr *p;
24041   if( pPager->aHash==0 ) return 0;
24042   p = pPager->aHash[pgno & (pPager->nHash-1)];
24043   while( p && p->pgno!=pgno ){
24044     p = p->pNextHash;
24045   }
24046   return p;
24047 }
24048
24049 /*
24050 ** Clear the in-memory cache.  This routine
24051 ** sets the state of the pager back to what it was when it was first
24052 ** opened.  Any outstanding pages are invalidated and subsequent attempts
24053 ** to access those pages will likely result in a coredump.
24054 */
24055 static void pager_reset(Pager *pPager){
24056   PgHdr *pPg, *pNext;
24057   if( pPager->errCode ) return;
24058   for(pPg=pPager->pAll; pPg; pPg=pNext){
24059     IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
24060     PAGER_INCR(sqlite3_pager_pgfree_count);
24061     pNext = pPg->pNextAll;
24062     lruListRemove(pPg);
24063     sqlite3_free(pPg->pData);
24064     sqlite3_free(pPg);
24065   }
24066   assert(pPager->lru.pFirst==0);
24067   assert(pPager->lru.pFirstSynced==0);
24068   assert(pPager->lru.pLast==0);
24069   pPager->pStmt = 0;
24070   pPager->pAll = 0;
24071   pPager->pDirty = 0;
24072   pPager->nHash = 0;
24073   sqlite3_free(pPager->aHash);
24074   pPager->nPage = 0;
24075   pPager->aHash = 0;
24076   pPager->nRef = 0;
24077 }
24078
24079 /*
24080 ** Unlock the database file. 
24081 **
24082 ** If the pager is currently in error state, discard the contents of 
24083 ** the cache and reset the Pager structure internal state. If there is
24084 ** an open journal-file, then the next time a shared-lock is obtained
24085 ** on the pager file (by this or any other process), it will be
24086 ** treated as a hot-journal and rolled back.
24087 */
24088 static void pager_unlock(Pager *pPager){
24089   if( !pPager->exclusiveMode ){
24090     if( !MEMDB ){
24091       int rc = osUnlock(pPager->fd, NO_LOCK);
24092       if( rc ) pPager->errCode = rc;
24093       pPager->dbSize = -1;
24094       IOTRACE(("UNLOCK %p\n", pPager))
24095
24096       /* If Pager.errCode is set, the contents of the pager cache cannot be
24097       ** trusted. Now that the pager file is unlocked, the contents of the
24098       ** cache can be discarded and the error code safely cleared.
24099       */
24100       if( pPager->errCode ){
24101         if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;
24102         pager_reset(pPager);
24103         if( pPager->stmtOpen ){
24104           sqlite3OsClose(pPager->stfd);
24105           sqlite3BitvecDestroy(pPager->pInStmt);
24106           pPager->pInStmt = 0;
24107         }
24108         if( pPager->journalOpen ){
24109           sqlite3OsClose(pPager->jfd);
24110           pPager->journalOpen = 0;
24111           sqlite3BitvecDestroy(pPager->pInJournal);
24112           pPager->pInJournal = 0;
24113         }
24114         pPager->stmtOpen = 0;
24115         pPager->stmtInUse = 0;
24116         pPager->journalOff = 0;
24117         pPager->journalStarted = 0;
24118         pPager->stmtAutoopen = 0;
24119         pPager->origDbSize = 0;
24120       }
24121     }
24122
24123     if( !MEMDB || pPager->errCode==SQLITE_OK ){
24124       pPager->state = PAGER_UNLOCK;
24125       pPager->changeCountDone = 0;
24126     }
24127   }
24128 }
24129
24130 /*
24131 ** Execute a rollback if a transaction is active and unlock the 
24132 ** database file. If the pager has already entered the error state, 
24133 ** do not attempt the rollback.
24134 */
24135 static void pagerUnlockAndRollback(Pager *p){
24136   assert( p->state>=PAGER_RESERVED || p->journalOpen==0 );
24137   if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
24138     sqlite3PagerRollback(p);
24139   }
24140   pager_unlock(p);
24141   assert( p->errCode || !p->journalOpen || (p->exclusiveMode&&!p->journalOff) );
24142   assert( p->errCode || !p->stmtOpen || p->exclusiveMode );
24143 }
24144
24145 /*
24146 ** This routine ends a transaction.  A transaction is ended by either
24147 ** a COMMIT or a ROLLBACK.
24148 **
24149 ** When this routine is called, the pager has the journal file open and
24150 ** a RESERVED or EXCLUSIVE lock on the database.  This routine will release
24151 ** the database lock and acquires a SHARED lock in its place if that is
24152 ** the appropriate thing to do.  Release locks usually is appropriate,
24153 ** unless we are in exclusive access mode or unless this is a 
24154 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
24155 **
24156 ** The journal file is either deleted or truncated.
24157 **
24158 ** TODO: Consider keeping the journal file open for temporary databases.
24159 ** This might give a performance improvement on windows where opening
24160 ** a file is an expensive operation.
24161 */
24162 static int pager_end_transaction(Pager *pPager){
24163   PgHdr *pPg;
24164   int rc = SQLITE_OK;
24165   int rc2 = SQLITE_OK;
24166   assert( !MEMDB );
24167   if( pPager->state<PAGER_RESERVED ){
24168     return SQLITE_OK;
24169   }
24170   sqlite3PagerStmtCommit(pPager);
24171   if( pPager->stmtOpen && !pPager->exclusiveMode ){
24172     sqlite3OsClose(pPager->stfd);
24173     pPager->stmtOpen = 0;
24174   }
24175   if( pPager->journalOpen ){
24176     if( pPager->exclusiveMode 
24177           && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){;
24178       pPager->journalOff = 0;
24179       pPager->journalStarted = 0;
24180     }else{
24181       sqlite3OsClose(pPager->jfd);
24182       pPager->journalOpen = 0;
24183       if( rc==SQLITE_OK ){
24184         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
24185       }
24186     }
24187     sqlite3BitvecDestroy(pPager->pInJournal);
24188     pPager->pInJournal = 0;
24189     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
24190       pPg->inJournal = 0;
24191       pPg->dirty = 0;
24192       pPg->needSync = 0;
24193       pPg->alwaysRollback = 0;
24194 #ifdef SQLITE_CHECK_PAGES
24195       pPg->pageHash = pager_pagehash(pPg);
24196 #endif
24197     }
24198     pPager->pDirty = 0;
24199     pPager->dirtyCache = 0;
24200     pPager->nRec = 0;
24201   }else{
24202     assert( pPager->pInJournal==0 );
24203     assert( pPager->dirtyCache==0 || pPager->useJournal==0 );
24204   }
24205
24206   if( !pPager->exclusiveMode ){
24207     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
24208     pPager->state = PAGER_SHARED;
24209   }else if( pPager->state==PAGER_SYNCED ){
24210     pPager->state = PAGER_EXCLUSIVE;
24211   }
24212   pPager->origDbSize = 0;
24213   pPager->setMaster = 0;
24214   pPager->needSync = 0;
24215   lruListSetFirstSynced(pPager);
24216   pPager->dbSize = -1;
24217
24218   return (rc==SQLITE_OK?rc2:rc);
24219 }
24220
24221 /*
24222 ** Compute and return a checksum for the page of data.
24223 **
24224 ** This is not a real checksum.  It is really just the sum of the 
24225 ** random initial value and the page number.  We experimented with
24226 ** a checksum of the entire data, but that was found to be too slow.
24227 **
24228 ** Note that the page number is stored at the beginning of data and
24229 ** the checksum is stored at the end.  This is important.  If journal
24230 ** corruption occurs due to a power failure, the most likely scenario
24231 ** is that one end or the other of the record will be changed.  It is
24232 ** much less likely that the two ends of the journal record will be
24233 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
24234 ** though fast and simple, catches the mostly likely kind of corruption.
24235 **
24236 ** FIX ME:  Consider adding every 200th (or so) byte of the data to the
24237 ** checksum.  That way if a single page spans 3 or more disk sectors and
24238 ** only the middle sector is corrupt, we will still have a reasonable
24239 ** chance of failing the checksum and thus detecting the problem.
24240 */
24241 static u32 pager_cksum(Pager *pPager, const u8 *aData){
24242   u32 cksum = pPager->cksumInit;
24243   int i = pPager->pageSize-200;
24244   while( i>0 ){
24245     cksum += aData[i];
24246     i -= 200;
24247   }
24248   return cksum;
24249 }
24250
24251 /* Forward declaration */
24252 static void makeClean(PgHdr*);
24253
24254 /*
24255 ** Read a single page from the journal file opened on file descriptor
24256 ** jfd.  Playback this one page.
24257 **
24258 ** If useCksum==0 it means this journal does not use checksums.  Checksums
24259 ** are not used in statement journals because statement journals do not
24260 ** need to survive power failures.
24261 */
24262 static int pager_playback_one_page(
24263   Pager *pPager, 
24264   sqlite3_file *jfd,
24265   i64 offset,
24266   int useCksum
24267 ){
24268   int rc;
24269   PgHdr *pPg;                   /* An existing page in the cache */
24270   Pgno pgno;                    /* The page number of a page in journal */
24271   u32 cksum;                    /* Checksum used for sanity checking */
24272   u8 *aData = (u8 *)pPager->pTmpSpace;   /* Temp storage for a page */
24273
24274   /* useCksum should be true for the main journal and false for
24275   ** statement journals.  Verify that this is always the case
24276   */
24277   assert( jfd == (useCksum ? pPager->jfd : pPager->stfd) );
24278   assert( aData );
24279
24280   rc = read32bits(jfd, offset, &pgno);
24281   if( rc!=SQLITE_OK ) return rc;
24282   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, offset+4);
24283   if( rc!=SQLITE_OK ) return rc;
24284   pPager->journalOff += pPager->pageSize + 4;
24285
24286   /* Sanity checking on the page.  This is more important that I originally
24287   ** thought.  If a power failure occurs while the journal is being written,
24288   ** it could cause invalid data to be written into the journal.  We need to
24289   ** detect this invalid data (with high probability) and ignore it.
24290   */
24291   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
24292     return SQLITE_DONE;
24293   }
24294   if( pgno>(unsigned)pPager->dbSize ){
24295     return SQLITE_OK;
24296   }
24297   if( useCksum ){
24298     rc = read32bits(jfd, offset+pPager->pageSize+4, &cksum);
24299     if( rc ) return rc;
24300     pPager->journalOff += 4;
24301     if( pager_cksum(pPager, aData)!=cksum ){
24302       return SQLITE_DONE;
24303     }
24304   }
24305
24306   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
24307
24308   /* If the pager is in RESERVED state, then there must be a copy of this
24309   ** page in the pager cache. In this case just update the pager cache,
24310   ** not the database file. The page is left marked dirty in this case.
24311   **
24312   ** An exception to the above rule: If the database is in no-sync mode
24313   ** and a page is moved during an incremental vacuum then the page may
24314   ** not be in the pager cache. Later: if a malloc() or IO error occurs
24315   ** during a Movepage() call, then the page may not be in the cache
24316   ** either. So the condition described in the above paragraph is not
24317   ** assert()able.
24318   **
24319   ** If in EXCLUSIVE state, then we update the pager cache if it exists
24320   ** and the main file. The page is then marked not dirty.
24321   **
24322   ** Ticket #1171:  The statement journal might contain page content that is
24323   ** different from the page content at the start of the transaction.
24324   ** This occurs when a page is changed prior to the start of a statement
24325   ** then changed again within the statement.  When rolling back such a
24326   ** statement we must not write to the original database unless we know
24327   ** for certain that original page contents are synced into the main rollback
24328   ** journal.  Otherwise, a power loss might leave modified data in the
24329   ** database file without an entry in the rollback journal that can
24330   ** restore the database to its original form.  Two conditions must be
24331   ** met before writing to the database files. (1) the database must be
24332   ** locked.  (2) we know that the original page content is fully synced
24333   ** in the main journal either because the page is not in cache or else
24334   ** the page is marked as needSync==0.
24335   */
24336   pPg = pager_lookup(pPager, pgno);
24337   PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
24338                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
24339   if( pPager->state>=PAGER_EXCLUSIVE && (pPg==0 || pPg->needSync==0) ){
24340     i64 offset = (pgno-1)*(i64)pPager->pageSize;
24341     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, offset);
24342     if( pPg ){
24343       makeClean(pPg);
24344     }
24345   }
24346   if( pPg ){
24347     /* No page should ever be explicitly rolled back that is in use, except
24348     ** for page 1 which is held in use in order to keep the lock on the
24349     ** database active. However such a page may be rolled back as a result
24350     ** of an internal error resulting in an automatic call to
24351     ** sqlite3PagerRollback().
24352     */
24353     void *pData;
24354     /* assert( pPg->nRef==0 || pPg->pgno==1 ); */
24355     pData = PGHDR_TO_DATA(pPg);
24356     memcpy(pData, aData, pPager->pageSize);
24357     if( pPager->xReiniter ){
24358       pPager->xReiniter(pPg, pPager->pageSize);
24359     }
24360 #ifdef SQLITE_CHECK_PAGES
24361     pPg->pageHash = pager_pagehash(pPg);
24362 #endif
24363     /* If this was page 1, then restore the value of Pager.dbFileVers.
24364     ** Do this before any decoding. */
24365     if( pgno==1 ){
24366       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
24367     }
24368
24369     /* Decode the page just read from disk */
24370     CODEC1(pPager, pData, pPg->pgno, 3);
24371   }
24372   return rc;
24373 }
24374
24375 /*
24376 ** Parameter zMaster is the name of a master journal file. A single journal
24377 ** file that referred to the master journal file has just been rolled back.
24378 ** This routine checks if it is possible to delete the master journal file,
24379 ** and does so if it is.
24380 **
24381 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
24382 ** available for use within this function.
24383 **
24384 **
24385 ** The master journal file contains the names of all child journals.
24386 ** To tell if a master journal can be deleted, check to each of the
24387 ** children.  If all children are either missing or do not refer to
24388 ** a different master journal, then this master journal can be deleted.
24389 */
24390 static int pager_delmaster(Pager *pPager, const char *zMaster){
24391   sqlite3_vfs *pVfs = pPager->pVfs;
24392   int rc;
24393   int master_open = 0;
24394   sqlite3_file *pMaster;
24395   sqlite3_file *pJournal;
24396   char *zMasterJournal = 0; /* Contents of master journal file */
24397   i64 nMasterJournal;       /* Size of master journal file */
24398
24399   /* Open the master journal file exclusively in case some other process
24400   ** is running this routine also. Not that it makes too much difference.
24401   */
24402   pMaster = (sqlite3_file *)sqlite3_malloc(pVfs->szOsFile * 2);
24403   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
24404   if( !pMaster ){
24405     rc = SQLITE_NOMEM;
24406   }else{
24407     int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
24408     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
24409   }
24410   if( rc!=SQLITE_OK ) goto delmaster_out;
24411   master_open = 1;
24412
24413   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
24414   if( rc!=SQLITE_OK ) goto delmaster_out;
24415
24416   if( nMasterJournal>0 ){
24417     char *zJournal;
24418     char *zMasterPtr = 0;
24419     int nMasterPtr = pPager->pVfs->mxPathname+1;
24420
24421     /* Load the entire master journal file into space obtained from
24422     ** sqlite3_malloc() and pointed to by zMasterJournal. 
24423     */
24424     zMasterJournal = (char *)sqlite3_malloc(nMasterJournal + nMasterPtr);
24425     if( !zMasterJournal ){
24426       rc = SQLITE_NOMEM;
24427       goto delmaster_out;
24428     }
24429     zMasterPtr = &zMasterJournal[nMasterJournal];
24430     rc = sqlite3OsRead(pMaster, zMasterJournal, nMasterJournal, 0);
24431     if( rc!=SQLITE_OK ) goto delmaster_out;
24432
24433     zJournal = zMasterJournal;
24434     while( (zJournal-zMasterJournal)<nMasterJournal ){
24435       if( sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS) ){
24436         /* One of the journals pointed to by the master journal exists.
24437         ** Open it and check if it points at the master journal. If
24438         ** so, return without deleting the master journal file.
24439         */
24440         int c;
24441         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
24442         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
24443         if( rc!=SQLITE_OK ){
24444           goto delmaster_out;
24445         }
24446
24447         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
24448         sqlite3OsClose(pJournal);
24449         if( rc!=SQLITE_OK ){
24450           goto delmaster_out;
24451         }
24452
24453         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
24454         if( c ){
24455           /* We have a match. Do not delete the master journal file. */
24456           goto delmaster_out;
24457         }
24458       }
24459       zJournal += (strlen(zJournal)+1);
24460     }
24461   }
24462   
24463   rc = sqlite3OsDelete(pVfs, zMaster, 0);
24464
24465 delmaster_out:
24466   if( zMasterJournal ){
24467     sqlite3_free(zMasterJournal);
24468   }  
24469   if( master_open ){
24470     sqlite3OsClose(pMaster);
24471   }
24472   sqlite3_free(pMaster);
24473   return rc;
24474 }
24475
24476
24477 static void pager_truncate_cache(Pager *pPager);
24478
24479 /*
24480 ** Truncate the main file of the given pager to the number of pages
24481 ** indicated. Also truncate the cached representation of the file.
24482 **
24483 ** Might might be the case that the file on disk is smaller than nPage.
24484 ** This can happen, for example, if we are in the middle of a transaction
24485 ** which has extended the file size and the new pages are still all held
24486 ** in cache, then an INSERT or UPDATE does a statement rollback.  Some
24487 ** operating system implementations can get confused if you try to
24488 ** truncate a file to some size that is larger than it currently is,
24489 ** so detect this case and do not do the truncation.
24490 */
24491 static int pager_truncate(Pager *pPager, int nPage){
24492   int rc = SQLITE_OK;
24493   if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
24494     i64 currentSize, newSize;
24495     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
24496     newSize = pPager->pageSize*(i64)nPage;
24497     if( rc==SQLITE_OK && currentSize>newSize ){
24498       rc = sqlite3OsTruncate(pPager->fd, newSize);
24499     }
24500   }
24501   if( rc==SQLITE_OK ){
24502     pPager->dbSize = nPage;
24503     pager_truncate_cache(pPager);
24504   }
24505   return rc;
24506 }
24507
24508 /*
24509 ** Set the sectorSize for the given pager.
24510 **
24511 ** The sector size is the larger of the sector size reported
24512 ** by sqlite3OsSectorSize() and the pageSize.
24513 */
24514 static void setSectorSize(Pager *pPager){
24515   assert(pPager->fd->pMethods||pPager->tempFile);
24516   if( !pPager->tempFile ){
24517     /* Sector size doesn't matter for temporary files. Also, the file
24518     ** may not have been opened yet, in whcih case the OsSectorSize()
24519     ** call will segfault.
24520     */
24521     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
24522   }
24523   if( pPager->sectorSize<pPager->pageSize ){
24524     pPager->sectorSize = pPager->pageSize;
24525   }
24526 }
24527
24528 /*
24529 ** Playback the journal and thus restore the database file to
24530 ** the state it was in before we started making changes.  
24531 **
24532 ** The journal file format is as follows: 
24533 **
24534 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
24535 **  (2)  4 byte big-endian integer which is the number of valid page records
24536 **       in the journal.  If this value is 0xffffffff, then compute the
24537 **       number of page records from the journal size.
24538 **  (3)  4 byte big-endian integer which is the initial value for the 
24539 **       sanity checksum.
24540 **  (4)  4 byte integer which is the number of pages to truncate the
24541 **       database to during a rollback.
24542 **  (5)  4 byte integer which is the number of bytes in the master journal
24543 **       name.  The value may be zero (indicate that there is no master
24544 **       journal.)
24545 **  (6)  N bytes of the master journal name.  The name will be nul-terminated
24546 **       and might be shorter than the value read from (5).  If the first byte
24547 **       of the name is \000 then there is no master journal.  The master
24548 **       journal name is stored in UTF-8.
24549 **  (7)  Zero or more pages instances, each as follows:
24550 **        +  4 byte page number.
24551 **        +  pPager->pageSize bytes of data.
24552 **        +  4 byte checksum
24553 **
24554 ** When we speak of the journal header, we mean the first 6 items above.
24555 ** Each entry in the journal is an instance of the 7th item.
24556 **
24557 ** Call the value from the second bullet "nRec".  nRec is the number of
24558 ** valid page entries in the journal.  In most cases, you can compute the
24559 ** value of nRec from the size of the journal file.  But if a power
24560 ** failure occurred while the journal was being written, it could be the
24561 ** case that the size of the journal file had already been increased but
24562 ** the extra entries had not yet made it safely to disk.  In such a case,
24563 ** the value of nRec computed from the file size would be too large.  For
24564 ** that reason, we always use the nRec value in the header.
24565 **
24566 ** If the nRec value is 0xffffffff it means that nRec should be computed
24567 ** from the file size.  This value is used when the user selects the
24568 ** no-sync option for the journal.  A power failure could lead to corruption
24569 ** in this case.  But for things like temporary table (which will be
24570 ** deleted when the power is restored) we don't care.  
24571 **
24572 ** If the file opened as the journal file is not a well-formed
24573 ** journal file then all pages up to the first corrupted page are rolled
24574 ** back (or no pages if the journal header is corrupted). The journal file
24575 ** is then deleted and SQLITE_OK returned, just as if no corruption had
24576 ** been encountered.
24577 **
24578 ** If an I/O or malloc() error occurs, the journal-file is not deleted
24579 ** and an error code is returned.
24580 */
24581 static int pager_playback(Pager *pPager, int isHot){
24582   sqlite3_vfs *pVfs = pPager->pVfs;
24583   i64 szJ;                 /* Size of the journal file in bytes */
24584   u32 nRec;                /* Number of Records in the journal */
24585   int i;                   /* Loop counter */
24586   Pgno mxPg = 0;           /* Size of the original file in pages */
24587   int rc;                  /* Result code of a subroutine */
24588   char *zMaster = 0;       /* Name of master journal file if any */
24589
24590   /* Figure out how many records are in the journal.  Abort early if
24591   ** the journal is empty.
24592   */
24593   assert( pPager->journalOpen );
24594   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
24595   if( rc!=SQLITE_OK || szJ==0 ){
24596     goto end_playback;
24597   }
24598
24599   /* Read the master journal name from the journal, if it is present.
24600   ** If a master journal file name is specified, but the file is not
24601   ** present on disk, then the journal is not hot and does not need to be
24602   ** played back.
24603   */
24604   zMaster = pPager->pTmpSpace;
24605   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
24606   assert( rc!=SQLITE_DONE );
24607   if( rc!=SQLITE_OK 
24608    || (zMaster[0] && !sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS)) 
24609   ){
24610     zMaster = 0;
24611     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
24612     goto end_playback;
24613   }
24614   pPager->journalOff = 0;
24615   zMaster = 0;
24616
24617   /* This loop terminates either when the readJournalHdr() call returns
24618   ** SQLITE_DONE or an IO error occurs. */
24619   while( 1 ){
24620
24621     /* Read the next journal header from the journal file.  If there are
24622     ** not enough bytes left in the journal file for a complete header, or
24623     ** it is corrupted, then a process must of failed while writing it.
24624     ** This indicates nothing more needs to be rolled back.
24625     */
24626     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
24627     if( rc!=SQLITE_OK ){ 
24628       if( rc==SQLITE_DONE ){
24629         rc = SQLITE_OK;
24630       }
24631       goto end_playback;
24632     }
24633
24634     /* If nRec is 0xffffffff, then this journal was created by a process
24635     ** working in no-sync mode. This means that the rest of the journal
24636     ** file consists of pages, there are no more journal headers. Compute
24637     ** the value of nRec based on this assumption.
24638     */
24639     if( nRec==0xffffffff ){
24640       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
24641       nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
24642     }
24643
24644     /* If nRec is 0 and this rollback is of a transaction created by this
24645     ** process and if this is the final header in the journal, then it means
24646     ** that this part of the journal was being filled but has not yet been
24647     ** synced to disk.  Compute the number of pages based on the remaining
24648     ** size of the file.
24649     **
24650     ** The third term of the test was added to fix ticket #2565.
24651     */
24652     if( nRec==0 && !isHot &&
24653         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
24654       nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
24655     }
24656
24657     /* If this is the first header read from the journal, truncate the
24658     ** database file back to its original size.
24659     */
24660     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
24661       rc = pager_truncate(pPager, mxPg);
24662       if( rc!=SQLITE_OK ){
24663         goto end_playback;
24664       }
24665     }
24666
24667     /* Copy original pages out of the journal and back into the database file.
24668     */
24669     for(i=0; i<nRec; i++){
24670       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
24671       if( rc!=SQLITE_OK ){
24672         if( rc==SQLITE_DONE ){
24673           rc = SQLITE_OK;
24674           pPager->journalOff = szJ;
24675           break;
24676         }else{
24677           goto end_playback;
24678         }
24679       }
24680     }
24681   }
24682   /*NOTREACHED*/
24683   assert( 0 );
24684
24685 end_playback:
24686   if( rc==SQLITE_OK ){
24687     zMaster = pPager->pTmpSpace;
24688     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
24689   }
24690   if( rc==SQLITE_OK ){
24691     rc = pager_end_transaction(pPager);
24692   }
24693   if( rc==SQLITE_OK && zMaster[0] ){
24694     /* If there was a master journal and this routine will return success,
24695     ** see if it is possible to delete the master journal.
24696     */
24697     rc = pager_delmaster(pPager, zMaster);
24698   }
24699
24700   /* The Pager.sectorSize variable may have been updated while rolling
24701   ** back a journal created by a process with a different sector size
24702   ** value. Reset it to the correct value for this process.
24703   */
24704   setSectorSize(pPager);
24705   return rc;
24706 }
24707
24708 /*
24709 ** Playback the statement journal.
24710 **
24711 ** This is similar to playing back the transaction journal but with
24712 ** a few extra twists.
24713 **
24714 **    (1)  The number of pages in the database file at the start of
24715 **         the statement is stored in pPager->stmtSize, not in the
24716 **         journal file itself.
24717 **
24718 **    (2)  In addition to playing back the statement journal, also
24719 **         playback all pages of the transaction journal beginning
24720 **         at offset pPager->stmtJSize.
24721 */
24722 static int pager_stmt_playback(Pager *pPager){
24723   i64 szJ;                 /* Size of the full journal */
24724   i64 hdrOff;
24725   int nRec;                /* Number of Records */
24726   int i;                   /* Loop counter */
24727   int rc;
24728
24729   szJ = pPager->journalOff;
24730 #ifndef NDEBUG 
24731   {
24732     i64 os_szJ;
24733     rc = sqlite3OsFileSize(pPager->jfd, &os_szJ);
24734     if( rc!=SQLITE_OK ) return rc;
24735     assert( szJ==os_szJ );
24736   }
24737 #endif
24738
24739   /* Set hdrOff to be the offset just after the end of the last journal
24740   ** page written before the first journal-header for this statement
24741   ** transaction was written, or the end of the file if no journal
24742   ** header was written.
24743   */
24744   hdrOff = pPager->stmtHdrOff;
24745   assert( pPager->fullSync || !hdrOff );
24746   if( !hdrOff ){
24747     hdrOff = szJ;
24748   }
24749   
24750   /* Truncate the database back to its original size.
24751   */
24752   rc = pager_truncate(pPager, pPager->stmtSize);
24753   assert( pPager->state>=PAGER_SHARED );
24754
24755   /* Figure out how many records are in the statement journal.
24756   */
24757   assert( pPager->stmtInUse && pPager->journalOpen );
24758   nRec = pPager->stmtNRec;
24759   
24760   /* Copy original pages out of the statement journal and back into the
24761   ** database file.  Note that the statement journal omits checksums from
24762   ** each record since power-failure recovery is not important to statement
24763   ** journals.
24764   */
24765   for(i=0; i<nRec; i++){
24766     i64 offset = i*(4+pPager->pageSize);
24767     rc = pager_playback_one_page(pPager, pPager->stfd, offset, 0);
24768     assert( rc!=SQLITE_DONE );
24769     if( rc!=SQLITE_OK ) goto end_stmt_playback;
24770   }
24771
24772   /* Now roll some pages back from the transaction journal. Pager.stmtJSize
24773   ** was the size of the journal file when this statement was started, so
24774   ** everything after that needs to be rolled back, either into the
24775   ** database, the memory cache, or both.
24776   **
24777   ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
24778   ** of the first journal header written during this statement transaction.
24779   */
24780   pPager->journalOff = pPager->stmtJSize;
24781   pPager->cksumInit = pPager->stmtCksum;
24782   while( pPager->journalOff < hdrOff ){
24783     rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
24784     assert( rc!=SQLITE_DONE );
24785     if( rc!=SQLITE_OK ) goto end_stmt_playback;
24786   }
24787
24788   while( pPager->journalOff < szJ ){
24789     u32 nJRec;         /* Number of Journal Records */
24790     u32 dummy;
24791     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
24792     if( rc!=SQLITE_OK ){
24793       assert( rc!=SQLITE_DONE );
24794       goto end_stmt_playback;
24795     }
24796     if( nJRec==0 ){
24797       nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
24798     }
24799     for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
24800       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
24801       assert( rc!=SQLITE_DONE );
24802       if( rc!=SQLITE_OK ) goto end_stmt_playback;
24803     }
24804   }
24805
24806   pPager->journalOff = szJ;
24807   
24808 end_stmt_playback:
24809   if( rc==SQLITE_OK) {
24810     pPager->journalOff = szJ;
24811     /* pager_reload_cache(pPager); */
24812   }
24813   return rc;
24814 }
24815
24816 /*
24817 ** Change the maximum number of in-memory pages that are allowed.
24818 */
24819 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
24820   if( mxPage>10 ){
24821     pPager->mxPage = mxPage;
24822   }else{
24823     pPager->mxPage = 10;
24824   }
24825 }
24826
24827 /*
24828 ** Adjust the robustness of the database to damage due to OS crashes
24829 ** or power failures by changing the number of syncs()s when writing
24830 ** the rollback journal.  There are three levels:
24831 **
24832 **    OFF       sqlite3OsSync() is never called.  This is the default
24833 **              for temporary and transient files.
24834 **
24835 **    NORMAL    The journal is synced once before writes begin on the
24836 **              database.  This is normally adequate protection, but
24837 **              it is theoretically possible, though very unlikely,
24838 **              that an inopertune power failure could leave the journal
24839 **              in a state which would cause damage to the database
24840 **              when it is rolled back.
24841 **
24842 **    FULL      The journal is synced twice before writes begin on the
24843 **              database (with some additional information - the nRec field
24844 **              of the journal header - being written in between the two
24845 **              syncs).  If we assume that writing a
24846 **              single disk sector is atomic, then this mode provides
24847 **              assurance that the journal will not be corrupted to the
24848 **              point of causing damage to the database during rollback.
24849 **
24850 ** Numeric values associated with these states are OFF==1, NORMAL=2,
24851 ** and FULL=3.
24852 */
24853 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
24854 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int full_fsync){
24855   pPager->noSync =  level==1 || pPager->tempFile;
24856   pPager->fullSync = level==3 && !pPager->tempFile;
24857   pPager->sync_flags = (full_fsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
24858   if( pPager->noSync ) pPager->needSync = 0;
24859 }
24860 #endif
24861
24862 /*
24863 ** The following global variable is incremented whenever the library
24864 ** attempts to open a temporary file.  This information is used for
24865 ** testing and analysis only.  
24866 */
24867 #ifdef SQLITE_TEST
24868 SQLITE_API int sqlite3_opentemp_count = 0;
24869 #endif
24870
24871 /*
24872 ** Open a temporary file. 
24873 **
24874 ** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
24875 ** other error code if we fail. The OS will automatically delete the temporary
24876 ** file when it is closed.
24877 */
24878 static int sqlite3PagerOpentemp(
24879   sqlite3_vfs *pVfs,    /* The virtual file system layer */
24880   sqlite3_file *pFile,  /* Write the file descriptor here */
24881   char *zFilename,      /* Name of the file.  Might be NULL */
24882   int vfsFlags          /* Flags passed through to the VFS */
24883 ){
24884   int rc;
24885   assert( zFilename!=0 );
24886
24887 #ifdef SQLITE_TEST
24888   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
24889 #endif
24890
24891   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
24892             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
24893   rc = sqlite3OsOpen(pVfs, zFilename, pFile, vfsFlags, 0);
24894   assert( rc!=SQLITE_OK || pFile->pMethods );
24895   return rc;
24896 }
24897
24898 /*
24899 ** Create a new page cache and put a pointer to the page cache in *ppPager.
24900 ** The file to be cached need not exist.  The file is not locked until
24901 ** the first call to sqlite3PagerGet() and is only held open until the
24902 ** last page is released using sqlite3PagerUnref().
24903 **
24904 ** If zFilename is NULL then a randomly-named temporary file is created
24905 ** and used as the file to be cached.  The file will be deleted
24906 ** automatically when it is closed.
24907 **
24908 ** If zFilename is ":memory:" then all information is held in cache.
24909 ** It is never written to disk.  This can be used to implement an
24910 ** in-memory database.
24911 */
24912 SQLITE_PRIVATE int sqlite3PagerOpen(
24913   sqlite3_vfs *pVfs,       /* The virtual file system to use */
24914   Pager **ppPager,         /* Return the Pager structure here */
24915   const char *zFilename,   /* Name of the database file to open */
24916   int nExtra,              /* Extra bytes append to each in-memory page */
24917   int flags,               /* flags controlling this file */
24918   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
24919 ){
24920   u8 *pPtr;
24921   Pager *pPager = 0;
24922   int rc = SQLITE_OK;
24923   int i;
24924   int tempFile = 0;
24925   int memDb = 0;
24926   int readOnly = 0;
24927   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
24928   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
24929   int journalFileSize = sqlite3JournalSize(pVfs);
24930   int nDefaultPage = SQLITE_DEFAULT_PAGE_SIZE;
24931   char *zPathname;
24932   int nPathname;
24933   char *zStmtJrnl;
24934   int nStmtJrnl;
24935
24936   /* The default return is a NULL pointer */
24937   *ppPager = 0;
24938
24939   /* Compute the full pathname */
24940   nPathname = pVfs->mxPathname+1;
24941   zPathname = sqlite3_malloc(nPathname*2);
24942   if( zPathname==0 ){
24943     return SQLITE_NOMEM;
24944   }
24945   if( zFilename && zFilename[0] ){
24946 #ifndef SQLITE_OMIT_MEMORYDB
24947     if( strcmp(zFilename,":memory:")==0 ){
24948       memDb = 1;
24949       zPathname[0] = 0;
24950     }else
24951 #endif
24952     {
24953       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
24954     }
24955   }else{
24956     rc = sqlite3OsGetTempname(pVfs, nPathname, zPathname);
24957   }
24958   if( rc!=SQLITE_OK ){
24959     sqlite3_free(zPathname);
24960     return rc;
24961   }
24962   nPathname = strlen(zPathname);
24963
24964   /* Put the statement journal in temporary disk space since this is
24965   ** sometimes RAM disk or other optimized storage.  Unlikely the main
24966   ** main journal file, the statement journal does not need to be 
24967   ** colocated with the database nor does it need to be persistent.
24968   */
24969   zStmtJrnl = &zPathname[nPathname+1];
24970   rc = sqlite3OsGetTempname(pVfs, pVfs->mxPathname+1, zStmtJrnl);
24971   if( rc!=SQLITE_OK ){
24972     sqlite3_free(zPathname);
24973     return rc;
24974   }
24975   nStmtJrnl = strlen(zStmtJrnl);
24976
24977   /* Allocate memory for the pager structure */
24978   pPager = sqlite3MallocZero(
24979     sizeof(*pPager) +           /* Pager structure */
24980     journalFileSize +           /* The journal file structure */ 
24981     pVfs->szOsFile * 3 +        /* The main db and two journal files */ 
24982     3*nPathname + 40 +          /* zFilename, zDirectory, zJournal */
24983     nStmtJrnl                   /* zStmtJrnl */
24984   );
24985   if( !pPager ){
24986     sqlite3_free(zPathname);
24987     return SQLITE_NOMEM;
24988   }
24989   pPtr = (u8 *)&pPager[1];
24990   pPager->vfsFlags = vfsFlags;
24991   pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
24992   pPager->stfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*1];
24993   pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*2];
24994   pPager->zFilename = (char*)&pPtr[pVfs->szOsFile*2+journalFileSize];
24995   pPager->zDirectory = &pPager->zFilename[nPathname+1];
24996   pPager->zJournal = &pPager->zDirectory[nPathname+1];
24997   pPager->zStmtJrnl = &pPager->zJournal[nPathname+10];
24998   pPager->pVfs = pVfs;
24999   memcpy(pPager->zFilename, zPathname, nPathname+1);
25000   memcpy(pPager->zStmtJrnl, zStmtJrnl, nStmtJrnl+1);
25001   sqlite3_free(zPathname);
25002
25003   /* Open the pager file.
25004   */
25005   if( zFilename && zFilename[0] && !memDb ){
25006     if( nPathname>(pVfs->mxPathname - sizeof("-journal")) ){
25007       rc = SQLITE_CANTOPEN;
25008     }else{
25009       int fout = 0;
25010       rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
25011                          pPager->vfsFlags, &fout);
25012       readOnly = (fout&SQLITE_OPEN_READONLY);
25013
25014       /* If the file was successfully opened for read/write access,
25015       ** choose a default page size in case we have to create the
25016       ** database file. The default page size is the maximum of:
25017       **
25018       **    + SQLITE_DEFAULT_PAGE_SIZE,
25019       **    + The value returned by sqlite3OsSectorSize()
25020       **    + The largest page size that can be written atomically.
25021       */
25022       if( rc==SQLITE_OK && !readOnly ){
25023         int iSectorSize = sqlite3OsSectorSize(pPager->fd);
25024         if( nDefaultPage<iSectorSize ){
25025           nDefaultPage = iSectorSize;
25026         }
25027 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
25028         {
25029           int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
25030           int ii;
25031           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
25032           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
25033           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
25034           for(ii=nDefaultPage; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
25035             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) nDefaultPage = ii;
25036           }
25037         }
25038 #endif
25039         if( nDefaultPage>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
25040           nDefaultPage = SQLITE_MAX_DEFAULT_PAGE_SIZE;
25041         }
25042       }
25043     }
25044   }else if( !memDb ){
25045     /* If a temporary file is requested, it is not opened immediately.
25046     ** In this case we accept the default page size and delay actually
25047     ** opening the file until the first call to OsWrite().
25048     */ 
25049     tempFile = 1;
25050     pPager->state = PAGER_EXCLUSIVE;
25051   }
25052
25053   if( pPager && rc==SQLITE_OK ){
25054     pPager->pTmpSpace = (char *)sqlite3_malloc(nDefaultPage);
25055   }
25056
25057   /* If an error occured in either of the blocks above.
25058   ** Free the Pager structure and close the file.
25059   ** Since the pager is not allocated there is no need to set 
25060   ** any Pager.errMask variables.
25061   */
25062   if( !pPager || !pPager->pTmpSpace ){
25063     sqlite3OsClose(pPager->fd);
25064     sqlite3_free(pPager);
25065     return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
25066   }
25067
25068   PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename);
25069   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
25070
25071   /* Fill in Pager.zDirectory[] */
25072   memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
25073   for(i=strlen(pPager->zDirectory); i>0 && pPager->zDirectory[i-1]!='/'; i--){}
25074   if( i>0 ) pPager->zDirectory[i-1] = 0;
25075
25076   /* Fill in Pager.zJournal[] */
25077   memcpy(pPager->zJournal, pPager->zFilename, nPathname);
25078   memcpy(&pPager->zJournal[nPathname], "-journal", 9);
25079
25080   /* pPager->journalOpen = 0; */
25081   pPager->useJournal = useJournal && !memDb;
25082   pPager->noReadlock = noReadlock && readOnly;
25083   /* pPager->stmtOpen = 0; */
25084   /* pPager->stmtInUse = 0; */
25085   /* pPager->nRef = 0; */
25086   pPager->dbSize = memDb-1;
25087   pPager->pageSize = nDefaultPage;
25088   /* pPager->stmtSize = 0; */
25089   /* pPager->stmtJSize = 0; */
25090   /* pPager->nPage = 0; */
25091   pPager->mxPage = 100;
25092   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
25093   /* pPager->state = PAGER_UNLOCK; */
25094   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
25095   /* pPager->errMask = 0; */
25096   pPager->tempFile = tempFile;
25097   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
25098           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
25099   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
25100   pPager->exclusiveMode = tempFile; 
25101   pPager->memDb = memDb;
25102   pPager->readOnly = readOnly;
25103   /* pPager->needSync = 0; */
25104   pPager->noSync = pPager->tempFile || !useJournal;
25105   pPager->fullSync = (pPager->noSync?0:1);
25106   pPager->sync_flags = SQLITE_SYNC_NORMAL;
25107   /* pPager->pFirst = 0; */
25108   /* pPager->pFirstSynced = 0; */
25109   /* pPager->pLast = 0; */
25110   pPager->nExtra = FORCE_ALIGNMENT(nExtra);
25111   assert(pPager->fd->pMethods||memDb||tempFile);
25112   if( !memDb ){
25113     setSectorSize(pPager);
25114   }
25115   /* pPager->pBusyHandler = 0; */
25116   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
25117   *ppPager = pPager;
25118 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
25119   pPager->iInUseMM = 0;
25120   pPager->iInUseDB = 0;
25121   if( !memDb ){
25122     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
25123     sqlite3_mutex_enter(mutex);
25124     pPager->pNext = sqlite3PagerList;
25125     if( sqlite3PagerList ){
25126       assert( sqlite3PagerList->pPrev==0 );
25127       sqlite3PagerList->pPrev = pPager;
25128     }
25129     pPager->pPrev = 0;
25130     sqlite3PagerList = pPager;
25131     sqlite3_mutex_leave(mutex);
25132   }
25133 #endif
25134   return SQLITE_OK;
25135 }
25136
25137 /*
25138 ** Set the busy handler function.
25139 */
25140 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
25141   pPager->pBusyHandler = pBusyHandler;
25142 }
25143
25144 /*
25145 ** Set the destructor for this pager.  If not NULL, the destructor is called
25146 ** when the reference count on each page reaches zero.  The destructor can
25147 ** be used to clean up information in the extra segment appended to each page.
25148 **
25149 ** The destructor is not called as a result sqlite3PagerClose().  
25150 ** Destructors are only called by sqlite3PagerUnref().
25151 */
25152 SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager *pPager, void (*xDesc)(DbPage*,int)){
25153   pPager->xDestructor = xDesc;
25154 }
25155
25156 /*
25157 ** Set the reinitializer for this pager.  If not NULL, the reinitializer
25158 ** is called when the content of a page in cache is restored to its original
25159 ** value as a result of a rollback.  The callback gives higher-level code
25160 ** an opportunity to restore the EXTRA section to agree with the restored
25161 ** page data.
25162 */
25163 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
25164   pPager->xReiniter = xReinit;
25165 }
25166
25167 /*
25168 ** Set the page size to *pPageSize. If the suggest new page size is
25169 ** inappropriate, then an alternative page size is set to that
25170 ** value before returning.
25171 */
25172 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
25173   int rc = SQLITE_OK;
25174   u16 pageSize = *pPageSize;
25175   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
25176   if( pageSize && pageSize!=pPager->pageSize 
25177    && !pPager->memDb && pPager->nRef==0 
25178   ){
25179     char *pNew = (char *)sqlite3_malloc(pageSize);
25180     if( !pNew ){
25181       rc = SQLITE_NOMEM;
25182     }else{
25183       pagerEnter(pPager);
25184       pager_reset(pPager);
25185       pPager->pageSize = pageSize;
25186       setSectorSize(pPager);
25187       sqlite3_free(pPager->pTmpSpace);
25188       pPager->pTmpSpace = pNew;
25189       pagerLeave(pPager);
25190     }
25191   }
25192   *pPageSize = pPager->pageSize;
25193   return rc;
25194 }
25195
25196 /*
25197 ** Return a pointer to the "temporary page" buffer held internally
25198 ** by the pager.  This is a buffer that is big enough to hold the
25199 ** entire content of a database page.  This buffer is used internally
25200 ** during rollback and will be overwritten whenever a rollback
25201 ** occurs.  But other modules are free to use it too, as long as
25202 ** no rollbacks are happening.
25203 */
25204 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
25205   return pPager->pTmpSpace;
25206 }
25207
25208 /*
25209 ** Attempt to set the maximum database page count if mxPage is positive. 
25210 ** Make no changes if mxPage is zero or negative.  And never reduce the
25211 ** maximum page count below the current size of the database.
25212 **
25213 ** Regardless of mxPage, return the current maximum page count.
25214 */
25215 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
25216   if( mxPage>0 ){
25217     pPager->mxPgno = mxPage;
25218   }
25219   sqlite3PagerPagecount(pPager);
25220   return pPager->mxPgno;
25221 }
25222
25223 /*
25224 ** The following set of routines are used to disable the simulated
25225 ** I/O error mechanism.  These routines are used to avoid simulated
25226 ** errors in places where we do not care about errors.
25227 **
25228 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
25229 ** and generate no code.
25230 */
25231 #ifdef SQLITE_TEST
25232 SQLITE_API extern int sqlite3_io_error_pending;
25233 SQLITE_API extern int sqlite3_io_error_hit;
25234 static int saved_cnt;
25235 void disable_simulated_io_errors(void){
25236   saved_cnt = sqlite3_io_error_pending;
25237   sqlite3_io_error_pending = -1;
25238 }
25239 void enable_simulated_io_errors(void){
25240   sqlite3_io_error_pending = saved_cnt;
25241 }
25242 #else
25243 # define disable_simulated_io_errors()
25244 # define enable_simulated_io_errors()
25245 #endif
25246
25247 /*
25248 ** Read the first N bytes from the beginning of the file into memory
25249 ** that pDest points to. 
25250 **
25251 ** No error checking is done. The rational for this is that this function 
25252 ** may be called even if the file does not exist or contain a header. In 
25253 ** these cases sqlite3OsRead() will return an error, to which the correct 
25254 ** response is to zero the memory at pDest and continue.  A real IO error 
25255 ** will presumably recur and be picked up later (Todo: Think about this).
25256 */
25257 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
25258   int rc = SQLITE_OK;
25259   memset(pDest, 0, N);
25260   assert(MEMDB||pPager->fd->pMethods||pPager->tempFile);
25261   if( pPager->fd->pMethods ){
25262     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
25263     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
25264     if( rc==SQLITE_IOERR_SHORT_READ ){
25265       rc = SQLITE_OK;
25266     }
25267   }
25268   return rc;
25269 }
25270
25271 /*
25272 ** Return the total number of pages in the disk file associated with
25273 ** pPager. 
25274 **
25275 ** If the PENDING_BYTE lies on the page directly after the end of the
25276 ** file, then consider this page part of the file too. For example, if
25277 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
25278 ** file is 4096 bytes, 5 is returned instead of 4.
25279 */
25280 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager){
25281   i64 n = 0;
25282   int rc;
25283   assert( pPager!=0 );
25284   if( pPager->errCode ){
25285     return -1;
25286   }
25287   if( pPager->dbSize>=0 ){
25288     n = pPager->dbSize;
25289   } else {
25290     assert(pPager->fd->pMethods||pPager->tempFile);
25291     if( (pPager->fd->pMethods)
25292      && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
25293       pPager->nRef++;
25294       pager_error(pPager, rc);
25295       pPager->nRef--;
25296       return -1;
25297     }
25298     if( n>0 && n<pPager->pageSize ){
25299       n = 1;
25300     }else{
25301       n /= pPager->pageSize;
25302     }
25303     if( pPager->state!=PAGER_UNLOCK ){
25304       pPager->dbSize = n;
25305     }
25306   }
25307   if( n==(PENDING_BYTE/pPager->pageSize) ){
25308     n++;
25309   }
25310   if( n>pPager->mxPgno ){
25311     pPager->mxPgno = n;
25312   }
25313   return n;
25314 }
25315
25316
25317 #ifndef SQLITE_OMIT_MEMORYDB
25318 /*
25319 ** Clear a PgHistory block
25320 */
25321 static void clearHistory(PgHistory *pHist){
25322   sqlite3_free(pHist->pOrig);
25323   sqlite3_free(pHist->pStmt);
25324   pHist->pOrig = 0;
25325   pHist->pStmt = 0;
25326 }
25327 #else
25328 #define clearHistory(x)
25329 #endif
25330
25331 /*
25332 ** Forward declaration
25333 */
25334 static int syncJournal(Pager*);
25335
25336 /*
25337 ** Unlink pPg from its hash chain. Also set the page number to 0 to indicate
25338 ** that the page is not part of any hash chain. This is required because the
25339 ** sqlite3PagerMovepage() routine can leave a page in the 
25340 ** pNextFree/pPrevFree list that is not a part of any hash-chain.
25341 */
25342 static void unlinkHashChain(Pager *pPager, PgHdr *pPg){
25343   if( pPg->pgno==0 ){
25344     assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
25345     return;
25346   }
25347   if( pPg->pNextHash ){
25348     pPg->pNextHash->pPrevHash = pPg->pPrevHash;
25349   }
25350   if( pPg->pPrevHash ){
25351     assert( pPager->aHash[pPg->pgno & (pPager->nHash-1)]!=pPg );
25352     pPg->pPrevHash->pNextHash = pPg->pNextHash;
25353   }else{
25354     int h = pPg->pgno & (pPager->nHash-1);
25355     pPager->aHash[h] = pPg->pNextHash;
25356   }
25357   if( MEMDB ){
25358     clearHistory(PGHDR_TO_HIST(pPg, pPager));
25359   }
25360   pPg->pgno = 0;
25361   pPg->pNextHash = pPg->pPrevHash = 0;
25362 }
25363
25364 /*
25365 ** Unlink a page from the free list (the list of all pages where nRef==0)
25366 ** and from its hash collision chain.
25367 */
25368 static void unlinkPage(PgHdr *pPg){
25369   Pager *pPager = pPg->pPager;
25370
25371   /* Unlink from free page list */
25372   lruListRemove(pPg);
25373
25374   /* Unlink from the pgno hash table */
25375   unlinkHashChain(pPager, pPg);
25376 }
25377
25378 /*
25379 ** This routine is used to truncate the cache when a database
25380 ** is truncated.  Drop from the cache all pages whose pgno is
25381 ** larger than pPager->dbSize and is unreferenced.
25382 **
25383 ** Referenced pages larger than pPager->dbSize are zeroed.
25384 **
25385 ** Actually, at the point this routine is called, it would be
25386 ** an error to have a referenced page.  But rather than delete
25387 ** that page and guarantee a subsequent segfault, it seems better
25388 ** to zero it and hope that we error out sanely.
25389 */
25390 static void pager_truncate_cache(Pager *pPager){
25391   PgHdr *pPg;
25392   PgHdr **ppPg;
25393   int dbSize = pPager->dbSize;
25394
25395   ppPg = &pPager->pAll;
25396   while( (pPg = *ppPg)!=0 ){
25397     if( pPg->pgno<=dbSize ){
25398       ppPg = &pPg->pNextAll;
25399     }else if( pPg->nRef>0 ){
25400       memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
25401       ppPg = &pPg->pNextAll;
25402     }else{
25403       *ppPg = pPg->pNextAll;
25404       IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
25405       PAGER_INCR(sqlite3_pager_pgfree_count);
25406       unlinkPage(pPg);
25407       makeClean(pPg);
25408       sqlite3_free(pPg->pData);
25409       sqlite3_free(pPg);
25410       pPager->nPage--;
25411     }
25412   }
25413 }
25414
25415 /*
25416 ** Try to obtain a lock on a file.  Invoke the busy callback if the lock
25417 ** is currently not available.  Repeat until the busy callback returns
25418 ** false or until the lock succeeds.
25419 **
25420 ** Return SQLITE_OK on success and an error code if we cannot obtain
25421 ** the lock.
25422 */
25423 static int pager_wait_on_lock(Pager *pPager, int locktype){
25424   int rc;
25425
25426   /* The OS lock values must be the same as the Pager lock values */
25427   assert( PAGER_SHARED==SHARED_LOCK );
25428   assert( PAGER_RESERVED==RESERVED_LOCK );
25429   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
25430
25431   /* If the file is currently unlocked then the size must be unknown */
25432   assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
25433
25434   if( pPager->state>=locktype ){
25435     rc = SQLITE_OK;
25436   }else{
25437     if( pPager->pBusyHandler ) pPager->pBusyHandler->nBusy = 0;
25438     do {
25439       rc = sqlite3OsLock(pPager->fd, locktype);
25440     }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
25441     if( rc==SQLITE_OK ){
25442       pPager->state = locktype;
25443       IOTRACE(("LOCK %p %d\n", pPager, locktype))
25444     }
25445   }
25446   return rc;
25447 }
25448
25449 /*
25450 ** Truncate the file to the number of pages specified.
25451 */
25452 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
25453   int rc;
25454   assert( pPager->state>=PAGER_SHARED || MEMDB );
25455   sqlite3PagerPagecount(pPager);
25456   if( pPager->errCode ){
25457     rc = pPager->errCode;
25458     return rc;
25459   }
25460   if( nPage>=(unsigned)pPager->dbSize ){
25461     return SQLITE_OK;
25462   }
25463   if( MEMDB ){
25464     pPager->dbSize = nPage;
25465     pager_truncate_cache(pPager);
25466     return SQLITE_OK;
25467   }
25468   pagerEnter(pPager);
25469   rc = syncJournal(pPager);
25470   pagerLeave(pPager);
25471   if( rc!=SQLITE_OK ){
25472     return rc;
25473   }
25474
25475   /* Get an exclusive lock on the database before truncating. */
25476   pagerEnter(pPager);
25477   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
25478   pagerLeave(pPager);
25479   if( rc!=SQLITE_OK ){
25480     return rc;
25481   }
25482
25483   rc = pager_truncate(pPager, nPage);
25484   return rc;
25485 }
25486
25487 /*
25488 ** Shutdown the page cache.  Free all memory and close all files.
25489 **
25490 ** If a transaction was in progress when this routine is called, that
25491 ** transaction is rolled back.  All outstanding pages are invalidated
25492 ** and their memory is freed.  Any attempt to use a page associated
25493 ** with this page cache after this function returns will likely
25494 ** result in a coredump.
25495 **
25496 ** This function always succeeds. If a transaction is active an attempt
25497 ** is made to roll it back. If an error occurs during the rollback 
25498 ** a hot journal may be left in the filesystem but no error is returned
25499 ** to the caller.
25500 */
25501 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
25502 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
25503   if( !MEMDB ){
25504     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
25505     sqlite3_mutex_enter(mutex);
25506     if( pPager->pPrev ){
25507       pPager->pPrev->pNext = pPager->pNext;
25508     }else{
25509       sqlite3PagerList = pPager->pNext;
25510     }
25511     if( pPager->pNext ){
25512       pPager->pNext->pPrev = pPager->pPrev;
25513     }
25514     sqlite3_mutex_leave(mutex);
25515   }
25516 #endif
25517
25518   disable_simulated_io_errors();
25519   pPager->errCode = 0;
25520   pPager->exclusiveMode = 0;
25521   pager_reset(pPager);
25522   pagerUnlockAndRollback(pPager);
25523   enable_simulated_io_errors();
25524   PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
25525   IOTRACE(("CLOSE %p\n", pPager))
25526   assert( pPager->errCode || (pPager->journalOpen==0 && pPager->stmtOpen==0) );
25527   if( pPager->journalOpen ){
25528     sqlite3OsClose(pPager->jfd);
25529   }
25530   sqlite3BitvecDestroy(pPager->pInJournal);
25531   if( pPager->stmtOpen ){
25532     sqlite3OsClose(pPager->stfd);
25533   }
25534   sqlite3OsClose(pPager->fd);
25535   /* Temp files are automatically deleted by the OS
25536   ** if( pPager->tempFile ){
25537   **   sqlite3OsDelete(pPager->zFilename);
25538   ** }
25539   */
25540
25541   sqlite3_free(pPager->aHash);
25542   sqlite3_free(pPager->pTmpSpace);
25543   sqlite3_free(pPager);
25544   return SQLITE_OK;
25545 }
25546
25547 #if !defined(NDEBUG) || defined(SQLITE_TEST)
25548 /*
25549 ** Return the page number for the given page data.
25550 */
25551 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
25552   return p->pgno;
25553 }
25554 #endif
25555
25556 /*
25557 ** The page_ref() function increments the reference count for a page.
25558 ** If the page is currently on the freelist (the reference count is zero) then
25559 ** remove it from the freelist.
25560 **
25561 ** For non-test systems, page_ref() is a macro that calls _page_ref()
25562 ** online of the reference count is zero.  For test systems, page_ref()
25563 ** is a real function so that we can set breakpoints and trace it.
25564 */
25565 static void _page_ref(PgHdr *pPg){
25566   if( pPg->nRef==0 ){
25567     /* The page is currently on the freelist.  Remove it. */
25568     lruListRemove(pPg);
25569     pPg->pPager->nRef++;
25570   }
25571   pPg->nRef++;
25572 }
25573 #ifdef SQLITE_DEBUG
25574   static void page_ref(PgHdr *pPg){
25575     if( pPg->nRef==0 ){
25576       _page_ref(pPg);
25577     }else{
25578       pPg->nRef++;
25579     }
25580   }
25581 #else
25582 # define page_ref(P)   ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
25583 #endif
25584
25585 /*
25586 ** Increment the reference count for a page.  The input pointer is
25587 ** a reference to the page data.
25588 */
25589 SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
25590   pagerEnter(pPg->pPager);
25591   page_ref(pPg);
25592   pagerLeave(pPg->pPager);
25593   return SQLITE_OK;
25594 }
25595
25596 /*
25597 ** Sync the journal.  In other words, make sure all the pages that have
25598 ** been written to the journal have actually reached the surface of the
25599 ** disk.  It is not safe to modify the original database file until after
25600 ** the journal has been synced.  If the original database is modified before
25601 ** the journal is synced and a power failure occurs, the unsynced journal
25602 ** data would be lost and we would be unable to completely rollback the
25603 ** database changes.  Database corruption would occur.
25604 ** 
25605 ** This routine also updates the nRec field in the header of the journal.
25606 ** (See comments on the pager_playback() routine for additional information.)
25607 ** If the sync mode is FULL, two syncs will occur.  First the whole journal
25608 ** is synced, then the nRec field is updated, then a second sync occurs.
25609 **
25610 ** For temporary databases, we do not care if we are able to rollback
25611 ** after a power failure, so no sync occurs.
25612 **
25613 ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
25614 ** the database is stored, then OsSync() is never called on the journal
25615 ** file. In this case all that is required is to update the nRec field in
25616 ** the journal header.
25617 **
25618 ** This routine clears the needSync field of every page current held in
25619 ** memory.
25620 */
25621 static int syncJournal(Pager *pPager){
25622   PgHdr *pPg;
25623   int rc = SQLITE_OK;
25624
25625
25626   /* Sync the journal before modifying the main database
25627   ** (assuming there is a journal and it needs to be synced.)
25628   */
25629   if( pPager->needSync ){
25630     if( !pPager->tempFile ){
25631       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
25632       assert( pPager->journalOpen );
25633
25634       /* assert( !pPager->noSync ); // noSync might be set if synchronous
25635       ** was turned off after the transaction was started.  Ticket #615 */
25636 #ifndef NDEBUG
25637       {
25638         /* Make sure the pPager->nRec counter we are keeping agrees
25639         ** with the nRec computed from the size of the journal file.
25640         */
25641         i64 jSz;
25642         rc = sqlite3OsFileSize(pPager->jfd, &jSz);
25643         if( rc!=0 ) return rc;
25644         assert( pPager->journalOff==jSz );
25645       }
25646 #endif
25647       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
25648         /* Write the nRec value into the journal file header. If in
25649         ** full-synchronous mode, sync the journal first. This ensures that
25650         ** all data has really hit the disk before nRec is updated to mark
25651         ** it as a candidate for rollback.
25652         **
25653         ** This is not required if the persistent media supports the
25654         ** SAFE_APPEND property. Because in this case it is not possible 
25655         ** for garbage data to be appended to the file, the nRec field
25656         ** is populated with 0xFFFFFFFF when the journal header is written
25657         ** and never needs to be updated.
25658         */
25659         i64 jrnlOff;
25660         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
25661           PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
25662           IOTRACE(("JSYNC %p\n", pPager))
25663           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
25664           if( rc!=0 ) return rc;
25665         }
25666
25667         jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
25668         IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
25669         rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
25670         if( rc ) return rc;
25671       }
25672       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
25673         PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
25674         IOTRACE(("JSYNC %p\n", pPager))
25675         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
25676           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
25677         );
25678         if( rc!=0 ) return rc;
25679       }
25680       pPager->journalStarted = 1;
25681     }
25682     pPager->needSync = 0;
25683
25684     /* Erase the needSync flag from every page.
25685     */
25686     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
25687       pPg->needSync = 0;
25688     }
25689     lruListSetFirstSynced(pPager);
25690   }
25691
25692 #ifndef NDEBUG
25693   /* If the Pager.needSync flag is clear then the PgHdr.needSync
25694   ** flag must also be clear for all pages.  Verify that this
25695   ** invariant is true.
25696   */
25697   else{
25698     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
25699       assert( pPg->needSync==0 );
25700     }
25701     assert( pPager->lru.pFirstSynced==pPager->lru.pFirst );
25702   }
25703 #endif
25704
25705   return rc;
25706 }
25707
25708 /*
25709 ** Merge two lists of pages connected by pDirty and in pgno order.
25710 ** Do not both fixing the pPrevDirty pointers.
25711 */
25712 static PgHdr *merge_pagelist(PgHdr *pA, PgHdr *pB){
25713   PgHdr result, *pTail;
25714   pTail = &result;
25715   while( pA && pB ){
25716     if( pA->pgno<pB->pgno ){
25717       pTail->pDirty = pA;
25718       pTail = pA;
25719       pA = pA->pDirty;
25720     }else{
25721       pTail->pDirty = pB;
25722       pTail = pB;
25723       pB = pB->pDirty;
25724     }
25725   }
25726   if( pA ){
25727     pTail->pDirty = pA;
25728   }else if( pB ){
25729     pTail->pDirty = pB;
25730   }else{
25731     pTail->pDirty = 0;
25732   }
25733   return result.pDirty;
25734 }
25735
25736 /*
25737 ** Sort the list of pages in accending order by pgno.  Pages are
25738 ** connected by pDirty pointers.  The pPrevDirty pointers are
25739 ** corrupted by this sort.
25740 */
25741 #define N_SORT_BUCKET_ALLOC 25
25742 #define N_SORT_BUCKET       25
25743 #ifdef SQLITE_TEST
25744   int sqlite3_pager_n_sort_bucket = 0;
25745   #undef N_SORT_BUCKET
25746   #define N_SORT_BUCKET \
25747    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
25748 #endif
25749 static PgHdr *sort_pagelist(PgHdr *pIn){
25750   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
25751   int i;
25752   memset(a, 0, sizeof(a));
25753   while( pIn ){
25754     p = pIn;
25755     pIn = p->pDirty;
25756     p->pDirty = 0;
25757     for(i=0; i<N_SORT_BUCKET-1; i++){
25758       if( a[i]==0 ){
25759         a[i] = p;
25760         break;
25761       }else{
25762         p = merge_pagelist(a[i], p);
25763         a[i] = 0;
25764       }
25765     }
25766     if( i==N_SORT_BUCKET-1 ){
25767       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET) 
25768       ** elements in the input list. This is possible, but impractical.
25769       ** Testing this line is the point of global variable
25770       ** sqlite3_pager_n_sort_bucket.
25771       */
25772       a[i] = merge_pagelist(a[i], p);
25773     }
25774   }
25775   p = a[0];
25776   for(i=1; i<N_SORT_BUCKET; i++){
25777     p = merge_pagelist(p, a[i]);
25778   }
25779   return p;
25780 }
25781
25782 /*
25783 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
25784 ** every one of those pages out to the database file and mark them all
25785 ** as clean.
25786 */
25787 static int pager_write_pagelist(PgHdr *pList){
25788   Pager *pPager;
25789   PgHdr *p;
25790   int rc;
25791
25792   if( pList==0 ) return SQLITE_OK;
25793   pPager = pList->pPager;
25794
25795   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
25796   ** database file. If there is already an EXCLUSIVE lock, the following
25797   ** calls to sqlite3OsLock() are no-ops.
25798   **
25799   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
25800   ** through an intermediate state PENDING.   A PENDING lock prevents new
25801   ** readers from attaching to the database but is unsufficient for us to
25802   ** write.  The idea of a PENDING lock is to prevent new readers from
25803   ** coming in while we wait for existing readers to clear.
25804   **
25805   ** While the pager is in the RESERVED state, the original database file
25806   ** is unchanged and we can rollback without having to playback the
25807   ** journal into the original database file.  Once we transition to
25808   ** EXCLUSIVE, it means the database file has been changed and any rollback
25809   ** will require a journal playback.
25810   */
25811   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
25812   if( rc!=SQLITE_OK ){
25813     return rc;
25814   }
25815
25816   pList = sort_pagelist(pList);
25817   for(p=pList; p; p=p->pDirty){
25818     assert( p->dirty );
25819     p->dirty = 0;
25820   }
25821   while( pList ){
25822
25823     /* If the file has not yet been opened, open it now. */
25824     if( !pPager->fd->pMethods ){
25825       assert(pPager->tempFile);
25826       rc = sqlite3PagerOpentemp(pPager->pVfs, pPager->fd, pPager->zFilename,
25827                                 pPager->vfsFlags);
25828       if( rc ) return rc;
25829     }
25830
25831     /* If there are dirty pages in the page cache with page numbers greater
25832     ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
25833     ** make the file smaller (presumably by auto-vacuum code). Do not write
25834     ** any such pages to the file.
25835     */
25836     if( pList->pgno<=pPager->dbSize ){
25837       i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
25838       char *pData = CODEC2(pPager, PGHDR_TO_DATA(pList), pList->pgno, 6);
25839       PAGERTRACE4("STORE %d page %d hash(%08x)\n",
25840                    PAGERID(pPager), pList->pgno, pager_pagehash(pList));
25841       IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
25842       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
25843       PAGER_INCR(sqlite3_pager_writedb_count);
25844       PAGER_INCR(pPager->nWrite);
25845       if( pList->pgno==1 ){
25846         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
25847       }
25848     }
25849 #ifndef NDEBUG
25850     else{
25851       PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
25852     }
25853 #endif
25854     if( rc ) return rc;
25855 #ifdef SQLITE_CHECK_PAGES
25856     pList->pageHash = pager_pagehash(pList);
25857 #endif
25858     pList = pList->pDirty;
25859   }
25860   return SQLITE_OK;
25861 }
25862
25863 /*
25864 ** Collect every dirty page into a dirty list and
25865 ** return a pointer to the head of that list.  All pages are
25866 ** collected even if they are still in use.
25867 */
25868 static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
25869
25870 #ifndef NDEBUG
25871   /* Verify the sanity of the dirty list when we are running
25872   ** in debugging mode.  This is expensive, so do not
25873   ** do this on a normal build. */
25874   int n1 = 0;
25875   int n2 = 0;
25876   PgHdr *p;
25877   for(p=pPager->pAll; p; p=p->pNextAll){ if( p->dirty ) n1++; }
25878   for(p=pPager->pDirty; p; p=p->pDirty){ n2++; }
25879   assert( n1==n2 );
25880 #endif
25881
25882   return pPager->pDirty;
25883 }
25884
25885 /*
25886 ** Return TRUE if there is a hot journal on the given pager.
25887 ** A hot journal is one that needs to be played back.
25888 **
25889 ** If the current size of the database file is 0 but a journal file
25890 ** exists, that is probably an old journal left over from a prior
25891 ** database with the same name.  Just delete the journal.
25892 */
25893 static int hasHotJournal(Pager *pPager){
25894   sqlite3_vfs *pVfs = pPager->pVfs;
25895   if( !pPager->useJournal ) return 0;
25896   if( !pPager->fd->pMethods ) return 0;
25897   if( !sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS) ){
25898     return 0;
25899   }
25900   if( sqlite3OsCheckReservedLock(pPager->fd) ){
25901     return 0;
25902   }
25903   if( sqlite3PagerPagecount(pPager)==0 ){
25904     sqlite3OsDelete(pVfs, pPager->zJournal, 0);
25905     return 0;
25906   }else{
25907     return 1;
25908   }
25909 }
25910
25911 /*
25912 ** Try to find a page in the cache that can be recycled. 
25913 **
25914 ** This routine may return SQLITE_IOERR, SQLITE_FULL or SQLITE_OK. It 
25915 ** does not set the pPager->errCode variable.
25916 */
25917 static int pager_recycle(Pager *pPager, PgHdr **ppPg){
25918   PgHdr *pPg;
25919   *ppPg = 0;
25920
25921   /* It is illegal to call this function unless the pager object
25922   ** pointed to by pPager has at least one free page (page with nRef==0).
25923   */ 
25924   assert(!MEMDB);
25925   assert(pPager->lru.pFirst);
25926
25927   /* Find a page to recycle.  Try to locate a page that does not
25928   ** require us to do an fsync() on the journal.
25929   */
25930   pPg = pPager->lru.pFirstSynced;
25931
25932   /* If we could not find a page that does not require an fsync()
25933   ** on the journal file then fsync the journal file.  This is a
25934   ** very slow operation, so we work hard to avoid it.  But sometimes
25935   ** it can't be helped.
25936   */
25937   if( pPg==0 && pPager->lru.pFirst){
25938     int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
25939     int rc = syncJournal(pPager);
25940     if( rc!=0 ){
25941       return rc;
25942     }
25943     if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
25944       /* If in full-sync mode, write a new journal header into the
25945       ** journal file. This is done to avoid ever modifying a journal
25946       ** header that is involved in the rollback of pages that have
25947       ** already been written to the database (in case the header is
25948       ** trashed when the nRec field is updated).
25949       */
25950       pPager->nRec = 0;
25951       assert( pPager->journalOff > 0 );
25952       assert( pPager->doNotSync==0 );
25953       rc = writeJournalHdr(pPager);
25954       if( rc!=0 ){
25955         return rc;
25956       }
25957     }
25958     pPg = pPager->lru.pFirst;
25959   }
25960
25961   assert( pPg->nRef==0 );
25962
25963   /* Write the page to the database file if it is dirty.
25964   */
25965   if( pPg->dirty ){
25966     int rc;
25967     assert( pPg->needSync==0 );
25968     makeClean(pPg);
25969     pPg->dirty = 1;
25970     pPg->pDirty = 0;
25971     rc = pager_write_pagelist( pPg );
25972     pPg->dirty = 0;
25973     if( rc!=SQLITE_OK ){
25974       return rc;
25975     }
25976   }
25977   assert( pPg->dirty==0 );
25978
25979   /* If the page we are recycling is marked as alwaysRollback, then
25980   ** set the global alwaysRollback flag, thus disabling the
25981   ** sqlite3PagerDontRollback() optimization for the rest of this transaction.
25982   ** It is necessary to do this because the page marked alwaysRollback
25983   ** might be reloaded at a later time but at that point we won't remember
25984   ** that is was marked alwaysRollback.  This means that all pages must
25985   ** be marked as alwaysRollback from here on out.
25986   */
25987   if( pPg->alwaysRollback ){
25988     IOTRACE(("ALWAYS_ROLLBACK %p\n", pPager))
25989     pPager->alwaysRollback = 1;
25990   }
25991
25992   /* Unlink the old page from the free list and the hash table
25993   */
25994   unlinkPage(pPg);
25995   assert( pPg->pgno==0 );
25996
25997   *ppPg = pPg;
25998   return SQLITE_OK;
25999 }
26000
26001 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26002 /*
26003 ** This function is called to free superfluous dynamically allocated memory
26004 ** held by the pager system. Memory in use by any SQLite pager allocated
26005 ** by the current thread may be sqlite3_free()ed.
26006 **
26007 ** nReq is the number of bytes of memory required. Once this much has
26008 ** been released, the function returns. The return value is the total number 
26009 ** of bytes of memory released.
26010 */
26011 SQLITE_PRIVATE int sqlite3PagerReleaseMemory(int nReq){
26012   int nReleased = 0;          /* Bytes of memory released so far */
26013   sqlite3_mutex *mutex;       /* The MEM2 mutex */
26014   Pager *pPager;              /* For looping over pagers */
26015   BusyHandler *savedBusy;     /* Saved copy of the busy handler */
26016   int rc = SQLITE_OK;
26017
26018   /* Acquire the memory-management mutex
26019   */
26020   mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
26021   sqlite3_mutex_enter(mutex);
26022
26023   /* Signal all database connections that memory management wants
26024   ** to have access to the pagers.
26025   */
26026   for(pPager=sqlite3PagerList; pPager; pPager=pPager->pNext){
26027      pPager->iInUseMM = 1;
26028   }
26029
26030   while( rc==SQLITE_OK && (nReq<0 || nReleased<nReq) ){
26031     PgHdr *pPg;
26032     PgHdr *pRecycled;
26033  
26034     /* Try to find a page to recycle that does not require a sync(). If
26035     ** this is not possible, find one that does require a sync().
26036     */
26037     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
26038     pPg = sqlite3LruPageList.pFirstSynced;
26039     while( pPg && (pPg->needSync || pPg->pPager->iInUseDB) ){
26040       pPg = pPg->gfree.pNext;
26041     }
26042     if( !pPg ){
26043       pPg = sqlite3LruPageList.pFirst;
26044       while( pPg && pPg->pPager->iInUseDB ){
26045         pPg = pPg->gfree.pNext;
26046       }
26047     }
26048     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
26049
26050     /* If pPg==0, then the block above has failed to find a page to
26051     ** recycle. In this case return early - no further memory will
26052     ** be released.
26053     */
26054     if( !pPg ) break;
26055
26056     pPager = pPg->pPager;
26057     assert(!pPg->needSync || pPg==pPager->lru.pFirst);
26058     assert(pPg->needSync || pPg==pPager->lru.pFirstSynced);
26059   
26060     savedBusy = pPager->pBusyHandler;
26061     pPager->pBusyHandler = 0;
26062     rc = pager_recycle(pPager, &pRecycled);
26063     pPager->pBusyHandler = savedBusy;
26064     assert(pRecycled==pPg || rc!=SQLITE_OK);
26065     if( rc==SQLITE_OK ){
26066       /* We've found a page to free. At this point the page has been 
26067       ** removed from the page hash-table, free-list and synced-list 
26068       ** (pFirstSynced). It is still in the all pages (pAll) list. 
26069       ** Remove it from this list before freeing.
26070       **
26071       ** Todo: Check the Pager.pStmt list to make sure this is Ok. It 
26072       ** probably is though.
26073       */
26074       PgHdr *pTmp;
26075       assert( pPg );
26076       if( pPg==pPager->pAll ){
26077          pPager->pAll = pPg->pNextAll;
26078       }else{
26079         for( pTmp=pPager->pAll; pTmp->pNextAll!=pPg; pTmp=pTmp->pNextAll ){}
26080         pTmp->pNextAll = pPg->pNextAll;
26081       }
26082       nReleased += (
26083           sizeof(*pPg) + pPager->pageSize
26084           + sizeof(u32) + pPager->nExtra
26085           + MEMDB*sizeof(PgHistory) 
26086       );
26087       IOTRACE(("PGFREE %p %d *\n", pPager, pPg->pgno));
26088       PAGER_INCR(sqlite3_pager_pgfree_count);
26089       sqlite3_free(pPg->pData);
26090       sqlite3_free(pPg);
26091       pPager->nPage--;
26092     }else{
26093       /* An error occured whilst writing to the database file or 
26094       ** journal in pager_recycle(). The error is not returned to the 
26095       ** caller of this function. Instead, set the Pager.errCode variable.
26096       ** The error will be returned to the user (or users, in the case 
26097       ** of a shared pager cache) of the pager for which the error occured.
26098       */
26099       assert(
26100           (rc&0xff)==SQLITE_IOERR ||
26101           rc==SQLITE_FULL ||
26102           rc==SQLITE_BUSY
26103       );
26104       assert( pPager->state>=PAGER_RESERVED );
26105       pager_error(pPager, rc);
26106     }
26107   }
26108
26109   /* Clear the memory management flags and release the mutex
26110   */
26111   for(pPager=sqlite3PagerList; pPager; pPager=pPager->pNext){
26112      pPager->iInUseMM = 0;
26113   }
26114   sqlite3_mutex_leave(mutex);
26115
26116   /* Return the number of bytes released
26117   */
26118   return nReleased;
26119 }
26120 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
26121
26122 /*
26123 ** Read the content of page pPg out of the database file.
26124 */
26125 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
26126   int rc;
26127   i64 offset;
26128   assert( MEMDB==0 );
26129   assert(pPager->fd->pMethods||pPager->tempFile);
26130   if( !pPager->fd->pMethods ){
26131     return SQLITE_IOERR_SHORT_READ;
26132   }
26133   offset = (pgno-1)*(i64)pPager->pageSize;
26134   rc = sqlite3OsRead(pPager->fd, PGHDR_TO_DATA(pPg), pPager->pageSize, offset);
26135   PAGER_INCR(sqlite3_pager_readdb_count);
26136   PAGER_INCR(pPager->nRead);
26137   IOTRACE(("PGIN %p %d\n", pPager, pgno));
26138   if( pgno==1 ){
26139     memcpy(&pPager->dbFileVers, &((u8*)PGHDR_TO_DATA(pPg))[24],
26140                                               sizeof(pPager->dbFileVers));
26141   }
26142   CODEC1(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
26143   PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
26144                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
26145   return rc;
26146 }
26147
26148
26149 /*
26150 ** This function is called to obtain the shared lock required before
26151 ** data may be read from the pager cache. If the shared lock has already
26152 ** been obtained, this function is a no-op.
26153 **
26154 ** Immediately after obtaining the shared lock (if required), this function
26155 ** checks for a hot-journal file. If one is found, an emergency rollback
26156 ** is performed immediately.
26157 */
26158 static int pagerSharedLock(Pager *pPager){
26159   int rc = SQLITE_OK;
26160   int isHot = 0;
26161
26162   /* If this database is opened for exclusive access, has no outstanding 
26163   ** page references and is in an error-state, now is the chance to clear
26164   ** the error. Discard the contents of the pager-cache and treat any
26165   ** open journal file as a hot-journal.
26166   */
26167   if( !MEMDB && pPager->exclusiveMode && pPager->nRef==0 && pPager->errCode ){
26168     if( pPager->journalOpen ){
26169       isHot = 1;
26170     }
26171     pager_reset(pPager);
26172     pPager->errCode = SQLITE_OK;
26173   }
26174
26175   /* If the pager is still in an error state, do not proceed. The error 
26176   ** state will be cleared at some point in the future when all page 
26177   ** references are dropped and the cache can be discarded.
26178   */
26179   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
26180     return pPager->errCode;
26181   }
26182
26183   if( pPager->state==PAGER_UNLOCK || isHot ){
26184     sqlite3_vfs *pVfs = pPager->pVfs;
26185     if( !MEMDB ){
26186       assert( pPager->nRef==0 );
26187       if( !pPager->noReadlock ){
26188         rc = pager_wait_on_lock(pPager, SHARED_LOCK);
26189         if( rc!=SQLITE_OK ){
26190           return pager_error(pPager, rc);
26191         }
26192         assert( pPager->state>=SHARED_LOCK );
26193       }
26194   
26195       /* If a journal file exists, and there is no RESERVED lock on the
26196       ** database file, then it either needs to be played back or deleted.
26197       */
26198       if( hasHotJournal(pPager) || isHot ){
26199         /* Get an EXCLUSIVE lock on the database file. At this point it is
26200         ** important that a RESERVED lock is not obtained on the way to the
26201         ** EXCLUSIVE lock. If it were, another process might open the
26202         ** database file, detect the RESERVED lock, and conclude that the
26203         ** database is safe to read while this process is still rolling it 
26204         ** back.
26205         ** 
26206         ** Because the intermediate RESERVED lock is not requested, the
26207         ** second process will get to this point in the code and fail to
26208         ** obtain its own EXCLUSIVE lock on the database file.
26209         */
26210         if( pPager->state<EXCLUSIVE_LOCK ){
26211           rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
26212           if( rc!=SQLITE_OK ){
26213             pager_unlock(pPager);
26214             return pager_error(pPager, rc);
26215           }
26216           pPager->state = PAGER_EXCLUSIVE;
26217         }
26218  
26219         /* Open the journal for reading only.  Return SQLITE_BUSY if
26220         ** we are unable to open the journal file. 
26221         **
26222         ** The journal file does not need to be locked itself.  The
26223         ** journal file is never open unless the main database file holds
26224         ** a write lock, so there is never any chance of two or more
26225         ** processes opening the journal at the same time.
26226         **
26227         ** Open the journal for read/write access. This is because in 
26228         ** exclusive-access mode the file descriptor will be kept open and
26229         ** possibly used for a transaction later on. On some systems, the
26230         ** OsTruncate() call used in exclusive-access mode also requires
26231         ** a read/write file handle.
26232         */
26233         if( !isHot ){
26234           rc = SQLITE_BUSY;
26235           if( sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS) ){
26236             int fout = 0;
26237             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
26238             assert( !pPager->tempFile );
26239             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
26240             assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
26241             if( fout&SQLITE_OPEN_READONLY ){
26242               rc = SQLITE_BUSY;
26243               sqlite3OsClose(pPager->jfd);
26244             }
26245           }
26246         }
26247         if( rc!=SQLITE_OK ){
26248           pager_unlock(pPager);
26249           switch( rc ){
26250             case SQLITE_NOMEM:
26251             case SQLITE_IOERR_UNLOCK:
26252             case SQLITE_IOERR_NOMEM:
26253               return rc;
26254             default:
26255               return SQLITE_BUSY;
26256           }
26257         }
26258         pPager->journalOpen = 1;
26259         pPager->journalStarted = 0;
26260         pPager->journalOff = 0;
26261         pPager->setMaster = 0;
26262         pPager->journalHdr = 0;
26263  
26264         /* Playback and delete the journal.  Drop the database write
26265         ** lock and reacquire the read lock.
26266         */
26267         rc = pager_playback(pPager, 1);
26268         if( rc!=SQLITE_OK ){
26269           return pager_error(pPager, rc);
26270         }
26271         assert(pPager->state==PAGER_SHARED || 
26272             (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
26273         );
26274       }
26275
26276       if( pPager->pAll ){
26277         /* The shared-lock has just been acquired on the database file
26278         ** and there are already pages in the cache (from a previous
26279         ** read or write transaction).  Check to see if the database
26280         ** has been modified.  If the database has changed, flush the
26281         ** cache.
26282         **
26283         ** Database changes is detected by looking at 15 bytes beginning
26284         ** at offset 24 into the file.  The first 4 of these 16 bytes are
26285         ** a 32-bit counter that is incremented with each change.  The
26286         ** other bytes change randomly with each file change when
26287         ** a codec is in use.
26288         ** 
26289         ** There is a vanishingly small chance that a change will not be 
26290         ** detected.  The chance of an undetected change is so small that
26291         ** it can be neglected.
26292         */
26293         char dbFileVers[sizeof(pPager->dbFileVers)];
26294         sqlite3PagerPagecount(pPager);
26295
26296         if( pPager->errCode ){
26297           return pPager->errCode;
26298         }
26299
26300         if( pPager->dbSize>0 ){
26301           IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
26302           rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
26303           if( rc!=SQLITE_OK ){
26304             return rc;
26305           }
26306         }else{
26307           memset(dbFileVers, 0, sizeof(dbFileVers));
26308         }
26309
26310         if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
26311           pager_reset(pPager);
26312         }
26313       }
26314     }
26315     assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
26316     if( pPager->state==PAGER_UNLOCK ){
26317       pPager->state = PAGER_SHARED;
26318     }
26319   }
26320
26321   return rc;
26322 }
26323
26324 /*
26325 ** Allocate a PgHdr object.   Either create a new one or reuse
26326 ** an existing one that is not otherwise in use.
26327 **
26328 ** A new PgHdr structure is created if any of the following are
26329 ** true:
26330 **
26331 **     (1)  We have not exceeded our maximum allocated cache size
26332 **          as set by the "PRAGMA cache_size" command.
26333 **
26334 **     (2)  There are no unused PgHdr objects available at this time.
26335 **
26336 **     (3)  This is an in-memory database.
26337 **
26338 **     (4)  There are no PgHdr objects that do not require a journal
26339 **          file sync and a sync of the journal file is currently
26340 **          prohibited.
26341 **
26342 ** Otherwise, reuse an existing PgHdr.  In other words, reuse an
26343 ** existing PgHdr if all of the following are true:
26344 **
26345 **     (1)  We have reached or exceeded the maximum cache size
26346 **          allowed by "PRAGMA cache_size".
26347 **
26348 **     (2)  There is a PgHdr available with PgHdr->nRef==0
26349 **
26350 **     (3)  We are not in an in-memory database
26351 **
26352 **     (4)  Either there is an available PgHdr that does not need
26353 **          to be synced to disk or else disk syncing is currently
26354 **          allowed.
26355 */
26356 static int pagerAllocatePage(Pager *pPager, PgHdr **ppPg){
26357   int rc = SQLITE_OK;
26358   PgHdr *pPg;
26359   int nByteHdr;
26360
26361   /* Create a new PgHdr if any of the four conditions defined 
26362   ** above are met: */
26363   if( pPager->nPage<pPager->mxPage
26364    || pPager->lru.pFirst==0 
26365    || MEMDB
26366    || (pPager->lru.pFirstSynced==0 && pPager->doNotSync)
26367   ){
26368     void *pData;
26369     if( pPager->nPage>=pPager->nHash ){
26370       pager_resize_hash_table(pPager,
26371          pPager->nHash<256 ? 256 : pPager->nHash*2);
26372       if( pPager->nHash==0 ){
26373         rc = SQLITE_NOMEM;
26374         goto pager_allocate_out;
26375       }
26376     }
26377     pagerLeave(pPager);
26378     nByteHdr = sizeof(*pPg) + sizeof(u32) + pPager->nExtra
26379               + MEMDB*sizeof(PgHistory);
26380     pPg = sqlite3_malloc( nByteHdr );
26381     if( pPg ){
26382       pData = sqlite3_malloc( pPager->pageSize );
26383       if( pData==0 ){
26384         sqlite3_free(pPg);
26385         pPg = 0;
26386       }
26387     }
26388     pagerEnter(pPager);
26389     if( pPg==0 ){
26390       rc = SQLITE_NOMEM;
26391       goto pager_allocate_out;
26392     }
26393     memset(pPg, 0, nByteHdr);
26394     pPg->pData = pData;
26395     pPg->pPager = pPager;
26396     pPg->pNextAll = pPager->pAll;
26397     pPager->pAll = pPg;
26398     pPager->nPage++;
26399   }else{
26400     /* Recycle an existing page with a zero ref-count. */
26401     rc = pager_recycle(pPager, &pPg);
26402     if( rc==SQLITE_BUSY ){
26403       rc = SQLITE_IOERR_BLOCKED;
26404     }
26405     if( rc!=SQLITE_OK ){
26406       goto pager_allocate_out;
26407     }
26408     assert( pPager->state>=SHARED_LOCK );
26409     assert(pPg);
26410   }
26411   *ppPg = pPg;
26412
26413 pager_allocate_out:
26414   return rc;
26415 }
26416
26417 /*
26418 ** Make sure we have the content for a page.  If the page was
26419 ** previously acquired with noContent==1, then the content was
26420 ** just initialized to zeros instead of being read from disk.
26421 ** But now we need the real data off of disk.  So make sure we
26422 ** have it.  Read it in if we do not have it already.
26423 */
26424 static int pager_get_content(PgHdr *pPg){
26425   if( pPg->needRead ){
26426     int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
26427     if( rc==SQLITE_OK ){
26428       pPg->needRead = 0;
26429     }else{
26430       return rc;
26431     }
26432   }
26433   return SQLITE_OK;
26434 }
26435
26436 /*
26437 ** Acquire a page.
26438 **
26439 ** A read lock on the disk file is obtained when the first page is acquired. 
26440 ** This read lock is dropped when the last page is released.
26441 **
26442 ** This routine works for any page number greater than 0.  If the database
26443 ** file is smaller than the requested page, then no actual disk
26444 ** read occurs and the memory image of the page is initialized to
26445 ** all zeros.  The extra data appended to a page is always initialized
26446 ** to zeros the first time a page is loaded into memory.
26447 **
26448 ** The acquisition might fail for several reasons.  In all cases,
26449 ** an appropriate error code is returned and *ppPage is set to NULL.
26450 **
26451 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
26452 ** to find a page in the in-memory cache first.  If the page is not already
26453 ** in memory, this routine goes to disk to read it in whereas Lookup()
26454 ** just returns 0.  This routine acquires a read-lock the first time it
26455 ** has to go to disk, and could also playback an old journal if necessary.
26456 ** Since Lookup() never goes to disk, it never has to deal with locks
26457 ** or journal files.
26458 **
26459 ** If noContent is false, the page contents are actually read from disk.
26460 ** If noContent is true, it means that we do not care about the contents
26461 ** of the page at this time, so do not do a disk read.  Just fill in the
26462 ** page content with zeros.  But mark the fact that we have not read the
26463 ** content by setting the PgHdr.needRead flag.  Later on, if 
26464 ** sqlite3PagerWrite() is called on this page or if this routine is
26465 ** called again with noContent==0, that means that the content is needed
26466 ** and the disk read should occur at that point.
26467 */
26468 static int pagerAcquire(
26469   Pager *pPager,      /* The pager open on the database file */
26470   Pgno pgno,          /* Page number to fetch */
26471   DbPage **ppPage,    /* Write a pointer to the page here */
26472   int noContent       /* Do not bother reading content from disk if true */
26473 ){
26474   PgHdr *pPg;
26475   int rc;
26476
26477   assert( pPager->state==PAGER_UNLOCK || pPager->nRef>0 || pgno==1 );
26478
26479   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
26480   ** number greater than this, or zero, is requested.
26481   */
26482   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
26483     return SQLITE_CORRUPT_BKPT;
26484   }
26485
26486   /* Make sure we have not hit any critical errors.
26487   */ 
26488   assert( pPager!=0 );
26489   *ppPage = 0;
26490
26491   /* If this is the first page accessed, then get a SHARED lock
26492   ** on the database file. pagerSharedLock() is a no-op if 
26493   ** a database lock is already held.
26494   */
26495   rc = pagerSharedLock(pPager);
26496   if( rc!=SQLITE_OK ){
26497     return rc;
26498   }
26499   assert( pPager->state!=PAGER_UNLOCK );
26500
26501   pPg = pager_lookup(pPager, pgno);
26502   if( pPg==0 ){
26503     /* The requested page is not in the page cache. */
26504     int nMax;
26505     int h;
26506     PAGER_INCR(pPager->nMiss);
26507     rc = pagerAllocatePage(pPager, &pPg);
26508     if( rc!=SQLITE_OK ){
26509       return rc;
26510     }
26511
26512     pPg->pgno = pgno;
26513     assert( !MEMDB || pgno>pPager->stmtSize );
26514     pPg->inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno);
26515     pPg->needSync = 0;
26516
26517     makeClean(pPg);
26518     pPg->nRef = 1;
26519
26520     pPager->nRef++;
26521     if( pPager->nExtra>0 ){
26522       memset(PGHDR_TO_EXTRA(pPg, pPager), 0, pPager->nExtra);
26523     }
26524     nMax = sqlite3PagerPagecount(pPager);
26525     if( pPager->errCode ){
26526       rc = pPager->errCode;
26527       sqlite3PagerUnref(pPg);
26528       return rc;
26529     }
26530
26531     /* Populate the page with data, either by reading from the database
26532     ** file, or by setting the entire page to zero.
26533     */
26534     if( nMax<(int)pgno || MEMDB || (noContent && !pPager->alwaysRollback) ){
26535       if( pgno>pPager->mxPgno ){
26536         sqlite3PagerUnref(pPg);
26537         return SQLITE_FULL;
26538       }
26539       memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
26540       pPg->needRead = noContent && !pPager->alwaysRollback;
26541       IOTRACE(("ZERO %p %d\n", pPager, pgno));
26542     }else{
26543       rc = readDbPage(pPager, pPg, pgno);
26544       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
26545         pPg->pgno = 0;
26546         sqlite3PagerUnref(pPg);
26547         return rc;
26548       }
26549       pPg->needRead = 0;
26550     }
26551
26552     /* Link the page into the page hash table */
26553     h = pgno & (pPager->nHash-1);
26554     assert( pgno!=0 );
26555     pPg->pNextHash = pPager->aHash[h];
26556     pPager->aHash[h] = pPg;
26557     if( pPg->pNextHash ){
26558       assert( pPg->pNextHash->pPrevHash==0 );
26559       pPg->pNextHash->pPrevHash = pPg;
26560     }
26561
26562 #ifdef SQLITE_CHECK_PAGES
26563     pPg->pageHash = pager_pagehash(pPg);
26564 #endif
26565   }else{
26566     /* The requested page is in the page cache. */
26567     assert(pPager->nRef>0 || pgno==1);
26568     PAGER_INCR(pPager->nHit);
26569     if( !noContent ){
26570       rc = pager_get_content(pPg);
26571       if( rc ){
26572         return rc;
26573       }
26574     }
26575     page_ref(pPg);
26576   }
26577   *ppPage = pPg;
26578   return SQLITE_OK;
26579 }
26580 SQLITE_PRIVATE int sqlite3PagerAcquire(
26581   Pager *pPager,      /* The pager open on the database file */
26582   Pgno pgno,          /* Page number to fetch */
26583   DbPage **ppPage,    /* Write a pointer to the page here */
26584   int noContent       /* Do not bother reading content from disk if true */
26585 ){
26586   int rc;
26587   pagerEnter(pPager);
26588   rc = pagerAcquire(pPager, pgno, ppPage, noContent);
26589   pagerLeave(pPager);
26590   return rc;
26591 }
26592
26593
26594 /*
26595 ** Acquire a page if it is already in the in-memory cache.  Do
26596 ** not read the page from disk.  Return a pointer to the page,
26597 ** or 0 if the page is not in cache.
26598 **
26599 ** See also sqlite3PagerGet().  The difference between this routine
26600 ** and sqlite3PagerGet() is that _get() will go to the disk and read
26601 ** in the page if the page is not already in cache.  This routine
26602 ** returns NULL if the page is not in cache or if a disk I/O error 
26603 ** has ever happened.
26604 */
26605 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
26606   PgHdr *pPg = 0;
26607
26608   assert( pPager!=0 );
26609   assert( pgno!=0 );
26610
26611   pagerEnter(pPager);
26612   if( pPager->state==PAGER_UNLOCK ){
26613     assert( !pPager->pAll || pPager->exclusiveMode );
26614   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
26615     /* Do nothing */
26616   }else if( (pPg = pager_lookup(pPager, pgno))!=0 ){
26617     page_ref(pPg);
26618   }
26619   pagerLeave(pPager);
26620   return pPg;
26621 }
26622
26623 /*
26624 ** Release a page.
26625 **
26626 ** If the number of references to the page drop to zero, then the
26627 ** page is added to the LRU list.  When all references to all pages
26628 ** are released, a rollback occurs and the lock on the database is
26629 ** removed.
26630 */
26631 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
26632   Pager *pPager = pPg->pPager;
26633
26634   /* Decrement the reference count for this page
26635   */
26636   assert( pPg->nRef>0 );
26637   pagerEnter(pPg->pPager);
26638   pPg->nRef--;
26639
26640   CHECK_PAGE(pPg);
26641
26642   /* When the number of references to a page reach 0, call the
26643   ** destructor and add the page to the freelist.
26644   */
26645   if( pPg->nRef==0 ){
26646
26647     lruListAdd(pPg);
26648     if( pPager->xDestructor ){
26649       pPager->xDestructor(pPg, pPager->pageSize);
26650     }
26651   
26652     /* When all pages reach the freelist, drop the read lock from
26653     ** the database file.
26654     */
26655     pPager->nRef--;
26656     assert( pPager->nRef>=0 );
26657     if( pPager->nRef==0 && (!pPager->exclusiveMode || pPager->journalOff>0) ){
26658       pagerUnlockAndRollback(pPager);
26659     }
26660   }
26661   pagerLeave(pPager);
26662   return SQLITE_OK;
26663 }
26664
26665 /*
26666 ** Create a journal file for pPager.  There should already be a RESERVED
26667 ** or EXCLUSIVE lock on the database file when this routine is called.
26668 **
26669 ** Return SQLITE_OK if everything.  Return an error code and release the
26670 ** write lock if anything goes wrong.
26671 */
26672 static int pager_open_journal(Pager *pPager){
26673   sqlite3_vfs *pVfs = pPager->pVfs;
26674   int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
26675
26676   int rc;
26677   assert( !MEMDB );
26678   assert( pPager->state>=PAGER_RESERVED );
26679   assert( pPager->journalOpen==0 );
26680   assert( pPager->useJournal );
26681   assert( pPager->pInJournal==0 );
26682   sqlite3PagerPagecount(pPager);
26683   pagerLeave(pPager);
26684   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
26685   pagerEnter(pPager);
26686   if( pPager->pInJournal==0 ){
26687     rc = SQLITE_NOMEM;
26688     goto failed_to_open_journal;
26689   }
26690
26691   if( pPager->tempFile ){
26692     flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
26693   }else{
26694     flags |= (SQLITE_OPEN_MAIN_JOURNAL);
26695   }
26696 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
26697   rc = sqlite3JournalOpen(
26698       pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
26699   );
26700 #else
26701   rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
26702 #endif
26703   assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
26704   pPager->journalOff = 0;
26705   pPager->setMaster = 0;
26706   pPager->journalHdr = 0;
26707   if( rc!=SQLITE_OK ){
26708     if( rc==SQLITE_NOMEM ){
26709       sqlite3OsDelete(pVfs, pPager->zJournal, 0);
26710     }
26711     goto failed_to_open_journal;
26712   }
26713   pPager->journalOpen = 1;
26714   pPager->journalStarted = 0;
26715   pPager->needSync = 0;
26716   pPager->alwaysRollback = 0;
26717   pPager->nRec = 0;
26718   if( pPager->errCode ){
26719     rc = pPager->errCode;
26720     goto failed_to_open_journal;
26721   }
26722   pPager->origDbSize = pPager->dbSize;
26723
26724   rc = writeJournalHdr(pPager);
26725
26726   if( pPager->stmtAutoopen && rc==SQLITE_OK ){
26727     rc = sqlite3PagerStmtBegin(pPager);
26728   }
26729   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
26730     rc = pager_end_transaction(pPager);
26731     if( rc==SQLITE_OK ){
26732       rc = SQLITE_FULL;
26733     }
26734   }
26735   return rc;
26736
26737 failed_to_open_journal:
26738   sqlite3BitvecDestroy(pPager->pInJournal);
26739   pPager->pInJournal = 0;
26740   return rc;
26741 }
26742
26743 /*
26744 ** Acquire a write-lock on the database.  The lock is removed when
26745 ** the any of the following happen:
26746 **
26747 **   *  sqlite3PagerCommitPhaseTwo() is called.
26748 **   *  sqlite3PagerRollback() is called.
26749 **   *  sqlite3PagerClose() is called.
26750 **   *  sqlite3PagerUnref() is called to on every outstanding page.
26751 **
26752 ** The first parameter to this routine is a pointer to any open page of the
26753 ** database file.  Nothing changes about the page - it is used merely to
26754 ** acquire a pointer to the Pager structure and as proof that there is
26755 ** already a read-lock on the database.
26756 **
26757 ** The second parameter indicates how much space in bytes to reserve for a
26758 ** master journal file-name at the start of the journal when it is created.
26759 **
26760 ** A journal file is opened if this is not a temporary file.  For temporary
26761 ** files, the opening of the journal file is deferred until there is an
26762 ** actual need to write to the journal.
26763 **
26764 ** If the database is already reserved for writing, this routine is a no-op.
26765 **
26766 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
26767 ** immediately instead of waiting until we try to flush the cache.  The
26768 ** exFlag is ignored if a transaction is already active.
26769 */
26770 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
26771   Pager *pPager = pPg->pPager;
26772   int rc = SQLITE_OK;
26773   pagerEnter(pPager);
26774   assert( pPg->nRef>0 );
26775   assert( pPager->state!=PAGER_UNLOCK );
26776   if( pPager->state==PAGER_SHARED ){
26777     assert( pPager->pInJournal==0 );
26778     if( MEMDB ){
26779       pPager->state = PAGER_EXCLUSIVE;
26780       pPager->origDbSize = pPager->dbSize;
26781     }else{
26782       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
26783       if( rc==SQLITE_OK ){
26784         pPager->state = PAGER_RESERVED;
26785         if( exFlag ){
26786           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
26787         }
26788       }
26789       if( rc!=SQLITE_OK ){
26790         pagerLeave(pPager);
26791         return rc;
26792       }
26793       pPager->dirtyCache = 0;
26794       PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
26795       if( pPager->useJournal && !pPager->tempFile ){
26796         rc = pager_open_journal(pPager);
26797       }
26798     }
26799   }else if( pPager->journalOpen && pPager->journalOff==0 ){
26800     /* This happens when the pager was in exclusive-access mode last
26801     ** time a (read or write) transaction was successfully concluded
26802     ** by this connection. Instead of deleting the journal file it was 
26803     ** kept open and truncated to 0 bytes.
26804     */
26805     assert( pPager->nRec==0 );
26806     assert( pPager->origDbSize==0 );
26807     assert( pPager->pInJournal==0 );
26808     sqlite3PagerPagecount(pPager);
26809     pagerLeave(pPager);
26810     pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
26811     pagerEnter(pPager);
26812     if( !pPager->pInJournal ){
26813       rc = SQLITE_NOMEM;
26814     }else{
26815       pPager->origDbSize = pPager->dbSize;
26816       rc = writeJournalHdr(pPager);
26817     }
26818   }
26819   assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
26820   pagerLeave(pPager);
26821   return rc;
26822 }
26823
26824 /*
26825 ** Make a page dirty.  Set its dirty flag and add it to the dirty
26826 ** page list.
26827 */
26828 static void makeDirty(PgHdr *pPg){
26829   if( pPg->dirty==0 ){
26830     Pager *pPager = pPg->pPager;
26831     pPg->dirty = 1;
26832     pPg->pDirty = pPager->pDirty;
26833     if( pPager->pDirty ){
26834       pPager->pDirty->pPrevDirty = pPg;
26835     }
26836     pPg->pPrevDirty = 0;
26837     pPager->pDirty = pPg;
26838   }
26839 }
26840
26841 /*
26842 ** Make a page clean.  Clear its dirty bit and remove it from the
26843 ** dirty page list.
26844 */
26845 static void makeClean(PgHdr *pPg){
26846   if( pPg->dirty ){
26847     pPg->dirty = 0;
26848     if( pPg->pDirty ){
26849       assert( pPg->pDirty->pPrevDirty==pPg );
26850       pPg->pDirty->pPrevDirty = pPg->pPrevDirty;
26851     }
26852     if( pPg->pPrevDirty ){
26853       assert( pPg->pPrevDirty->pDirty==pPg );
26854       pPg->pPrevDirty->pDirty = pPg->pDirty;
26855     }else{
26856       assert( pPg->pPager->pDirty==pPg );
26857       pPg->pPager->pDirty = pPg->pDirty;
26858     }
26859   }
26860 }
26861
26862
26863 /*
26864 ** Mark a data page as writeable.  The page is written into the journal 
26865 ** if it is not there already.  This routine must be called before making
26866 ** changes to a page.
26867 **
26868 ** The first time this routine is called, the pager creates a new
26869 ** journal and acquires a RESERVED lock on the database.  If the RESERVED
26870 ** lock could not be acquired, this routine returns SQLITE_BUSY.  The
26871 ** calling routine must check for that return value and be careful not to
26872 ** change any page data until this routine returns SQLITE_OK.
26873 **
26874 ** If the journal file could not be written because the disk is full,
26875 ** then this routine returns SQLITE_FULL and does an immediate rollback.
26876 ** All subsequent write attempts also return SQLITE_FULL until there
26877 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
26878 ** reset.
26879 */
26880 static int pager_write(PgHdr *pPg){
26881   void *pData = PGHDR_TO_DATA(pPg);
26882   Pager *pPager = pPg->pPager;
26883   int rc = SQLITE_OK;
26884
26885   /* Check for errors
26886   */
26887   if( pPager->errCode ){ 
26888     return pPager->errCode;
26889   }
26890   if( pPager->readOnly ){
26891     return SQLITE_PERM;
26892   }
26893
26894   assert( !pPager->setMaster );
26895
26896   CHECK_PAGE(pPg);
26897
26898   /* If this page was previously acquired with noContent==1, that means
26899   ** we didn't really read in the content of the page.  This can happen
26900   ** (for example) when the page is being moved to the freelist.  But
26901   ** now we are (perhaps) moving the page off of the freelist for
26902   ** reuse and we need to know its original content so that content
26903   ** can be stored in the rollback journal.  So do the read at this
26904   ** time.
26905   */
26906   rc = pager_get_content(pPg);
26907   if( rc ){
26908     return rc;
26909   }
26910
26911   /* Mark the page as dirty.  If the page has already been written
26912   ** to the journal then we can return right away.
26913   */
26914   makeDirty(pPg);
26915   if( pPg->inJournal && (pageInStatement(pPg) || pPager->stmtInUse==0) ){
26916     pPager->dirtyCache = 1;
26917   }else{
26918
26919     /* If we get this far, it means that the page needs to be
26920     ** written to the transaction journal or the ckeckpoint journal
26921     ** or both.
26922     **
26923     ** First check to see that the transaction journal exists and
26924     ** create it if it does not.
26925     */
26926     assert( pPager->state!=PAGER_UNLOCK );
26927     rc = sqlite3PagerBegin(pPg, 0);
26928     if( rc!=SQLITE_OK ){
26929       return rc;
26930     }
26931     assert( pPager->state>=PAGER_RESERVED );
26932     if( !pPager->journalOpen && pPager->useJournal ){
26933       rc = pager_open_journal(pPager);
26934       if( rc!=SQLITE_OK ) return rc;
26935     }
26936     assert( pPager->journalOpen || !pPager->useJournal );
26937     pPager->dirtyCache = 1;
26938   
26939     /* The transaction journal now exists and we have a RESERVED or an
26940     ** EXCLUSIVE lock on the main database file.  Write the current page to
26941     ** the transaction journal if it is not there already.
26942     */
26943     if( !pPg->inJournal && (pPager->useJournal || MEMDB) ){
26944       if( (int)pPg->pgno <= pPager->origDbSize ){
26945         if( MEMDB ){
26946           PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
26947           PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
26948           assert( pHist->pOrig==0 );
26949           pHist->pOrig = sqlite3_malloc( pPager->pageSize );
26950           if( !pHist->pOrig ){
26951             return SQLITE_NOMEM;
26952           }
26953           memcpy(pHist->pOrig, PGHDR_TO_DATA(pPg), pPager->pageSize);
26954         }else{
26955           u32 cksum;
26956           char *pData2;
26957
26958           /* We should never write to the journal file the page that
26959           ** contains the database locks.  The following assert verifies
26960           ** that we do not. */
26961           assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
26962           pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
26963           cksum = pager_cksum(pPager, (u8*)pData2);
26964           rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
26965           if( rc==SQLITE_OK ){
26966             rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
26967                                 pPager->journalOff + 4);
26968             pPager->journalOff += pPager->pageSize+4;
26969           }
26970           if( rc==SQLITE_OK ){
26971             rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
26972             pPager->journalOff += 4;
26973           }
26974           IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
26975                    pPager->journalOff, pPager->pageSize));
26976           PAGER_INCR(sqlite3_pager_writej_count);
26977           PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
26978                PAGERID(pPager), pPg->pgno, pPg->needSync, pager_pagehash(pPg));
26979
26980           /* An error has occured writing to the journal file. The 
26981           ** transaction will be rolled back by the layer above.
26982           */
26983           if( rc!=SQLITE_OK ){
26984             return rc;
26985           }
26986
26987           pPager->nRec++;
26988           assert( pPager->pInJournal!=0 );
26989           sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
26990           pPg->needSync = !pPager->noSync;
26991           if( pPager->stmtInUse ){
26992             sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
26993           }
26994         }
26995       }else{
26996         pPg->needSync = !pPager->journalStarted && !pPager->noSync;
26997         PAGERTRACE4("APPEND %d page %d needSync=%d\n",
26998                 PAGERID(pPager), pPg->pgno, pPg->needSync);
26999       }
27000       if( pPg->needSync ){
27001         pPager->needSync = 1;
27002       }
27003       pPg->inJournal = 1;
27004     }
27005   
27006     /* If the statement journal is open and the page is not in it,
27007     ** then write the current page to the statement journal.  Note that
27008     ** the statement journal format differs from the standard journal format
27009     ** in that it omits the checksums and the header.
27010     */
27011     if( pPager->stmtInUse 
27012      && !pageInStatement(pPg) 
27013      && (int)pPg->pgno<=pPager->stmtSize 
27014     ){
27015       assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
27016       if( MEMDB ){
27017         PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
27018         assert( pHist->pStmt==0 );
27019         pHist->pStmt = sqlite3_malloc( pPager->pageSize );
27020         if( pHist->pStmt ){
27021           memcpy(pHist->pStmt, PGHDR_TO_DATA(pPg), pPager->pageSize);
27022         }
27023         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
27024         page_add_to_stmt_list(pPg);
27025       }else{
27026         i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
27027         char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
27028         rc = write32bits(pPager->stfd, offset, pPg->pgno);
27029         if( rc==SQLITE_OK ){
27030           rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize, offset+4);
27031         }
27032         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
27033         if( rc!=SQLITE_OK ){
27034           return rc;
27035         }
27036         pPager->stmtNRec++;
27037         assert( pPager->pInStmt!=0 );
27038         sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
27039       }
27040     }
27041   }
27042
27043   /* Update the database size and return.
27044   */
27045   assert( pPager->state>=PAGER_SHARED );
27046   if( pPager->dbSize<(int)pPg->pgno ){
27047     pPager->dbSize = pPg->pgno;
27048     if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
27049       pPager->dbSize++;
27050     }
27051   }
27052   return rc;
27053 }
27054
27055 /*
27056 ** This function is used to mark a data-page as writable. It uses 
27057 ** pager_write() to open a journal file (if it is not already open)
27058 ** and write the page *pData to the journal.
27059 **
27060 ** The difference between this function and pager_write() is that this
27061 ** function also deals with the special case where 2 or more pages
27062 ** fit on a single disk sector. In this case all co-resident pages
27063 ** must have been written to the journal file before returning.
27064 */
27065 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
27066   int rc = SQLITE_OK;
27067
27068   PgHdr *pPg = pDbPage;
27069   Pager *pPager = pPg->pPager;
27070   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
27071
27072   pagerEnter(pPager);
27073   if( !MEMDB && nPagePerSector>1 ){
27074     Pgno nPageCount;          /* Total number of pages in database file */
27075     Pgno pg1;                 /* First page of the sector pPg is located on. */
27076     int nPage;                /* Number of pages starting at pg1 to journal */
27077     int ii;
27078     int needSync = 0;
27079
27080     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
27081     ** header to be written between the pages journaled by this function.
27082     */
27083     assert( pPager->doNotSync==0 );
27084     pPager->doNotSync = 1;
27085
27086     /* This trick assumes that both the page-size and sector-size are
27087     ** an integer power of 2. It sets variable pg1 to the identifier
27088     ** of the first page of the sector pPg is located on.
27089     */
27090     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
27091
27092     nPageCount = sqlite3PagerPagecount(pPager);
27093     if( pPg->pgno>nPageCount ){
27094       nPage = (pPg->pgno - pg1)+1;
27095     }else if( (pg1+nPagePerSector-1)>nPageCount ){
27096       nPage = nPageCount+1-pg1;
27097     }else{
27098       nPage = nPagePerSector;
27099     }
27100     assert(nPage>0);
27101     assert(pg1<=pPg->pgno);
27102     assert((pg1+nPage)>pPg->pgno);
27103
27104     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
27105       Pgno pg = pg1+ii;
27106       PgHdr *pPage;
27107       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
27108         if( pg!=PAGER_MJ_PGNO(pPager) ){
27109           rc = sqlite3PagerGet(pPager, pg, &pPage);
27110           if( rc==SQLITE_OK ){
27111             rc = pager_write(pPage);
27112             if( pPage->needSync ){
27113               needSync = 1;
27114             }
27115             sqlite3PagerUnref(pPage);
27116           }
27117         }
27118       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
27119         if( pPage->needSync ){
27120           needSync = 1;
27121         }
27122       }
27123     }
27124
27125     /* If the PgHdr.needSync flag is set for any of the nPage pages 
27126     ** starting at pg1, then it needs to be set for all of them. Because
27127     ** writing to any of these nPage pages may damage the others, the
27128     ** journal file must contain sync()ed copies of all of them
27129     ** before any of them can be written out to the database file.
27130     */
27131     if( needSync ){
27132       for(ii=0; ii<nPage && needSync; ii++){
27133         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
27134         if( pPage ) pPage->needSync = 1;
27135       }
27136       assert(pPager->needSync);
27137     }
27138
27139     assert( pPager->doNotSync==1 );
27140     pPager->doNotSync = 0;
27141   }else{
27142     rc = pager_write(pDbPage);
27143   }
27144   pagerLeave(pPager);
27145   return rc;
27146 }
27147
27148 /*
27149 ** Return TRUE if the page given in the argument was previously passed
27150 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
27151 ** to change the content of the page.
27152 */
27153 #ifndef NDEBUG
27154 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
27155   return pPg->dirty;
27156 }
27157 #endif
27158
27159 #ifndef SQLITE_OMIT_VACUUM
27160 /*
27161 ** Replace the content of a single page with the information in the third
27162 ** argument.
27163 */
27164 SQLITE_PRIVATE int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void *pData){
27165   PgHdr *pPg;
27166   int rc;
27167
27168   pagerEnter(pPager);
27169   rc = sqlite3PagerGet(pPager, pgno, &pPg);
27170   if( rc==SQLITE_OK ){
27171     rc = sqlite3PagerWrite(pPg);
27172     if( rc==SQLITE_OK ){
27173       memcpy(sqlite3PagerGetData(pPg), pData, pPager->pageSize);
27174     }
27175     sqlite3PagerUnref(pPg);
27176   }
27177   pagerLeave(pPager);
27178   return rc;
27179 }
27180 #endif
27181
27182 /*
27183 ** A call to this routine tells the pager that it is not necessary to
27184 ** write the information on page pPg back to the disk, even though
27185 ** that page might be marked as dirty.
27186 **
27187 ** The overlying software layer calls this routine when all of the data
27188 ** on the given page is unused.  The pager marks the page as clean so
27189 ** that it does not get written to disk.
27190 **
27191 ** Tests show that this optimization, together with the
27192 ** sqlite3PagerDontRollback() below, more than double the speed
27193 ** of large INSERT operations and quadruple the speed of large DELETEs.
27194 **
27195 ** When this routine is called, set the alwaysRollback flag to true.
27196 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
27197 ** will thereafter be ignored.  This is necessary to avoid a problem
27198 ** where a page with data is added to the freelist during one part of
27199 ** a transaction then removed from the freelist during a later part
27200 ** of the same transaction and reused for some other purpose.  When it
27201 ** is first added to the freelist, this routine is called.  When reused,
27202 ** the sqlite3PagerDontRollback() routine is called.  But because the
27203 ** page contains critical data, we still need to be sure it gets
27204 ** rolled back in spite of the sqlite3PagerDontRollback() call.
27205 */
27206 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage *pDbPage){
27207   PgHdr *pPg = pDbPage;
27208   Pager *pPager = pPg->pPager;
27209
27210   if( MEMDB ) return;
27211   pagerEnter(pPager);
27212   pPg->alwaysRollback = 1;
27213   if( pPg->dirty && !pPager->stmtInUse ){
27214     assert( pPager->state>=PAGER_SHARED );
27215     if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
27216       /* If this pages is the last page in the file and the file has grown
27217       ** during the current transaction, then do NOT mark the page as clean.
27218       ** When the database file grows, we must make sure that the last page
27219       ** gets written at least once so that the disk file will be the correct
27220       ** size. If you do not write this page and the size of the file
27221       ** on the disk ends up being too small, that can lead to database
27222       ** corruption during the next transaction.
27223       */
27224     }else{
27225       PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
27226       IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
27227       makeClean(pPg);
27228 #ifdef SQLITE_CHECK_PAGES
27229       pPg->pageHash = pager_pagehash(pPg);
27230 #endif
27231     }
27232   }
27233   pagerLeave(pPager);
27234 }
27235
27236 /*
27237 ** A call to this routine tells the pager that if a rollback occurs,
27238 ** it is not necessary to restore the data on the given page.  This
27239 ** means that the pager does not have to record the given page in the
27240 ** rollback journal.
27241 **
27242 ** If we have not yet actually read the content of this page (if
27243 ** the PgHdr.needRead flag is set) then this routine acts as a promise
27244 ** that we will never need to read the page content in the future.
27245 ** so the needRead flag can be cleared at this point.
27246 **
27247 ** This routine is only called from a single place in the sqlite btree
27248 ** code (when a leaf is removed from the free-list). This allows the
27249 ** following assumptions to be made about pPg:
27250 **
27251 **   1. PagerDontWrite() has been called on the page, OR 
27252 **      PagerWrite() has not yet been called on the page.
27253 **
27254 **   2. The page existed when the transaction was started.
27255 **
27256 ** Details: DontRollback() (this routine) is only called when a leaf is
27257 ** removed from the free list. DontWrite() is called whenever a page 
27258 ** becomes a free-list leaf.
27259 */
27260 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
27261   Pager *pPager = pPg->pPager;
27262
27263   pagerEnter(pPager);
27264   assert( pPager->state>=PAGER_RESERVED );
27265
27266   /* If the journal file is not open, or DontWrite() has been called on
27267   ** this page (DontWrite() sets the alwaysRollback flag), then this
27268   ** function is a no-op.
27269   */
27270   if( pPager->journalOpen==0 || pPg->alwaysRollback || pPager->alwaysRollback ){
27271     pagerLeave(pPager);
27272     return;
27273   }
27274   assert( !MEMDB );    /* For a memdb, pPager->journalOpen is always 0 */
27275
27276   /* Check that PagerWrite() has not yet been called on this page, and
27277   ** that the page existed when the transaction started.
27278   */
27279   assert( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize );
27280
27281   assert( pPager->pInJournal!=0 );
27282   sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
27283   pPg->inJournal = 1;
27284   pPg->needRead = 0;
27285   if( pPager->stmtInUse ){
27286     assert( pPager->stmtSize <= pPager->origDbSize );
27287     sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
27288   }
27289   PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
27290   IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
27291   pagerLeave(pPager);
27292 }
27293
27294
27295 /*
27296 ** This routine is called to increment the database file change-counter,
27297 ** stored at byte 24 of the pager file.
27298 */
27299 static int pager_incr_changecounter(Pager *pPager, int isDirect){
27300   PgHdr *pPgHdr;
27301   u32 change_counter;
27302   int rc = SQLITE_OK;
27303
27304   if( !pPager->changeCountDone ){
27305     /* Open page 1 of the file for writing. */
27306     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
27307     if( rc!=SQLITE_OK ) return rc;
27308
27309     if( !isDirect ){
27310       rc = sqlite3PagerWrite(pPgHdr);
27311       if( rc!=SQLITE_OK ){
27312         sqlite3PagerUnref(pPgHdr);
27313         return rc;
27314       }
27315     }
27316
27317     /* Increment the value just read and write it back to byte 24. */
27318     change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
27319     change_counter++;
27320     put32bits(((char*)PGHDR_TO_DATA(pPgHdr))+24, change_counter);
27321
27322     if( isDirect && pPager->fd->pMethods ){
27323       const void *zBuf = PGHDR_TO_DATA(pPgHdr);
27324       rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
27325     }
27326
27327     /* Release the page reference. */
27328     sqlite3PagerUnref(pPgHdr);
27329     pPager->changeCountDone = 1;
27330   }
27331   return rc;
27332 }
27333
27334 /*
27335 ** Sync the database file for the pager pPager. zMaster points to the name
27336 ** of a master journal file that should be written into the individual
27337 ** journal file. zMaster may be NULL, which is interpreted as no master
27338 ** journal (a single database transaction).
27339 **
27340 ** This routine ensures that the journal is synced, all dirty pages written
27341 ** to the database file and the database file synced. The only thing that
27342 ** remains to commit the transaction is to delete the journal file (or
27343 ** master journal file if specified).
27344 **
27345 ** Note that if zMaster==NULL, this does not overwrite a previous value
27346 ** passed to an sqlite3PagerCommitPhaseOne() call.
27347 **
27348 ** If parameter nTrunc is non-zero, then the pager file is truncated to
27349 ** nTrunc pages (this is used by auto-vacuum databases).
27350 */
27351 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager *pPager, const char *zMaster, Pgno nTrunc){
27352   int rc = SQLITE_OK;
27353
27354   PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
27355       pPager->zFilename, zMaster, nTrunc);
27356   pagerEnter(pPager);
27357
27358   /* If this is an in-memory db, or no pages have been written to, or this
27359   ** function has already been called, it is a no-op.
27360   */
27361   if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
27362     PgHdr *pPg;
27363
27364 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
27365     /* The atomic-write optimization can be used if all of the
27366     ** following are true:
27367     **
27368     **    + The file-system supports the atomic-write property for
27369     **      blocks of size page-size, and
27370     **    + This commit is not part of a multi-file transaction, and
27371     **    + Exactly one page has been modified and store in the journal file.
27372     **
27373     ** If the optimization can be used, then the journal file will never
27374     ** be created for this transaction.
27375     */
27376     int useAtomicWrite = (
27377         !zMaster && 
27378         pPager->journalOff==jrnlBufferSize(pPager) && 
27379         nTrunc==0 && 
27380         (0==pPager->pDirty || 0==pPager->pDirty->pDirty)
27381     );
27382     if( useAtomicWrite ){
27383       /* Update the nRec field in the journal file. */
27384       int offset = pPager->journalHdr + sizeof(aJournalMagic);
27385       assert(pPager->nRec==1);
27386       rc = write32bits(pPager->jfd, offset, pPager->nRec);
27387
27388       /* Update the db file change counter. The following call will modify
27389       ** the in-memory representation of page 1 to include the updated
27390       ** change counter and then write page 1 directly to the database
27391       ** file. Because of the atomic-write property of the host file-system, 
27392       ** this is safe.
27393       */
27394       if( rc==SQLITE_OK ){
27395         rc = pager_incr_changecounter(pPager, 1);
27396       }
27397     }else{
27398       rc = sqlite3JournalCreate(pPager->jfd);
27399     }
27400
27401     if( !useAtomicWrite && rc==SQLITE_OK )
27402 #endif
27403
27404     /* If a master journal file name has already been written to the
27405     ** journal file, then no sync is required. This happens when it is
27406     ** written, then the process fails to upgrade from a RESERVED to an
27407     ** EXCLUSIVE lock. The next time the process tries to commit the
27408     ** transaction the m-j name will have already been written.
27409     */
27410     if( !pPager->setMaster ){
27411       assert( pPager->journalOpen );
27412       rc = pager_incr_changecounter(pPager, 0);
27413       if( rc!=SQLITE_OK ) goto sync_exit;
27414 #ifndef SQLITE_OMIT_AUTOVACUUM
27415       if( nTrunc!=0 ){
27416         /* If this transaction has made the database smaller, then all pages
27417         ** being discarded by the truncation must be written to the journal
27418         ** file.
27419         */
27420         Pgno i;
27421         int iSkip = PAGER_MJ_PGNO(pPager);
27422         for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
27423           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
27424             rc = sqlite3PagerGet(pPager, i, &pPg);
27425             if( rc!=SQLITE_OK ) goto sync_exit;
27426             rc = sqlite3PagerWrite(pPg);
27427             sqlite3PagerUnref(pPg);
27428             if( rc!=SQLITE_OK ) goto sync_exit;
27429           }
27430         } 
27431       }
27432 #endif
27433       rc = writeMasterJournal(pPager, zMaster);
27434       if( rc!=SQLITE_OK ) goto sync_exit;
27435       rc = syncJournal(pPager);
27436     }
27437     if( rc!=SQLITE_OK ) goto sync_exit;
27438
27439 #ifndef SQLITE_OMIT_AUTOVACUUM
27440     if( nTrunc!=0 ){
27441       rc = sqlite3PagerTruncate(pPager, nTrunc);
27442       if( rc!=SQLITE_OK ) goto sync_exit;
27443     }
27444 #endif
27445
27446     /* Write all dirty pages to the database file */
27447     pPg = pager_get_all_dirty_pages(pPager);
27448     rc = pager_write_pagelist(pPg);
27449     if( rc!=SQLITE_OK ){
27450       assert( rc!=SQLITE_IOERR_BLOCKED );
27451       /* The error might have left the dirty list all fouled up here,
27452       ** but that does not matter because if the if the dirty list did
27453       ** get corrupted, then the transaction will roll back and
27454       ** discard the dirty list.  There is an assert in
27455       ** pager_get_all_dirty_pages() that verifies that no attempt
27456       ** is made to use an invalid dirty list.
27457       */
27458       goto sync_exit;
27459     }
27460     pPager->pDirty = 0;
27461
27462     /* Sync the database file. */
27463     if( !pPager->noSync ){
27464       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
27465     }
27466     IOTRACE(("DBSYNC %p\n", pPager))
27467
27468     pPager->state = PAGER_SYNCED;
27469   }else if( MEMDB && nTrunc!=0 ){
27470     rc = sqlite3PagerTruncate(pPager, nTrunc);
27471   }
27472
27473 sync_exit:
27474   if( rc==SQLITE_IOERR_BLOCKED ){
27475     /* pager_incr_changecounter() may attempt to obtain an exclusive
27476      * lock to spill the cache and return IOERR_BLOCKED. But since 
27477      * there is no chance the cache is inconsistent, it is
27478      * better to return SQLITE_BUSY.
27479      */
27480     rc = SQLITE_BUSY;
27481   }
27482   pagerLeave(pPager);
27483   return rc;
27484 }
27485
27486
27487 /*
27488 ** Commit all changes to the database and release the write lock.
27489 **
27490 ** If the commit fails for any reason, a rollback attempt is made
27491 ** and an error code is returned.  If the commit worked, SQLITE_OK
27492 ** is returned.
27493 */
27494 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
27495   int rc;
27496   PgHdr *pPg;
27497
27498   if( pPager->errCode ){
27499     return pPager->errCode;
27500   }
27501   if( pPager->state<PAGER_RESERVED ){
27502     return SQLITE_ERROR;
27503   }
27504   pagerEnter(pPager);
27505   PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
27506   if( MEMDB ){
27507     pPg = pager_get_all_dirty_pages(pPager);
27508     while( pPg ){
27509       PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
27510       clearHistory(pHist);
27511       pPg->dirty = 0;
27512       pPg->inJournal = 0;
27513       pHist->inStmt = 0;
27514       pPg->needSync = 0;
27515       pHist->pPrevStmt = pHist->pNextStmt = 0;
27516       pPg = pPg->pDirty;
27517     }
27518     pPager->pDirty = 0;
27519 #ifndef NDEBUG
27520     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
27521       PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
27522       assert( !pPg->alwaysRollback );
27523       assert( !pHist->pOrig );
27524       assert( !pHist->pStmt );
27525     }
27526 #endif
27527     pPager->pStmt = 0;
27528     pPager->state = PAGER_SHARED;
27529     pagerLeave(pPager);
27530     return SQLITE_OK;
27531   }
27532   assert( pPager->journalOpen || !pPager->dirtyCache );
27533   assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
27534   rc = pager_end_transaction(pPager);
27535   rc = pager_error(pPager, rc);
27536   pagerLeave(pPager);
27537   return rc;
27538 }
27539
27540 /*
27541 ** Rollback all changes.  The database falls back to PAGER_SHARED mode.
27542 ** All in-memory cache pages revert to their original data contents.
27543 ** The journal is deleted.
27544 **
27545 ** This routine cannot fail unless some other process is not following
27546 ** the correct locking protocol or unless some other
27547 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
27548 ** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
27549 ** codes are returned for all these occasions.  Otherwise,
27550 ** SQLITE_OK is returned.
27551 */
27552 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
27553   int rc;
27554   PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
27555   if( MEMDB ){
27556     PgHdr *p;
27557     for(p=pPager->pAll; p; p=p->pNextAll){
27558       PgHistory *pHist;
27559       assert( !p->alwaysRollback );
27560       if( !p->dirty ){
27561         assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pOrig );
27562         assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pStmt );
27563         continue;
27564       }
27565
27566       pHist = PGHDR_TO_HIST(p, pPager);
27567       if( pHist->pOrig ){
27568         memcpy(PGHDR_TO_DATA(p), pHist->pOrig, pPager->pageSize);
27569         PAGERTRACE3("ROLLBACK-PAGE %d of %d\n", p->pgno, PAGERID(pPager));
27570       }else{
27571         PAGERTRACE3("PAGE %d is clean on %d\n", p->pgno, PAGERID(pPager));
27572       }
27573       clearHistory(pHist);
27574       p->dirty = 0;
27575       p->inJournal = 0;
27576       pHist->inStmt = 0;
27577       pHist->pPrevStmt = pHist->pNextStmt = 0;
27578       if( pPager->xReiniter ){
27579         pPager->xReiniter(p, pPager->pageSize);
27580       }
27581     }
27582     pPager->pDirty = 0;
27583     pPager->pStmt = 0;
27584     pPager->dbSize = pPager->origDbSize;
27585     pager_truncate_cache(pPager);
27586     pPager->stmtInUse = 0;
27587     pPager->state = PAGER_SHARED;
27588     return SQLITE_OK;
27589   }
27590
27591   pagerEnter(pPager);
27592   if( !pPager->dirtyCache || !pPager->journalOpen ){
27593     rc = pager_end_transaction(pPager);
27594     pagerLeave(pPager);
27595     return rc;
27596   }
27597
27598   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
27599     if( pPager->state>=PAGER_EXCLUSIVE ){
27600       pager_playback(pPager, 0);
27601     }
27602     pagerLeave(pPager);
27603     return pPager->errCode;
27604   }
27605   if( pPager->state==PAGER_RESERVED ){
27606     int rc2;
27607     rc = pager_playback(pPager, 0);
27608     rc2 = pager_end_transaction(pPager);
27609     if( rc==SQLITE_OK ){
27610       rc = rc2;
27611     }
27612   }else{
27613     rc = pager_playback(pPager, 0);
27614   }
27615   /* pager_reset(pPager); */
27616   pPager->dbSize = -1;
27617
27618   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
27619   ** cache. So call pager_error() on the way out to make any error 
27620   ** persistent.
27621   */
27622   rc = pager_error(pPager, rc);
27623   pagerLeave(pPager);
27624   return rc;
27625 }
27626
27627 /*
27628 ** Return TRUE if the database file is opened read-only.  Return FALSE
27629 ** if the database is (in theory) writable.
27630 */
27631 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager *pPager){
27632   return pPager->readOnly;
27633 }
27634
27635 /*
27636 ** Return the number of references to the pager.
27637 */
27638 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
27639   return pPager->nRef;
27640 }
27641
27642 #ifdef SQLITE_TEST
27643 /*
27644 ** This routine is used for testing and analysis only.
27645 */
27646 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
27647   static int a[11];
27648   a[0] = pPager->nRef;
27649   a[1] = pPager->nPage;
27650   a[2] = pPager->mxPage;
27651   a[3] = pPager->dbSize;
27652   a[4] = pPager->state;
27653   a[5] = pPager->errCode;
27654   a[6] = pPager->nHit;
27655   a[7] = pPager->nMiss;
27656   a[8] = 0;  /* Used to be pPager->nOvfl */
27657   a[9] = pPager->nRead;
27658   a[10] = pPager->nWrite;
27659   return a;
27660 }
27661 #endif
27662
27663 /*
27664 ** Set the statement rollback point.
27665 **
27666 ** This routine should be called with the transaction journal already
27667 ** open.  A new statement journal is created that can be used to rollback
27668 ** changes of a single SQL command within a larger transaction.
27669 */
27670 static int pagerStmtBegin(Pager *pPager){
27671   int rc;
27672   assert( !pPager->stmtInUse );
27673   assert( pPager->state>=PAGER_SHARED );
27674   assert( pPager->dbSize>=0 );
27675   PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
27676   if( MEMDB ){
27677     pPager->stmtInUse = 1;
27678     pPager->stmtSize = pPager->dbSize;
27679     return SQLITE_OK;
27680   }
27681   if( !pPager->journalOpen ){
27682     pPager->stmtAutoopen = 1;
27683     return SQLITE_OK;
27684   }
27685   assert( pPager->journalOpen );
27686   pagerLeave(pPager);
27687   assert( pPager->pInStmt==0 );
27688   pPager->pInStmt = sqlite3BitvecCreate(pPager->dbSize);
27689   pagerEnter(pPager);
27690   if( pPager->pInStmt==0 ){
27691     /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
27692     return SQLITE_NOMEM;
27693   }
27694 #ifndef NDEBUG
27695   rc = sqlite3OsFileSize(pPager->jfd, &pPager->stmtJSize);
27696   if( rc ) goto stmt_begin_failed;
27697   assert( pPager->stmtJSize == pPager->journalOff );
27698 #endif
27699   pPager->stmtJSize = pPager->journalOff;
27700   pPager->stmtSize = pPager->dbSize;
27701   pPager->stmtHdrOff = 0;
27702   pPager->stmtCksum = pPager->cksumInit;
27703   if( !pPager->stmtOpen ){
27704     rc = sqlite3PagerOpentemp(pPager->pVfs, pPager->stfd, pPager->zStmtJrnl,
27705                               SQLITE_OPEN_SUBJOURNAL);
27706     if( rc ){
27707       goto stmt_begin_failed;
27708     }
27709     pPager->stmtOpen = 1;
27710     pPager->stmtNRec = 0;
27711   }
27712   pPager->stmtInUse = 1;
27713   return SQLITE_OK;
27714  
27715 stmt_begin_failed:
27716   if( pPager->pInStmt ){
27717     sqlite3BitvecDestroy(pPager->pInStmt);
27718     pPager->pInStmt = 0;
27719   }
27720   return rc;
27721 }
27722 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager *pPager){
27723   int rc;
27724   pagerEnter(pPager);
27725   rc = pagerStmtBegin(pPager);
27726   pagerLeave(pPager);
27727   return rc;
27728 }
27729
27730 /*
27731 ** Commit a statement.
27732 */
27733 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager *pPager){
27734   pagerEnter(pPager);
27735   if( pPager->stmtInUse ){
27736     PgHdr *pPg, *pNext;
27737     PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
27738     if( !MEMDB ){
27739       /* sqlite3OsTruncate(pPager->stfd, 0); */
27740       sqlite3BitvecDestroy(pPager->pInStmt);
27741       pPager->pInStmt = 0;
27742     }else{
27743       for(pPg=pPager->pStmt; pPg; pPg=pNext){
27744         PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
27745         pNext = pHist->pNextStmt;
27746         assert( pHist->inStmt );
27747         pHist->inStmt = 0;
27748         pHist->pPrevStmt = pHist->pNextStmt = 0;
27749         sqlite3_free(pHist->pStmt);
27750         pHist->pStmt = 0;
27751       }
27752     }
27753     pPager->stmtNRec = 0;
27754     pPager->stmtInUse = 0;
27755     pPager->pStmt = 0;
27756   }
27757   pPager->stmtAutoopen = 0;
27758   pagerLeave(pPager);
27759   return SQLITE_OK;
27760 }
27761
27762 /*
27763 ** Rollback a statement.
27764 */
27765 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager *pPager){
27766   int rc;
27767   pagerEnter(pPager);
27768   if( pPager->stmtInUse ){
27769     PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
27770     if( MEMDB ){
27771       PgHdr *pPg;
27772       PgHistory *pHist;
27773       for(pPg=pPager->pStmt; pPg; pPg=pHist->pNextStmt){
27774         pHist = PGHDR_TO_HIST(pPg, pPager);
27775         if( pHist->pStmt ){
27776           memcpy(PGHDR_TO_DATA(pPg), pHist->pStmt, pPager->pageSize);
27777           sqlite3_free(pHist->pStmt);
27778           pHist->pStmt = 0;
27779         }
27780       }
27781       pPager->dbSize = pPager->stmtSize;
27782       pager_truncate_cache(pPager);
27783       rc = SQLITE_OK;
27784     }else{
27785       rc = pager_stmt_playback(pPager);
27786     }
27787     sqlite3PagerStmtCommit(pPager);
27788   }else{
27789     rc = SQLITE_OK;
27790   }
27791   pPager->stmtAutoopen = 0;
27792   pagerLeave(pPager);
27793   return rc;
27794 }
27795
27796 /*
27797 ** Return the full pathname of the database file.
27798 */
27799 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
27800   return pPager->zFilename;
27801 }
27802
27803 /*
27804 ** Return the VFS structure for the pager.
27805 */
27806 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
27807   return pPager->pVfs;
27808 }
27809
27810 /*
27811 ** Return the file handle for the database file associated
27812 ** with the pager.  This might return NULL if the file has
27813 ** not yet been opened.
27814 */
27815 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
27816   return pPager->fd;
27817 }
27818
27819 /*
27820 ** Return the directory of the database file.
27821 */
27822 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
27823   return pPager->zDirectory;
27824 }
27825
27826 /*
27827 ** Return the full pathname of the journal file.
27828 */
27829 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
27830   return pPager->zJournal;
27831 }
27832
27833 /*
27834 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
27835 ** if fsync()s are executed normally.
27836 */
27837 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
27838   return pPager->noSync;
27839 }
27840
27841 #ifdef SQLITE_HAS_CODEC
27842 /*
27843 ** Set the codec for this pager
27844 */
27845 SQLITE_PRIVATE void sqlite3PagerSetCodec(
27846   Pager *pPager,
27847   void *(*xCodec)(void*,void*,Pgno,int),
27848   void *pCodecArg
27849 ){
27850   pPager->xCodec = xCodec;
27851   pPager->pCodecArg = pCodecArg;
27852 }
27853 #endif
27854
27855 #ifndef SQLITE_OMIT_AUTOVACUUM
27856 /*
27857 ** Move the page pPg to location pgno in the file.
27858 **
27859 ** There must be no references to the page previously located at
27860 ** pgno (which we call pPgOld) though that page is allowed to be
27861 ** in cache.  If the page previous located at pgno is not already
27862 ** in the rollback journal, it is not put there by by this routine.
27863 **
27864 ** References to the page pPg remain valid. Updating any
27865 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
27866 ** allocated along with the page) is the responsibility of the caller.
27867 **
27868 ** A transaction must be active when this routine is called. It used to be
27869 ** required that a statement transaction was not active, but this restriction
27870 ** has been removed (CREATE INDEX needs to move a page when a statement
27871 ** transaction is active).
27872 */
27873 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno){
27874   PgHdr *pPgOld;  /* The page being overwritten. */
27875   int h;
27876   Pgno needSyncPgno = 0;
27877
27878   pagerEnter(pPager);
27879   assert( pPg->nRef>0 );
27880
27881   PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
27882       PAGERID(pPager), pPg->pgno, pPg->needSync, pgno);
27883   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
27884
27885   pager_get_content(pPg);
27886   if( pPg->needSync ){
27887     needSyncPgno = pPg->pgno;
27888     assert( pPg->inJournal || (int)pgno>pPager->origDbSize );
27889     assert( pPg->dirty );
27890     assert( pPager->needSync );
27891   }
27892
27893   /* Unlink pPg from its hash-chain */
27894   unlinkHashChain(pPager, pPg);
27895
27896   /* If the cache contains a page with page-number pgno, remove it
27897   ** from its hash chain. Also, if the PgHdr.needSync was set for 
27898   ** page pgno before the 'move' operation, it needs to be retained 
27899   ** for the page moved there.
27900   */
27901   pPg->needSync = 0;
27902   pPgOld = pager_lookup(pPager, pgno);
27903   if( pPgOld ){
27904     assert( pPgOld->nRef==0 );
27905     unlinkHashChain(pPager, pPgOld);
27906     makeClean(pPgOld);
27907     pPg->needSync = pPgOld->needSync;
27908   }else{
27909     pPg->needSync = 0;
27910   }
27911   pPg->inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno);
27912
27913   /* Change the page number for pPg and insert it into the new hash-chain. */
27914   assert( pgno!=0 );
27915   pPg->pgno = pgno;
27916   h = pgno & (pPager->nHash-1);
27917   if( pPager->aHash[h] ){
27918     assert( pPager->aHash[h]->pPrevHash==0 );
27919     pPager->aHash[h]->pPrevHash = pPg;
27920   }
27921   pPg->pNextHash = pPager->aHash[h];
27922   pPager->aHash[h] = pPg;
27923   pPg->pPrevHash = 0;
27924
27925   makeDirty(pPg);
27926   pPager->dirtyCache = 1;
27927
27928   if( needSyncPgno ){
27929     /* If needSyncPgno is non-zero, then the journal file needs to be 
27930     ** sync()ed before any data is written to database file page needSyncPgno.
27931     ** Currently, no such page exists in the page-cache and the 
27932     ** Pager.pInJournal bit has been set. This needs to be remedied by loading
27933     ** the page into the pager-cache and setting the PgHdr.needSync flag.
27934     **
27935     ** If the attempt to load the page into the page-cache fails, (due
27936     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
27937     ** array. Otherwise, if the page is loaded and written again in
27938     ** this transaction, it may be written to the database file before
27939     ** it is synced into the journal file. This way, it may end up in
27940     ** the journal file twice, but that is not a problem.
27941     **
27942     ** The sqlite3PagerGet() call may cause the journal to sync. So make
27943     ** sure the Pager.needSync flag is set too.
27944     */
27945     int rc;
27946     PgHdr *pPgHdr;
27947     assert( pPager->needSync );
27948     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
27949     if( rc!=SQLITE_OK ){
27950       if( pPager->pInJournal && (int)needSyncPgno<=pPager->origDbSize ){
27951         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
27952       }
27953       pagerLeave(pPager);
27954       return rc;
27955     }
27956     pPager->needSync = 1;
27957     pPgHdr->needSync = 1;
27958     pPgHdr->inJournal = 1;
27959     makeDirty(pPgHdr);
27960     sqlite3PagerUnref(pPgHdr);
27961   }
27962
27963   pagerLeave(pPager);
27964   return SQLITE_OK;
27965 }
27966 #endif
27967
27968 /*
27969 ** Return a pointer to the data for the specified page.
27970 */
27971 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
27972   return PGHDR_TO_DATA(pPg);
27973 }
27974
27975 /*
27976 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
27977 ** allocated along with the specified page.
27978 */
27979 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
27980   Pager *pPager = pPg->pPager;
27981   return (pPager?PGHDR_TO_EXTRA(pPg, pPager):0);
27982 }
27983
27984 /*
27985 ** Get/set the locking-mode for this pager. Parameter eMode must be one
27986 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
27987 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
27988 ** the locking-mode is set to the value specified.
27989 **
27990 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
27991 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
27992 ** locking-mode.
27993 */
27994 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
27995   assert( eMode==PAGER_LOCKINGMODE_QUERY
27996             || eMode==PAGER_LOCKINGMODE_NORMAL
27997             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
27998   assert( PAGER_LOCKINGMODE_QUERY<0 );
27999   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
28000   if( eMode>=0 && !pPager->tempFile ){
28001     pPager->exclusiveMode = eMode;
28002   }
28003   return (int)pPager->exclusiveMode;
28004 }
28005
28006 #ifdef SQLITE_TEST
28007 /*
28008 ** Print a listing of all referenced pages and their ref count.
28009 */
28010 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager *pPager){
28011   PgHdr *pPg;
28012   for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
28013     if( pPg->nRef<=0 ) continue;
28014     sqlite3DebugPrintf("PAGE %3d addr=%p nRef=%d\n", 
28015        pPg->pgno, PGHDR_TO_DATA(pPg), pPg->nRef);
28016   }
28017 }
28018 #endif
28019
28020 #endif /* SQLITE_OMIT_DISKIO */
28021
28022 /************** End of pager.c ***********************************************/
28023 /************** Begin file btmutex.c *****************************************/
28024 /*
28025 ** 2007 August 27
28026 **
28027 ** The author disclaims copyright to this source code.  In place of
28028 ** a legal notice, here is a blessing:
28029 **
28030 **    May you do good and not evil.
28031 **    May you find forgiveness for yourself and forgive others.
28032 **    May you share freely, never taking more than you give.
28033 **
28034 *************************************************************************
28035 **
28036 ** $Id: btmutex.c,v 1.9 2008/01/23 12:52:41 drh Exp $
28037 **
28038 ** This file contains code used to implement mutexes on Btree objects.
28039 ** This code really belongs in btree.c.  But btree.c is getting too
28040 ** big and we want to break it down some.  This packaged seemed like
28041 ** a good breakout.
28042 */
28043 /************** Include btreeInt.h in the middle of btmutex.c ****************/
28044 /************** Begin file btreeInt.h ****************************************/
28045 /*
28046 ** 2004 April 6
28047 **
28048 ** The author disclaims copyright to this source code.  In place of
28049 ** a legal notice, here is a blessing:
28050 **
28051 **    May you do good and not evil.
28052 **    May you find forgiveness for yourself and forgive others.
28053 **    May you share freely, never taking more than you give.
28054 **
28055 *************************************************************************
28056 ** $Id: btreeInt.h,v 1.17 2008/03/04 17:45:01 mlcreech Exp $
28057 **
28058 ** This file implements a external (disk-based) database using BTrees.
28059 ** For a detailed discussion of BTrees, refer to
28060 **
28061 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
28062 **     "Sorting And Searching", pages 473-480. Addison-Wesley
28063 **     Publishing Company, Reading, Massachusetts.
28064 **
28065 ** The basic idea is that each page of the file contains N database
28066 ** entries and N+1 pointers to subpages.
28067 **
28068 **   ----------------------------------------------------------------
28069 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
28070 **   ----------------------------------------------------------------
28071 **
28072 ** All of the keys on the page that Ptr(0) points to have values less
28073 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
28074 ** values greater than Key(0) and less than Key(1).  All of the keys
28075 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
28076 ** so forth.
28077 **
28078 ** Finding a particular key requires reading O(log(M)) pages from the 
28079 ** disk where M is the number of entries in the tree.
28080 **
28081 ** In this implementation, a single file can hold one or more separate 
28082 ** BTrees.  Each BTree is identified by the index of its root page.  The
28083 ** key and data for any entry are combined to form the "payload".  A
28084 ** fixed amount of payload can be carried directly on the database
28085 ** page.  If the payload is larger than the preset amount then surplus
28086 ** bytes are stored on overflow pages.  The payload for an entry
28087 ** and the preceding pointer are combined to form a "Cell".  Each 
28088 ** page has a small header which contains the Ptr(N) pointer and other
28089 ** information such as the size of key and data.
28090 **
28091 ** FORMAT DETAILS
28092 **
28093 ** The file is divided into pages.  The first page is called page 1,
28094 ** the second is page 2, and so forth.  A page number of zero indicates
28095 ** "no such page".  The page size can be anything between 512 and 65536.
28096 ** Each page can be either a btree page, a freelist page or an overflow
28097 ** page.
28098 **
28099 ** The first page is always a btree page.  The first 100 bytes of the first
28100 ** page contain a special header (the "file header") that describes the file.
28101 ** The format of the file header is as follows:
28102 **
28103 **   OFFSET   SIZE    DESCRIPTION
28104 **      0      16     Header string: "SQLite format 3\000"
28105 **     16       2     Page size in bytes.  
28106 **     18       1     File format write version
28107 **     19       1     File format read version
28108 **     20       1     Bytes of unused space at the end of each page
28109 **     21       1     Max embedded payload fraction
28110 **     22       1     Min embedded payload fraction
28111 **     23       1     Min leaf payload fraction
28112 **     24       4     File change counter
28113 **     28       4     Reserved for future use
28114 **     32       4     First freelist page
28115 **     36       4     Number of freelist pages in the file
28116 **     40      60     15 4-byte meta values passed to higher layers
28117 **
28118 ** All of the integer values are big-endian (most significant byte first).
28119 **
28120 ** The file change counter is incremented when the database is changed
28121 ** This counter allows other processes to know when the file has changed
28122 ** and thus when they need to flush their cache.
28123 **
28124 ** The max embedded payload fraction is the amount of the total usable
28125 ** space in a page that can be consumed by a single cell for standard
28126 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
28127 ** is to limit the maximum cell size so that at least 4 cells will fit
28128 ** on one page.  Thus the default max embedded payload fraction is 64.
28129 **
28130 ** If the payload for a cell is larger than the max payload, then extra
28131 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
28132 ** as many bytes as possible are moved into the overflow pages without letting
28133 ** the cell size drop below the min embedded payload fraction.
28134 **
28135 ** The min leaf payload fraction is like the min embedded payload fraction
28136 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
28137 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
28138 ** not specified in the header.
28139 **
28140 ** Each btree pages is divided into three sections:  The header, the
28141 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
28142 ** file header that occurs before the page header.
28143 **
28144 **      |----------------|
28145 **      | file header    |   100 bytes.  Page 1 only.
28146 **      |----------------|
28147 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
28148 **      |----------------|
28149 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
28150 **      | array          |   |  Grows downward
28151 **      |                |   v
28152 **      |----------------|
28153 **      | unallocated    |
28154 **      | space          |
28155 **      |----------------|   ^  Grows upwards
28156 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
28157 **      | area           |   |  and free space fragments.
28158 **      |----------------|
28159 **
28160 ** The page headers looks like this:
28161 **
28162 **   OFFSET   SIZE     DESCRIPTION
28163 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
28164 **      1       2      byte offset to the first freeblock
28165 **      3       2      number of cells on this page
28166 **      5       2      first byte of the cell content area
28167 **      7       1      number of fragmented free bytes
28168 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
28169 **
28170 ** The flags define the format of this btree page.  The leaf flag means that
28171 ** this page has no children.  The zerodata flag means that this page carries
28172 ** only keys and no data.  The intkey flag means that the key is a integer
28173 ** which is stored in the key size entry of the cell header rather than in
28174 ** the payload area.
28175 **
28176 ** The cell pointer array begins on the first byte after the page header.
28177 ** The cell pointer array contains zero or more 2-byte numbers which are
28178 ** offsets from the beginning of the page to the cell content in the cell
28179 ** content area.  The cell pointers occur in sorted order.  The system strives
28180 ** to keep free space after the last cell pointer so that new cells can
28181 ** be easily added without having to defragment the page.
28182 **
28183 ** Cell content is stored at the very end of the page and grows toward the
28184 ** beginning of the page.
28185 **
28186 ** Unused space within the cell content area is collected into a linked list of
28187 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
28188 ** to the first freeblock is given in the header.  Freeblocks occur in
28189 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
28190 ** any group of 3 or fewer unused bytes in the cell content area cannot
28191 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
28192 ** a fragment.  The total number of bytes in all fragments is recorded.
28193 ** in the page header at offset 7.
28194 **
28195 **    SIZE    DESCRIPTION
28196 **      2     Byte offset of the next freeblock
28197 **      2     Bytes in this freeblock
28198 **
28199 ** Cells are of variable length.  Cells are stored in the cell content area at
28200 ** the end of the page.  Pointers to the cells are in the cell pointer array
28201 ** that immediately follows the page header.  Cells is not necessarily
28202 ** contiguous or in order, but cell pointers are contiguous and in order.
28203 **
28204 ** Cell content makes use of variable length integers.  A variable
28205 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
28206 ** byte are used.  The integer consists of all bytes that have bit 8 set and
28207 ** the first byte with bit 8 clear.  The most significant byte of the integer
28208 ** appears first.  A variable-length integer may not be more than 9 bytes long.
28209 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
28210 ** allows a 64-bit integer to be encoded in 9 bytes.
28211 **
28212 **    0x00                      becomes  0x00000000
28213 **    0x7f                      becomes  0x0000007f
28214 **    0x81 0x00                 becomes  0x00000080
28215 **    0x82 0x00                 becomes  0x00000100
28216 **    0x80 0x7f                 becomes  0x0000007f
28217 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
28218 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
28219 **
28220 ** Variable length integers are used for rowids and to hold the number of
28221 ** bytes of key and data in a btree cell.
28222 **
28223 ** The content of a cell looks like this:
28224 **
28225 **    SIZE    DESCRIPTION
28226 **      4     Page number of the left child. Omitted if leaf flag is set.
28227 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
28228 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
28229 **      *     Payload
28230 **      4     First page of the overflow chain.  Omitted if no overflow
28231 **
28232 ** Overflow pages form a linked list.  Each page except the last is completely
28233 ** filled with data (pagesize - 4 bytes).  The last page can have as little
28234 ** as 1 byte of data.
28235 **
28236 **    SIZE    DESCRIPTION
28237 **      4     Page number of next overflow page
28238 **      *     Data
28239 **
28240 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
28241 ** file header points to the first in a linked list of trunk page.  Each trunk
28242 ** page points to multiple leaf pages.  The content of a leaf page is
28243 ** unspecified.  A trunk page looks like this:
28244 **
28245 **    SIZE    DESCRIPTION
28246 **      4     Page number of next trunk page
28247 **      4     Number of leaf pointers on this page
28248 **      *     zero or more pages numbers of leaves
28249 */
28250
28251 /* Round up a number to the next larger multiple of 8.  This is used
28252 ** to force 8-byte alignment on 64-bit architectures.
28253 */
28254 #define ROUND8(x)   ((x+7)&~7)
28255
28256
28257 /* The following value is the maximum cell size assuming a maximum page
28258 ** size give above.
28259 */
28260 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
28261
28262 /* The maximum number of cells on a single page of the database.  This
28263 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
28264 ** plus 2 bytes for the index to the cell in the page header).  Such
28265 ** small cells will be rare, but they are possible.
28266 */
28267 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
28268
28269 /* Forward declarations */
28270 typedef struct MemPage MemPage;
28271 typedef struct BtLock BtLock;
28272
28273 /*
28274 ** This is a magic string that appears at the beginning of every
28275 ** SQLite database in order to identify the file as a real database.
28276 **
28277 ** You can change this value at compile-time by specifying a
28278 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
28279 ** header must be exactly 16 bytes including the zero-terminator so
28280 ** the string itself should be 15 characters long.  If you change
28281 ** the header, then your custom library will not be able to read 
28282 ** databases generated by the standard tools and the standard tools
28283 ** will not be able to read databases created by your custom library.
28284 */
28285 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
28286 #  define SQLITE_FILE_HEADER "SQLite format 3"
28287 #endif
28288
28289 /*
28290 ** Page type flags.  An ORed combination of these flags appear as the
28291 ** first byte of on-disk image of every BTree page.
28292 */
28293 #define PTF_INTKEY    0x01
28294 #define PTF_ZERODATA  0x02
28295 #define PTF_LEAFDATA  0x04
28296 #define PTF_LEAF      0x08
28297
28298 /*
28299 ** As each page of the file is loaded into memory, an instance of the following
28300 ** structure is appended and initialized to zero.  This structure stores
28301 ** information about the page that is decoded from the raw file page.
28302 **
28303 ** The pParent field points back to the parent page.  This allows us to
28304 ** walk up the BTree from any leaf to the root.  Care must be taken to
28305 ** unref() the parent page pointer when this page is no longer referenced.
28306 ** The pageDestructor() routine handles that chore.
28307 **
28308 ** Access to all fields of this structure is controlled by the mutex
28309 ** stored in MemPage.pBt->mutex.
28310 */
28311 struct MemPage {
28312   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
28313   u8 idxShift;         /* True if Cell indices have changed */
28314   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
28315   u8 intKey;           /* True if intkey flag is set */
28316   u8 leaf;             /* True if leaf flag is set */
28317   u8 zeroData;         /* True if table stores keys only */
28318   u8 leafData;         /* True if tables stores data on leaves only */
28319   u8 hasData;          /* True if this page stores data */
28320   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
28321   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
28322   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
28323   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
28324   u16 cellOffset;      /* Index in aData of first cell pointer */
28325   u16 idxParent;       /* Index in parent of this node */
28326   u16 nFree;           /* Number of free bytes on the page */
28327   u16 nCell;           /* Number of cells on this page, local and ovfl */
28328   struct _OvflCell {   /* Cells that will not fit on aData[] */
28329     u8 *pCell;          /* Pointers to the body of the overflow cell */
28330     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
28331   } aOvfl[5];
28332   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
28333   u8 *aData;           /* Pointer to disk image of the page data */
28334   DbPage *pDbPage;     /* Pager page handle */
28335   Pgno pgno;           /* Page number for this page */
28336   MemPage *pParent;    /* The parent of this page.  NULL for root */
28337 };
28338
28339 /*
28340 ** The in-memory image of a disk page has the auxiliary information appended
28341 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
28342 ** that extra information.
28343 */
28344 #define EXTRA_SIZE sizeof(MemPage)
28345
28346 /* A Btree handle
28347 **
28348 ** A database connection contains a pointer to an instance of
28349 ** this object for every database file that it has open.  This structure
28350 ** is opaque to the database connection.  The database connection cannot
28351 ** see the internals of this structure and only deals with pointers to
28352 ** this structure.
28353 **
28354 ** For some database files, the same underlying database cache might be 
28355 ** shared between multiple connections.  In that case, each contection
28356 ** has it own pointer to this object.  But each instance of this object
28357 ** points to the same BtShared object.  The database cache and the
28358 ** schema associated with the database file are all contained within
28359 ** the BtShared object.
28360 **
28361 ** All fields in this structure are accessed under sqlite3.mutex.
28362 ** The pBt pointer itself may not be changed while there exists cursors 
28363 ** in the referenced BtShared that point back to this Btree since those
28364 ** cursors have to do go through this Btree to find their BtShared and
28365 ** they often do so without holding sqlite3.mutex.
28366 */
28367 struct Btree {
28368   sqlite3 *db;       /* The database connection holding this btree */
28369   BtShared *pBt;     /* Sharable content of this btree */
28370   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
28371   u8 sharable;       /* True if we can share pBt with another db */
28372   u8 locked;         /* True if db currently has pBt locked */
28373   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
28374   Btree *pNext;      /* List of other sharable Btrees from the same db */
28375   Btree *pPrev;      /* Back pointer of the same list */
28376 };
28377
28378 /*
28379 ** Btree.inTrans may take one of the following values.
28380 **
28381 ** If the shared-data extension is enabled, there may be multiple users
28382 ** of the Btree structure. At most one of these may open a write transaction,
28383 ** but any number may have active read transactions.
28384 */
28385 #define TRANS_NONE  0
28386 #define TRANS_READ  1
28387 #define TRANS_WRITE 2
28388
28389 /*
28390 ** An instance of this object represents a single database file.
28391 ** 
28392 ** A single database file can be in use as the same time by two
28393 ** or more database connections.  When two or more connections are
28394 ** sharing the same database file, each connection has it own
28395 ** private Btree object for the file and each of those Btrees points
28396 ** to this one BtShared object.  BtShared.nRef is the number of
28397 ** connections currently sharing this database file.
28398 **
28399 ** Fields in this structure are accessed under the BtShared.mutex
28400 ** mutex, except for nRef and pNext which are accessed under the
28401 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
28402 ** may not be modified once it is initially set as long as nRef>0.
28403 ** The pSchema field may be set once under BtShared.mutex and
28404 ** thereafter is unchanged as long as nRef>0.
28405 */
28406 struct BtShared {
28407   Pager *pPager;        /* The page cache */
28408   sqlite3 *db;          /* Database connection currently using this Btree */
28409   BtCursor *pCursor;    /* A list of all open cursors */
28410   MemPage *pPage1;      /* First page of the database */
28411   u8 inStmt;            /* True if we are in a statement subtransaction */
28412   u8 readOnly;          /* True if the underlying file is readonly */
28413   u8 maxEmbedFrac;      /* Maximum payload as % of total page size */
28414   u8 minEmbedFrac;      /* Minimum payload as % of total page size */
28415   u8 minLeafFrac;       /* Minimum leaf payload as % of total page size */
28416   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
28417 #ifndef SQLITE_OMIT_AUTOVACUUM
28418   u8 autoVacuum;        /* True if auto-vacuum is enabled */
28419   u8 incrVacuum;        /* True if incr-vacuum is enabled */
28420   Pgno nTrunc;          /* Non-zero if the db will be truncated (incr vacuum) */
28421 #endif
28422   u16 pageSize;         /* Total number of bytes on a page */
28423   u16 usableSize;       /* Number of usable bytes on each page */
28424   int maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
28425   int minLocal;         /* Minimum local payload in non-LEAFDATA tables */
28426   int maxLeaf;          /* Maximum local payload in a LEAFDATA table */
28427   int minLeaf;          /* Minimum local payload in a LEAFDATA table */
28428   u8 inTransaction;     /* Transaction state */
28429   int nTransaction;     /* Number of open transactions (read + write) */
28430   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
28431   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
28432   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
28433   BusyHandler busyHdr;  /* The busy handler for this btree */
28434 #ifndef SQLITE_OMIT_SHARED_CACHE
28435   int nRef;             /* Number of references to this structure */
28436   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
28437   BtLock *pLock;        /* List of locks held on this shared-btree struct */
28438   Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
28439 #endif
28440 };
28441
28442 /*
28443 ** An instance of the following structure is used to hold information
28444 ** about a cell.  The parseCellPtr() function fills in this structure
28445 ** based on information extract from the raw disk page.
28446 */
28447 typedef struct CellInfo CellInfo;
28448 struct CellInfo {
28449   u8 *pCell;     /* Pointer to the start of cell content */
28450   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
28451   u32 nData;     /* Number of bytes of data */
28452   u32 nPayload;  /* Total amount of payload */
28453   u16 nHeader;   /* Size of the cell content header in bytes */
28454   u16 nLocal;    /* Amount of payload held locally */
28455   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
28456   u16 nSize;     /* Size of the cell content on the main b-tree page */
28457 };
28458
28459 /*
28460 ** A cursor is a pointer to a particular entry within a particular
28461 ** b-tree within a database file.
28462 **
28463 ** The entry is identified by its MemPage and the index in
28464 ** MemPage.aCell[] of the entry.
28465 **
28466 ** When a single database file can shared by two more database connections,
28467 ** but cursors cannot be shared.  Each cursor is associated with a
28468 ** particular database connection identified BtCursor.pBtree.db.
28469 **
28470 ** Fields in this structure are accessed under the BtShared.mutex
28471 ** found at self->pBt->mutex. 
28472 */
28473 struct BtCursor {
28474   Btree *pBtree;            /* The Btree to which this cursor belongs */
28475   BtShared *pBt;            /* The BtShared this cursor points to */
28476   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
28477   int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
28478   void *pArg;               /* First arg to xCompare() */
28479   Pgno pgnoRoot;            /* The root page of this tree */
28480   MemPage *pPage;           /* Page that contains the entry */
28481   int idx;                  /* Index of the entry in pPage->aCell[] */
28482   CellInfo info;            /* A parse of the cell we are pointing at */
28483   u8 wrFlag;                /* True if writable */
28484   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
28485   void *pKey;      /* Saved key that was cursor's last known position */
28486   i64 nKey;        /* Size of pKey, or last integer key */
28487   int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
28488 #ifndef SQLITE_OMIT_INCRBLOB
28489   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
28490   Pgno *aOverflow;          /* Cache of overflow page locations */
28491 #endif
28492 };
28493
28494 /*
28495 ** Potential values for BtCursor.eState.
28496 **
28497 ** CURSOR_VALID:
28498 **   Cursor points to a valid entry. getPayload() etc. may be called.
28499 **
28500 ** CURSOR_INVALID:
28501 **   Cursor does not point to a valid entry. This can happen (for example) 
28502 **   because the table is empty or because BtreeCursorFirst() has not been
28503 **   called.
28504 **
28505 ** CURSOR_REQUIRESEEK:
28506 **   The table that this cursor was opened on still exists, but has been 
28507 **   modified since the cursor was last used. The cursor position is saved
28508 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
28509 **   this state, restoreOrClearCursorPosition() can be called to attempt to
28510 **   seek the cursor to the saved position.
28511 **
28512 ** CURSOR_FAULT:
28513 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
28514 **   on a different connection that shares the BtShared cache with this
28515 **   cursor.  The error has left the cache in an inconsistent state.
28516 **   Do nothing else with this cursor.  Any attempt to use the cursor
28517 **   should return the error code stored in BtCursor.skip
28518 */
28519 #define CURSOR_INVALID           0
28520 #define CURSOR_VALID             1
28521 #define CURSOR_REQUIRESEEK       2
28522 #define CURSOR_FAULT             3
28523
28524 /*
28525 ** The TRACE macro will print high-level status information about the
28526 ** btree operation when the global variable sqlite3BtreeTrace is
28527 ** enabled.
28528 */
28529 #if SQLITE_TEST
28530 # define TRACE(X)   if( sqlite3BtreeTrace ){ printf X; fflush(stdout); }
28531 #else
28532 # define TRACE(X)
28533 #endif
28534
28535 /*
28536 ** Routines to read and write variable-length integers.  These used to
28537 ** be defined locally, but now we use the varint routines in the util.c
28538 ** file.
28539 */
28540 #define getVarint    sqlite3GetVarint
28541 #define getVarint32(A,B)  ((*B=*(A))<=0x7f?1:sqlite3GetVarint32(A,B))
28542 #define putVarint    sqlite3PutVarint
28543
28544 /* The database page the PENDING_BYTE occupies. This page is never used.
28545 ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
28546 ** should possibly be consolidated (presumably in pager.h).
28547 **
28548 ** If disk I/O is omitted (meaning that the database is stored purely
28549 ** in memory) then there is no pending byte.
28550 */
28551 #ifdef SQLITE_OMIT_DISKIO
28552 # define PENDING_BYTE_PAGE(pBt)  0x7fffffff
28553 #else
28554 # define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
28555 #endif
28556
28557 /*
28558 ** A linked list of the following structures is stored at BtShared.pLock.
28559 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
28560 ** is opened on the table with root page BtShared.iTable. Locks are removed
28561 ** from this list when a transaction is committed or rolled back, or when
28562 ** a btree handle is closed.
28563 */
28564 struct BtLock {
28565   Btree *pBtree;        /* Btree handle holding this lock */
28566   Pgno iTable;          /* Root page of table */
28567   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
28568   BtLock *pNext;        /* Next in BtShared.pLock list */
28569 };
28570
28571 /* Candidate values for BtLock.eLock */
28572 #define READ_LOCK     1
28573 #define WRITE_LOCK    2
28574
28575 /*
28576 ** These macros define the location of the pointer-map entry for a 
28577 ** database page. The first argument to each is the number of usable
28578 ** bytes on each page of the database (often 1024). The second is the
28579 ** page number to look up in the pointer map.
28580 **
28581 ** PTRMAP_PAGENO returns the database page number of the pointer-map
28582 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
28583 ** the offset of the requested map entry.
28584 **
28585 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
28586 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
28587 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
28588 ** this test.
28589 */
28590 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
28591 #define PTRMAP_PTROFFSET(pBt, pgno) (5*(pgno-ptrmapPageno(pBt, pgno)-1))
28592 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
28593
28594 /*
28595 ** The pointer map is a lookup table that identifies the parent page for
28596 ** each child page in the database file.  The parent page is the page that
28597 ** contains a pointer to the child.  Every page in the database contains
28598 ** 0 or 1 parent pages.  (In this context 'database page' refers
28599 ** to any page that is not part of the pointer map itself.)  Each pointer map
28600 ** entry consists of a single byte 'type' and a 4 byte parent page number.
28601 ** The PTRMAP_XXX identifiers below are the valid types.
28602 **
28603 ** The purpose of the pointer map is to facility moving pages from one
28604 ** position in the file to another as part of autovacuum.  When a page
28605 ** is moved, the pointer in its parent must be updated to point to the
28606 ** new location.  The pointer map is used to locate the parent page quickly.
28607 **
28608 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
28609 **                  used in this case.
28610 **
28611 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
28612 **                  is not used in this case.
28613 **
28614 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
28615 **                   overflow pages. The page number identifies the page that
28616 **                   contains the cell with a pointer to this overflow page.
28617 **
28618 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
28619 **                   overflow pages. The page-number identifies the previous
28620 **                   page in the overflow page list.
28621 **
28622 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
28623 **               identifies the parent page in the btree.
28624 */
28625 #define PTRMAP_ROOTPAGE 1
28626 #define PTRMAP_FREEPAGE 2
28627 #define PTRMAP_OVERFLOW1 3
28628 #define PTRMAP_OVERFLOW2 4
28629 #define PTRMAP_BTREE 5
28630
28631 /* A bunch of assert() statements to check the transaction state variables
28632 ** of handle p (type Btree*) are internally consistent.
28633 */
28634 #define btreeIntegrity(p) \
28635   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
28636   assert( p->pBt->inTransaction>=p->inTrans ); 
28637
28638
28639 /*
28640 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
28641 ** if the database supports auto-vacuum or not. Because it is used
28642 ** within an expression that is an argument to another macro 
28643 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
28644 ** So, this macro is defined instead.
28645 */
28646 #ifndef SQLITE_OMIT_AUTOVACUUM
28647 #define ISAUTOVACUUM (pBt->autoVacuum)
28648 #else
28649 #define ISAUTOVACUUM 0
28650 #endif
28651
28652
28653 /*
28654 ** This structure is passed around through all the sanity checking routines
28655 ** in order to keep track of some global state information.
28656 */
28657 typedef struct IntegrityCk IntegrityCk;
28658 struct IntegrityCk {
28659   BtShared *pBt;    /* The tree being checked out */
28660   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
28661   int nPage;        /* Number of pages in the database */
28662   int *anRef;       /* Number of times each page is referenced */
28663   int mxErr;        /* Stop accumulating errors when this reaches zero */
28664   char *zErrMsg;    /* An error message.  NULL if no errors seen. */
28665   int nErr;         /* Number of messages written to zErrMsg so far */
28666 };
28667
28668 /*
28669 ** Read or write a two- and four-byte big-endian integer values.
28670 */
28671 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
28672 #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
28673 #define get4byte sqlite3Get4byte
28674 #define put4byte sqlite3Put4byte
28675
28676 /*
28677 ** Internal routines that should be accessed by the btree layer only.
28678 */
28679 SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
28680 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
28681 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
28682 SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
28683 #ifdef SQLITE_TEST
28684 SQLITE_PRIVATE u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell);
28685 #endif
28686 SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur);
28687 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
28688 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
28689 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage);
28690 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
28691
28692 /************** End of btreeInt.h ********************************************/
28693 /************** Continuing where we left off in btmutex.c ********************/
28694 #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
28695
28696
28697 /*
28698 ** Enter a mutex on the given BTree object.
28699 **
28700 ** If the object is not sharable, then no mutex is ever required
28701 ** and this routine is a no-op.  The underlying mutex is non-recursive.
28702 ** But we keep a reference count in Btree.wantToLock so the behavior
28703 ** of this interface is recursive.
28704 **
28705 ** To avoid deadlocks, multiple Btrees are locked in the same order
28706 ** by all database connections.  The p->pNext is a list of other
28707 ** Btrees belonging to the same database connection as the p Btree
28708 ** which need to be locked after p.  If we cannot get a lock on
28709 ** p, then first unlock all of the others on p->pNext, then wait
28710 ** for the lock to become available on p, then relock all of the
28711 ** subsequent Btrees that desire a lock.
28712 */
28713 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
28714   Btree *pLater;
28715
28716   /* Some basic sanity checking on the Btree.  The list of Btrees
28717   ** connected by pNext and pPrev should be in sorted order by
28718   ** Btree.pBt value. All elements of the list should belong to
28719   ** the same connection. Only shared Btrees are on the list. */
28720   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
28721   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
28722   assert( p->pNext==0 || p->pNext->db==p->db );
28723   assert( p->pPrev==0 || p->pPrev->db==p->db );
28724   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
28725
28726   /* Check for locking consistency */
28727   assert( !p->locked || p->wantToLock>0 );
28728   assert( p->sharable || p->wantToLock==0 );
28729
28730   /* We should already hold a lock on the database connection */
28731   assert( sqlite3_mutex_held(p->db->mutex) );
28732
28733   if( !p->sharable ) return;
28734   p->wantToLock++;
28735   if( p->locked ) return;
28736
28737 #ifndef SQLITE_MUTEX_NOOP
28738   /* In most cases, we should be able to acquire the lock we
28739   ** want without having to go throught the ascending lock
28740   ** procedure that follows.  Just be sure not to block.
28741   */
28742   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
28743     p->locked = 1;
28744     return;
28745   }
28746
28747   /* To avoid deadlock, first release all locks with a larger
28748   ** BtShared address.  Then acquire our lock.  Then reacquire
28749   ** the other BtShared locks that we used to hold in ascending
28750   ** order.
28751   */
28752   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
28753     assert( pLater->sharable );
28754     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
28755     assert( !pLater->locked || pLater->wantToLock>0 );
28756     if( pLater->locked ){
28757       sqlite3_mutex_leave(pLater->pBt->mutex);
28758       pLater->locked = 0;
28759     }
28760   }
28761   sqlite3_mutex_enter(p->pBt->mutex);
28762   p->locked = 1;
28763   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
28764     if( pLater->wantToLock ){
28765       sqlite3_mutex_enter(pLater->pBt->mutex);
28766       pLater->locked = 1;
28767     }
28768   }
28769 #endif /* SQLITE_MUTEX_NOOP */
28770 }
28771
28772 /*
28773 ** Exit the recursive mutex on a Btree.
28774 */
28775 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
28776   if( p->sharable ){
28777     assert( p->wantToLock>0 );
28778     p->wantToLock--;
28779     if( p->wantToLock==0 ){
28780       assert( p->locked );
28781       sqlite3_mutex_leave(p->pBt->mutex);
28782       p->locked = 0;
28783     }
28784   }
28785 }
28786
28787 #ifndef NDEBUG
28788 /*
28789 ** Return true if the BtShared mutex is held on the btree.  
28790 **
28791 ** This routine makes no determination one why or another if the
28792 ** database connection mutex is held.
28793 **
28794 ** This routine is used only from within assert() statements.
28795 */
28796 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
28797   return (p->sharable==0 ||
28798              (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
28799 }
28800 #endif
28801
28802
28803 #ifndef SQLITE_OMIT_INCRBLOB
28804 /*
28805 ** Enter and leave a mutex on a Btree given a cursor owned by that
28806 ** Btree.  These entry points are used by incremental I/O and can be
28807 ** omitted if that module is not used.
28808 */
28809 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
28810   sqlite3BtreeEnter(pCur->pBtree);
28811 }
28812 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
28813   sqlite3BtreeLeave(pCur->pBtree);
28814 }
28815 #endif /* SQLITE_OMIT_INCRBLOB */
28816
28817
28818 /*
28819 ** Enter the mutex on every Btree associated with a database
28820 ** connection.  This is needed (for example) prior to parsing
28821 ** a statement since we will be comparing table and column names
28822 ** against all schemas and we do not want those schemas being
28823 ** reset out from under us.
28824 **
28825 ** There is a corresponding leave-all procedures.
28826 **
28827 ** Enter the mutexes in accending order by BtShared pointer address
28828 ** to avoid the possibility of deadlock when two threads with
28829 ** two or more btrees in common both try to lock all their btrees
28830 ** at the same instant.
28831 */
28832 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
28833   int i;
28834   Btree *p, *pLater;
28835   assert( sqlite3_mutex_held(db->mutex) );
28836   for(i=0; i<db->nDb; i++){
28837     p = db->aDb[i].pBt;
28838     if( p && p->sharable ){
28839       p->wantToLock++;
28840       if( !p->locked ){
28841         assert( p->wantToLock==1 );
28842         while( p->pPrev ) p = p->pPrev;
28843         while( p->locked && p->pNext ) p = p->pNext;
28844         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
28845           if( pLater->locked ){
28846             sqlite3_mutex_leave(pLater->pBt->mutex);
28847             pLater->locked = 0;
28848           }
28849         }
28850         while( p ){
28851           sqlite3_mutex_enter(p->pBt->mutex);
28852           p->locked++;
28853           p = p->pNext;
28854         }
28855       }
28856     }
28857   }
28858 }
28859 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
28860   int i;
28861   Btree *p;
28862   assert( sqlite3_mutex_held(db->mutex) );
28863   for(i=0; i<db->nDb; i++){
28864     p = db->aDb[i].pBt;
28865     if( p && p->sharable ){
28866       assert( p->wantToLock>0 );
28867       p->wantToLock--;
28868       if( p->wantToLock==0 ){
28869         assert( p->locked );
28870         sqlite3_mutex_leave(p->pBt->mutex);
28871         p->locked = 0;
28872       }
28873     }
28874   }
28875 }
28876
28877 #ifndef NDEBUG
28878 /*
28879 ** Return true if the current thread holds the database connection
28880 ** mutex and all required BtShared mutexes.
28881 **
28882 ** This routine is used inside assert() statements only.
28883 */
28884 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
28885   int i;
28886   if( !sqlite3_mutex_held(db->mutex) ){
28887     return 0;
28888   }
28889   for(i=0; i<db->nDb; i++){
28890     Btree *p;
28891     p = db->aDb[i].pBt;
28892     if( p && p->sharable &&
28893          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
28894       return 0;
28895     }
28896   }
28897   return 1;
28898 }
28899 #endif /* NDEBUG */
28900
28901 /*
28902 ** Potentially dd a new Btree pointer to a BtreeMutexArray.
28903 ** Really only add the Btree if it can possibly be shared with
28904 ** another database connection.
28905 **
28906 ** The Btrees are kept in sorted order by pBtree->pBt.  That
28907 ** way when we go to enter all the mutexes, we can enter them
28908 ** in order without every having to backup and retry and without
28909 ** worrying about deadlock.
28910 **
28911 ** The number of shared btrees will always be small (usually 0 or 1)
28912 ** so an insertion sort is an adequate algorithm here.
28913 */
28914 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
28915   int i, j;
28916   BtShared *pBt;
28917   if( pBtree==0 || pBtree->sharable==0 ) return;
28918 #ifndef NDEBUG
28919   {
28920     for(i=0; i<pArray->nMutex; i++){
28921       assert( pArray->aBtree[i]!=pBtree );
28922     }
28923   }
28924 #endif
28925   assert( pArray->nMutex>=0 );
28926   assert( pArray->nMutex<sizeof(pArray->aBtree)/sizeof(pArray->aBtree[0])-1 );
28927   pBt = pBtree->pBt;
28928   for(i=0; i<pArray->nMutex; i++){
28929     assert( pArray->aBtree[i]!=pBtree );
28930     if( pArray->aBtree[i]->pBt>pBt ){
28931       for(j=pArray->nMutex; j>i; j--){
28932         pArray->aBtree[j] = pArray->aBtree[j-1];
28933       }
28934       pArray->aBtree[i] = pBtree;
28935       pArray->nMutex++;
28936       return;
28937     }
28938   }
28939   pArray->aBtree[pArray->nMutex++] = pBtree;
28940 }
28941
28942 /*
28943 ** Enter the mutex of every btree in the array.  This routine is
28944 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
28945 ** exited at the end of the same function.
28946 */
28947 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
28948   int i;
28949   for(i=0; i<pArray->nMutex; i++){
28950     Btree *p = pArray->aBtree[i];
28951     /* Some basic sanity checking */
28952     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
28953     assert( !p->locked || p->wantToLock>0 );
28954
28955     /* We should already hold a lock on the database connection */
28956     assert( sqlite3_mutex_held(p->db->mutex) );
28957
28958     p->wantToLock++;
28959     if( !p->locked && p->sharable ){
28960       sqlite3_mutex_enter(p->pBt->mutex);
28961       p->locked = 1;
28962     }
28963   }
28964 }
28965
28966 /*
28967 ** Leave the mutex of every btree in the group.
28968 */
28969 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
28970   int i;
28971   for(i=0; i<pArray->nMutex; i++){
28972     Btree *p = pArray->aBtree[i];
28973     /* Some basic sanity checking */
28974     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
28975     assert( p->locked || !p->sharable );
28976     assert( p->wantToLock>0 );
28977
28978     /* We should already hold a lock on the database connection */
28979     assert( sqlite3_mutex_held(p->db->mutex) );
28980
28981     p->wantToLock--;
28982     if( p->wantToLock==0 && p->locked ){
28983       sqlite3_mutex_leave(p->pBt->mutex);
28984       p->locked = 0;
28985     }
28986   }
28987 }
28988
28989
28990 #endif  /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
28991
28992 /************** End of btmutex.c *********************************************/
28993 /************** Begin file btree.c *******************************************/
28994 /*
28995 ** 2004 April 6
28996 **
28997 ** The author disclaims copyright to this source code.  In place of
28998 ** a legal notice, here is a blessing:
28999 **
29000 **    May you do good and not evil.
29001 **    May you find forgiveness for yourself and forgive others.
29002 **    May you share freely, never taking more than you give.
29003 **
29004 *************************************************************************
29005 ** $Id: btree.c,v 1.440 2008/03/04 17:45:01 mlcreech Exp $
29006 **
29007 ** This file implements a external (disk-based) database using BTrees.
29008 ** See the header comment on "btreeInt.h" for additional information.
29009 ** Including a description of file format and an overview of operation.
29010 */
29011
29012 /*
29013 ** The header string that appears at the beginning of every
29014 ** SQLite database.
29015 */
29016 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
29017
29018 /*
29019 ** Set this global variable to 1 to enable tracing using the TRACE
29020 ** macro.
29021 */
29022 #if SQLITE_TEST
29023 int sqlite3BtreeTrace=0;  /* True to enable tracing */
29024 #endif
29025
29026
29027
29028 #ifndef SQLITE_OMIT_SHARED_CACHE
29029 /*
29030 ** A flag to indicate whether or not shared cache is enabled.  Also,
29031 ** a list of BtShared objects that are eligible for participation
29032 ** in shared cache.  The variables have file scope during normal builds,
29033 ** but the test harness needs to access these variables so we make them
29034 ** global for test builds.
29035 */
29036 #ifdef SQLITE_TEST
29037 SQLITE_PRIVATE BtShared *sqlite3SharedCacheList = 0;
29038 SQLITE_PRIVATE int sqlite3SharedCacheEnabled = 0;
29039 #else
29040 static BtShared *sqlite3SharedCacheList = 0;
29041 static int sqlite3SharedCacheEnabled = 0;
29042 #endif
29043 #endif /* SQLITE_OMIT_SHARED_CACHE */
29044
29045 #ifndef SQLITE_OMIT_SHARED_CACHE
29046 /*
29047 ** Enable or disable the shared pager and schema features.
29048 **
29049 ** This routine has no effect on existing database connections.
29050 ** The shared cache setting effects only future calls to
29051 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
29052 */
29053 SQLITE_API int sqlite3_enable_shared_cache(int enable){
29054   sqlite3SharedCacheEnabled = enable;
29055   return SQLITE_OK;
29056 }
29057 #endif
29058
29059
29060 /*
29061 ** Forward declaration
29062 */
29063 static int checkReadLocks(Btree*,Pgno,BtCursor*);
29064
29065
29066 #ifdef SQLITE_OMIT_SHARED_CACHE
29067   /*
29068   ** The functions queryTableLock(), lockTable() and unlockAllTables()
29069   ** manipulate entries in the BtShared.pLock linked list used to store
29070   ** shared-cache table level locks. If the library is compiled with the
29071   ** shared-cache feature disabled, then there is only ever one user
29072   ** of each BtShared structure and so this locking is not necessary. 
29073   ** So define the lock related functions as no-ops.
29074   */
29075   #define queryTableLock(a,b,c) SQLITE_OK
29076   #define lockTable(a,b,c) SQLITE_OK
29077   #define unlockAllTables(a)
29078 #endif
29079
29080 #ifndef SQLITE_OMIT_SHARED_CACHE
29081 /*
29082 ** Query to see if btree handle p may obtain a lock of type eLock 
29083 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
29084 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
29085 ** SQLITE_LOCKED if not.
29086 */
29087 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
29088   BtShared *pBt = p->pBt;
29089   BtLock *pIter;
29090
29091   assert( sqlite3BtreeHoldsMutex(p) );
29092   
29093   /* This is a no-op if the shared-cache is not enabled */
29094   if( !p->sharable ){
29095     return SQLITE_OK;
29096   }
29097
29098   /* If some other connection is holding an exclusive lock, the
29099   ** requested lock may not be obtained.
29100   */
29101   if( pBt->pExclusive && pBt->pExclusive!=p ){
29102     return SQLITE_LOCKED;
29103   }
29104
29105   /* This (along with lockTable()) is where the ReadUncommitted flag is
29106   ** dealt with. If the caller is querying for a read-lock and the flag is
29107   ** set, it is unconditionally granted - even if there are write-locks
29108   ** on the table. If a write-lock is requested, the ReadUncommitted flag
29109   ** is not considered.
29110   **
29111   ** In function lockTable(), if a read-lock is demanded and the 
29112   ** ReadUncommitted flag is set, no entry is added to the locks list 
29113   ** (BtShared.pLock).
29114   **
29115   ** To summarize: If the ReadUncommitted flag is set, then read cursors do
29116   ** not create or respect table locks. The locking procedure for a 
29117   ** write-cursor does not change.
29118   */
29119   if( 
29120     !p->db || 
29121     0==(p->db->flags&SQLITE_ReadUncommitted) || 
29122     eLock==WRITE_LOCK ||
29123     iTab==MASTER_ROOT
29124   ){
29125     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
29126       if( pIter->pBtree!=p && pIter->iTable==iTab && 
29127           (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
29128         return SQLITE_LOCKED;
29129       }
29130     }
29131   }
29132   return SQLITE_OK;
29133 }
29134 #endif /* !SQLITE_OMIT_SHARED_CACHE */
29135
29136 #ifndef SQLITE_OMIT_SHARED_CACHE
29137 /*
29138 ** Add a lock on the table with root-page iTable to the shared-btree used
29139 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
29140 ** WRITE_LOCK.
29141 **
29142 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
29143 ** SQLITE_NOMEM may also be returned.
29144 */
29145 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
29146   BtShared *pBt = p->pBt;
29147   BtLock *pLock = 0;
29148   BtLock *pIter;
29149
29150   assert( sqlite3BtreeHoldsMutex(p) );
29151
29152   /* This is a no-op if the shared-cache is not enabled */
29153   if( !p->sharable ){
29154     return SQLITE_OK;
29155   }
29156
29157   assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
29158
29159   /* If the read-uncommitted flag is set and a read-lock is requested,
29160   ** return early without adding an entry to the BtShared.pLock list. See
29161   ** comment in function queryTableLock() for more info on handling 
29162   ** the ReadUncommitted flag.
29163   */
29164   if( 
29165     (p->db) && 
29166     (p->db->flags&SQLITE_ReadUncommitted) && 
29167     (eLock==READ_LOCK) &&
29168     iTable!=MASTER_ROOT
29169   ){
29170     return SQLITE_OK;
29171   }
29172
29173   /* First search the list for an existing lock on this table. */
29174   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
29175     if( pIter->iTable==iTable && pIter->pBtree==p ){
29176       pLock = pIter;
29177       break;
29178     }
29179   }
29180
29181   /* If the above search did not find a BtLock struct associating Btree p
29182   ** with table iTable, allocate one and link it into the list.
29183   */
29184   if( !pLock ){
29185     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
29186     if( !pLock ){
29187       return SQLITE_NOMEM;
29188     }
29189     pLock->iTable = iTable;
29190     pLock->pBtree = p;
29191     pLock->pNext = pBt->pLock;
29192     pBt->pLock = pLock;
29193   }
29194
29195   /* Set the BtLock.eLock variable to the maximum of the current lock
29196   ** and the requested lock. This means if a write-lock was already held
29197   ** and a read-lock requested, we don't incorrectly downgrade the lock.
29198   */
29199   assert( WRITE_LOCK>READ_LOCK );
29200   if( eLock>pLock->eLock ){
29201     pLock->eLock = eLock;
29202   }
29203
29204   return SQLITE_OK;
29205 }
29206 #endif /* !SQLITE_OMIT_SHARED_CACHE */
29207
29208 #ifndef SQLITE_OMIT_SHARED_CACHE
29209 /*
29210 ** Release all the table locks (locks obtained via calls to the lockTable()
29211 ** procedure) held by Btree handle p.
29212 */
29213 static void unlockAllTables(Btree *p){
29214   BtShared *pBt = p->pBt;
29215   BtLock **ppIter = &pBt->pLock;
29216
29217   assert( sqlite3BtreeHoldsMutex(p) );
29218   assert( p->sharable || 0==*ppIter );
29219
29220   while( *ppIter ){
29221     BtLock *pLock = *ppIter;
29222     assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
29223     if( pLock->pBtree==p ){
29224       *ppIter = pLock->pNext;
29225       sqlite3_free(pLock);
29226     }else{
29227       ppIter = &pLock->pNext;
29228     }
29229   }
29230
29231   if( pBt->pExclusive==p ){
29232     pBt->pExclusive = 0;
29233   }
29234 }
29235 #endif /* SQLITE_OMIT_SHARED_CACHE */
29236
29237 static void releasePage(MemPage *pPage);  /* Forward reference */
29238
29239 /*
29240 ** Verify that the cursor holds a mutex on the BtShared
29241 */
29242 #ifndef NDEBUG
29243 static int cursorHoldsMutex(BtCursor *p){
29244   return sqlite3_mutex_held(p->pBt->mutex);
29245 }
29246 #endif
29247
29248
29249 #ifndef SQLITE_OMIT_INCRBLOB
29250 /*
29251 ** Invalidate the overflow page-list cache for cursor pCur, if any.
29252 */
29253 static void invalidateOverflowCache(BtCursor *pCur){
29254   assert( cursorHoldsMutex(pCur) );
29255   sqlite3_free(pCur->aOverflow);
29256   pCur->aOverflow = 0;
29257 }
29258
29259 /*
29260 ** Invalidate the overflow page-list cache for all cursors opened
29261 ** on the shared btree structure pBt.
29262 */
29263 static void invalidateAllOverflowCache(BtShared *pBt){
29264   BtCursor *p;
29265   assert( sqlite3_mutex_held(pBt->mutex) );
29266   for(p=pBt->pCursor; p; p=p->pNext){
29267     invalidateOverflowCache(p);
29268   }
29269 }
29270 #else
29271   #define invalidateOverflowCache(x)
29272   #define invalidateAllOverflowCache(x)
29273 #endif
29274
29275 /*
29276 ** Save the current cursor position in the variables BtCursor.nKey 
29277 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
29278 */
29279 static int saveCursorPosition(BtCursor *pCur){
29280   int rc;
29281
29282   assert( CURSOR_VALID==pCur->eState );
29283   assert( 0==pCur->pKey );
29284   assert( cursorHoldsMutex(pCur) );
29285
29286   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
29287
29288   /* If this is an intKey table, then the above call to BtreeKeySize()
29289   ** stores the integer key in pCur->nKey. In this case this value is
29290   ** all that is required. Otherwise, if pCur is not open on an intKey
29291   ** table, then malloc space for and store the pCur->nKey bytes of key 
29292   ** data.
29293   */
29294   if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
29295     void *pKey = sqlite3_malloc(pCur->nKey);
29296     if( pKey ){
29297       rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
29298       if( rc==SQLITE_OK ){
29299         pCur->pKey = pKey;
29300       }else{
29301         sqlite3_free(pKey);
29302       }
29303     }else{
29304       rc = SQLITE_NOMEM;
29305     }
29306   }
29307   assert( !pCur->pPage->intKey || !pCur->pKey );
29308
29309   if( rc==SQLITE_OK ){
29310     releasePage(pCur->pPage);
29311     pCur->pPage = 0;
29312     pCur->eState = CURSOR_REQUIRESEEK;
29313   }
29314
29315   invalidateOverflowCache(pCur);
29316   return rc;
29317 }
29318
29319 /*
29320 ** Save the positions of all cursors except pExcept open on the table 
29321 ** with root-page iRoot. Usually, this is called just before cursor
29322 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
29323 */
29324 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
29325   BtCursor *p;
29326   assert( sqlite3_mutex_held(pBt->mutex) );
29327   assert( pExcept==0 || pExcept->pBt==pBt );
29328   for(p=pBt->pCursor; p; p=p->pNext){
29329     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
29330         p->eState==CURSOR_VALID ){
29331       int rc = saveCursorPosition(p);
29332       if( SQLITE_OK!=rc ){
29333         return rc;
29334       }
29335     }
29336   }
29337   return SQLITE_OK;
29338 }
29339
29340 /*
29341 ** Clear the current cursor position.
29342 */
29343 static void clearCursorPosition(BtCursor *pCur){
29344   assert( cursorHoldsMutex(pCur) );
29345   sqlite3_free(pCur->pKey);
29346   pCur->pKey = 0;
29347   pCur->eState = CURSOR_INVALID;
29348 }
29349
29350 /*
29351 ** Restore the cursor to the position it was in (or as close to as possible)
29352 ** when saveCursorPosition() was called. Note that this call deletes the 
29353 ** saved position info stored by saveCursorPosition(), so there can be
29354 ** at most one effective restoreOrClearCursorPosition() call after each 
29355 ** saveCursorPosition().
29356 **
29357 ** If the second argument argument - doSeek - is false, then instead of 
29358 ** returning the cursor to its saved position, any saved position is deleted
29359 ** and the cursor state set to CURSOR_INVALID.
29360 */
29361 SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
29362   int rc;
29363   assert( cursorHoldsMutex(pCur) );
29364   assert( pCur->eState>=CURSOR_REQUIRESEEK );
29365   if( pCur->eState==CURSOR_FAULT ){
29366     return pCur->skip;
29367   }
29368 #ifndef SQLITE_OMIT_INCRBLOB
29369   if( pCur->isIncrblobHandle ){
29370     return SQLITE_ABORT;
29371   }
29372 #endif
29373   pCur->eState = CURSOR_INVALID;
29374   rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
29375   if( rc==SQLITE_OK ){
29376     sqlite3_free(pCur->pKey);
29377     pCur->pKey = 0;
29378     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
29379   }
29380   return rc;
29381 }
29382
29383 #define restoreOrClearCursorPosition(p) \
29384   (p->eState>=CURSOR_REQUIRESEEK ? \
29385          sqlite3BtreeRestoreOrClearCursorPosition(p) : \
29386          SQLITE_OK)
29387
29388 #ifndef SQLITE_OMIT_AUTOVACUUM
29389 /*
29390 ** Given a page number of a regular database page, return the page
29391 ** number for the pointer-map page that contains the entry for the
29392 ** input page number.
29393 */
29394 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
29395   int nPagesPerMapPage, iPtrMap, ret;
29396   assert( sqlite3_mutex_held(pBt->mutex) );
29397   nPagesPerMapPage = (pBt->usableSize/5)+1;
29398   iPtrMap = (pgno-2)/nPagesPerMapPage;
29399   ret = (iPtrMap*nPagesPerMapPage) + 2; 
29400   if( ret==PENDING_BYTE_PAGE(pBt) ){
29401     ret++;
29402   }
29403   return ret;
29404 }
29405
29406 /*
29407 ** Write an entry into the pointer map.
29408 **
29409 ** This routine updates the pointer map entry for page number 'key'
29410 ** so that it maps to type 'eType' and parent page number 'pgno'.
29411 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
29412 */
29413 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
29414   DbPage *pDbPage;  /* The pointer map page */
29415   u8 *pPtrmap;      /* The pointer map data */
29416   Pgno iPtrmap;     /* The pointer map page number */
29417   int offset;       /* Offset in pointer map page */
29418   int rc;
29419
29420   assert( sqlite3_mutex_held(pBt->mutex) );
29421   /* The master-journal page number must never be used as a pointer map page */
29422   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
29423
29424   assert( pBt->autoVacuum );
29425   if( key==0 ){
29426     return SQLITE_CORRUPT_BKPT;
29427   }
29428   iPtrmap = PTRMAP_PAGENO(pBt, key);
29429   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
29430   if( rc!=SQLITE_OK ){
29431     return rc;
29432   }
29433   offset = PTRMAP_PTROFFSET(pBt, key);
29434   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
29435
29436   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
29437     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
29438     rc = sqlite3PagerWrite(pDbPage);
29439     if( rc==SQLITE_OK ){
29440       pPtrmap[offset] = eType;
29441       put4byte(&pPtrmap[offset+1], parent);
29442     }
29443   }
29444
29445   sqlite3PagerUnref(pDbPage);
29446   return rc;
29447 }
29448
29449 /*
29450 ** Read an entry from the pointer map.
29451 **
29452 ** This routine retrieves the pointer map entry for page 'key', writing
29453 ** the type and parent page number to *pEType and *pPgno respectively.
29454 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
29455 */
29456 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
29457   DbPage *pDbPage;   /* The pointer map page */
29458   int iPtrmap;       /* Pointer map page index */
29459   u8 *pPtrmap;       /* Pointer map page data */
29460   int offset;        /* Offset of entry in pointer map */
29461   int rc;
29462
29463   assert( sqlite3_mutex_held(pBt->mutex) );
29464
29465   iPtrmap = PTRMAP_PAGENO(pBt, key);
29466   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
29467   if( rc!=0 ){
29468     return rc;
29469   }
29470   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
29471
29472   offset = PTRMAP_PTROFFSET(pBt, key);
29473   assert( pEType!=0 );
29474   *pEType = pPtrmap[offset];
29475   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
29476
29477   sqlite3PagerUnref(pDbPage);
29478   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
29479   return SQLITE_OK;
29480 }
29481
29482 #endif /* SQLITE_OMIT_AUTOVACUUM */
29483
29484 /*
29485 ** Given a btree page and a cell index (0 means the first cell on
29486 ** the page, 1 means the second cell, and so forth) return a pointer
29487 ** to the cell content.
29488 **
29489 ** This routine works only for pages that do not contain overflow cells.
29490 */
29491 #define findCell(pPage, iCell) \
29492   ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
29493 #ifdef SQLITE_TEST
29494 SQLITE_PRIVATE u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
29495   assert( iCell>=0 );
29496   assert( iCell<get2byte(&pPage->aData[pPage->hdrOffset+3]) );
29497   return findCell(pPage, iCell);
29498 }
29499 #endif
29500
29501 /*
29502 ** This a more complex version of sqlite3BtreeFindCell() that works for
29503 ** pages that do contain overflow cells.  See insert
29504 */
29505 static u8 *findOverflowCell(MemPage *pPage, int iCell){
29506   int i;
29507   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
29508   for(i=pPage->nOverflow-1; i>=0; i--){
29509     int k;
29510     struct _OvflCell *pOvfl;
29511     pOvfl = &pPage->aOvfl[i];
29512     k = pOvfl->idx;
29513     if( k<=iCell ){
29514       if( k==iCell ){
29515         return pOvfl->pCell;
29516       }
29517       iCell--;
29518     }
29519   }
29520   return findCell(pPage, iCell);
29521 }
29522
29523 /*
29524 ** Parse a cell content block and fill in the CellInfo structure.  There
29525 ** are two versions of this function.  sqlite3BtreeParseCell() takes a 
29526 ** cell index as the second argument and sqlite3BtreeParseCellPtr() 
29527 ** takes a pointer to the body of the cell as its second argument.
29528 **
29529 ** Within this file, the parseCell() macro can be called instead of
29530 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
29531 */
29532 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
29533   MemPage *pPage,         /* Page containing the cell */
29534   u8 *pCell,              /* Pointer to the cell text. */
29535   CellInfo *pInfo         /* Fill in this structure */
29536 ){
29537   int n;                  /* Number bytes in cell content header */
29538   u32 nPayload;           /* Number of bytes of cell payload */
29539
29540   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
29541
29542   pInfo->pCell = pCell;
29543   assert( pPage->leaf==0 || pPage->leaf==1 );
29544   n = pPage->childPtrSize;
29545   assert( n==4-4*pPage->leaf );
29546   if( pPage->hasData ){
29547     n += getVarint32(&pCell[n], &nPayload);
29548   }else{
29549     nPayload = 0;
29550   }
29551   pInfo->nData = nPayload;
29552   if( pPage->intKey ){
29553     n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
29554   }else{
29555     u32 x;
29556     n += getVarint32(&pCell[n], &x);
29557     pInfo->nKey = x;
29558     nPayload += x;
29559   }
29560   pInfo->nPayload = nPayload;
29561   pInfo->nHeader = n;
29562   if( nPayload<=pPage->maxLocal ){
29563     /* This is the (easy) common case where the entire payload fits
29564     ** on the local page.  No overflow is required.
29565     */
29566     int nSize;          /* Total size of cell content in bytes */
29567     pInfo->nLocal = nPayload;
29568     pInfo->iOverflow = 0;
29569     nSize = nPayload + n;
29570     if( nSize<4 ){
29571       nSize = 4;        /* Minimum cell size is 4 */
29572     }
29573     pInfo->nSize = nSize;
29574   }else{
29575     /* If the payload will not fit completely on the local page, we have
29576     ** to decide how much to store locally and how much to spill onto
29577     ** overflow pages.  The strategy is to minimize the amount of unused
29578     ** space on overflow pages while keeping the amount of local storage
29579     ** in between minLocal and maxLocal.
29580     **
29581     ** Warning:  changing the way overflow payload is distributed in any
29582     ** way will result in an incompatible file format.
29583     */
29584     int minLocal;  /* Minimum amount of payload held locally */
29585     int maxLocal;  /* Maximum amount of payload held locally */
29586     int surplus;   /* Overflow payload available for local storage */
29587
29588     minLocal = pPage->minLocal;
29589     maxLocal = pPage->maxLocal;
29590     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
29591     if( surplus <= maxLocal ){
29592       pInfo->nLocal = surplus;
29593     }else{
29594       pInfo->nLocal = minLocal;
29595     }
29596     pInfo->iOverflow = pInfo->nLocal + n;
29597     pInfo->nSize = pInfo->iOverflow + 4;
29598   }
29599 }
29600 #define parseCell(pPage, iCell, pInfo) \
29601   sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
29602 SQLITE_PRIVATE void sqlite3BtreeParseCell(
29603   MemPage *pPage,         /* Page containing the cell */
29604   int iCell,              /* The cell index.  First cell is 0 */
29605   CellInfo *pInfo         /* Fill in this structure */
29606 ){
29607   parseCell(pPage, iCell, pInfo);
29608 }
29609
29610 /*
29611 ** Compute the total number of bytes that a Cell needs in the cell
29612 ** data area of the btree-page.  The return number includes the cell
29613 ** data header and the local payload, but not any overflow page or
29614 ** the space used by the cell pointer.
29615 */
29616 #ifndef NDEBUG
29617 static u16 cellSize(MemPage *pPage, int iCell){
29618   CellInfo info;
29619   sqlite3BtreeParseCell(pPage, iCell, &info);
29620   return info.nSize;
29621 }
29622 #endif
29623 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
29624   CellInfo info;
29625   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
29626   return info.nSize;
29627 }
29628
29629 #ifndef SQLITE_OMIT_AUTOVACUUM
29630 /*
29631 ** If the cell pCell, part of page pPage contains a pointer
29632 ** to an overflow page, insert an entry into the pointer-map
29633 ** for the overflow page.
29634 */
29635 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
29636   if( pCell ){
29637     CellInfo info;
29638     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
29639     assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
29640     if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
29641       Pgno ovfl = get4byte(&pCell[info.iOverflow]);
29642       return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
29643     }
29644   }
29645   return SQLITE_OK;
29646 }
29647 /*
29648 ** If the cell with index iCell on page pPage contains a pointer
29649 ** to an overflow page, insert an entry into the pointer-map
29650 ** for the overflow page.
29651 */
29652 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
29653   u8 *pCell;
29654   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
29655   pCell = findOverflowCell(pPage, iCell);
29656   return ptrmapPutOvflPtr(pPage, pCell);
29657 }
29658 #endif
29659
29660
29661 /*
29662 ** Defragment the page given.  All Cells are moved to the
29663 ** end of the page and all free space is collected into one
29664 ** big FreeBlk that occurs in between the header and cell
29665 ** pointer array and the cell content area.
29666 */
29667 static int defragmentPage(MemPage *pPage){
29668   int i;                     /* Loop counter */
29669   int pc;                    /* Address of a i-th cell */
29670   int addr;                  /* Offset of first byte after cell pointer array */
29671   int hdr;                   /* Offset to the page header */
29672   int size;                  /* Size of a cell */
29673   int usableSize;            /* Number of usable bytes on a page */
29674   int cellOffset;            /* Offset to the cell pointer array */
29675   int brk;                   /* Offset to the cell content area */
29676   int nCell;                 /* Number of cells on the page */
29677   unsigned char *data;       /* The page data */
29678   unsigned char *temp;       /* Temp area for cell content */
29679
29680   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
29681   assert( pPage->pBt!=0 );
29682   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
29683   assert( pPage->nOverflow==0 );
29684   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
29685   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
29686   data = pPage->aData;
29687   hdr = pPage->hdrOffset;
29688   cellOffset = pPage->cellOffset;
29689   nCell = pPage->nCell;
29690   assert( nCell==get2byte(&data[hdr+3]) );
29691   usableSize = pPage->pBt->usableSize;
29692   brk = get2byte(&data[hdr+5]);
29693   memcpy(&temp[brk], &data[brk], usableSize - brk);
29694   brk = usableSize;
29695   for(i=0; i<nCell; i++){
29696     u8 *pAddr;     /* The i-th cell pointer */
29697     pAddr = &data[cellOffset + i*2];
29698     pc = get2byte(pAddr);
29699     assert( pc<pPage->pBt->usableSize );
29700     size = cellSizePtr(pPage, &temp[pc]);
29701     brk -= size;
29702     memcpy(&data[brk], &temp[pc], size);
29703     put2byte(pAddr, brk);
29704   }
29705   assert( brk>=cellOffset+2*nCell );
29706   put2byte(&data[hdr+5], brk);
29707   data[hdr+1] = 0;
29708   data[hdr+2] = 0;
29709   data[hdr+7] = 0;
29710   addr = cellOffset+2*nCell;
29711   memset(&data[addr], 0, brk-addr);
29712   return SQLITE_OK;
29713 }
29714
29715 /*
29716 ** Allocate nByte bytes of space on a page.
29717 **
29718 ** Return the index into pPage->aData[] of the first byte of
29719 ** the new allocation. Or return 0 if there is not enough free
29720 ** space on the page to satisfy the allocation request.
29721 **
29722 ** If the page contains nBytes of free space but does not contain
29723 ** nBytes of contiguous free space, then this routine automatically
29724 ** calls defragementPage() to consolidate all free space before 
29725 ** allocating the new chunk.
29726 */
29727 static int allocateSpace(MemPage *pPage, int nByte){
29728   int addr, pc, hdr;
29729   int size;
29730   int nFrag;
29731   int top;
29732   int nCell;
29733   int cellOffset;
29734   unsigned char *data;
29735   
29736   data = pPage->aData;
29737   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
29738   assert( pPage->pBt );
29739   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
29740   if( nByte<4 ) nByte = 4;
29741   if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
29742   pPage->nFree -= nByte;
29743   hdr = pPage->hdrOffset;
29744
29745   nFrag = data[hdr+7];
29746   if( nFrag<60 ){
29747     /* Search the freelist looking for a slot big enough to satisfy the
29748     ** space request. */
29749     addr = hdr+1;
29750     while( (pc = get2byte(&data[addr]))>0 ){
29751       size = get2byte(&data[pc+2]);
29752       if( size>=nByte ){
29753         if( size<nByte+4 ){
29754           memcpy(&data[addr], &data[pc], 2);
29755           data[hdr+7] = nFrag + size - nByte;
29756           return pc;
29757         }else{
29758           put2byte(&data[pc+2], size-nByte);
29759           return pc + size - nByte;
29760         }
29761       }
29762       addr = pc;
29763     }
29764   }
29765
29766   /* Allocate memory from the gap in between the cell pointer array
29767   ** and the cell content area.
29768   */
29769   top = get2byte(&data[hdr+5]);
29770   nCell = get2byte(&data[hdr+3]);
29771   cellOffset = pPage->cellOffset;
29772   if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
29773     if( defragmentPage(pPage) ) return 0;
29774     top = get2byte(&data[hdr+5]);
29775   }
29776   top -= nByte;
29777   assert( cellOffset + 2*nCell <= top );
29778   put2byte(&data[hdr+5], top);
29779   return top;
29780 }
29781
29782 /*
29783 ** Return a section of the pPage->aData to the freelist.
29784 ** The first byte of the new free block is pPage->aDisk[start]
29785 ** and the size of the block is "size" bytes.
29786 **
29787 ** Most of the effort here is involved in coalesing adjacent
29788 ** free blocks into a single big free block.
29789 */
29790 static void freeSpace(MemPage *pPage, int start, int size){
29791   int addr, pbegin, hdr;
29792   unsigned char *data = pPage->aData;
29793
29794   assert( pPage->pBt!=0 );
29795   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
29796   assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
29797   assert( (start + size)<=pPage->pBt->usableSize );
29798   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
29799   if( size<4 ) size = 4;
29800
29801 #ifdef SQLITE_SECURE_DELETE
29802   /* Overwrite deleted information with zeros when the SECURE_DELETE 
29803   ** option is enabled at compile-time */
29804   memset(&data[start], 0, size);
29805 #endif
29806
29807   /* Add the space back into the linked list of freeblocks */
29808   hdr = pPage->hdrOffset;
29809   addr = hdr + 1;
29810   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
29811     assert( pbegin<=pPage->pBt->usableSize-4 );
29812     assert( pbegin>addr );
29813     addr = pbegin;
29814   }
29815   assert( pbegin<=pPage->pBt->usableSize-4 );
29816   assert( pbegin>addr || pbegin==0 );
29817   put2byte(&data[addr], start);
29818   put2byte(&data[start], pbegin);
29819   put2byte(&data[start+2], size);
29820   pPage->nFree += size;
29821
29822   /* Coalesce adjacent free blocks */
29823   addr = pPage->hdrOffset + 1;
29824   while( (pbegin = get2byte(&data[addr]))>0 ){
29825     int pnext, psize;
29826     assert( pbegin>addr );
29827     assert( pbegin<=pPage->pBt->usableSize-4 );
29828     pnext = get2byte(&data[pbegin]);
29829     psize = get2byte(&data[pbegin+2]);
29830     if( pbegin + psize + 3 >= pnext && pnext>0 ){
29831       int frag = pnext - (pbegin+psize);
29832       assert( frag<=data[pPage->hdrOffset+7] );
29833       data[pPage->hdrOffset+7] -= frag;
29834       put2byte(&data[pbegin], get2byte(&data[pnext]));
29835       put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
29836     }else{
29837       addr = pbegin;
29838     }
29839   }
29840
29841   /* If the cell content area begins with a freeblock, remove it. */
29842   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
29843     int top;
29844     pbegin = get2byte(&data[hdr+1]);
29845     memcpy(&data[hdr+1], &data[pbegin], 2);
29846     top = get2byte(&data[hdr+5]);
29847     put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
29848   }
29849 }
29850
29851 /*
29852 ** Decode the flags byte (the first byte of the header) for a page
29853 ** and initialize fields of the MemPage structure accordingly.
29854 */
29855 static void decodeFlags(MemPage *pPage, int flagByte){
29856   BtShared *pBt;     /* A copy of pPage->pBt */
29857
29858   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
29859   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
29860   pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
29861   pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
29862   pPage->leaf = (flagByte & PTF_LEAF)!=0;
29863   pPage->childPtrSize = 4*(pPage->leaf==0);
29864   pBt = pPage->pBt;
29865   if( flagByte & PTF_LEAFDATA ){
29866     pPage->leafData = 1;
29867     pPage->maxLocal = pBt->maxLeaf;
29868     pPage->minLocal = pBt->minLeaf;
29869   }else{
29870     pPage->leafData = 0;
29871     pPage->maxLocal = pBt->maxLocal;
29872     pPage->minLocal = pBt->minLocal;
29873   }
29874   pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
29875 }
29876
29877 /*
29878 ** Initialize the auxiliary information for a disk block.
29879 **
29880 ** The pParent parameter must be a pointer to the MemPage which
29881 ** is the parent of the page being initialized.  The root of a
29882 ** BTree has no parent and so for that page, pParent==NULL.
29883 **
29884 ** Return SQLITE_OK on success.  If we see that the page does
29885 ** not contain a well-formed database page, then return 
29886 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
29887 ** guarantee that the page is well-formed.  It only shows that
29888 ** we failed to detect any corruption.
29889 */
29890 SQLITE_PRIVATE int sqlite3BtreeInitPage(
29891   MemPage *pPage,        /* The page to be initialized */
29892   MemPage *pParent       /* The parent.  Might be NULL */
29893 ){
29894   int pc;            /* Address of a freeblock within pPage->aData[] */
29895   int hdr;           /* Offset to beginning of page header */
29896   u8 *data;          /* Equal to pPage->aData */
29897   BtShared *pBt;        /* The main btree structure */
29898   int usableSize;    /* Amount of usable space on each page */
29899   int cellOffset;    /* Offset from start of page to first cell pointer */
29900   int nFree;         /* Number of unused bytes on the page */
29901   int top;           /* First byte of the cell content area */
29902
29903   pBt = pPage->pBt;
29904   assert( pBt!=0 );
29905   assert( pParent==0 || pParent->pBt==pBt );
29906   assert( sqlite3_mutex_held(pBt->mutex) );
29907   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
29908   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
29909   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
29910   if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
29911     /* The parent page should never change unless the file is corrupt */
29912     return SQLITE_CORRUPT_BKPT;
29913   }
29914   if( pPage->isInit ) return SQLITE_OK;
29915   if( pPage->pParent==0 && pParent!=0 ){
29916     pPage->pParent = pParent;
29917     sqlite3PagerRef(pParent->pDbPage);
29918   }
29919   hdr = pPage->hdrOffset;
29920   data = pPage->aData;
29921   decodeFlags(pPage, data[hdr]);
29922   pPage->nOverflow = 0;
29923   pPage->idxShift = 0;
29924   usableSize = pBt->usableSize;
29925   pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
29926   top = get2byte(&data[hdr+5]);
29927   pPage->nCell = get2byte(&data[hdr+3]);
29928   if( pPage->nCell>MX_CELL(pBt) ){
29929     /* To many cells for a single page.  The page must be corrupt */
29930     return SQLITE_CORRUPT_BKPT;
29931   }
29932   if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
29933     /* All pages must have at least one cell, except for root pages */
29934     return SQLITE_CORRUPT_BKPT;
29935   }
29936
29937   /* Compute the total free space on the page */
29938   pc = get2byte(&data[hdr+1]);
29939   nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
29940   while( pc>0 ){
29941     int next, size;
29942     if( pc>usableSize-4 ){
29943       /* Free block is off the page */
29944       return SQLITE_CORRUPT_BKPT; 
29945     }
29946     next = get2byte(&data[pc]);
29947     size = get2byte(&data[pc+2]);
29948     if( next>0 && next<=pc+size+3 ){
29949       /* Free blocks must be in accending order */
29950       return SQLITE_CORRUPT_BKPT; 
29951     }
29952     nFree += size;
29953     pc = next;
29954   }
29955   pPage->nFree = nFree;
29956   if( nFree>=usableSize ){
29957     /* Free space cannot exceed total page size */
29958     return SQLITE_CORRUPT_BKPT; 
29959   }
29960
29961   pPage->isInit = 1;
29962   return SQLITE_OK;
29963 }
29964
29965 /*
29966 ** Set up a raw page so that it looks like a database page holding
29967 ** no entries.
29968 */
29969 static void zeroPage(MemPage *pPage, int flags){
29970   unsigned char *data = pPage->aData;
29971   BtShared *pBt = pPage->pBt;
29972   int hdr = pPage->hdrOffset;
29973   int first;
29974
29975   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
29976   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
29977   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
29978   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
29979   assert( sqlite3_mutex_held(pBt->mutex) );
29980   memset(&data[hdr], 0, pBt->usableSize - hdr);
29981   data[hdr] = flags;
29982   first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
29983   memset(&data[hdr+1], 0, 4);
29984   data[hdr+7] = 0;
29985   put2byte(&data[hdr+5], pBt->usableSize);
29986   pPage->nFree = pBt->usableSize - first;
29987   decodeFlags(pPage, flags);
29988   pPage->hdrOffset = hdr;
29989   pPage->cellOffset = first;
29990   pPage->nOverflow = 0;
29991   pPage->idxShift = 0;
29992   pPage->nCell = 0;
29993   pPage->isInit = 1;
29994 }
29995
29996 /*
29997 ** Get a page from the pager.  Initialize the MemPage.pBt and
29998 ** MemPage.aData elements if needed.
29999 **
30000 ** If the noContent flag is set, it means that we do not care about
30001 ** the content of the page at this time.  So do not go to the disk
30002 ** to fetch the content.  Just fill in the content with zeros for now.
30003 ** If in the future we call sqlite3PagerWrite() on this page, that
30004 ** means we have started to be concerned about content and the disk
30005 ** read should occur at that point.
30006 */
30007 SQLITE_PRIVATE int sqlite3BtreeGetPage(
30008   BtShared *pBt,       /* The btree */
30009   Pgno pgno,           /* Number of the page to fetch */
30010   MemPage **ppPage,    /* Return the page in this parameter */
30011   int noContent        /* Do not load page content if true */
30012 ){
30013   int rc;
30014   MemPage *pPage;
30015   DbPage *pDbPage;
30016
30017   assert( sqlite3_mutex_held(pBt->mutex) );
30018   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
30019   if( rc ) return rc;
30020   pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
30021   pPage->aData = sqlite3PagerGetData(pDbPage);
30022   pPage->pDbPage = pDbPage;
30023   pPage->pBt = pBt;
30024   pPage->pgno = pgno;
30025   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
30026   *ppPage = pPage;
30027   return SQLITE_OK;
30028 }
30029
30030 /*
30031 ** Get a page from the pager and initialize it.  This routine
30032 ** is just a convenience wrapper around separate calls to
30033 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
30034 */
30035 static int getAndInitPage(
30036   BtShared *pBt,          /* The database file */
30037   Pgno pgno,           /* Number of the page to get */
30038   MemPage **ppPage,    /* Write the page pointer here */
30039   MemPage *pParent     /* Parent of the page */
30040 ){
30041   int rc;
30042   assert( sqlite3_mutex_held(pBt->mutex) );
30043   if( pgno==0 ){
30044     return SQLITE_CORRUPT_BKPT; 
30045   }
30046   rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
30047   if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
30048     rc = sqlite3BtreeInitPage(*ppPage, pParent);
30049   }
30050   return rc;
30051 }
30052
30053 /*
30054 ** Release a MemPage.  This should be called once for each prior
30055 ** call to sqlite3BtreeGetPage.
30056 */
30057 static void releasePage(MemPage *pPage){
30058   if( pPage ){
30059     assert( pPage->aData );
30060     assert( pPage->pBt );
30061     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
30062     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
30063     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30064     sqlite3PagerUnref(pPage->pDbPage);
30065   }
30066 }
30067
30068 /*
30069 ** This routine is called when the reference count for a page
30070 ** reaches zero.  We need to unref the pParent pointer when that
30071 ** happens.
30072 */
30073 static void pageDestructor(DbPage *pData, int pageSize){
30074   MemPage *pPage;
30075   assert( (pageSize & 7)==0 );
30076   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
30077   assert( pPage->isInit==0 || sqlite3_mutex_held(pPage->pBt->mutex) );
30078   if( pPage->pParent ){
30079     MemPage *pParent = pPage->pParent;
30080     assert( pParent->pBt==pPage->pBt );
30081     pPage->pParent = 0;
30082     releasePage(pParent);
30083   }
30084   pPage->isInit = 0;
30085 }
30086
30087 /*
30088 ** During a rollback, when the pager reloads information into the cache
30089 ** so that the cache is restored to its original state at the start of
30090 ** the transaction, for each page restored this routine is called.
30091 **
30092 ** This routine needs to reset the extra data section at the end of the
30093 ** page to agree with the restored data.
30094 */
30095 static void pageReinit(DbPage *pData, int pageSize){
30096   MemPage *pPage;
30097   assert( (pageSize & 7)==0 );
30098   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
30099   if( pPage->isInit ){
30100     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30101     pPage->isInit = 0;
30102     sqlite3BtreeInitPage(pPage, pPage->pParent);
30103   }
30104 }
30105
30106 /*
30107 ** Invoke the busy handler for a btree.
30108 */
30109 static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
30110   BtShared *pBt = (BtShared*)pArg;
30111   assert( pBt->db );
30112   assert( sqlite3_mutex_held(pBt->db->mutex) );
30113   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
30114 }
30115
30116 /*
30117 ** Open a database file.
30118 ** 
30119 ** zFilename is the name of the database file.  If zFilename is NULL
30120 ** a new database with a random name is created.  This randomly named
30121 ** database file will be deleted when sqlite3BtreeClose() is called.
30122 ** If zFilename is ":memory:" then an in-memory database is created
30123 ** that is automatically destroyed when it is closed.
30124 */
30125 SQLITE_PRIVATE int sqlite3BtreeOpen(
30126   const char *zFilename,  /* Name of the file containing the BTree database */
30127   sqlite3 *db,            /* Associated database handle */
30128   Btree **ppBtree,        /* Pointer to new Btree object written here */
30129   int flags,              /* Options */
30130   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
30131 ){
30132   sqlite3_vfs *pVfs;      /* The VFS to use for this btree */
30133   BtShared *pBt = 0;      /* Shared part of btree structure */
30134   Btree *p;               /* Handle to return */
30135   int rc = SQLITE_OK;
30136   int nReserve;
30137   unsigned char zDbHeader[100];
30138
30139   /* Set the variable isMemdb to true for an in-memory database, or 
30140   ** false for a file-based database. This symbol is only required if
30141   ** either of the shared-data or autovacuum features are compiled 
30142   ** into the library.
30143   */
30144 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
30145   #ifdef SQLITE_OMIT_MEMORYDB
30146     const int isMemdb = 0;
30147   #else
30148     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
30149   #endif
30150 #endif
30151
30152   assert( db!=0 );
30153   assert( sqlite3_mutex_held(db->mutex) );
30154
30155   pVfs = db->pVfs;
30156   p = sqlite3MallocZero(sizeof(Btree));
30157   if( !p ){
30158     return SQLITE_NOMEM;
30159   }
30160   p->inTrans = TRANS_NONE;
30161   p->db = db;
30162
30163 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
30164   /*
30165   ** If this Btree is a candidate for shared cache, try to find an
30166   ** existing BtShared object that we can share with
30167   */
30168   if( (flags & BTREE_PRIVATE)==0
30169    && isMemdb==0
30170    && (db->flags & SQLITE_Vtab)==0
30171    && zFilename && zFilename[0]
30172   ){
30173     if( sqlite3SharedCacheEnabled ){
30174       int nFullPathname = pVfs->mxPathname+1;
30175       char *zFullPathname = (char *)sqlite3_malloc(nFullPathname);
30176       sqlite3_mutex *mutexShared;
30177       p->sharable = 1;
30178       if( db ){
30179         db->flags |= SQLITE_SharedCache;
30180       }
30181       if( !zFullPathname ){
30182         sqlite3_free(p);
30183         return SQLITE_NOMEM;
30184       }
30185       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
30186       mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
30187       sqlite3_mutex_enter(mutexShared);
30188       for(pBt=sqlite3SharedCacheList; pBt; pBt=pBt->pNext){
30189         assert( pBt->nRef>0 );
30190         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
30191                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
30192           p->pBt = pBt;
30193           pBt->nRef++;
30194           break;
30195         }
30196       }
30197       sqlite3_mutex_leave(mutexShared);
30198       sqlite3_free(zFullPathname);
30199     }
30200 #ifdef SQLITE_DEBUG
30201     else{
30202       /* In debug mode, we mark all persistent databases as sharable
30203       ** even when they are not.  This exercises the locking code and
30204       ** gives more opportunity for asserts(sqlite3_mutex_held())
30205       ** statements to find locking problems.
30206       */
30207       p->sharable = 1;
30208     }
30209 #endif
30210   }
30211 #endif
30212   if( pBt==0 ){
30213     /*
30214     ** The following asserts make sure that structures used by the btree are
30215     ** the right size.  This is to guard against size changes that result
30216     ** when compiling on a different architecture.
30217     */
30218     assert( sizeof(i64)==8 || sizeof(i64)==4 );
30219     assert( sizeof(u64)==8 || sizeof(u64)==4 );
30220     assert( sizeof(u32)==4 );
30221     assert( sizeof(u16)==2 );
30222     assert( sizeof(Pgno)==4 );
30223   
30224     pBt = sqlite3MallocZero( sizeof(*pBt) );
30225     if( pBt==0 ){
30226       rc = SQLITE_NOMEM;
30227       goto btree_open_out;
30228     }
30229     pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
30230     pBt->busyHdr.pArg = pBt;
30231     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
30232                           EXTRA_SIZE, flags, vfsFlags);
30233     if( rc==SQLITE_OK ){
30234       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
30235     }
30236     if( rc!=SQLITE_OK ){
30237       goto btree_open_out;
30238     }
30239     sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
30240     p->pBt = pBt;
30241   
30242     sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
30243     sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
30244     pBt->pCursor = 0;
30245     pBt->pPage1 = 0;
30246     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
30247     pBt->pageSize = get2byte(&zDbHeader[16]);
30248     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
30249          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
30250       pBt->pageSize = 0;
30251       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
30252       pBt->maxEmbedFrac = 64;   /* 25% */
30253       pBt->minEmbedFrac = 32;   /* 12.5% */
30254       pBt->minLeafFrac = 32;    /* 12.5% */
30255 #ifndef SQLITE_OMIT_AUTOVACUUM
30256       /* If the magic name ":memory:" will create an in-memory database, then
30257       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
30258       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
30259       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
30260       ** regular file-name. In this case the auto-vacuum applies as per normal.
30261       */
30262       if( zFilename && !isMemdb ){
30263         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
30264         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
30265       }
30266 #endif
30267       nReserve = 0;
30268     }else{
30269       nReserve = zDbHeader[20];
30270       pBt->maxEmbedFrac = zDbHeader[21];
30271       pBt->minEmbedFrac = zDbHeader[22];
30272       pBt->minLeafFrac = zDbHeader[23];
30273       pBt->pageSizeFixed = 1;
30274 #ifndef SQLITE_OMIT_AUTOVACUUM
30275       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
30276       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
30277 #endif
30278     }
30279     pBt->usableSize = pBt->pageSize - nReserve;
30280     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
30281     sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
30282    
30283 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
30284     /* Add the new BtShared object to the linked list sharable BtShareds.
30285     */
30286     if( p->sharable ){
30287       sqlite3_mutex *mutexShared;
30288       pBt->nRef = 1;
30289       mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
30290       if( SQLITE_THREADSAFE ){
30291         pBt->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30292         if( pBt->mutex==0 ){
30293           rc = SQLITE_NOMEM;
30294           db->mallocFailed = 0;
30295           goto btree_open_out;
30296         }
30297       }
30298       sqlite3_mutex_enter(mutexShared);
30299       pBt->pNext = sqlite3SharedCacheList;
30300       sqlite3SharedCacheList = pBt;
30301       sqlite3_mutex_leave(mutexShared);
30302     }
30303 #endif
30304   }
30305
30306 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
30307   /* If the new Btree uses a sharable pBtShared, then link the new
30308   ** Btree into the list of all sharable Btrees for the same connection.
30309   ** The list is kept in ascending order by pBt address.
30310   */
30311   if( p->sharable ){
30312     int i;
30313     Btree *pSib;
30314     for(i=0; i<db->nDb; i++){
30315       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
30316         while( pSib->pPrev ){ pSib = pSib->pPrev; }
30317         if( p->pBt<pSib->pBt ){
30318           p->pNext = pSib;
30319           p->pPrev = 0;
30320           pSib->pPrev = p;
30321         }else{
30322           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
30323             pSib = pSib->pNext;
30324           }
30325           p->pNext = pSib->pNext;
30326           p->pPrev = pSib;
30327           if( p->pNext ){
30328             p->pNext->pPrev = p;
30329           }
30330           pSib->pNext = p;
30331         }
30332         break;
30333       }
30334     }
30335   }
30336 #endif
30337   *ppBtree = p;
30338
30339 btree_open_out:
30340   if( rc!=SQLITE_OK ){
30341     if( pBt && pBt->pPager ){
30342       sqlite3PagerClose(pBt->pPager);
30343     }
30344     sqlite3_free(pBt);
30345     sqlite3_free(p);
30346     *ppBtree = 0;
30347   }
30348   return rc;
30349 }
30350
30351 /*
30352 ** Decrement the BtShared.nRef counter.  When it reaches zero,
30353 ** remove the BtShared structure from the sharing list.  Return
30354 ** true if the BtShared.nRef counter reaches zero and return
30355 ** false if it is still positive.
30356 */
30357 static int removeFromSharingList(BtShared *pBt){
30358 #ifndef SQLITE_OMIT_SHARED_CACHE
30359   sqlite3_mutex *pMaster;
30360   BtShared *pList;
30361   int removed = 0;
30362
30363   assert( sqlite3_mutex_notheld(pBt->mutex) );
30364   pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
30365   sqlite3_mutex_enter(pMaster);
30366   pBt->nRef--;
30367   if( pBt->nRef<=0 ){
30368     if( sqlite3SharedCacheList==pBt ){
30369       sqlite3SharedCacheList = pBt->pNext;
30370     }else{
30371       pList = sqlite3SharedCacheList;
30372       while( pList && pList->pNext!=pBt ){
30373         pList=pList->pNext;
30374       }
30375       if( pList ){
30376         pList->pNext = pBt->pNext;
30377       }
30378     }
30379     if( SQLITE_THREADSAFE ){
30380       sqlite3_mutex_free(pBt->mutex);
30381     }
30382     removed = 1;
30383   }
30384   sqlite3_mutex_leave(pMaster);
30385   return removed;
30386 #else
30387   return 1;
30388 #endif
30389 }
30390
30391 /*
30392 ** Close an open database and invalidate all cursors.
30393 */
30394 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
30395   BtShared *pBt = p->pBt;
30396   BtCursor *pCur;
30397
30398   /* Close all cursors opened via this handle.  */
30399   assert( sqlite3_mutex_held(p->db->mutex) );
30400   sqlite3BtreeEnter(p);
30401   pBt->db = p->db;
30402   pCur = pBt->pCursor;
30403   while( pCur ){
30404     BtCursor *pTmp = pCur;
30405     pCur = pCur->pNext;
30406     if( pTmp->pBtree==p ){
30407       sqlite3BtreeCloseCursor(pTmp);
30408     }
30409   }
30410
30411   /* Rollback any active transaction and free the handle structure.
30412   ** The call to sqlite3BtreeRollback() drops any table-locks held by
30413   ** this handle.
30414   */
30415   sqlite3BtreeRollback(p);
30416   sqlite3BtreeLeave(p);
30417
30418   /* If there are still other outstanding references to the shared-btree
30419   ** structure, return now. The remainder of this procedure cleans 
30420   ** up the shared-btree.
30421   */
30422   assert( p->wantToLock==0 && p->locked==0 );
30423   if( !p->sharable || removeFromSharingList(pBt) ){
30424     /* The pBt is no longer on the sharing list, so we can access
30425     ** it without having to hold the mutex.
30426     **
30427     ** Clean out and delete the BtShared object.
30428     */
30429     assert( !pBt->pCursor );
30430     sqlite3PagerClose(pBt->pPager);
30431     if( pBt->xFreeSchema && pBt->pSchema ){
30432       pBt->xFreeSchema(pBt->pSchema);
30433     }
30434     sqlite3_free(pBt->pSchema);
30435     sqlite3_free(pBt);
30436   }
30437
30438 #ifndef SQLITE_OMIT_SHARED_CACHE
30439   assert( p->wantToLock==0 );
30440   assert( p->locked==0 );
30441   if( p->pPrev ) p->pPrev->pNext = p->pNext;
30442   if( p->pNext ) p->pNext->pPrev = p->pPrev;
30443 #endif
30444
30445   sqlite3_free(p);
30446   return SQLITE_OK;
30447 }
30448
30449 /*
30450 ** Change the limit on the number of pages allowed in the cache.
30451 **
30452 ** The maximum number of cache pages is set to the absolute
30453 ** value of mxPage.  If mxPage is negative, the pager will
30454 ** operate asynchronously - it will not stop to do fsync()s
30455 ** to insure data is written to the disk surface before
30456 ** continuing.  Transactions still work if synchronous is off,
30457 ** and the database cannot be corrupted if this program
30458 ** crashes.  But if the operating system crashes or there is
30459 ** an abrupt power failure when synchronous is off, the database
30460 ** could be left in an inconsistent and unrecoverable state.
30461 ** Synchronous is on by default so database corruption is not
30462 ** normally a worry.
30463 */
30464 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
30465   BtShared *pBt = p->pBt;
30466   assert( sqlite3_mutex_held(p->db->mutex) );
30467   sqlite3BtreeEnter(p);
30468   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
30469   sqlite3BtreeLeave(p);
30470   return SQLITE_OK;
30471 }
30472
30473 /*
30474 ** Change the way data is synced to disk in order to increase or decrease
30475 ** how well the database resists damage due to OS crashes and power
30476 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
30477 ** there is a high probability of damage)  Level 2 is the default.  There
30478 ** is a very low but non-zero probability of damage.  Level 3 reduces the
30479 ** probability of damage to near zero but with a write performance reduction.
30480 */
30481 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
30482 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
30483   BtShared *pBt = p->pBt;
30484   assert( sqlite3_mutex_held(p->db->mutex) );
30485   sqlite3BtreeEnter(p);
30486   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
30487   sqlite3BtreeLeave(p);
30488   return SQLITE_OK;
30489 }
30490 #endif
30491
30492 /*
30493 ** Return TRUE if the given btree is set to safety level 1.  In other
30494 ** words, return TRUE if no sync() occurs on the disk files.
30495 */
30496 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
30497   BtShared *pBt = p->pBt;
30498   int rc;
30499   assert( sqlite3_mutex_held(p->db->mutex) );  
30500   sqlite3BtreeEnter(p);
30501   assert( pBt && pBt->pPager );
30502   rc = sqlite3PagerNosync(pBt->pPager);
30503   sqlite3BtreeLeave(p);
30504   return rc;
30505 }
30506
30507 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
30508 /*
30509 ** Change the default pages size and the number of reserved bytes per page.
30510 **
30511 ** The page size must be a power of 2 between 512 and 65536.  If the page
30512 ** size supplied does not meet this constraint then the page size is not
30513 ** changed.
30514 **
30515 ** Page sizes are constrained to be a power of two so that the region
30516 ** of the database file used for locking (beginning at PENDING_BYTE,
30517 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
30518 ** at the beginning of a page.
30519 **
30520 ** If parameter nReserve is less than zero, then the number of reserved
30521 ** bytes per page is left unchanged.
30522 */
30523 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
30524   int rc = SQLITE_OK;
30525   BtShared *pBt = p->pBt;
30526   sqlite3BtreeEnter(p);
30527   if( pBt->pageSizeFixed ){
30528     sqlite3BtreeLeave(p);
30529     return SQLITE_READONLY;
30530   }
30531   if( nReserve<0 ){
30532     nReserve = pBt->pageSize - pBt->usableSize;
30533   }
30534   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
30535         ((pageSize-1)&pageSize)==0 ){
30536     assert( (pageSize & 7)==0 );
30537     assert( !pBt->pPage1 && !pBt->pCursor );
30538     pBt->pageSize = pageSize;
30539     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
30540   }
30541   pBt->usableSize = pBt->pageSize - nReserve;
30542   sqlite3BtreeLeave(p);
30543   return rc;
30544 }
30545
30546 /*
30547 ** Return the currently defined page size
30548 */
30549 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
30550   return p->pBt->pageSize;
30551 }
30552 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
30553   int n;
30554   sqlite3BtreeEnter(p);
30555   n = p->pBt->pageSize - p->pBt->usableSize;
30556   sqlite3BtreeLeave(p);
30557   return n;
30558 }
30559
30560 /*
30561 ** Set the maximum page count for a database if mxPage is positive.
30562 ** No changes are made if mxPage is 0 or negative.
30563 ** Regardless of the value of mxPage, return the maximum page count.
30564 */
30565 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
30566   int n;
30567   sqlite3BtreeEnter(p);
30568   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
30569   sqlite3BtreeLeave(p);
30570   return n;
30571 }
30572 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
30573
30574 /*
30575 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
30576 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
30577 ** is disabled. The default value for the auto-vacuum property is 
30578 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
30579 */
30580 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
30581 #ifdef SQLITE_OMIT_AUTOVACUUM
30582   return SQLITE_READONLY;
30583 #else
30584   BtShared *pBt = p->pBt;
30585   int rc = SQLITE_OK;
30586   int av = (autoVacuum?1:0);
30587
30588   sqlite3BtreeEnter(p);
30589   if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
30590     rc = SQLITE_READONLY;
30591   }else{
30592     pBt->autoVacuum = av;
30593   }
30594   sqlite3BtreeLeave(p);
30595   return rc;
30596 #endif
30597 }
30598
30599 /*
30600 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
30601 ** enabled 1 is returned. Otherwise 0.
30602 */
30603 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
30604 #ifdef SQLITE_OMIT_AUTOVACUUM
30605   return BTREE_AUTOVACUUM_NONE;
30606 #else
30607   int rc;
30608   sqlite3BtreeEnter(p);
30609   rc = (
30610     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
30611     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
30612     BTREE_AUTOVACUUM_INCR
30613   );
30614   sqlite3BtreeLeave(p);
30615   return rc;
30616 #endif
30617 }
30618
30619
30620 /*
30621 ** Get a reference to pPage1 of the database file.  This will
30622 ** also acquire a readlock on that file.
30623 **
30624 ** SQLITE_OK is returned on success.  If the file is not a
30625 ** well-formed database file, then SQLITE_CORRUPT is returned.
30626 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
30627 ** is returned if we run out of memory. 
30628 */
30629 static int lockBtree(BtShared *pBt){
30630   int rc, pageSize;
30631   MemPage *pPage1;
30632
30633   assert( sqlite3_mutex_held(pBt->mutex) );
30634   if( pBt->pPage1 ) return SQLITE_OK;
30635   rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
30636   if( rc!=SQLITE_OK ) return rc;
30637   
30638
30639   /* Do some checking to help insure the file we opened really is
30640   ** a valid database file. 
30641   */
30642   rc = SQLITE_NOTADB;
30643   if( sqlite3PagerPagecount(pBt->pPager)>0 ){
30644     u8 *page1 = pPage1->aData;
30645     if( memcmp(page1, zMagicHeader, 16)!=0 ){
30646       goto page1_init_failed;
30647     }
30648     if( page1[18]>1 ){
30649       pBt->readOnly = 1;
30650     }
30651     if( page1[19]>1 ){
30652       goto page1_init_failed;
30653     }
30654     pageSize = get2byte(&page1[16]);
30655     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
30656         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
30657     ){
30658       goto page1_init_failed;
30659     }
30660     assert( (pageSize & 7)==0 );
30661     pBt->pageSize = pageSize;
30662     pBt->usableSize = pageSize - page1[20];
30663     if( pBt->usableSize<500 ){
30664       goto page1_init_failed;
30665     }
30666     pBt->maxEmbedFrac = page1[21];
30667     pBt->minEmbedFrac = page1[22];
30668     pBt->minLeafFrac = page1[23];
30669 #ifndef SQLITE_OMIT_AUTOVACUUM
30670     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
30671     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
30672 #endif
30673   }
30674
30675   /* maxLocal is the maximum amount of payload to store locally for
30676   ** a cell.  Make sure it is small enough so that at least minFanout
30677   ** cells can will fit on one page.  We assume a 10-byte page header.
30678   ** Besides the payload, the cell must store:
30679   **     2-byte pointer to the cell
30680   **     4-byte child pointer
30681   **     9-byte nKey value
30682   **     4-byte nData value
30683   **     4-byte overflow page pointer
30684   ** So a cell consists of a 2-byte poiner, a header which is as much as
30685   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
30686   ** page pointer.
30687   */
30688   pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
30689   pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
30690   pBt->maxLeaf = pBt->usableSize - 35;
30691   pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
30692   if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
30693     goto page1_init_failed;
30694   }
30695   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
30696   pBt->pPage1 = pPage1;
30697   return SQLITE_OK;
30698
30699 page1_init_failed:
30700   releasePage(pPage1);
30701   pBt->pPage1 = 0;
30702   return rc;
30703 }
30704
30705 /*
30706 ** This routine works like lockBtree() except that it also invokes the
30707 ** busy callback if there is lock contention.
30708 */
30709 static int lockBtreeWithRetry(Btree *pRef){
30710   int rc = SQLITE_OK;
30711
30712   assert( sqlite3BtreeHoldsMutex(pRef) );
30713   if( pRef->inTrans==TRANS_NONE ){
30714     u8 inTransaction = pRef->pBt->inTransaction;
30715     btreeIntegrity(pRef);
30716     rc = sqlite3BtreeBeginTrans(pRef, 0);
30717     pRef->pBt->inTransaction = inTransaction;
30718     pRef->inTrans = TRANS_NONE;
30719     if( rc==SQLITE_OK ){
30720       pRef->pBt->nTransaction--;
30721     }
30722     btreeIntegrity(pRef);
30723   }
30724   return rc;
30725 }
30726        
30727
30728 /*
30729 ** If there are no outstanding cursors and we are not in the middle
30730 ** of a transaction but there is a read lock on the database, then
30731 ** this routine unrefs the first page of the database file which 
30732 ** has the effect of releasing the read lock.
30733 **
30734 ** If there are any outstanding cursors, this routine is a no-op.
30735 **
30736 ** If there is a transaction in progress, this routine is a no-op.
30737 */
30738 static void unlockBtreeIfUnused(BtShared *pBt){
30739   assert( sqlite3_mutex_held(pBt->mutex) );
30740   if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
30741     if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
30742       assert( pBt->pPage1->aData );
30743 #if 0
30744       if( pBt->pPage1->aData==0 ){
30745         MemPage *pPage = pBt->pPage1;
30746         pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
30747         pPage->pBt = pBt;
30748         pPage->pgno = 1;
30749       }
30750 #endif
30751       releasePage(pBt->pPage1);
30752     }
30753     pBt->pPage1 = 0;
30754     pBt->inStmt = 0;
30755   }
30756 }
30757
30758 /*
30759 ** Create a new database by initializing the first page of the
30760 ** file.
30761 */
30762 static int newDatabase(BtShared *pBt){
30763   MemPage *pP1;
30764   unsigned char *data;
30765   int rc;
30766
30767   assert( sqlite3_mutex_held(pBt->mutex) );
30768   if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
30769   pP1 = pBt->pPage1;
30770   assert( pP1!=0 );
30771   data = pP1->aData;
30772   rc = sqlite3PagerWrite(pP1->pDbPage);
30773   if( rc ) return rc;
30774   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
30775   assert( sizeof(zMagicHeader)==16 );
30776   put2byte(&data[16], pBt->pageSize);
30777   data[18] = 1;
30778   data[19] = 1;
30779   data[20] = pBt->pageSize - pBt->usableSize;
30780   data[21] = pBt->maxEmbedFrac;
30781   data[22] = pBt->minEmbedFrac;
30782   data[23] = pBt->minLeafFrac;
30783   memset(&data[24], 0, 100-24);
30784   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
30785   pBt->pageSizeFixed = 1;
30786 #ifndef SQLITE_OMIT_AUTOVACUUM
30787   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
30788   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
30789   put4byte(&data[36 + 4*4], pBt->autoVacuum);
30790   put4byte(&data[36 + 7*4], pBt->incrVacuum);
30791 #endif
30792   return SQLITE_OK;
30793 }
30794
30795 /*
30796 ** Attempt to start a new transaction. A write-transaction
30797 ** is started if the second argument is nonzero, otherwise a read-
30798 ** transaction.  If the second argument is 2 or more and exclusive
30799 ** transaction is started, meaning that no other process is allowed
30800 ** to access the database.  A preexisting transaction may not be
30801 ** upgraded to exclusive by calling this routine a second time - the
30802 ** exclusivity flag only works for a new transaction.
30803 **
30804 ** A write-transaction must be started before attempting any 
30805 ** changes to the database.  None of the following routines 
30806 ** will work unless a transaction is started first:
30807 **
30808 **      sqlite3BtreeCreateTable()
30809 **      sqlite3BtreeCreateIndex()
30810 **      sqlite3BtreeClearTable()
30811 **      sqlite3BtreeDropTable()
30812 **      sqlite3BtreeInsert()
30813 **      sqlite3BtreeDelete()
30814 **      sqlite3BtreeUpdateMeta()
30815 **
30816 ** If an initial attempt to acquire the lock fails because of lock contention
30817 ** and the database was previously unlocked, then invoke the busy handler
30818 ** if there is one.  But if there was previously a read-lock, do not
30819 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
30820 ** returned when there is already a read-lock in order to avoid a deadlock.
30821 **
30822 ** Suppose there are two processes A and B.  A has a read lock and B has
30823 ** a reserved lock.  B tries to promote to exclusive but is blocked because
30824 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
30825 ** One or the other of the two processes must give way or there can be
30826 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
30827 ** when A already has a read lock, we encourage A to give up and let B
30828 ** proceed.
30829 */
30830 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
30831   BtShared *pBt = p->pBt;
30832   int rc = SQLITE_OK;
30833
30834   sqlite3BtreeEnter(p);
30835   pBt->db = p->db;
30836   btreeIntegrity(p);
30837
30838   /* If the btree is already in a write-transaction, or it
30839   ** is already in a read-transaction and a read-transaction
30840   ** is requested, this is a no-op.
30841   */
30842   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
30843     goto trans_begun;
30844   }
30845
30846   /* Write transactions are not possible on a read-only database */
30847   if( pBt->readOnly && wrflag ){
30848     rc = SQLITE_READONLY;
30849     goto trans_begun;
30850   }
30851
30852   /* If another database handle has already opened a write transaction 
30853   ** on this shared-btree structure and a second write transaction is
30854   ** requested, return SQLITE_BUSY.
30855   */
30856   if( pBt->inTransaction==TRANS_WRITE && wrflag ){
30857     rc = SQLITE_BUSY;
30858     goto trans_begun;
30859   }
30860
30861 #ifndef SQLITE_OMIT_SHARED_CACHE
30862   if( wrflag>1 ){
30863     BtLock *pIter;
30864     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
30865       if( pIter->pBtree!=p ){
30866         rc = SQLITE_BUSY;
30867         goto trans_begun;
30868       }
30869     }
30870   }
30871 #endif
30872
30873   do {
30874     if( pBt->pPage1==0 ){
30875       rc = lockBtree(pBt);
30876     }
30877
30878     if( rc==SQLITE_OK && wrflag ){
30879       if( pBt->readOnly ){
30880         rc = SQLITE_READONLY;
30881       }else{
30882         rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
30883         if( rc==SQLITE_OK ){
30884           rc = newDatabase(pBt);
30885         }
30886       }
30887     }
30888   
30889     if( rc==SQLITE_OK ){
30890       if( wrflag ) pBt->inStmt = 0;
30891     }else{
30892       unlockBtreeIfUnused(pBt);
30893     }
30894   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
30895           sqlite3BtreeInvokeBusyHandler(pBt, 0) );
30896
30897   if( rc==SQLITE_OK ){
30898     if( p->inTrans==TRANS_NONE ){
30899       pBt->nTransaction++;
30900     }
30901     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
30902     if( p->inTrans>pBt->inTransaction ){
30903       pBt->inTransaction = p->inTrans;
30904     }
30905 #ifndef SQLITE_OMIT_SHARED_CACHE
30906     if( wrflag>1 ){
30907       assert( !pBt->pExclusive );
30908       pBt->pExclusive = p;
30909     }
30910 #endif
30911   }
30912
30913
30914 trans_begun:
30915   btreeIntegrity(p);
30916   sqlite3BtreeLeave(p);
30917   return rc;
30918 }
30919
30920 #ifndef SQLITE_OMIT_AUTOVACUUM
30921
30922 /*
30923 ** Set the pointer-map entries for all children of page pPage. Also, if
30924 ** pPage contains cells that point to overflow pages, set the pointer
30925 ** map entries for the overflow pages as well.
30926 */
30927 static int setChildPtrmaps(MemPage *pPage){
30928   int i;                             /* Counter variable */
30929   int nCell;                         /* Number of cells in page pPage */
30930   int rc;                            /* Return code */
30931   BtShared *pBt = pPage->pBt;
30932   int isInitOrig = pPage->isInit;
30933   Pgno pgno = pPage->pgno;
30934
30935   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30936   rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
30937   if( rc!=SQLITE_OK ){
30938     goto set_child_ptrmaps_out;
30939   }
30940   nCell = pPage->nCell;
30941
30942   for(i=0; i<nCell; i++){
30943     u8 *pCell = findCell(pPage, i);
30944
30945     rc = ptrmapPutOvflPtr(pPage, pCell);
30946     if( rc!=SQLITE_OK ){
30947       goto set_child_ptrmaps_out;
30948     }
30949
30950     if( !pPage->leaf ){
30951       Pgno childPgno = get4byte(pCell);
30952       rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
30953       if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
30954     }
30955   }
30956
30957   if( !pPage->leaf ){
30958     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
30959     rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
30960   }
30961
30962 set_child_ptrmaps_out:
30963   pPage->isInit = isInitOrig;
30964   return rc;
30965 }
30966
30967 /*
30968 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
30969 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
30970 ** iTo. Parameter eType describes the type of pointer to be modified, as 
30971 ** follows:
30972 **
30973 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
30974 **                   page of pPage.
30975 **
30976 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
30977 **                   page pointed to by one of the cells on pPage.
30978 **
30979 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
30980 **                   overflow page in the list.
30981 */
30982 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
30983   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30984   if( eType==PTRMAP_OVERFLOW2 ){
30985     /* The pointer is always the first 4 bytes of the page in this case.  */
30986     if( get4byte(pPage->aData)!=iFrom ){
30987       return SQLITE_CORRUPT_BKPT;
30988     }
30989     put4byte(pPage->aData, iTo);
30990   }else{
30991     int isInitOrig = pPage->isInit;
30992     int i;
30993     int nCell;
30994
30995     sqlite3BtreeInitPage(pPage, 0);
30996     nCell = pPage->nCell;
30997
30998     for(i=0; i<nCell; i++){
30999       u8 *pCell = findCell(pPage, i);
31000       if( eType==PTRMAP_OVERFLOW1 ){
31001         CellInfo info;
31002         sqlite3BtreeParseCellPtr(pPage, pCell, &info);
31003         if( info.iOverflow ){
31004           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
31005             put4byte(&pCell[info.iOverflow], iTo);
31006             break;
31007           }
31008         }
31009       }else{
31010         if( get4byte(pCell)==iFrom ){
31011           put4byte(pCell, iTo);
31012           break;
31013         }
31014       }
31015     }
31016   
31017     if( i==nCell ){
31018       if( eType!=PTRMAP_BTREE || 
31019           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
31020         return SQLITE_CORRUPT_BKPT;
31021       }
31022       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
31023     }
31024
31025     pPage->isInit = isInitOrig;
31026   }
31027   return SQLITE_OK;
31028 }
31029
31030
31031 /*
31032 ** Move the open database page pDbPage to location iFreePage in the 
31033 ** database. The pDbPage reference remains valid.
31034 */
31035 static int relocatePage(
31036   BtShared *pBt,           /* Btree */
31037   MemPage *pDbPage,        /* Open page to move */
31038   u8 eType,                /* Pointer map 'type' entry for pDbPage */
31039   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
31040   Pgno iFreePage           /* The location to move pDbPage to */
31041 ){
31042   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
31043   Pgno iDbPage = pDbPage->pgno;
31044   Pager *pPager = pBt->pPager;
31045   int rc;
31046
31047   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
31048       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
31049   assert( sqlite3_mutex_held(pBt->mutex) );
31050   assert( pDbPage->pBt==pBt );
31051
31052   /* Move page iDbPage from its current location to page number iFreePage */
31053   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
31054       iDbPage, iFreePage, iPtrPage, eType));
31055   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
31056   if( rc!=SQLITE_OK ){
31057     return rc;
31058   }
31059   pDbPage->pgno = iFreePage;
31060
31061   /* If pDbPage was a btree-page, then it may have child pages and/or cells
31062   ** that point to overflow pages. The pointer map entries for all these
31063   ** pages need to be changed.
31064   **
31065   ** If pDbPage is an overflow page, then the first 4 bytes may store a
31066   ** pointer to a subsequent overflow page. If this is the case, then
31067   ** the pointer map needs to be updated for the subsequent overflow page.
31068   */
31069   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
31070     rc = setChildPtrmaps(pDbPage);
31071     if( rc!=SQLITE_OK ){
31072       return rc;
31073     }
31074   }else{
31075     Pgno nextOvfl = get4byte(pDbPage->aData);
31076     if( nextOvfl!=0 ){
31077       rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
31078       if( rc!=SQLITE_OK ){
31079         return rc;
31080       }
31081     }
31082   }
31083
31084   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
31085   ** that it points at iFreePage. Also fix the pointer map entry for
31086   ** iPtrPage.
31087   */
31088   if( eType!=PTRMAP_ROOTPAGE ){
31089     rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
31090     if( rc!=SQLITE_OK ){
31091       return rc;
31092     }
31093     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
31094     if( rc!=SQLITE_OK ){
31095       releasePage(pPtrPage);
31096       return rc;
31097     }
31098     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
31099     releasePage(pPtrPage);
31100     if( rc==SQLITE_OK ){
31101       rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
31102     }
31103   }
31104   return rc;
31105 }
31106
31107 /* Forward declaration required by incrVacuumStep(). */
31108 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
31109
31110 /*
31111 ** Perform a single step of an incremental-vacuum. If successful,
31112 ** return SQLITE_OK. If there is no work to do (and therefore no
31113 ** point in calling this function again), return SQLITE_DONE.
31114 **
31115 ** More specificly, this function attempts to re-organize the 
31116 ** database so that the last page of the file currently in use
31117 ** is no longer in use.
31118 **
31119 ** If the nFin parameter is non-zero, the implementation assumes
31120 ** that the caller will keep calling incrVacuumStep() until
31121 ** it returns SQLITE_DONE or an error, and that nFin is the
31122 ** number of pages the database file will contain after this 
31123 ** process is complete.
31124 */
31125 static int incrVacuumStep(BtShared *pBt, Pgno nFin){
31126   Pgno iLastPg;             /* Last page in the database */
31127   Pgno nFreeList;           /* Number of pages still on the free-list */
31128
31129   assert( sqlite3_mutex_held(pBt->mutex) );
31130   iLastPg = pBt->nTrunc;
31131   if( iLastPg==0 ){
31132     iLastPg = sqlite3PagerPagecount(pBt->pPager);
31133   }
31134
31135   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
31136     int rc;
31137     u8 eType;
31138     Pgno iPtrPage;
31139
31140     nFreeList = get4byte(&pBt->pPage1->aData[36]);
31141     if( nFreeList==0 || nFin==iLastPg ){
31142       return SQLITE_DONE;
31143     }
31144
31145     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
31146     if( rc!=SQLITE_OK ){
31147       return rc;
31148     }
31149     if( eType==PTRMAP_ROOTPAGE ){
31150       return SQLITE_CORRUPT_BKPT;
31151     }
31152
31153     if( eType==PTRMAP_FREEPAGE ){
31154       if( nFin==0 ){
31155         /* Remove the page from the files free-list. This is not required
31156         ** if nFin is non-zero. In that case, the free-list will be
31157         ** truncated to zero after this function returns, so it doesn't 
31158         ** matter if it still contains some garbage entries.
31159         */
31160         Pgno iFreePg;
31161         MemPage *pFreePg;
31162         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
31163         if( rc!=SQLITE_OK ){
31164           return rc;
31165         }
31166         assert( iFreePg==iLastPg );
31167         releasePage(pFreePg);
31168       }
31169     } else {
31170       Pgno iFreePg;             /* Index of free page to move pLastPg to */
31171       MemPage *pLastPg;
31172
31173       rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
31174       if( rc!=SQLITE_OK ){
31175         return rc;
31176       }
31177
31178       /* If nFin is zero, this loop runs exactly once and page pLastPg
31179       ** is swapped with the first free page pulled off the free list.
31180       **
31181       ** On the other hand, if nFin is greater than zero, then keep
31182       ** looping until a free-page located within the first nFin pages
31183       ** of the file is found.
31184       */
31185       do {
31186         MemPage *pFreePg;
31187         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
31188         if( rc!=SQLITE_OK ){
31189           releasePage(pLastPg);
31190           return rc;
31191         }
31192         releasePage(pFreePg);
31193       }while( nFin!=0 && iFreePg>nFin );
31194       assert( iFreePg<iLastPg );
31195       
31196       rc = sqlite3PagerWrite(pLastPg->pDbPage);
31197       if( rc==SQLITE_OK ){
31198         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
31199       }
31200       releasePage(pLastPg);
31201       if( rc!=SQLITE_OK ){
31202         return rc;
31203       }
31204     }
31205   }
31206
31207   pBt->nTrunc = iLastPg - 1;
31208   while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
31209     pBt->nTrunc--;
31210   }
31211   return SQLITE_OK;
31212 }
31213
31214 /*
31215 ** A write-transaction must be opened before calling this function.
31216 ** It performs a single unit of work towards an incremental vacuum.
31217 **
31218 ** If the incremental vacuum is finished after this function has run,
31219 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
31220 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
31221 */
31222 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
31223   int rc;
31224   BtShared *pBt = p->pBt;
31225
31226   sqlite3BtreeEnter(p);
31227   pBt->db = p->db;
31228   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
31229   if( !pBt->autoVacuum ){
31230     rc = SQLITE_DONE;
31231   }else{
31232     invalidateAllOverflowCache(pBt);
31233     rc = incrVacuumStep(pBt, 0);
31234   }
31235   sqlite3BtreeLeave(p);
31236   return rc;
31237 }
31238
31239 /*
31240 ** This routine is called prior to sqlite3PagerCommit when a transaction
31241 ** is commited for an auto-vacuum database.
31242 **
31243 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
31244 ** the database file should be truncated to during the commit process. 
31245 ** i.e. the database has been reorganized so that only the first *pnTrunc
31246 ** pages are in use.
31247 */
31248 static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
31249   int rc = SQLITE_OK;
31250   Pager *pPager = pBt->pPager;
31251 #ifndef NDEBUG
31252   int nRef = sqlite3PagerRefcount(pPager);
31253 #endif
31254
31255   assert( sqlite3_mutex_held(pBt->mutex) );
31256   invalidateAllOverflowCache(pBt);
31257   assert(pBt->autoVacuum);
31258   if( !pBt->incrVacuum ){
31259     Pgno nFin = 0;
31260
31261     if( pBt->nTrunc==0 ){
31262       Pgno nFree;
31263       Pgno nPtrmap;
31264       const int pgsz = pBt->pageSize;
31265       Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
31266
31267       if( PTRMAP_ISPAGE(pBt, nOrig) ){
31268         return SQLITE_CORRUPT_BKPT;
31269       }
31270       if( nOrig==PENDING_BYTE_PAGE(pBt) ){
31271         nOrig--;
31272       }
31273       nFree = get4byte(&pBt->pPage1->aData[36]);
31274       nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
31275       nFin = nOrig - nFree - nPtrmap;
31276       if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
31277         nFin--;
31278       }
31279       while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
31280         nFin--;
31281       }
31282     }
31283
31284     while( rc==SQLITE_OK ){
31285       rc = incrVacuumStep(pBt, nFin);
31286     }
31287     if( rc==SQLITE_DONE ){
31288       assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
31289       rc = SQLITE_OK;
31290       if( pBt->nTrunc ){
31291         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
31292         put4byte(&pBt->pPage1->aData[32], 0);
31293         put4byte(&pBt->pPage1->aData[36], 0);
31294         pBt->nTrunc = nFin;
31295       }
31296     }
31297     if( rc!=SQLITE_OK ){
31298       sqlite3PagerRollback(pPager);
31299     }
31300   }
31301
31302   if( rc==SQLITE_OK ){
31303     *pnTrunc = pBt->nTrunc;
31304     pBt->nTrunc = 0;
31305   }
31306   assert( nRef==sqlite3PagerRefcount(pPager) );
31307   return rc;
31308 }
31309
31310 #endif
31311
31312 /*
31313 ** This routine does the first phase of a two-phase commit.  This routine
31314 ** causes a rollback journal to be created (if it does not already exist)
31315 ** and populated with enough information so that if a power loss occurs
31316 ** the database can be restored to its original state by playing back
31317 ** the journal.  Then the contents of the journal are flushed out to
31318 ** the disk.  After the journal is safely on oxide, the changes to the
31319 ** database are written into the database file and flushed to oxide.
31320 ** At the end of this call, the rollback journal still exists on the
31321 ** disk and we are still holding all locks, so the transaction has not
31322 ** committed.  See sqlite3BtreeCommit() for the second phase of the
31323 ** commit process.
31324 **
31325 ** This call is a no-op if no write-transaction is currently active on pBt.
31326 **
31327 ** Otherwise, sync the database file for the btree pBt. zMaster points to
31328 ** the name of a master journal file that should be written into the
31329 ** individual journal file, or is NULL, indicating no master journal file 
31330 ** (single database transaction).
31331 **
31332 ** When this is called, the master journal should already have been
31333 ** created, populated with this journal pointer and synced to disk.
31334 **
31335 ** Once this is routine has returned, the only thing required to commit
31336 ** the write-transaction for this database file is to delete the journal.
31337 */
31338 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
31339   int rc = SQLITE_OK;
31340   if( p->inTrans==TRANS_WRITE ){
31341     BtShared *pBt = p->pBt;
31342     Pgno nTrunc = 0;
31343     sqlite3BtreeEnter(p);
31344     pBt->db = p->db;
31345 #ifndef SQLITE_OMIT_AUTOVACUUM
31346     if( pBt->autoVacuum ){
31347       rc = autoVacuumCommit(pBt, &nTrunc); 
31348       if( rc!=SQLITE_OK ){
31349         sqlite3BtreeLeave(p);
31350         return rc;
31351       }
31352     }
31353 #endif
31354     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc);
31355     sqlite3BtreeLeave(p);
31356   }
31357   return rc;
31358 }
31359
31360 /*
31361 ** Commit the transaction currently in progress.
31362 **
31363 ** This routine implements the second phase of a 2-phase commit.  The
31364 ** sqlite3BtreeSync() routine does the first phase and should be invoked
31365 ** prior to calling this routine.  The sqlite3BtreeSync() routine did
31366 ** all the work of writing information out to disk and flushing the
31367 ** contents so that they are written onto the disk platter.  All this
31368 ** routine has to do is delete or truncate the rollback journal
31369 ** (which causes the transaction to commit) and drop locks.
31370 **
31371 ** This will release the write lock on the database file.  If there
31372 ** are no active cursors, it also releases the read lock.
31373 */
31374 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
31375   BtShared *pBt = p->pBt;
31376
31377   sqlite3BtreeEnter(p);
31378   pBt->db = p->db;
31379   btreeIntegrity(p);
31380
31381   /* If the handle has a write-transaction open, commit the shared-btrees 
31382   ** transaction and set the shared state to TRANS_READ.
31383   */
31384   if( p->inTrans==TRANS_WRITE ){
31385     int rc;
31386     assert( pBt->inTransaction==TRANS_WRITE );
31387     assert( pBt->nTransaction>0 );
31388     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
31389     if( rc!=SQLITE_OK ){
31390       sqlite3BtreeLeave(p);
31391       return rc;
31392     }
31393     pBt->inTransaction = TRANS_READ;
31394     pBt->inStmt = 0;
31395   }
31396   unlockAllTables(p);
31397
31398   /* If the handle has any kind of transaction open, decrement the transaction
31399   ** count of the shared btree. If the transaction count reaches 0, set
31400   ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
31401   ** will unlock the pager.
31402   */
31403   if( p->inTrans!=TRANS_NONE ){
31404     pBt->nTransaction--;
31405     if( 0==pBt->nTransaction ){
31406       pBt->inTransaction = TRANS_NONE;
31407     }
31408   }
31409
31410   /* Set the handles current transaction state to TRANS_NONE and unlock
31411   ** the pager if this call closed the only read or write transaction.
31412   */
31413   p->inTrans = TRANS_NONE;
31414   unlockBtreeIfUnused(pBt);
31415
31416   btreeIntegrity(p);
31417   sqlite3BtreeLeave(p);
31418   return SQLITE_OK;
31419 }
31420
31421 /*
31422 ** Do both phases of a commit.
31423 */
31424 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
31425   int rc;
31426   sqlite3BtreeEnter(p);
31427   rc = sqlite3BtreeCommitPhaseOne(p, 0);
31428   if( rc==SQLITE_OK ){
31429     rc = sqlite3BtreeCommitPhaseTwo(p);
31430   }
31431   sqlite3BtreeLeave(p);
31432   return rc;
31433 }
31434
31435 #ifndef NDEBUG
31436 /*
31437 ** Return the number of write-cursors open on this handle. This is for use
31438 ** in assert() expressions, so it is only compiled if NDEBUG is not
31439 ** defined.
31440 **
31441 ** For the purposes of this routine, a write-cursor is any cursor that
31442 ** is capable of writing to the databse.  That means the cursor was
31443 ** originally opened for writing and the cursor has not be disabled
31444 ** by having its state changed to CURSOR_FAULT.
31445 */
31446 static int countWriteCursors(BtShared *pBt){
31447   BtCursor *pCur;
31448   int r = 0;
31449   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
31450     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
31451   }
31452   return r;
31453 }
31454 #endif
31455
31456 /*
31457 ** This routine sets the state to CURSOR_FAULT and the error
31458 ** code to errCode for every cursor on BtShared that pBtree
31459 ** references.
31460 **
31461 ** Every cursor is tripped, including cursors that belong
31462 ** to other database connections that happen to be sharing
31463 ** the cache with pBtree.
31464 **
31465 ** This routine gets called when a rollback occurs.
31466 ** All cursors using the same cache must be tripped
31467 ** to prevent them from trying to use the btree after
31468 ** the rollback.  The rollback may have deleted tables
31469 ** or moved root pages, so it is not sufficient to
31470 ** save the state of the cursor.  The cursor must be
31471 ** invalidated.
31472 */
31473 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
31474   BtCursor *p;
31475   sqlite3BtreeEnter(pBtree);
31476   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
31477     clearCursorPosition(p);
31478     p->eState = CURSOR_FAULT;
31479     p->skip = errCode;
31480   }
31481   sqlite3BtreeLeave(pBtree);
31482 }
31483
31484 /*
31485 ** Rollback the transaction in progress.  All cursors will be
31486 ** invalided by this operation.  Any attempt to use a cursor
31487 ** that was open at the beginning of this operation will result
31488 ** in an error.
31489 **
31490 ** This will release the write lock on the database file.  If there
31491 ** are no active cursors, it also releases the read lock.
31492 */
31493 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
31494   int rc;
31495   BtShared *pBt = p->pBt;
31496   MemPage *pPage1;
31497
31498   sqlite3BtreeEnter(p);
31499   pBt->db = p->db;
31500   rc = saveAllCursors(pBt, 0, 0);
31501 #ifndef SQLITE_OMIT_SHARED_CACHE
31502   if( rc!=SQLITE_OK ){
31503     /* This is a horrible situation. An IO or malloc() error occured whilst
31504     ** trying to save cursor positions. If this is an automatic rollback (as
31505     ** the result of a constraint, malloc() failure or IO error) then 
31506     ** the cache may be internally inconsistent (not contain valid trees) so
31507     ** we cannot simply return the error to the caller. Instead, abort 
31508     ** all queries that may be using any of the cursors that failed to save.
31509     */
31510     sqlite3BtreeTripAllCursors(p, rc);
31511   }
31512 #endif
31513   btreeIntegrity(p);
31514   unlockAllTables(p);
31515
31516   if( p->inTrans==TRANS_WRITE ){
31517     int rc2;
31518
31519 #ifndef SQLITE_OMIT_AUTOVACUUM
31520     pBt->nTrunc = 0;
31521 #endif
31522
31523     assert( TRANS_WRITE==pBt->inTransaction );
31524     rc2 = sqlite3PagerRollback(pBt->pPager);
31525     if( rc2!=SQLITE_OK ){
31526       rc = rc2;
31527     }
31528
31529     /* The rollback may have destroyed the pPage1->aData value.  So
31530     ** call sqlite3BtreeGetPage() on page 1 again to make
31531     ** sure pPage1->aData is set correctly. */
31532     if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
31533       releasePage(pPage1);
31534     }
31535     assert( countWriteCursors(pBt)==0 );
31536     pBt->inTransaction = TRANS_READ;
31537   }
31538
31539   if( p->inTrans!=TRANS_NONE ){
31540     assert( pBt->nTransaction>0 );
31541     pBt->nTransaction--;
31542     if( 0==pBt->nTransaction ){
31543       pBt->inTransaction = TRANS_NONE;
31544     }
31545   }
31546
31547   p->inTrans = TRANS_NONE;
31548   pBt->inStmt = 0;
31549   unlockBtreeIfUnused(pBt);
31550
31551   btreeIntegrity(p);
31552   sqlite3BtreeLeave(p);
31553   return rc;
31554 }
31555
31556 /*
31557 ** Start a statement subtransaction.  The subtransaction can
31558 ** can be rolled back independently of the main transaction.
31559 ** You must start a transaction before starting a subtransaction.
31560 ** The subtransaction is ended automatically if the main transaction
31561 ** commits or rolls back.
31562 **
31563 ** Only one subtransaction may be active at a time.  It is an error to try
31564 ** to start a new subtransaction if another subtransaction is already active.
31565 **
31566 ** Statement subtransactions are used around individual SQL statements
31567 ** that are contained within a BEGIN...COMMIT block.  If a constraint
31568 ** error occurs within the statement, the effect of that one statement
31569 ** can be rolled back without having to rollback the entire transaction.
31570 */
31571 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
31572   int rc;
31573   BtShared *pBt = p->pBt;
31574   sqlite3BtreeEnter(p);
31575   pBt->db = p->db;
31576   if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
31577     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
31578   }else{
31579     assert( pBt->inTransaction==TRANS_WRITE );
31580     rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
31581     pBt->inStmt = 1;
31582   }
31583   sqlite3BtreeLeave(p);
31584   return rc;
31585 }
31586
31587
31588 /*
31589 ** Commit the statment subtransaction currently in progress.  If no
31590 ** subtransaction is active, this is a no-op.
31591 */
31592 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
31593   int rc;
31594   BtShared *pBt = p->pBt;
31595   sqlite3BtreeEnter(p);
31596   pBt->db = p->db;
31597   if( pBt->inStmt && !pBt->readOnly ){
31598     rc = sqlite3PagerStmtCommit(pBt->pPager);
31599   }else{
31600     rc = SQLITE_OK;
31601   }
31602   pBt->inStmt = 0;
31603   sqlite3BtreeLeave(p);
31604   return rc;
31605 }
31606
31607 /*
31608 ** Rollback the active statement subtransaction.  If no subtransaction
31609 ** is active this routine is a no-op.
31610 **
31611 ** All cursors will be invalidated by this operation.  Any attempt
31612 ** to use a cursor that was open at the beginning of this operation
31613 ** will result in an error.
31614 */
31615 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
31616   int rc = SQLITE_OK;
31617   BtShared *pBt = p->pBt;
31618   sqlite3BtreeEnter(p);
31619   pBt->db = p->db;
31620   if( pBt->inStmt && !pBt->readOnly ){
31621     rc = sqlite3PagerStmtRollback(pBt->pPager);
31622     assert( countWriteCursors(pBt)==0 );
31623     pBt->inStmt = 0;
31624   }
31625   sqlite3BtreeLeave(p);
31626   return rc;
31627 }
31628
31629 /*
31630 ** Default key comparison function to be used if no comparison function
31631 ** is specified on the sqlite3BtreeCursor() call.
31632 */
31633 static int dfltCompare(
31634   void *NotUsed,             /* User data is not used */
31635   int n1, const void *p1,    /* First key to compare */
31636   int n2, const void *p2     /* Second key to compare */
31637 ){
31638   int c;
31639   c = memcmp(p1, p2, n1<n2 ? n1 : n2);
31640   if( c==0 ){
31641     c = n1 - n2;
31642   }
31643   return c;
31644 }
31645
31646 /*
31647 ** Create a new cursor for the BTree whose root is on the page
31648 ** iTable.  The act of acquiring a cursor gets a read lock on 
31649 ** the database file.
31650 **
31651 ** If wrFlag==0, then the cursor can only be used for reading.
31652 ** If wrFlag==1, then the cursor can be used for reading or for
31653 ** writing if other conditions for writing are also met.  These
31654 ** are the conditions that must be met in order for writing to
31655 ** be allowed:
31656 **
31657 ** 1:  The cursor must have been opened with wrFlag==1
31658 **
31659 ** 2:  Other database connections that share the same pager cache
31660 **     but which are not in the READ_UNCOMMITTED state may not have
31661 **     cursors open with wrFlag==0 on the same table.  Otherwise
31662 **     the changes made by this write cursor would be visible to
31663 **     the read cursors in the other database connection.
31664 **
31665 ** 3:  The database must be writable (not on read-only media)
31666 **
31667 ** 4:  There must be an active transaction.
31668 **
31669 ** No checking is done to make sure that page iTable really is the
31670 ** root page of a b-tree.  If it is not, then the cursor acquired
31671 ** will not work correctly.
31672 **
31673 ** The comparison function must be logically the same for every cursor
31674 ** on a particular table.  Changing the comparison function will result
31675 ** in incorrect operations.  If the comparison function is NULL, a
31676 ** default comparison function is used.  The comparison function is
31677 ** always ignored for INTKEY tables.
31678 */
31679 static int btreeCursor(
31680   Btree *p,                                   /* The btree */
31681   int iTable,                                 /* Root page of table to open */
31682   int wrFlag,                                 /* 1 to write. 0 read-only */
31683   int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
31684   void *pArg,                                 /* First arg to xCompare() */
31685   BtCursor **ppCur                            /* Write new cursor here */
31686 ){
31687   int rc;
31688   BtCursor *pCur;
31689   BtShared *pBt = p->pBt;
31690
31691   assert( sqlite3BtreeHoldsMutex(p) );
31692   *ppCur = 0;
31693   if( wrFlag ){
31694     if( pBt->readOnly ){
31695       return SQLITE_READONLY;
31696     }
31697     if( checkReadLocks(p, iTable, 0) ){
31698       return SQLITE_LOCKED;
31699     }
31700   }
31701
31702   if( pBt->pPage1==0 ){
31703     rc = lockBtreeWithRetry(p);
31704     if( rc!=SQLITE_OK ){
31705       return rc;
31706     }
31707     if( pBt->readOnly && wrFlag ){
31708       return SQLITE_READONLY;
31709     }
31710   }
31711   pCur = sqlite3MallocZero( sizeof(*pCur) );
31712   if( pCur==0 ){
31713     rc = SQLITE_NOMEM;
31714     goto create_cursor_exception;
31715   }
31716   pCur->pgnoRoot = (Pgno)iTable;
31717   if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
31718     rc = SQLITE_EMPTY;
31719     goto create_cursor_exception;
31720   }
31721   rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
31722   if( rc!=SQLITE_OK ){
31723     goto create_cursor_exception;
31724   }
31725
31726   /* Now that no other errors can occur, finish filling in the BtCursor
31727   ** variables, link the cursor into the BtShared list and set *ppCur (the
31728   ** output argument to this function).
31729   */
31730   pCur->xCompare = xCmp ? xCmp : dfltCompare;
31731   pCur->pArg = pArg;
31732   pCur->pBtree = p;
31733   pCur->pBt = pBt;
31734   pCur->wrFlag = wrFlag;
31735   pCur->pNext = pBt->pCursor;
31736   if( pCur->pNext ){
31737     pCur->pNext->pPrev = pCur;
31738   }
31739   pBt->pCursor = pCur;
31740   pCur->eState = CURSOR_INVALID;
31741   *ppCur = pCur;
31742
31743   return SQLITE_OK;
31744
31745 create_cursor_exception:
31746   if( pCur ){
31747     releasePage(pCur->pPage);
31748     sqlite3_free(pCur);
31749   }
31750   unlockBtreeIfUnused(pBt);
31751   return rc;
31752 }
31753 SQLITE_PRIVATE int sqlite3BtreeCursor(
31754   Btree *p,                                   /* The btree */
31755   int iTable,                                 /* Root page of table to open */
31756   int wrFlag,                                 /* 1 to write. 0 read-only */
31757   int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
31758   void *pArg,                                 /* First arg to xCompare() */
31759   BtCursor **ppCur                            /* Write new cursor here */
31760 ){
31761   int rc;
31762   sqlite3BtreeEnter(p);
31763   p->pBt->db = p->db;
31764   rc = btreeCursor(p, iTable, wrFlag, xCmp, pArg, ppCur);
31765   sqlite3BtreeLeave(p);
31766   return rc;
31767 }
31768
31769
31770 /*
31771 ** Close a cursor.  The read lock on the database file is released
31772 ** when the last cursor is closed.
31773 */
31774 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
31775   BtShared *pBt = pCur->pBt;
31776   Btree *pBtree = pCur->pBtree;
31777
31778   sqlite3BtreeEnter(pBtree);
31779   pBt->db = pBtree->db;
31780   clearCursorPosition(pCur);
31781   if( pCur->pPrev ){
31782     pCur->pPrev->pNext = pCur->pNext;
31783   }else{
31784     pBt->pCursor = pCur->pNext;
31785   }
31786   if( pCur->pNext ){
31787     pCur->pNext->pPrev = pCur->pPrev;
31788   }
31789   releasePage(pCur->pPage);
31790   unlockBtreeIfUnused(pBt);
31791   invalidateOverflowCache(pCur);
31792   sqlite3_free(pCur);
31793   sqlite3BtreeLeave(pBtree);
31794   return SQLITE_OK;
31795 }
31796
31797 /*
31798 ** Make a temporary cursor by filling in the fields of pTempCur.
31799 ** The temporary cursor is not on the cursor list for the Btree.
31800 */
31801 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
31802   assert( cursorHoldsMutex(pCur) );
31803   memcpy(pTempCur, pCur, sizeof(*pCur));
31804   pTempCur->pNext = 0;
31805   pTempCur->pPrev = 0;
31806   if( pTempCur->pPage ){
31807     sqlite3PagerRef(pTempCur->pPage->pDbPage);
31808   }
31809 }
31810
31811 /*
31812 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
31813 ** function above.
31814 */
31815 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
31816   assert( cursorHoldsMutex(pCur) );
31817   if( pCur->pPage ){
31818     sqlite3PagerUnref(pCur->pPage->pDbPage);
31819   }
31820 }
31821
31822 /*
31823 ** Make sure the BtCursor* given in the argument has a valid
31824 ** BtCursor.info structure.  If it is not already valid, call
31825 ** sqlite3BtreeParseCell() to fill it in.
31826 **
31827 ** BtCursor.info is a cache of the information in the current cell.
31828 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
31829 **
31830 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
31831 ** compiler to crash when getCellInfo() is implemented as a macro.
31832 ** But there is a measureable speed advantage to using the macro on gcc
31833 ** (when less compiler optimizations like -Os or -O0 are used and the
31834 ** compiler is not doing agressive inlining.)  So we use a real function
31835 ** for MSVC and a macro for everything else.  Ticket #2457.
31836 */
31837 #ifndef NDEBUG
31838   static void assertCellInfo(BtCursor *pCur){
31839     CellInfo info;
31840     memset(&info, 0, sizeof(info));
31841     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
31842     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
31843   }
31844 #else
31845   #define assertCellInfo(x)
31846 #endif
31847 #ifdef _MSC_VER
31848   /* Use a real function in MSVC to work around bugs in that compiler. */
31849   static void getCellInfo(BtCursor *pCur){
31850     if( pCur->info.nSize==0 ){
31851       sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
31852     }else{
31853       assertCellInfo(pCur);
31854     }
31855   }
31856 #else /* if not _MSC_VER */
31857   /* Use a macro in all other compilers so that the function is inlined */
31858 #define getCellInfo(pCur)                                               \
31859   if( pCur->info.nSize==0 ){                                            \
31860     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);         \
31861   }else{                                                                \
31862     assertCellInfo(pCur);                                               \
31863   }
31864 #endif /* _MSC_VER */
31865
31866 /*
31867 ** Set *pSize to the size of the buffer needed to hold the value of
31868 ** the key for the current entry.  If the cursor is not pointing
31869 ** to a valid entry, *pSize is set to 0. 
31870 **
31871 ** For a table with the INTKEY flag set, this routine returns the key
31872 ** itself, not the number of bytes in the key.
31873 */
31874 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
31875   int rc;
31876
31877   assert( cursorHoldsMutex(pCur) );
31878   rc = restoreOrClearCursorPosition(pCur);
31879   if( rc==SQLITE_OK ){
31880     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
31881     if( pCur->eState==CURSOR_INVALID ){
31882       *pSize = 0;
31883     }else{
31884       getCellInfo(pCur);
31885       *pSize = pCur->info.nKey;
31886     }
31887   }
31888   return rc;
31889 }
31890
31891 /*
31892 ** Set *pSize to the number of bytes of data in the entry the
31893 ** cursor currently points to.  Always return SQLITE_OK.
31894 ** Failure is not possible.  If the cursor is not currently
31895 ** pointing to an entry (which can happen, for example, if
31896 ** the database is empty) then *pSize is set to 0.
31897 */
31898 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
31899   int rc;
31900
31901   assert( cursorHoldsMutex(pCur) );
31902   rc = restoreOrClearCursorPosition(pCur);
31903   if( rc==SQLITE_OK ){
31904     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
31905     if( pCur->eState==CURSOR_INVALID ){
31906       /* Not pointing at a valid entry - set *pSize to 0. */
31907       *pSize = 0;
31908     }else{
31909       getCellInfo(pCur);
31910       *pSize = pCur->info.nData;
31911     }
31912   }
31913   return rc;
31914 }
31915
31916 /*
31917 ** Given the page number of an overflow page in the database (parameter
31918 ** ovfl), this function finds the page number of the next page in the 
31919 ** linked list of overflow pages. If possible, it uses the auto-vacuum
31920 ** pointer-map data instead of reading the content of page ovfl to do so. 
31921 **
31922 ** If an error occurs an SQLite error code is returned. Otherwise:
31923 **
31924 ** Unless pPgnoNext is NULL, the page number of the next overflow 
31925 ** page in the linked list is written to *pPgnoNext. If page ovfl
31926 ** is the last page in its linked list, *pPgnoNext is set to zero. 
31927 **
31928 ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
31929 ** for page ovfl. The underlying pager page may have been requested
31930 ** with the noContent flag set, so the page data accessable via
31931 ** this handle may not be trusted.
31932 */
31933 static int getOverflowPage(
31934   BtShared *pBt, 
31935   Pgno ovfl,                   /* Overflow page */
31936   MemPage **ppPage,            /* OUT: MemPage handle */
31937   Pgno *pPgnoNext              /* OUT: Next overflow page number */
31938 ){
31939   Pgno next = 0;
31940   int rc;
31941
31942   assert( sqlite3_mutex_held(pBt->mutex) );
31943   /* One of these must not be NULL. Otherwise, why call this function? */
31944   assert(ppPage || pPgnoNext);
31945
31946   /* If pPgnoNext is NULL, then this function is being called to obtain
31947   ** a MemPage* reference only. No page-data is required in this case.
31948   */
31949   if( !pPgnoNext ){
31950     return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
31951   }
31952
31953 #ifndef SQLITE_OMIT_AUTOVACUUM
31954   /* Try to find the next page in the overflow list using the
31955   ** autovacuum pointer-map pages. Guess that the next page in 
31956   ** the overflow list is page number (ovfl+1). If that guess turns 
31957   ** out to be wrong, fall back to loading the data of page 
31958   ** number ovfl to determine the next page number.
31959   */
31960   if( pBt->autoVacuum ){
31961     Pgno pgno;
31962     Pgno iGuess = ovfl+1;
31963     u8 eType;
31964
31965     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
31966       iGuess++;
31967     }
31968
31969     if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
31970       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
31971       if( rc!=SQLITE_OK ){
31972         return rc;
31973       }
31974       if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
31975         next = iGuess;
31976       }
31977     }
31978   }
31979 #endif
31980
31981   if( next==0 || ppPage ){
31982     MemPage *pPage = 0;
31983
31984     rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
31985     assert(rc==SQLITE_OK || pPage==0);
31986     if( next==0 && rc==SQLITE_OK ){
31987       next = get4byte(pPage->aData);
31988     }
31989
31990     if( ppPage ){
31991       *ppPage = pPage;
31992     }else{
31993       releasePage(pPage);
31994     }
31995   }
31996   *pPgnoNext = next;
31997
31998   return rc;
31999 }
32000
32001 /*
32002 ** Copy data from a buffer to a page, or from a page to a buffer.
32003 **
32004 ** pPayload is a pointer to data stored on database page pDbPage.
32005 ** If argument eOp is false, then nByte bytes of data are copied
32006 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
32007 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
32008 ** of data are copied from the buffer pBuf to pPayload.
32009 **
32010 ** SQLITE_OK is returned on success, otherwise an error code.
32011 */
32012 static int copyPayload(
32013   void *pPayload,           /* Pointer to page data */
32014   void *pBuf,               /* Pointer to buffer */
32015   int nByte,                /* Number of bytes to copy */
32016   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
32017   DbPage *pDbPage           /* Page containing pPayload */
32018 ){
32019   if( eOp ){
32020     /* Copy data from buffer to page (a write operation) */
32021     int rc = sqlite3PagerWrite(pDbPage);
32022     if( rc!=SQLITE_OK ){
32023       return rc;
32024     }
32025     memcpy(pPayload, pBuf, nByte);
32026   }else{
32027     /* Copy data from page to buffer (a read operation) */
32028     memcpy(pBuf, pPayload, nByte);
32029   }
32030   return SQLITE_OK;
32031 }
32032
32033 /*
32034 ** This function is used to read or overwrite payload information
32035 ** for the entry that the pCur cursor is pointing to. If the eOp
32036 ** parameter is 0, this is a read operation (data copied into
32037 ** buffer pBuf). If it is non-zero, a write (data copied from
32038 ** buffer pBuf).
32039 **
32040 ** A total of "amt" bytes are read or written beginning at "offset".
32041 ** Data is read to or from the buffer pBuf.
32042 **
32043 ** This routine does not make a distinction between key and data.
32044 ** It just reads or writes bytes from the payload area.  Data might 
32045 ** appear on the main page or be scattered out on multiple overflow 
32046 ** pages.
32047 **
32048 ** If the BtCursor.isIncrblobHandle flag is set, and the current
32049 ** cursor entry uses one or more overflow pages, this function
32050 ** allocates space for and lazily popluates the overflow page-list 
32051 ** cache array (BtCursor.aOverflow). Subsequent calls use this
32052 ** cache to make seeking to the supplied offset more efficient.
32053 **
32054 ** Once an overflow page-list cache has been allocated, it may be
32055 ** invalidated if some other cursor writes to the same table, or if
32056 ** the cursor is moved to a different row. Additionally, in auto-vacuum
32057 ** mode, the following events may invalidate an overflow page-list cache.
32058 **
32059 **   * An incremental vacuum,
32060 **   * A commit in auto_vacuum="full" mode,
32061 **   * Creating a table (may require moving an overflow page).
32062 */
32063 static int accessPayload(
32064   BtCursor *pCur,      /* Cursor pointing to entry to read from */
32065   int offset,          /* Begin reading this far into payload */
32066   int amt,             /* Read this many bytes */
32067   unsigned char *pBuf, /* Write the bytes into this buffer */ 
32068   int skipKey,         /* offset begins at data if this is true */
32069   int eOp              /* zero to read. non-zero to write. */
32070 ){
32071   unsigned char *aPayload;
32072   int rc = SQLITE_OK;
32073   u32 nKey;
32074   int iIdx = 0;
32075   MemPage *pPage = pCur->pPage;     /* Btree page of current cursor entry */
32076   BtShared *pBt;                   /* Btree this cursor belongs to */
32077
32078   assert( pPage );
32079   assert( pCur->eState==CURSOR_VALID );
32080   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
32081   assert( offset>=0 );
32082   assert( cursorHoldsMutex(pCur) );
32083
32084   getCellInfo(pCur);
32085   aPayload = pCur->info.pCell + pCur->info.nHeader;
32086   nKey = (pPage->intKey ? 0 : pCur->info.nKey);
32087
32088   if( skipKey ){
32089     offset += nKey;
32090   }
32091   if( offset+amt > nKey+pCur->info.nData ){
32092     /* Trying to read or write past the end of the data is an error */
32093     return SQLITE_ERROR;
32094   }
32095
32096   /* Check if data must be read/written to/from the btree page itself. */
32097   if( offset<pCur->info.nLocal ){
32098     int a = amt;
32099     if( a+offset>pCur->info.nLocal ){
32100       a = pCur->info.nLocal - offset;
32101     }
32102     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
32103     offset = 0;
32104     pBuf += a;
32105     amt -= a;
32106   }else{
32107     offset -= pCur->info.nLocal;
32108   }
32109
32110   pBt = pCur->pBt;
32111   if( rc==SQLITE_OK && amt>0 ){
32112     const int ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
32113     Pgno nextPage;
32114
32115     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
32116
32117 #ifndef SQLITE_OMIT_INCRBLOB
32118     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
32119     ** has not been allocated, allocate it now. The array is sized at
32120     ** one entry for each overflow page in the overflow chain. The
32121     ** page number of the first overflow page is stored in aOverflow[0],
32122     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
32123     ** (the cache is lazily populated).
32124     */
32125     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
32126       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
32127       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
32128       if( nOvfl && !pCur->aOverflow ){
32129         rc = SQLITE_NOMEM;
32130       }
32131     }
32132
32133     /* If the overflow page-list cache has been allocated and the
32134     ** entry for the first required overflow page is valid, skip
32135     ** directly to it.
32136     */
32137     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
32138       iIdx = (offset/ovflSize);
32139       nextPage = pCur->aOverflow[iIdx];
32140       offset = (offset%ovflSize);
32141     }
32142 #endif
32143
32144     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
32145
32146 #ifndef SQLITE_OMIT_INCRBLOB
32147       /* If required, populate the overflow page-list cache. */
32148       if( pCur->aOverflow ){
32149         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
32150         pCur->aOverflow[iIdx] = nextPage;
32151       }
32152 #endif
32153
32154       if( offset>=ovflSize ){
32155         /* The only reason to read this page is to obtain the page
32156         ** number for the next page in the overflow chain. The page
32157         ** data is not required. So first try to lookup the overflow
32158         ** page-list cache, if any, then fall back to the getOverflowPage()
32159         ** function.
32160         */
32161 #ifndef SQLITE_OMIT_INCRBLOB
32162         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
32163           nextPage = pCur->aOverflow[iIdx+1];
32164         } else 
32165 #endif
32166           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
32167         offset -= ovflSize;
32168       }else{
32169         /* Need to read this page properly. It contains some of the
32170         ** range of data that is being read (eOp==0) or written (eOp!=0).
32171         */
32172         DbPage *pDbPage;
32173         int a = amt;
32174         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
32175         if( rc==SQLITE_OK ){
32176           aPayload = sqlite3PagerGetData(pDbPage);
32177           nextPage = get4byte(aPayload);
32178           if( a + offset > ovflSize ){
32179             a = ovflSize - offset;
32180           }
32181           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
32182           sqlite3PagerUnref(pDbPage);
32183           offset = 0;
32184           amt -= a;
32185           pBuf += a;
32186         }
32187       }
32188     }
32189   }
32190
32191   if( rc==SQLITE_OK && amt>0 ){
32192     return SQLITE_CORRUPT_BKPT;
32193   }
32194   return rc;
32195 }
32196
32197 /*
32198 ** Read part of the key associated with cursor pCur.  Exactly
32199 ** "amt" bytes will be transfered into pBuf[].  The transfer
32200 ** begins at "offset".
32201 **
32202 ** Return SQLITE_OK on success or an error code if anything goes
32203 ** wrong.  An error is returned if "offset+amt" is larger than
32204 ** the available payload.
32205 */
32206 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
32207   int rc;
32208
32209   assert( cursorHoldsMutex(pCur) );
32210   rc = restoreOrClearCursorPosition(pCur);
32211   if( rc==SQLITE_OK ){
32212     assert( pCur->eState==CURSOR_VALID );
32213     assert( pCur->pPage!=0 );
32214     if( pCur->pPage->intKey ){
32215       return SQLITE_CORRUPT_BKPT;
32216     }
32217     assert( pCur->pPage->intKey==0 );
32218     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
32219     rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
32220   }
32221   return rc;
32222 }
32223
32224 /*
32225 ** Read part of the data associated with cursor pCur.  Exactly
32226 ** "amt" bytes will be transfered into pBuf[].  The transfer
32227 ** begins at "offset".
32228 **
32229 ** Return SQLITE_OK on success or an error code if anything goes
32230 ** wrong.  An error is returned if "offset+amt" is larger than
32231 ** the available payload.
32232 */
32233 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
32234   int rc;
32235
32236   assert( cursorHoldsMutex(pCur) );
32237   rc = restoreOrClearCursorPosition(pCur);
32238   if( rc==SQLITE_OK ){
32239     assert( pCur->eState==CURSOR_VALID );
32240     assert( pCur->pPage!=0 );
32241     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
32242     rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
32243   }
32244   return rc;
32245 }
32246
32247 /*
32248 ** Return a pointer to payload information from the entry that the 
32249 ** pCur cursor is pointing to.  The pointer is to the beginning of
32250 ** the key if skipKey==0 and it points to the beginning of data if
32251 ** skipKey==1.  The number of bytes of available key/data is written
32252 ** into *pAmt.  If *pAmt==0, then the value returned will not be
32253 ** a valid pointer.
32254 **
32255 ** This routine is an optimization.  It is common for the entire key
32256 ** and data to fit on the local page and for there to be no overflow
32257 ** pages.  When that is so, this routine can be used to access the
32258 ** key and data without making a copy.  If the key and/or data spills
32259 ** onto overflow pages, then accessPayload() must be used to reassembly
32260 ** the key/data and copy it into a preallocated buffer.
32261 **
32262 ** The pointer returned by this routine looks directly into the cached
32263 ** page of the database.  The data might change or move the next time
32264 ** any btree routine is called.
32265 */
32266 static const unsigned char *fetchPayload(
32267   BtCursor *pCur,      /* Cursor pointing to entry to read from */
32268   int *pAmt,           /* Write the number of available bytes here */
32269   int skipKey          /* read beginning at data if this is true */
32270 ){
32271   unsigned char *aPayload;
32272   MemPage *pPage;
32273   u32 nKey;
32274   int nLocal;
32275
32276   assert( pCur!=0 && pCur->pPage!=0 );
32277   assert( pCur->eState==CURSOR_VALID );
32278   assert( cursorHoldsMutex(pCur) );
32279   pPage = pCur->pPage;
32280   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
32281   getCellInfo(pCur);
32282   aPayload = pCur->info.pCell;
32283   aPayload += pCur->info.nHeader;
32284   if( pPage->intKey ){
32285     nKey = 0;
32286   }else{
32287     nKey = pCur->info.nKey;
32288   }
32289   if( skipKey ){
32290     aPayload += nKey;
32291     nLocal = pCur->info.nLocal - nKey;
32292   }else{
32293     nLocal = pCur->info.nLocal;
32294     if( nLocal>nKey ){
32295       nLocal = nKey;
32296     }
32297   }
32298   *pAmt = nLocal;
32299   return aPayload;
32300 }
32301
32302
32303 /*
32304 ** For the entry that cursor pCur is point to, return as
32305 ** many bytes of the key or data as are available on the local
32306 ** b-tree page.  Write the number of available bytes into *pAmt.
32307 **
32308 ** The pointer returned is ephemeral.  The key/data may move
32309 ** or be destroyed on the next call to any Btree routine,
32310 ** including calls from other threads against the same cache.
32311 ** Hence, a mutex on the BtShared should be held prior to calling
32312 ** this routine.
32313 **
32314 ** These routines is used to get quick access to key and data
32315 ** in the common case where no overflow pages are used.
32316 */
32317 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
32318   assert( cursorHoldsMutex(pCur) );
32319   if( pCur->eState==CURSOR_VALID ){
32320     return (const void*)fetchPayload(pCur, pAmt, 0);
32321   }
32322   return 0;
32323 }
32324 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
32325   assert( cursorHoldsMutex(pCur) );
32326   if( pCur->eState==CURSOR_VALID ){
32327     return (const void*)fetchPayload(pCur, pAmt, 1);
32328   }
32329   return 0;
32330 }
32331
32332
32333 /*
32334 ** Move the cursor down to a new child page.  The newPgno argument is the
32335 ** page number of the child page to move to.
32336 */
32337 static int moveToChild(BtCursor *pCur, u32 newPgno){
32338   int rc;
32339   MemPage *pNewPage;
32340   MemPage *pOldPage;
32341   BtShared *pBt = pCur->pBt;
32342
32343   assert( cursorHoldsMutex(pCur) );
32344   assert( pCur->eState==CURSOR_VALID );
32345   rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
32346   if( rc ) return rc;
32347   pNewPage->idxParent = pCur->idx;
32348   pOldPage = pCur->pPage;
32349   pOldPage->idxShift = 0;
32350   releasePage(pOldPage);
32351   pCur->pPage = pNewPage;
32352   pCur->idx = 0;
32353   pCur->info.nSize = 0;
32354   if( pNewPage->nCell<1 ){
32355     return SQLITE_CORRUPT_BKPT;
32356   }
32357   return SQLITE_OK;
32358 }
32359
32360 /*
32361 ** Return true if the page is the virtual root of its table.
32362 **
32363 ** The virtual root page is the root page for most tables.  But
32364 ** for the table rooted on page 1, sometime the real root page
32365 ** is empty except for the right-pointer.  In such cases the
32366 ** virtual root page is the page that the right-pointer of page
32367 ** 1 is pointing to.
32368 */
32369 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage){
32370   MemPage *pParent;
32371
32372   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
32373   pParent = pPage->pParent;
32374   if( pParent==0 ) return 1;
32375   if( pParent->pgno>1 ) return 0;
32376   if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
32377   return 0;
32378 }
32379
32380 /*
32381 ** Move the cursor up to the parent page.
32382 **
32383 ** pCur->idx is set to the cell index that contains the pointer
32384 ** to the page we are coming from.  If we are coming from the
32385 ** right-most child page then pCur->idx is set to one more than
32386 ** the largest cell index.
32387 */
32388 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
32389   MemPage *pParent;
32390   MemPage *pPage;
32391   int idxParent;
32392
32393   assert( cursorHoldsMutex(pCur) );
32394   assert( pCur->eState==CURSOR_VALID );
32395   pPage = pCur->pPage;
32396   assert( pPage!=0 );
32397   assert( !sqlite3BtreeIsRootPage(pPage) );
32398   pParent = pPage->pParent;
32399   assert( pParent!=0 );
32400   idxParent = pPage->idxParent;
32401   sqlite3PagerRef(pParent->pDbPage);
32402   releasePage(pPage);
32403   pCur->pPage = pParent;
32404   pCur->info.nSize = 0;
32405   assert( pParent->idxShift==0 );
32406   pCur->idx = idxParent;
32407 }
32408
32409 /*
32410 ** Move the cursor to the root page
32411 */
32412 static int moveToRoot(BtCursor *pCur){
32413   MemPage *pRoot;
32414   int rc = SQLITE_OK;
32415   Btree *p = pCur->pBtree;
32416   BtShared *pBt = p->pBt;
32417
32418   assert( cursorHoldsMutex(pCur) );
32419   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
32420   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
32421   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
32422   if( pCur->eState>=CURSOR_REQUIRESEEK ){
32423     if( pCur->eState==CURSOR_FAULT ){
32424       return pCur->skip;
32425     }
32426     clearCursorPosition(pCur);
32427   }
32428   pRoot = pCur->pPage;
32429   if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
32430     assert( pRoot->isInit );
32431   }else{
32432     if( 
32433       SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
32434     ){
32435       pCur->eState = CURSOR_INVALID;
32436       return rc;
32437     }
32438     releasePage(pCur->pPage);
32439     pCur->pPage = pRoot;
32440   }
32441   pCur->idx = 0;
32442   pCur->info.nSize = 0;
32443   if( pRoot->nCell==0 && !pRoot->leaf ){
32444     Pgno subpage;
32445     assert( pRoot->pgno==1 );
32446     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
32447     assert( subpage>0 );
32448     pCur->eState = CURSOR_VALID;
32449     rc = moveToChild(pCur, subpage);
32450   }
32451   pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
32452   return rc;
32453 }
32454
32455 /*
32456 ** Move the cursor down to the left-most leaf entry beneath the
32457 ** entry to which it is currently pointing.
32458 **
32459 ** The left-most leaf is the one with the smallest key - the first
32460 ** in ascending order.
32461 */
32462 static int moveToLeftmost(BtCursor *pCur){
32463   Pgno pgno;
32464   int rc = SQLITE_OK;
32465   MemPage *pPage;
32466
32467   assert( cursorHoldsMutex(pCur) );
32468   assert( pCur->eState==CURSOR_VALID );
32469   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
32470     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
32471     pgno = get4byte(findCell(pPage, pCur->idx));
32472     rc = moveToChild(pCur, pgno);
32473   }
32474   return rc;
32475 }
32476
32477 /*
32478 ** Move the cursor down to the right-most leaf entry beneath the
32479 ** page to which it is currently pointing.  Notice the difference
32480 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
32481 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
32482 ** finds the right-most entry beneath the *page*.
32483 **
32484 ** The right-most entry is the one with the largest key - the last
32485 ** key in ascending order.
32486 */
32487 static int moveToRightmost(BtCursor *pCur){
32488   Pgno pgno;
32489   int rc = SQLITE_OK;
32490   MemPage *pPage;
32491
32492   assert( cursorHoldsMutex(pCur) );
32493   assert( pCur->eState==CURSOR_VALID );
32494   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
32495     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
32496     pCur->idx = pPage->nCell;
32497     rc = moveToChild(pCur, pgno);
32498   }
32499   if( rc==SQLITE_OK ){
32500     pCur->idx = pPage->nCell - 1;
32501     pCur->info.nSize = 0;
32502   }
32503   return SQLITE_OK;
32504 }
32505
32506 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
32507 ** on success.  Set *pRes to 0 if the cursor actually points to something
32508 ** or set *pRes to 1 if the table is empty.
32509 */
32510 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
32511   int rc;
32512
32513   assert( cursorHoldsMutex(pCur) );
32514   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
32515   rc = moveToRoot(pCur);
32516   if( rc==SQLITE_OK ){
32517     if( pCur->eState==CURSOR_INVALID ){
32518       assert( pCur->pPage->nCell==0 );
32519       *pRes = 1;
32520       rc = SQLITE_OK;
32521     }else{
32522       assert( pCur->pPage->nCell>0 );
32523       *pRes = 0;
32524       rc = moveToLeftmost(pCur);
32525     }
32526   }
32527   return rc;
32528 }
32529
32530 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
32531 ** on success.  Set *pRes to 0 if the cursor actually points to something
32532 ** or set *pRes to 1 if the table is empty.
32533 */
32534 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
32535   int rc;
32536  
32537   assert( cursorHoldsMutex(pCur) );
32538   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
32539   rc = moveToRoot(pCur);
32540   if( rc==SQLITE_OK ){
32541     if( CURSOR_INVALID==pCur->eState ){
32542       assert( pCur->pPage->nCell==0 );
32543       *pRes = 1;
32544     }else{
32545       assert( pCur->eState==CURSOR_VALID );
32546       *pRes = 0;
32547       rc = moveToRightmost(pCur);
32548     }
32549   }
32550   return rc;
32551 }
32552
32553 /* Move the cursor so that it points to an entry near pKey/nKey.
32554 ** Return a success code.
32555 **
32556 ** For INTKEY tables, only the nKey parameter is used.  pKey is
32557 ** ignored.  For other tables, nKey is the number of bytes of data
32558 ** in pKey.  The comparison function specified when the cursor was
32559 ** created is used to compare keys.
32560 **
32561 ** If an exact match is not found, then the cursor is always
32562 ** left pointing at a leaf page which would hold the entry if it
32563 ** were present.  The cursor might point to an entry that comes
32564 ** before or after the key.
32565 **
32566 ** The result of comparing the key with the entry to which the
32567 ** cursor is written to *pRes if pRes!=NULL.  The meaning of
32568 ** this value is as follows:
32569 **
32570 **     *pRes<0      The cursor is left pointing at an entry that
32571 **                  is smaller than pKey or if the table is empty
32572 **                  and the cursor is therefore left point to nothing.
32573 **
32574 **     *pRes==0     The cursor is left pointing at an entry that
32575 **                  exactly matches pKey.
32576 **
32577 **     *pRes>0      The cursor is left pointing at an entry that
32578 **                  is larger than pKey.
32579 **
32580 */
32581 SQLITE_PRIVATE int sqlite3BtreeMoveto(
32582   BtCursor *pCur,        /* The cursor to be moved */
32583   const void *pKey,      /* The key content for indices.  Not used by tables */
32584   i64 nKey,              /* Size of pKey.  Or the key for tables */
32585   int biasRight,         /* If true, bias the search to the high end */
32586   int *pRes              /* Search result flag */
32587 ){
32588   int rc;
32589
32590   assert( cursorHoldsMutex(pCur) );
32591   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
32592   rc = moveToRoot(pCur);
32593   if( rc ){
32594     return rc;
32595   }
32596   assert( pCur->pPage );
32597   assert( pCur->pPage->isInit );
32598   if( pCur->eState==CURSOR_INVALID ){
32599     *pRes = -1;
32600     assert( pCur->pPage->nCell==0 );
32601     return SQLITE_OK;
32602   }
32603   for(;;){
32604     int lwr, upr;
32605     Pgno chldPg;
32606     MemPage *pPage = pCur->pPage;
32607     int c = -1;  /* pRes return if table is empty must be -1 */
32608     lwr = 0;
32609     upr = pPage->nCell-1;
32610     if( !pPage->intKey && pKey==0 ){
32611       return SQLITE_CORRUPT_BKPT;
32612     }
32613     if( biasRight ){
32614       pCur->idx = upr;
32615     }else{
32616       pCur->idx = (upr+lwr)/2;
32617     }
32618     if( lwr<=upr ) for(;;){
32619       void *pCellKey;
32620       i64 nCellKey;
32621       pCur->info.nSize = 0;
32622       if( pPage->intKey ){
32623         u8 *pCell;
32624         pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
32625         if( pPage->hasData ){
32626           u32 dummy;
32627           pCell += getVarint32(pCell, &dummy);
32628         }
32629         getVarint(pCell, (u64 *)&nCellKey);
32630         if( nCellKey<nKey ){
32631           c = -1;
32632         }else if( nCellKey>nKey ){
32633           c = +1;
32634         }else{
32635           c = 0;
32636         }
32637       }else{
32638         int available;
32639         pCellKey = (void *)fetchPayload(pCur, &available, 0);
32640         nCellKey = pCur->info.nKey;
32641         if( available>=nCellKey ){
32642           c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
32643         }else{
32644           pCellKey = sqlite3_malloc( nCellKey );
32645           if( pCellKey==0 ) return SQLITE_NOMEM;
32646           rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
32647           c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
32648           sqlite3_free(pCellKey);
32649           if( rc ){
32650             return rc;
32651           }
32652         }
32653       }
32654       if( c==0 ){
32655         if( pPage->leafData && !pPage->leaf ){
32656           lwr = pCur->idx;
32657           upr = lwr - 1;
32658           break;
32659         }else{
32660           if( pRes ) *pRes = 0;
32661           return SQLITE_OK;
32662         }
32663       }
32664       if( c<0 ){
32665         lwr = pCur->idx+1;
32666       }else{
32667         upr = pCur->idx-1;
32668       }
32669       if( lwr>upr ){
32670         break;
32671       }
32672       pCur->idx = (lwr+upr)/2;
32673     }
32674     assert( lwr==upr+1 );
32675     assert( pPage->isInit );
32676     if( pPage->leaf ){
32677       chldPg = 0;
32678     }else if( lwr>=pPage->nCell ){
32679       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
32680     }else{
32681       chldPg = get4byte(findCell(pPage, lwr));
32682     }
32683     if( chldPg==0 ){
32684       assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
32685       if( pRes ) *pRes = c;
32686       return SQLITE_OK;
32687     }
32688     pCur->idx = lwr;
32689     pCur->info.nSize = 0;
32690     rc = moveToChild(pCur, chldPg);
32691     if( rc ){
32692       return rc;
32693     }
32694   }
32695   /* NOT REACHED */
32696 }
32697
32698
32699 /*
32700 ** Return TRUE if the cursor is not pointing at an entry of the table.
32701 **
32702 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
32703 ** past the last entry in the table or sqlite3BtreePrev() moves past
32704 ** the first entry.  TRUE is also returned if the table is empty.
32705 */
32706 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
32707   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
32708   ** have been deleted? This API will need to change to return an error code
32709   ** as well as the boolean result value.
32710   */
32711   return (CURSOR_VALID!=pCur->eState);
32712 }
32713
32714 /*
32715 ** Return the database connection handle for a cursor.
32716 */
32717 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
32718   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
32719   return pCur->pBtree->db;
32720 }
32721
32722 /*
32723 ** Advance the cursor to the next entry in the database.  If
32724 ** successful then set *pRes=0.  If the cursor
32725 ** was already pointing to the last entry in the database before
32726 ** this routine was called, then set *pRes=1.
32727 */
32728 static int btreeNext(BtCursor *pCur, int *pRes){
32729   int rc;
32730   MemPage *pPage;
32731
32732   assert( cursorHoldsMutex(pCur) );
32733   rc = restoreOrClearCursorPosition(pCur);
32734   if( rc!=SQLITE_OK ){
32735     return rc;
32736   }
32737   assert( pRes!=0 );
32738   pPage = pCur->pPage;
32739   if( CURSOR_INVALID==pCur->eState ){
32740     *pRes = 1;
32741     return SQLITE_OK;
32742   }
32743   if( pCur->skip>0 ){
32744     pCur->skip = 0;
32745     *pRes = 0;
32746     return SQLITE_OK;
32747   }
32748   pCur->skip = 0;
32749
32750   assert( pPage->isInit );
32751   assert( pCur->idx<pPage->nCell );
32752
32753   pCur->idx++;
32754   pCur->info.nSize = 0;
32755   if( pCur->idx>=pPage->nCell ){
32756     if( !pPage->leaf ){
32757       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
32758       if( rc ) return rc;
32759       rc = moveToLeftmost(pCur);
32760       *pRes = 0;
32761       return rc;
32762     }
32763     do{
32764       if( sqlite3BtreeIsRootPage(pPage) ){
32765         *pRes = 1;
32766         pCur->eState = CURSOR_INVALID;
32767         return SQLITE_OK;
32768       }
32769       sqlite3BtreeMoveToParent(pCur);
32770       pPage = pCur->pPage;
32771     }while( pCur->idx>=pPage->nCell );
32772     *pRes = 0;
32773     if( pPage->leafData ){
32774       rc = sqlite3BtreeNext(pCur, pRes);
32775     }else{
32776       rc = SQLITE_OK;
32777     }
32778     return rc;
32779   }
32780   *pRes = 0;
32781   if( pPage->leaf ){
32782     return SQLITE_OK;
32783   }
32784   rc = moveToLeftmost(pCur);
32785   return rc;
32786 }
32787 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
32788   int rc;
32789   assert( cursorHoldsMutex(pCur) );
32790   rc = btreeNext(pCur, pRes);
32791   return rc;
32792 }
32793
32794
32795 /*
32796 ** Step the cursor to the back to the previous entry in the database.  If
32797 ** successful then set *pRes=0.  If the cursor
32798 ** was already pointing to the first entry in the database before
32799 ** this routine was called, then set *pRes=1.
32800 */
32801 static int btreePrevious(BtCursor *pCur, int *pRes){
32802   int rc;
32803   Pgno pgno;
32804   MemPage *pPage;
32805
32806   assert( cursorHoldsMutex(pCur) );
32807   rc = restoreOrClearCursorPosition(pCur);
32808   if( rc!=SQLITE_OK ){
32809     return rc;
32810   }
32811   if( CURSOR_INVALID==pCur->eState ){
32812     *pRes = 1;
32813     return SQLITE_OK;
32814   }
32815   if( pCur->skip<0 ){
32816     pCur->skip = 0;
32817     *pRes = 0;
32818     return SQLITE_OK;
32819   }
32820   pCur->skip = 0;
32821
32822   pPage = pCur->pPage;
32823   assert( pPage->isInit );
32824   assert( pCur->idx>=0 );
32825   if( !pPage->leaf ){
32826     pgno = get4byte( findCell(pPage, pCur->idx) );
32827     rc = moveToChild(pCur, pgno);
32828     if( rc ){
32829       return rc;
32830     }
32831     rc = moveToRightmost(pCur);
32832   }else{
32833     while( pCur->idx==0 ){
32834       if( sqlite3BtreeIsRootPage(pPage) ){
32835         pCur->eState = CURSOR_INVALID;
32836         *pRes = 1;
32837         return SQLITE_OK;
32838       }
32839       sqlite3BtreeMoveToParent(pCur);
32840       pPage = pCur->pPage;
32841     }
32842     pCur->idx--;
32843     pCur->info.nSize = 0;
32844     if( pPage->leafData && !pPage->leaf ){
32845       rc = sqlite3BtreePrevious(pCur, pRes);
32846     }else{
32847       rc = SQLITE_OK;
32848     }
32849   }
32850   *pRes = 0;
32851   return rc;
32852 }
32853 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
32854   int rc;
32855   assert( cursorHoldsMutex(pCur) );
32856   rc = btreePrevious(pCur, pRes);
32857   return rc;
32858 }
32859
32860 /*
32861 ** Allocate a new page from the database file.
32862 **
32863 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
32864 ** has already been called on the new page.)  The new page has also
32865 ** been referenced and the calling routine is responsible for calling
32866 ** sqlite3PagerUnref() on the new page when it is done.
32867 **
32868 ** SQLITE_OK is returned on success.  Any other return value indicates
32869 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
32870 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
32871 **
32872 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
32873 ** locate a page close to the page number "nearby".  This can be used in an
32874 ** attempt to keep related pages close to each other in the database file,
32875 ** which in turn can make database access faster.
32876 **
32877 ** If the "exact" parameter is not 0, and the page-number nearby exists 
32878 ** anywhere on the free-list, then it is guarenteed to be returned. This
32879 ** is only used by auto-vacuum databases when allocating a new table.
32880 */
32881 static int allocateBtreePage(
32882   BtShared *pBt, 
32883   MemPage **ppPage, 
32884   Pgno *pPgno, 
32885   Pgno nearby,
32886   u8 exact
32887 ){
32888   MemPage *pPage1;
32889   int rc;
32890   int n;     /* Number of pages on the freelist */
32891   int k;     /* Number of leaves on the trunk of the freelist */
32892   MemPage *pTrunk = 0;
32893   MemPage *pPrevTrunk = 0;
32894
32895   assert( sqlite3_mutex_held(pBt->mutex) );
32896   pPage1 = pBt->pPage1;
32897   n = get4byte(&pPage1->aData[36]);
32898   if( n>0 ){
32899     /* There are pages on the freelist.  Reuse one of those pages. */
32900     Pgno iTrunk;
32901     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
32902     
32903     /* If the 'exact' parameter was true and a query of the pointer-map
32904     ** shows that the page 'nearby' is somewhere on the free-list, then
32905     ** the entire-list will be searched for that page.
32906     */
32907 #ifndef SQLITE_OMIT_AUTOVACUUM
32908     if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){
32909       u8 eType;
32910       assert( nearby>0 );
32911       assert( pBt->autoVacuum );
32912       rc = ptrmapGet(pBt, nearby, &eType, 0);
32913       if( rc ) return rc;
32914       if( eType==PTRMAP_FREEPAGE ){
32915         searchList = 1;
32916       }
32917       *pPgno = nearby;
32918     }
32919 #endif
32920
32921     /* Decrement the free-list count by 1. Set iTrunk to the index of the
32922     ** first free-list trunk page. iPrevTrunk is initially 1.
32923     */
32924     rc = sqlite3PagerWrite(pPage1->pDbPage);
32925     if( rc ) return rc;
32926     put4byte(&pPage1->aData[36], n-1);
32927
32928     /* The code within this loop is run only once if the 'searchList' variable
32929     ** is not true. Otherwise, it runs once for each trunk-page on the
32930     ** free-list until the page 'nearby' is located.
32931     */
32932     do {
32933       pPrevTrunk = pTrunk;
32934       if( pPrevTrunk ){
32935         iTrunk = get4byte(&pPrevTrunk->aData[0]);
32936       }else{
32937         iTrunk = get4byte(&pPage1->aData[32]);
32938       }
32939       rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
32940       if( rc ){
32941         pTrunk = 0;
32942         goto end_allocate_page;
32943       }
32944
32945       k = get4byte(&pTrunk->aData[4]);
32946       if( k==0 && !searchList ){
32947         /* The trunk has no leaves and the list is not being searched. 
32948         ** So extract the trunk page itself and use it as the newly 
32949         ** allocated page */
32950         assert( pPrevTrunk==0 );
32951         rc = sqlite3PagerWrite(pTrunk->pDbPage);
32952         if( rc ){
32953           goto end_allocate_page;
32954         }
32955         *pPgno = iTrunk;
32956         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
32957         *ppPage = pTrunk;
32958         pTrunk = 0;
32959         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
32960       }else if( k>pBt->usableSize/4 - 8 ){
32961         /* Value of k is out of range.  Database corruption */
32962         rc = SQLITE_CORRUPT_BKPT;
32963         goto end_allocate_page;
32964 #ifndef SQLITE_OMIT_AUTOVACUUM
32965       }else if( searchList && nearby==iTrunk ){
32966         /* The list is being searched and this trunk page is the page
32967         ** to allocate, regardless of whether it has leaves.
32968         */
32969         assert( *pPgno==iTrunk );
32970         *ppPage = pTrunk;
32971         searchList = 0;
32972         rc = sqlite3PagerWrite(pTrunk->pDbPage);
32973         if( rc ){
32974           goto end_allocate_page;
32975         }
32976         if( k==0 ){
32977           if( !pPrevTrunk ){
32978             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
32979           }else{
32980             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
32981           }
32982         }else{
32983           /* The trunk page is required by the caller but it contains 
32984           ** pointers to free-list leaves. The first leaf becomes a trunk
32985           ** page in this case.
32986           */
32987           MemPage *pNewTrunk;
32988           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
32989           rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
32990           if( rc!=SQLITE_OK ){
32991             goto end_allocate_page;
32992           }
32993           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
32994           if( rc!=SQLITE_OK ){
32995             releasePage(pNewTrunk);
32996             goto end_allocate_page;
32997           }
32998           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
32999           put4byte(&pNewTrunk->aData[4], k-1);
33000           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
33001           releasePage(pNewTrunk);
33002           if( !pPrevTrunk ){
33003             put4byte(&pPage1->aData[32], iNewTrunk);
33004           }else{
33005             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
33006             if( rc ){
33007               goto end_allocate_page;
33008             }
33009             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
33010           }
33011         }
33012         pTrunk = 0;
33013         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
33014 #endif
33015       }else{
33016         /* Extract a leaf from the trunk */
33017         int closest;
33018         Pgno iPage;
33019         unsigned char *aData = pTrunk->aData;
33020         rc = sqlite3PagerWrite(pTrunk->pDbPage);
33021         if( rc ){
33022           goto end_allocate_page;
33023         }
33024         if( nearby>0 ){
33025           int i, dist;
33026           closest = 0;
33027           dist = get4byte(&aData[8]) - nearby;
33028           if( dist<0 ) dist = -dist;
33029           for(i=1; i<k; i++){
33030             int d2 = get4byte(&aData[8+i*4]) - nearby;
33031             if( d2<0 ) d2 = -d2;
33032             if( d2<dist ){
33033               closest = i;
33034               dist = d2;
33035             }
33036           }
33037         }else{
33038           closest = 0;
33039         }
33040
33041         iPage = get4byte(&aData[8+closest*4]);
33042         if( !searchList || iPage==nearby ){
33043           *pPgno = iPage;
33044           if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
33045             /* Free page off the end of the file */
33046             return SQLITE_CORRUPT_BKPT;
33047           }
33048           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
33049                  ": %d more free pages\n",
33050                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
33051           if( closest<k-1 ){
33052             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
33053           }
33054           put4byte(&aData[4], k-1);
33055           rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
33056           if( rc==SQLITE_OK ){
33057             sqlite3PagerDontRollback((*ppPage)->pDbPage);
33058             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
33059             if( rc!=SQLITE_OK ){
33060               releasePage(*ppPage);
33061             }
33062           }
33063           searchList = 0;
33064         }
33065       }
33066       releasePage(pPrevTrunk);
33067       pPrevTrunk = 0;
33068     }while( searchList );
33069   }else{
33070     /* There are no pages on the freelist, so create a new page at the
33071     ** end of the file */
33072     *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
33073
33074 #ifndef SQLITE_OMIT_AUTOVACUUM
33075     if( pBt->nTrunc ){
33076       /* An incr-vacuum has already run within this transaction. So the
33077       ** page to allocate is not from the physical end of the file, but
33078       ** at pBt->nTrunc. 
33079       */
33080       *pPgno = pBt->nTrunc+1;
33081       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
33082         (*pPgno)++;
33083       }
33084     }
33085     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
33086       /* If *pPgno refers to a pointer-map page, allocate two new pages
33087       ** at the end of the file instead of one. The first allocated page
33088       ** becomes a new pointer-map page, the second is used by the caller.
33089       */
33090       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
33091       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
33092       (*pPgno)++;
33093       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
33094     }
33095     if( pBt->nTrunc ){
33096       pBt->nTrunc = *pPgno;
33097     }
33098 #endif
33099
33100     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
33101     rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
33102     if( rc ) return rc;
33103     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
33104     if( rc!=SQLITE_OK ){
33105       releasePage(*ppPage);
33106     }
33107     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
33108   }
33109
33110   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
33111
33112 end_allocate_page:
33113   releasePage(pTrunk);
33114   releasePage(pPrevTrunk);
33115   return rc;
33116 }
33117
33118 /*
33119 ** Add a page of the database file to the freelist.
33120 **
33121 ** sqlite3PagerUnref() is NOT called for pPage.
33122 */
33123 static int freePage(MemPage *pPage){
33124   BtShared *pBt = pPage->pBt;
33125   MemPage *pPage1 = pBt->pPage1;
33126   int rc, n, k;
33127
33128   /* Prepare the page for freeing */
33129   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33130   assert( pPage->pgno>1 );
33131   pPage->isInit = 0;
33132   releasePage(pPage->pParent);
33133   pPage->pParent = 0;
33134
33135   /* Increment the free page count on pPage1 */
33136   rc = sqlite3PagerWrite(pPage1->pDbPage);
33137   if( rc ) return rc;
33138   n = get4byte(&pPage1->aData[36]);
33139   put4byte(&pPage1->aData[36], n+1);
33140
33141 #ifdef SQLITE_SECURE_DELETE
33142   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
33143   ** always fully overwrite deleted information with zeros.
33144   */
33145   rc = sqlite3PagerWrite(pPage->pDbPage);
33146   if( rc ) return rc;
33147   memset(pPage->aData, 0, pPage->pBt->pageSize);
33148 #endif
33149
33150 #ifndef SQLITE_OMIT_AUTOVACUUM
33151   /* If the database supports auto-vacuum, write an entry in the pointer-map
33152   ** to indicate that the page is free.
33153   */
33154   if( pBt->autoVacuum ){
33155     rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
33156     if( rc ) return rc;
33157   }
33158 #endif
33159
33160   if( n==0 ){
33161     /* This is the first free page */
33162     rc = sqlite3PagerWrite(pPage->pDbPage);
33163     if( rc ) return rc;
33164     memset(pPage->aData, 0, 8);
33165     put4byte(&pPage1->aData[32], pPage->pgno);
33166     TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
33167   }else{
33168     /* Other free pages already exist.  Retrive the first trunk page
33169     ** of the freelist and find out how many leaves it has. */
33170     MemPage *pTrunk;
33171     rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
33172     if( rc ) return rc;
33173     k = get4byte(&pTrunk->aData[4]);
33174     if( k>=pBt->usableSize/4 - 8 ){
33175       /* The trunk is full.  Turn the page being freed into a new
33176       ** trunk page with no leaves. */
33177       rc = sqlite3PagerWrite(pPage->pDbPage);
33178       if( rc==SQLITE_OK ){
33179         put4byte(pPage->aData, pTrunk->pgno);
33180         put4byte(&pPage->aData[4], 0);
33181         put4byte(&pPage1->aData[32], pPage->pgno);
33182         TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
33183                 pPage->pgno, pTrunk->pgno));
33184       }
33185     }else if( k<0 ){
33186       rc = SQLITE_CORRUPT;
33187     }else{
33188       /* Add the newly freed page as a leaf on the current trunk */
33189       rc = sqlite3PagerWrite(pTrunk->pDbPage);
33190       if( rc==SQLITE_OK ){
33191         put4byte(&pTrunk->aData[4], k+1);
33192         put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
33193 #ifndef SQLITE_SECURE_DELETE
33194         sqlite3PagerDontWrite(pPage->pDbPage);
33195 #endif
33196       }
33197       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
33198     }
33199     releasePage(pTrunk);
33200   }
33201   return rc;
33202 }
33203
33204 /*
33205 ** Free any overflow pages associated with the given Cell.
33206 */
33207 static int clearCell(MemPage *pPage, unsigned char *pCell){
33208   BtShared *pBt = pPage->pBt;
33209   CellInfo info;
33210   Pgno ovflPgno;
33211   int rc;
33212   int nOvfl;
33213   int ovflPageSize;
33214
33215   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33216   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
33217   if( info.iOverflow==0 ){
33218     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
33219   }
33220   ovflPgno = get4byte(&pCell[info.iOverflow]);
33221   ovflPageSize = pBt->usableSize - 4;
33222   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
33223   assert( ovflPgno==0 || nOvfl>0 );
33224   while( nOvfl-- ){
33225     MemPage *pOvfl;
33226     if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
33227       return SQLITE_CORRUPT_BKPT;
33228     }
33229
33230     rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
33231     if( rc ) return rc;
33232     rc = freePage(pOvfl);
33233     sqlite3PagerUnref(pOvfl->pDbPage);
33234     if( rc ) return rc;
33235   }
33236   return SQLITE_OK;
33237 }
33238
33239 /*
33240 ** Create the byte sequence used to represent a cell on page pPage
33241 ** and write that byte sequence into pCell[].  Overflow pages are
33242 ** allocated and filled in as necessary.  The calling procedure
33243 ** is responsible for making sure sufficient space has been allocated
33244 ** for pCell[].
33245 **
33246 ** Note that pCell does not necessary need to point to the pPage->aData
33247 ** area.  pCell might point to some temporary storage.  The cell will
33248 ** be constructed in this temporary area then copied into pPage->aData
33249 ** later.
33250 */
33251 static int fillInCell(
33252   MemPage *pPage,                /* The page that contains the cell */
33253   unsigned char *pCell,          /* Complete text of the cell */
33254   const void *pKey, i64 nKey,    /* The key */
33255   const void *pData,int nData,   /* The data */
33256   int nZero,                     /* Extra zero bytes to append to pData */
33257   int *pnSize                    /* Write cell size here */
33258 ){
33259   int nPayload;
33260   const u8 *pSrc;
33261   int nSrc, n, rc;
33262   int spaceLeft;
33263   MemPage *pOvfl = 0;
33264   MemPage *pToRelease = 0;
33265   unsigned char *pPrior;
33266   unsigned char *pPayload;
33267   BtShared *pBt = pPage->pBt;
33268   Pgno pgnoOvfl = 0;
33269   int nHeader;
33270   CellInfo info;
33271
33272   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33273
33274   /* Fill in the header. */
33275   nHeader = 0;
33276   if( !pPage->leaf ){
33277     nHeader += 4;
33278   }
33279   if( pPage->hasData ){
33280     nHeader += putVarint(&pCell[nHeader], nData+nZero);
33281   }else{
33282     nData = nZero = 0;
33283   }
33284   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
33285   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
33286   assert( info.nHeader==nHeader );
33287   assert( info.nKey==nKey );
33288   assert( info.nData==nData+nZero );
33289   
33290   /* Fill in the payload */
33291   nPayload = nData + nZero;
33292   if( pPage->intKey ){
33293     pSrc = pData;
33294     nSrc = nData;
33295     nData = 0;
33296   }else{
33297     nPayload += nKey;
33298     pSrc = pKey;
33299     nSrc = nKey;
33300   }
33301   *pnSize = info.nSize;
33302   spaceLeft = info.nLocal;
33303   pPayload = &pCell[nHeader];
33304   pPrior = &pCell[info.iOverflow];
33305
33306   while( nPayload>0 ){
33307     if( spaceLeft==0 ){
33308       int isExact = 0;
33309 #ifndef SQLITE_OMIT_AUTOVACUUM
33310       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
33311       if( pBt->autoVacuum ){
33312         do{
33313           pgnoOvfl++;
33314         } while( 
33315           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
33316         );
33317         if( pgnoOvfl>1 ){
33318           /* isExact = 1; */
33319         }
33320       }
33321 #endif
33322       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
33323 #ifndef SQLITE_OMIT_AUTOVACUUM
33324       /* If the database supports auto-vacuum, and the second or subsequent
33325       ** overflow page is being allocated, add an entry to the pointer-map
33326       ** for that page now. 
33327       **
33328       ** If this is the first overflow page, then write a partial entry 
33329       ** to the pointer-map. If we write nothing to this pointer-map slot,
33330       ** then the optimistic overflow chain processing in clearCell()
33331       ** may misinterpret the uninitialised values and delete the
33332       ** wrong pages from the database.
33333       */
33334       if( pBt->autoVacuum && rc==SQLITE_OK ){
33335         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
33336         rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
33337         if( rc ){
33338           releasePage(pOvfl);
33339         }
33340       }
33341 #endif
33342       if( rc ){
33343         releasePage(pToRelease);
33344         return rc;
33345       }
33346       put4byte(pPrior, pgnoOvfl);
33347       releasePage(pToRelease);
33348       pToRelease = pOvfl;
33349       pPrior = pOvfl->aData;
33350       put4byte(pPrior, 0);
33351       pPayload = &pOvfl->aData[4];
33352       spaceLeft = pBt->usableSize - 4;
33353     }
33354     n = nPayload;
33355     if( n>spaceLeft ) n = spaceLeft;
33356     if( nSrc>0 ){
33357       if( n>nSrc ) n = nSrc;
33358       assert( pSrc );
33359       memcpy(pPayload, pSrc, n);
33360     }else{
33361       memset(pPayload, 0, n);
33362     }
33363     nPayload -= n;
33364     pPayload += n;
33365     pSrc += n;
33366     nSrc -= n;
33367     spaceLeft -= n;
33368     if( nSrc==0 ){
33369       nSrc = nData;
33370       pSrc = pData;
33371     }
33372   }
33373   releasePage(pToRelease);
33374   return SQLITE_OK;
33375 }
33376
33377 /*
33378 ** Change the MemPage.pParent pointer on the page whose number is
33379 ** given in the second argument so that MemPage.pParent holds the
33380 ** pointer in the third argument.
33381 */
33382 static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
33383   MemPage *pThis;
33384   DbPage *pDbPage;
33385
33386   assert( sqlite3_mutex_held(pBt->mutex) );
33387   assert( pNewParent!=0 );
33388   if( pgno==0 ) return SQLITE_OK;
33389   assert( pBt->pPager!=0 );
33390   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
33391   if( pDbPage ){
33392     pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
33393     if( pThis->isInit ){
33394       assert( pThis->aData==sqlite3PagerGetData(pDbPage) );
33395       if( pThis->pParent!=pNewParent ){
33396         if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
33397         pThis->pParent = pNewParent;
33398         sqlite3PagerRef(pNewParent->pDbPage);
33399       }
33400       pThis->idxParent = idx;
33401     }
33402     sqlite3PagerUnref(pDbPage);
33403   }
33404
33405 #ifndef SQLITE_OMIT_AUTOVACUUM
33406   if( pBt->autoVacuum ){
33407     return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
33408   }
33409 #endif
33410   return SQLITE_OK;
33411 }
33412
33413
33414
33415 /*
33416 ** Change the pParent pointer of all children of pPage to point back
33417 ** to pPage.
33418 **
33419 ** In other words, for every child of pPage, invoke reparentPage()
33420 ** to make sure that each child knows that pPage is its parent.
33421 **
33422 ** This routine gets called after you memcpy() one page into
33423 ** another.
33424 */
33425 static int reparentChildPages(MemPage *pPage){
33426   int i;
33427   BtShared *pBt = pPage->pBt;
33428   int rc = SQLITE_OK;
33429
33430   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33431   if( pPage->leaf ) return SQLITE_OK;
33432
33433   for(i=0; i<pPage->nCell; i++){
33434     u8 *pCell = findCell(pPage, i);
33435     if( !pPage->leaf ){
33436       rc = reparentPage(pBt, get4byte(pCell), pPage, i);
33437       if( rc!=SQLITE_OK ) return rc;
33438     }
33439   }
33440   if( !pPage->leaf ){
33441     rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]), 
33442        pPage, i);
33443     pPage->idxShift = 0;
33444   }
33445   return rc;
33446 }
33447
33448 /*
33449 ** Remove the i-th cell from pPage.  This routine effects pPage only.
33450 ** The cell content is not freed or deallocated.  It is assumed that
33451 ** the cell content has been copied someplace else.  This routine just
33452 ** removes the reference to the cell from pPage.
33453 **
33454 ** "sz" must be the number of bytes in the cell.
33455 */
33456 static void dropCell(MemPage *pPage, int idx, int sz){
33457   int i;          /* Loop counter */
33458   int pc;         /* Offset to cell content of cell being deleted */
33459   u8 *data;       /* pPage->aData */
33460   u8 *ptr;        /* Used to move bytes around within data[] */
33461
33462   assert( idx>=0 && idx<pPage->nCell );
33463   assert( sz==cellSize(pPage, idx) );
33464   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
33465   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33466   data = pPage->aData;
33467   ptr = &data[pPage->cellOffset + 2*idx];
33468   pc = get2byte(ptr);
33469   assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
33470   freeSpace(pPage, pc, sz);
33471   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
33472     ptr[0] = ptr[2];
33473     ptr[1] = ptr[3];
33474   }
33475   pPage->nCell--;
33476   put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
33477   pPage->nFree += 2;
33478   pPage->idxShift = 1;
33479 }
33480
33481 /*
33482 ** Insert a new cell on pPage at cell index "i".  pCell points to the
33483 ** content of the cell.
33484 **
33485 ** If the cell content will fit on the page, then put it there.  If it
33486 ** will not fit, then make a copy of the cell content into pTemp if
33487 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
33488 ** in pPage->aOvfl[] and make it point to the cell content (either
33489 ** in pTemp or the original pCell) and also record its index. 
33490 ** Allocating a new entry in pPage->aCell[] implies that 
33491 ** pPage->nOverflow is incremented.
33492 **
33493 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
33494 ** cell. The caller will overwrite them after this function returns. If
33495 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
33496 ** (but pCell+nSkip is always valid).
33497 */
33498 static int insertCell(
33499   MemPage *pPage,   /* Page into which we are copying */
33500   int i,            /* New cell becomes the i-th cell of the page */
33501   u8 *pCell,        /* Content of the new cell */
33502   int sz,           /* Bytes of content in pCell */
33503   u8 *pTemp,        /* Temp storage space for pCell, if needed */
33504   u8 nSkip          /* Do not write the first nSkip bytes of the cell */
33505 ){
33506   int idx;          /* Where to write new cell content in data[] */
33507   int j;            /* Loop counter */
33508   int top;          /* First byte of content for any cell in data[] */
33509   int end;          /* First byte past the last cell pointer in data[] */
33510   int ins;          /* Index in data[] where new cell pointer is inserted */
33511   int hdr;          /* Offset into data[] of the page header */
33512   int cellOffset;   /* Address of first cell pointer in data[] */
33513   u8 *data;         /* The content of the whole page */
33514   u8 *ptr;          /* Used for moving information around in data[] */
33515
33516   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
33517   assert( sz==cellSizePtr(pPage, pCell) );
33518   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33519   if( pPage->nOverflow || sz+2>pPage->nFree ){
33520     if( pTemp ){
33521       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
33522       pCell = pTemp;
33523     }
33524     j = pPage->nOverflow++;
33525     assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
33526     pPage->aOvfl[j].pCell = pCell;
33527     pPage->aOvfl[j].idx = i;
33528     pPage->nFree = 0;
33529   }else{
33530     int rc = sqlite3PagerWrite(pPage->pDbPage);
33531     if( rc!=SQLITE_OK ){
33532       return rc;
33533     }
33534     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
33535     data = pPage->aData;
33536     hdr = pPage->hdrOffset;
33537     top = get2byte(&data[hdr+5]);
33538     cellOffset = pPage->cellOffset;
33539     end = cellOffset + 2*pPage->nCell + 2;
33540     ins = cellOffset + 2*i;
33541     if( end > top - sz ){
33542       rc = defragmentPage(pPage);
33543       if( rc!=SQLITE_OK ) return rc;
33544       top = get2byte(&data[hdr+5]);
33545       assert( end + sz <= top );
33546     }
33547     idx = allocateSpace(pPage, sz);
33548     assert( idx>0 );
33549     assert( end <= get2byte(&data[hdr+5]) );
33550     pPage->nCell++;
33551     pPage->nFree -= 2;
33552     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
33553     for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
33554       ptr[0] = ptr[-2];
33555       ptr[1] = ptr[-1];
33556     }
33557     put2byte(&data[ins], idx);
33558     put2byte(&data[hdr+3], pPage->nCell);
33559     pPage->idxShift = 1;
33560 #ifndef SQLITE_OMIT_AUTOVACUUM
33561     if( pPage->pBt->autoVacuum ){
33562       /* The cell may contain a pointer to an overflow page. If so, write
33563       ** the entry for the overflow page into the pointer map.
33564       */
33565       CellInfo info;
33566       sqlite3BtreeParseCellPtr(pPage, pCell, &info);
33567       assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
33568       if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
33569         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
33570         rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
33571         if( rc!=SQLITE_OK ) return rc;
33572       }
33573     }
33574 #endif
33575   }
33576
33577   return SQLITE_OK;
33578 }
33579
33580 /*
33581 ** Add a list of cells to a page.  The page should be initially empty.
33582 ** The cells are guaranteed to fit on the page.
33583 */
33584 static void assemblePage(
33585   MemPage *pPage,   /* The page to be assemblied */
33586   int nCell,        /* The number of cells to add to this page */
33587   u8 **apCell,      /* Pointers to cell bodies */
33588   u16 *aSize        /* Sizes of the cells */
33589 ){
33590   int i;            /* Loop counter */
33591   int totalSize;    /* Total size of all cells */
33592   int hdr;          /* Index of page header */
33593   int cellptr;      /* Address of next cell pointer */
33594   int cellbody;     /* Address of next cell body */
33595   u8 *data;         /* Data for the page */
33596
33597   assert( pPage->nOverflow==0 );
33598   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33599   totalSize = 0;
33600   for(i=0; i<nCell; i++){
33601     totalSize += aSize[i];
33602   }
33603   assert( totalSize+2*nCell<=pPage->nFree );
33604   assert( pPage->nCell==0 );
33605   cellptr = pPage->cellOffset;
33606   data = pPage->aData;
33607   hdr = pPage->hdrOffset;
33608   put2byte(&data[hdr+3], nCell);
33609   if( nCell ){
33610     cellbody = allocateSpace(pPage, totalSize);
33611     assert( cellbody>0 );
33612     assert( pPage->nFree >= 2*nCell );
33613     pPage->nFree -= 2*nCell;
33614     for(i=0; i<nCell; i++){
33615       put2byte(&data[cellptr], cellbody);
33616       memcpy(&data[cellbody], apCell[i], aSize[i]);
33617       cellptr += 2;
33618       cellbody += aSize[i];
33619     }
33620     assert( cellbody==pPage->pBt->usableSize );
33621   }
33622   pPage->nCell = nCell;
33623 }
33624
33625 /*
33626 ** The following parameters determine how many adjacent pages get involved
33627 ** in a balancing operation.  NN is the number of neighbors on either side
33628 ** of the page that participate in the balancing operation.  NB is the
33629 ** total number of pages that participate, including the target page and
33630 ** NN neighbors on either side.
33631 **
33632 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
33633 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
33634 ** in exchange for a larger degradation in INSERT and UPDATE performance.
33635 ** The value of NN appears to give the best results overall.
33636 */
33637 #define NN 1             /* Number of neighbors on either side of pPage */
33638 #define NB (NN*2+1)      /* Total pages involved in the balance */
33639
33640 /* Forward reference */
33641 static int balance(MemPage*, int);
33642
33643 #ifndef SQLITE_OMIT_QUICKBALANCE
33644 /*
33645 ** This version of balance() handles the common special case where
33646 ** a new entry is being inserted on the extreme right-end of the
33647 ** tree, in other words, when the new entry will become the largest
33648 ** entry in the tree.
33649 **
33650 ** Instead of trying balance the 3 right-most leaf pages, just add
33651 ** a new page to the right-hand side and put the one new entry in
33652 ** that page.  This leaves the right side of the tree somewhat
33653 ** unbalanced.  But odds are that we will be inserting new entries
33654 ** at the end soon afterwards so the nearly empty page will quickly
33655 ** fill up.  On average.
33656 **
33657 ** pPage is the leaf page which is the right-most page in the tree.
33658 ** pParent is its parent.  pPage must have a single overflow entry
33659 ** which is also the right-most entry on the page.
33660 */
33661 static int balance_quick(MemPage *pPage, MemPage *pParent){
33662   int rc;
33663   MemPage *pNew;
33664   Pgno pgnoNew;
33665   u8 *pCell;
33666   u16 szCell;
33667   CellInfo info;
33668   BtShared *pBt = pPage->pBt;
33669   int parentIdx = pParent->nCell;   /* pParent new divider cell index */
33670   int parentSize;                   /* Size of new divider cell */
33671   u8 parentCell[64];                /* Space for the new divider cell */
33672
33673   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33674
33675   /* Allocate a new page. Insert the overflow cell from pPage
33676   ** into it. Then remove the overflow cell from pPage.
33677   */
33678   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
33679   if( rc!=SQLITE_OK ){
33680     return rc;
33681   }
33682   pCell = pPage->aOvfl[0].pCell;
33683   szCell = cellSizePtr(pPage, pCell);
33684   zeroPage(pNew, pPage->aData[0]);
33685   assemblePage(pNew, 1, &pCell, &szCell);
33686   pPage->nOverflow = 0;
33687
33688   /* Set the parent of the newly allocated page to pParent. */
33689   pNew->pParent = pParent;
33690   sqlite3PagerRef(pParent->pDbPage);
33691
33692   /* pPage is currently the right-child of pParent. Change this
33693   ** so that the right-child is the new page allocated above and
33694   ** pPage is the next-to-right child. 
33695   */
33696   assert( pPage->nCell>0 );
33697   pCell = findCell(pPage, pPage->nCell-1);
33698   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
33699   rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
33700   if( rc!=SQLITE_OK ){
33701     return rc;
33702   }
33703   assert( parentSize<64 );
33704   rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
33705   if( rc!=SQLITE_OK ){
33706     return rc;
33707   }
33708   put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
33709   put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
33710
33711 #ifndef SQLITE_OMIT_AUTOVACUUM
33712   /* If this is an auto-vacuum database, update the pointer map
33713   ** with entries for the new page, and any pointer from the 
33714   ** cell on the page to an overflow page.
33715   */
33716   if( pBt->autoVacuum ){
33717     rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
33718     if( rc==SQLITE_OK ){
33719       rc = ptrmapPutOvfl(pNew, 0);
33720     }
33721     if( rc!=SQLITE_OK ){
33722       releasePage(pNew);
33723       return rc;
33724     }
33725   }
33726 #endif
33727
33728   /* Release the reference to the new page and balance the parent page,
33729   ** in case the divider cell inserted caused it to become overfull.
33730   */
33731   releasePage(pNew);
33732   return balance(pParent, 0);
33733 }
33734 #endif /* SQLITE_OMIT_QUICKBALANCE */
33735
33736 /*
33737 ** This routine redistributes Cells on pPage and up to NN*2 siblings
33738 ** of pPage so that all pages have about the same amount of free space.
33739 ** Usually NN siblings on either side of pPage is used in the balancing,
33740 ** though more siblings might come from one side if pPage is the first
33741 ** or last child of its parent.  If pPage has fewer than 2*NN siblings
33742 ** (something which can only happen if pPage is the root page or a 
33743 ** child of root) then all available siblings participate in the balancing.
33744 **
33745 ** The number of siblings of pPage might be increased or decreased by one or
33746 ** two in an effort to keep pages nearly full but not over full. The root page
33747 ** is special and is allowed to be nearly empty. If pPage is 
33748 ** the root page, then the depth of the tree might be increased
33749 ** or decreased by one, as necessary, to keep the root page from being
33750 ** overfull or completely empty.
33751 **
33752 ** Note that when this routine is called, some of the Cells on pPage
33753 ** might not actually be stored in pPage->aData[].  This can happen
33754 ** if the page is overfull.  Part of the job of this routine is to
33755 ** make sure all Cells for pPage once again fit in pPage->aData[].
33756 **
33757 ** In the course of balancing the siblings of pPage, the parent of pPage
33758 ** might become overfull or underfull.  If that happens, then this routine
33759 ** is called recursively on the parent.
33760 **
33761 ** If this routine fails for any reason, it might leave the database
33762 ** in a corrupted state.  So if this routine fails, the database should
33763 ** be rolled back.
33764 */
33765 static int balance_nonroot(MemPage *pPage){
33766   MemPage *pParent;            /* The parent of pPage */
33767   BtShared *pBt;               /* The whole database */
33768   int nCell = 0;               /* Number of cells in apCell[] */
33769   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
33770   int nOld;                    /* Number of pages in apOld[] */
33771   int nNew;                    /* Number of pages in apNew[] */
33772   int nDiv;                    /* Number of cells in apDiv[] */
33773   int i, j, k;                 /* Loop counters */
33774   int idx;                     /* Index of pPage in pParent->aCell[] */
33775   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
33776   int rc;                      /* The return code */
33777   int leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
33778   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
33779   int usableSpace;             /* Bytes in pPage beyond the header */
33780   int pageFlags;               /* Value of pPage->aData[0] */
33781   int subtotal;                /* Subtotal of bytes in cells on one page */
33782   int iSpace = 0;              /* First unused byte of aSpace[] */
33783   MemPage *apOld[NB];          /* pPage and up to two siblings */
33784   Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
33785   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
33786   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
33787   Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
33788   u8 *apDiv[NB];               /* Divider cells in pParent */
33789   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
33790   int szNew[NB+2];             /* Combined size of cells place on i-th page */
33791   u8 **apCell = 0;             /* All cells begin balanced */
33792   u16 *szCell;                 /* Local size of all cells in apCell[] */
33793   u8 *aCopy[NB];               /* Space for holding data of apCopy[] */
33794   u8 *aSpace;                  /* Space to hold copies of dividers cells */
33795 #ifndef SQLITE_OMIT_AUTOVACUUM
33796   u8 *aFrom = 0;
33797 #endif
33798
33799   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33800
33801   /* 
33802   ** Find the parent page.
33803   */
33804   assert( pPage->isInit );
33805   assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
33806   pBt = pPage->pBt;
33807   pParent = pPage->pParent;
33808   assert( pParent );
33809   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
33810     return rc;
33811   }
33812   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
33813
33814 #ifndef SQLITE_OMIT_QUICKBALANCE
33815   /*
33816   ** A special case:  If a new entry has just been inserted into a
33817   ** table (that is, a btree with integer keys and all data at the leaves)
33818   ** and the new entry is the right-most entry in the tree (it has the
33819   ** largest key) then use the special balance_quick() routine for
33820   ** balancing.  balance_quick() is much faster and results in a tighter
33821   ** packing of data in the common case.
33822   */
33823   if( pPage->leaf &&
33824       pPage->intKey &&
33825       pPage->leafData &&
33826       pPage->nOverflow==1 &&
33827       pPage->aOvfl[0].idx==pPage->nCell &&
33828       pPage->pParent->pgno!=1 &&
33829       get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
33830   ){
33831     /*
33832     ** TODO: Check the siblings to the left of pPage. It may be that
33833     ** they are not full and no new page is required.
33834     */
33835     return balance_quick(pPage, pParent);
33836   }
33837 #endif
33838
33839   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
33840     return rc;
33841   }
33842
33843   /*
33844   ** Find the cell in the parent page whose left child points back
33845   ** to pPage.  The "idx" variable is the index of that cell.  If pPage
33846   ** is the rightmost child of pParent then set idx to pParent->nCell 
33847   */
33848   if( pParent->idxShift ){
33849     Pgno pgno;
33850     pgno = pPage->pgno;
33851     assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
33852     for(idx=0; idx<pParent->nCell; idx++){
33853       if( get4byte(findCell(pParent, idx))==pgno ){
33854         break;
33855       }
33856     }
33857     assert( idx<pParent->nCell
33858              || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
33859   }else{
33860     idx = pPage->idxParent;
33861   }
33862
33863   /*
33864   ** Initialize variables so that it will be safe to jump
33865   ** directly to balance_cleanup at any moment.
33866   */
33867   nOld = nNew = 0;
33868   sqlite3PagerRef(pParent->pDbPage);
33869
33870   /*
33871   ** Find sibling pages to pPage and the cells in pParent that divide
33872   ** the siblings.  An attempt is made to find NN siblings on either
33873   ** side of pPage.  More siblings are taken from one side, however, if
33874   ** pPage there are fewer than NN siblings on the other side.  If pParent
33875   ** has NB or fewer children then all children of pParent are taken.
33876   */
33877   nxDiv = idx - NN;
33878   if( nxDiv + NB > pParent->nCell ){
33879     nxDiv = pParent->nCell - NB + 1;
33880   }
33881   if( nxDiv<0 ){
33882     nxDiv = 0;
33883   }
33884   nDiv = 0;
33885   for(i=0, k=nxDiv; i<NB; i++, k++){
33886     if( k<pParent->nCell ){
33887       apDiv[i] = findCell(pParent, k);
33888       nDiv++;
33889       assert( !pParent->leaf );
33890       pgnoOld[i] = get4byte(apDiv[i]);
33891     }else if( k==pParent->nCell ){
33892       pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
33893     }else{
33894       break;
33895     }
33896     rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
33897     if( rc ) goto balance_cleanup;
33898     apOld[i]->idxParent = k;
33899     apCopy[i] = 0;
33900     assert( i==nOld );
33901     nOld++;
33902     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
33903   }
33904
33905   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
33906   ** alignment */
33907   nMaxCells = (nMaxCells + 3)&~3;
33908
33909   /*
33910   ** Allocate space for memory structures
33911   */
33912   apCell = sqlite3_malloc( 
33913        nMaxCells*sizeof(u8*)                       /* apCell */
33914      + nMaxCells*sizeof(u16)                       /* szCell */
33915      + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB  /* aCopy */
33916      + pBt->pageSize*5                             /* aSpace */
33917      + (ISAUTOVACUUM ? nMaxCells : 0)              /* aFrom */
33918   );
33919   if( apCell==0 ){
33920     rc = SQLITE_NOMEM;
33921     goto balance_cleanup;
33922   }
33923   szCell = (u16*)&apCell[nMaxCells];
33924   aCopy[0] = (u8*)&szCell[nMaxCells];
33925   assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
33926   for(i=1; i<NB; i++){
33927     aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
33928     assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
33929   }
33930   aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
33931   assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
33932 #ifndef SQLITE_OMIT_AUTOVACUUM
33933   if( pBt->autoVacuum ){
33934     aFrom = &aSpace[5*pBt->pageSize];
33935   }
33936 #endif
33937   
33938   /*
33939   ** Make copies of the content of pPage and its siblings into aOld[].
33940   ** The rest of this function will use data from the copies rather
33941   ** that the original pages since the original pages will be in the
33942   ** process of being overwritten.
33943   */
33944   for(i=0; i<nOld; i++){
33945     MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
33946     memcpy(p, apOld[i], sizeof(MemPage));
33947     p->aData = (void*)&p[1];
33948     memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
33949   }
33950
33951   /*
33952   ** Load pointers to all cells on sibling pages and the divider cells
33953   ** into the local apCell[] array.  Make copies of the divider cells
33954   ** into space obtained form aSpace[] and remove the the divider Cells
33955   ** from pParent.
33956   **
33957   ** If the siblings are on leaf pages, then the child pointers of the
33958   ** divider cells are stripped from the cells before they are copied
33959   ** into aSpace[].  In this way, all cells in apCell[] are without
33960   ** child pointers.  If siblings are not leaves, then all cell in
33961   ** apCell[] include child pointers.  Either way, all cells in apCell[]
33962   ** are alike.
33963   **
33964   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
33965   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
33966   */
33967   nCell = 0;
33968   leafCorrection = pPage->leaf*4;
33969   leafData = pPage->leafData && pPage->leaf;
33970   for(i=0; i<nOld; i++){
33971     MemPage *pOld = apCopy[i];
33972     int limit = pOld->nCell+pOld->nOverflow;
33973     for(j=0; j<limit; j++){
33974       assert( nCell<nMaxCells );
33975       apCell[nCell] = findOverflowCell(pOld, j);
33976       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
33977 #ifndef SQLITE_OMIT_AUTOVACUUM
33978       if( pBt->autoVacuum ){
33979         int a;
33980         aFrom[nCell] = i;
33981         for(a=0; a<pOld->nOverflow; a++){
33982           if( pOld->aOvfl[a].pCell==apCell[nCell] ){
33983             aFrom[nCell] = 0xFF;
33984             break;
33985           }
33986         }
33987       }
33988 #endif
33989       nCell++;
33990     }
33991     if( i<nOld-1 ){
33992       u16 sz = cellSizePtr(pParent, apDiv[i]);
33993       if( leafData ){
33994         /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
33995         ** are duplicates of keys on the child pages.  We need to remove
33996         ** the divider cells from pParent, but the dividers cells are not
33997         ** added to apCell[] because they are duplicates of child cells.
33998         */
33999         dropCell(pParent, nxDiv, sz);
34000       }else{
34001         u8 *pTemp;
34002         assert( nCell<nMaxCells );
34003         szCell[nCell] = sz;
34004         pTemp = &aSpace[iSpace];
34005         iSpace += sz;
34006         assert( iSpace<=pBt->pageSize*5 );
34007         memcpy(pTemp, apDiv[i], sz);
34008         apCell[nCell] = pTemp+leafCorrection;
34009 #ifndef SQLITE_OMIT_AUTOVACUUM
34010         if( pBt->autoVacuum ){
34011           aFrom[nCell] = 0xFF;
34012         }
34013 #endif
34014         dropCell(pParent, nxDiv, sz);
34015         szCell[nCell] -= leafCorrection;
34016         assert( get4byte(pTemp)==pgnoOld[i] );
34017         if( !pOld->leaf ){
34018           assert( leafCorrection==0 );
34019           /* The right pointer of the child page pOld becomes the left
34020           ** pointer of the divider cell */
34021           memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
34022         }else{
34023           assert( leafCorrection==4 );
34024           if( szCell[nCell]<4 ){
34025             /* Do not allow any cells smaller than 4 bytes. */
34026             szCell[nCell] = 4;
34027           }
34028         }
34029         nCell++;
34030       }
34031     }
34032   }
34033
34034   /*
34035   ** Figure out the number of pages needed to hold all nCell cells.
34036   ** Store this number in "k".  Also compute szNew[] which is the total
34037   ** size of all cells on the i-th page and cntNew[] which is the index
34038   ** in apCell[] of the cell that divides page i from page i+1.  
34039   ** cntNew[k] should equal nCell.
34040   **
34041   ** Values computed by this block:
34042   **
34043   **           k: The total number of sibling pages
34044   **    szNew[i]: Spaced used on the i-th sibling page.
34045   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
34046   **              the right of the i-th sibling page.
34047   ** usableSpace: Number of bytes of space available on each sibling.
34048   ** 
34049   */
34050   usableSpace = pBt->usableSize - 12 + leafCorrection;
34051   for(subtotal=k=i=0; i<nCell; i++){
34052     assert( i<nMaxCells );
34053     subtotal += szCell[i] + 2;
34054     if( subtotal > usableSpace ){
34055       szNew[k] = subtotal - szCell[i];
34056       cntNew[k] = i;
34057       if( leafData ){ i--; }
34058       subtotal = 0;
34059       k++;
34060     }
34061   }
34062   szNew[k] = subtotal;
34063   cntNew[k] = nCell;
34064   k++;
34065
34066   /*
34067   ** The packing computed by the previous block is biased toward the siblings
34068   ** on the left side.  The left siblings are always nearly full, while the
34069   ** right-most sibling might be nearly empty.  This block of code attempts
34070   ** to adjust the packing of siblings to get a better balance.
34071   **
34072   ** This adjustment is more than an optimization.  The packing above might
34073   ** be so out of balance as to be illegal.  For example, the right-most
34074   ** sibling might be completely empty.  This adjustment is not optional.
34075   */
34076   for(i=k-1; i>0; i--){
34077     int szRight = szNew[i];  /* Size of sibling on the right */
34078     int szLeft = szNew[i-1]; /* Size of sibling on the left */
34079     int r;              /* Index of right-most cell in left sibling */
34080     int d;              /* Index of first cell to the left of right sibling */
34081
34082     r = cntNew[i-1] - 1;
34083     d = r + 1 - leafData;
34084     assert( d<nMaxCells );
34085     assert( r<nMaxCells );
34086     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
34087       szRight += szCell[d] + 2;
34088       szLeft -= szCell[r] + 2;
34089       cntNew[i-1]--;
34090       r = cntNew[i-1] - 1;
34091       d = r + 1 - leafData;
34092     }
34093     szNew[i] = szRight;
34094     szNew[i-1] = szLeft;
34095   }
34096
34097   /* Either we found one or more cells (cntnew[0])>0) or we are the
34098   ** a virtual root page.  A virtual root page is when the real root
34099   ** page is page 1 and we are the only child of that page.
34100   */
34101   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
34102
34103   /*
34104   ** Allocate k new pages.  Reuse old pages where possible.
34105   */
34106   assert( pPage->pgno>1 );
34107   pageFlags = pPage->aData[0];
34108   for(i=0; i<k; i++){
34109     MemPage *pNew;
34110     if( i<nOld ){
34111       pNew = apNew[i] = apOld[i];
34112       pgnoNew[i] = pgnoOld[i];
34113       apOld[i] = 0;
34114       rc = sqlite3PagerWrite(pNew->pDbPage);
34115       nNew++;
34116       if( rc ) goto balance_cleanup;
34117     }else{
34118       assert( i>0 );
34119       rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
34120       if( rc ) goto balance_cleanup;
34121       apNew[i] = pNew;
34122       nNew++;
34123     }
34124     zeroPage(pNew, pageFlags);
34125   }
34126
34127   /* Free any old pages that were not reused as new pages.
34128   */
34129   while( i<nOld ){
34130     rc = freePage(apOld[i]);
34131     if( rc ) goto balance_cleanup;
34132     releasePage(apOld[i]);
34133     apOld[i] = 0;
34134     i++;
34135   }
34136
34137   /*
34138   ** Put the new pages in accending order.  This helps to
34139   ** keep entries in the disk file in order so that a scan
34140   ** of the table is a linear scan through the file.  That
34141   ** in turn helps the operating system to deliver pages
34142   ** from the disk more rapidly.
34143   **
34144   ** An O(n^2) insertion sort algorithm is used, but since
34145   ** n is never more than NB (a small constant), that should
34146   ** not be a problem.
34147   **
34148   ** When NB==3, this one optimization makes the database
34149   ** about 25% faster for large insertions and deletions.
34150   */
34151   for(i=0; i<k-1; i++){
34152     int minV = pgnoNew[i];
34153     int minI = i;
34154     for(j=i+1; j<k; j++){
34155       if( pgnoNew[j]<(unsigned)minV ){
34156         minI = j;
34157         minV = pgnoNew[j];
34158       }
34159     }
34160     if( minI>i ){
34161       int t;
34162       MemPage *pT;
34163       t = pgnoNew[i];
34164       pT = apNew[i];
34165       pgnoNew[i] = pgnoNew[minI];
34166       apNew[i] = apNew[minI];
34167       pgnoNew[minI] = t;
34168       apNew[minI] = pT;
34169     }
34170   }
34171   TRACE(("BALANCE: old: %d %d %d  new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
34172     pgnoOld[0], 
34173     nOld>=2 ? pgnoOld[1] : 0,
34174     nOld>=3 ? pgnoOld[2] : 0,
34175     pgnoNew[0], szNew[0],
34176     nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
34177     nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
34178     nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
34179     nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
34180
34181   /*
34182   ** Evenly distribute the data in apCell[] across the new pages.
34183   ** Insert divider cells into pParent as necessary.
34184   */
34185   j = 0;
34186   for(i=0; i<nNew; i++){
34187     /* Assemble the new sibling page. */
34188     MemPage *pNew = apNew[i];
34189     assert( j<nMaxCells );
34190     assert( pNew->pgno==pgnoNew[i] );
34191     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
34192     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
34193     assert( pNew->nOverflow==0 );
34194
34195 #ifndef SQLITE_OMIT_AUTOVACUUM
34196     /* If this is an auto-vacuum database, update the pointer map entries
34197     ** that point to the siblings that were rearranged. These can be: left
34198     ** children of cells, the right-child of the page, or overflow pages
34199     ** pointed to by cells.
34200     */
34201     if( pBt->autoVacuum ){
34202       for(k=j; k<cntNew[i]; k++){
34203         assert( k<nMaxCells );
34204         if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
34205           rc = ptrmapPutOvfl(pNew, k-j);
34206           if( rc!=SQLITE_OK ){
34207             goto balance_cleanup;
34208           }
34209         }
34210       }
34211     }
34212 #endif
34213
34214     j = cntNew[i];
34215
34216     /* If the sibling page assembled above was not the right-most sibling,
34217     ** insert a divider cell into the parent page.
34218     */
34219     if( i<nNew-1 && j<nCell ){
34220       u8 *pCell;
34221       u8 *pTemp;
34222       int sz;
34223
34224       assert( j<nMaxCells );
34225       pCell = apCell[j];
34226       sz = szCell[j] + leafCorrection;
34227       if( !pNew->leaf ){
34228         memcpy(&pNew->aData[8], pCell, 4);
34229         pTemp = 0;
34230       }else if( leafData ){
34231         /* If the tree is a leaf-data tree, and the siblings are leaves, 
34232         ** then there is no divider cell in apCell[]. Instead, the divider 
34233         ** cell consists of the integer key for the right-most cell of 
34234         ** the sibling-page assembled above only.
34235         */
34236         CellInfo info;
34237         j--;
34238         sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
34239         pCell = &aSpace[iSpace];
34240         fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
34241         iSpace += sz;
34242         assert( iSpace<=pBt->pageSize*5 );
34243         pTemp = 0;
34244       }else{
34245         pCell -= 4;
34246         pTemp = &aSpace[iSpace];
34247         iSpace += sz;
34248         assert( iSpace<=pBt->pageSize*5 );
34249         /* Obscure case for non-leaf-data trees: If the cell at pCell was
34250         ** previously stored on a leaf node, and its reported size was 4
34251         ** bytes, then it may actually be smaller than this 
34252         ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
34253         ** any cell). But it is important to pass the correct size to 
34254         ** insertCell(), so reparse the cell now.
34255         **
34256         ** Note that this can never happen in an SQLite data file, as all
34257         ** cells are at least 4 bytes. It only happens in b-trees used
34258         ** to evaluate "IN (SELECT ...)" and similar clauses.
34259         */
34260         if( szCell[j]==4 ){
34261           assert(leafCorrection==4);
34262           sz = cellSizePtr(pParent, pCell);
34263         }
34264       }
34265       rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
34266       if( rc!=SQLITE_OK ) goto balance_cleanup;
34267       put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
34268 #ifndef SQLITE_OMIT_AUTOVACUUM
34269       /* If this is an auto-vacuum database, and not a leaf-data tree,
34270       ** then update the pointer map with an entry for the overflow page
34271       ** that the cell just inserted points to (if any).
34272       */
34273       if( pBt->autoVacuum && !leafData ){
34274         rc = ptrmapPutOvfl(pParent, nxDiv);
34275         if( rc!=SQLITE_OK ){
34276           goto balance_cleanup;
34277         }
34278       }
34279 #endif
34280       j++;
34281       nxDiv++;
34282     }
34283   }
34284   assert( j==nCell );
34285   assert( nOld>0 );
34286   assert( nNew>0 );
34287   if( (pageFlags & PTF_LEAF)==0 ){
34288     memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
34289   }
34290   if( nxDiv==pParent->nCell+pParent->nOverflow ){
34291     /* Right-most sibling is the right-most child of pParent */
34292     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
34293   }else{
34294     /* Right-most sibling is the left child of the first entry in pParent
34295     ** past the right-most divider entry */
34296     put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
34297   }
34298
34299   /*
34300   ** Reparent children of all cells.
34301   */
34302   for(i=0; i<nNew; i++){
34303     rc = reparentChildPages(apNew[i]);
34304     if( rc!=SQLITE_OK ) goto balance_cleanup;
34305   }
34306   rc = reparentChildPages(pParent);
34307   if( rc!=SQLITE_OK ) goto balance_cleanup;
34308
34309   /*
34310   ** Balance the parent page.  Note that the current page (pPage) might
34311   ** have been added to the freelist so it might no longer be initialized.
34312   ** But the parent page will always be initialized.
34313   */
34314   assert( pParent->isInit );
34315   rc = balance(pParent, 0);
34316   
34317   /*
34318   ** Cleanup before returning.
34319   */
34320 balance_cleanup:
34321   sqlite3_free(apCell);
34322   for(i=0; i<nOld; i++){
34323     releasePage(apOld[i]);
34324   }
34325   for(i=0; i<nNew; i++){
34326     releasePage(apNew[i]);
34327   }
34328   releasePage(pParent);
34329   TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
34330           pPage->pgno, nOld, nNew, nCell));
34331   return rc;
34332 }
34333
34334 /*
34335 ** This routine is called for the root page of a btree when the root
34336 ** page contains no cells.  This is an opportunity to make the tree
34337 ** shallower by one level.
34338 */
34339 static int balance_shallower(MemPage *pPage){
34340   MemPage *pChild;             /* The only child page of pPage */
34341   Pgno pgnoChild;              /* Page number for pChild */
34342   int rc = SQLITE_OK;          /* Return code from subprocedures */
34343   BtShared *pBt;                  /* The main BTree structure */
34344   int mxCellPerPage;           /* Maximum number of cells per page */
34345   u8 **apCell;                 /* All cells from pages being balanced */
34346   u16 *szCell;                 /* Local size of all cells */
34347
34348   assert( pPage->pParent==0 );
34349   assert( pPage->nCell==0 );
34350   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34351   pBt = pPage->pBt;
34352   mxCellPerPage = MX_CELL(pBt);
34353   apCell = sqlite3_malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
34354   if( apCell==0 ) return SQLITE_NOMEM;
34355   szCell = (u16*)&apCell[mxCellPerPage];
34356   if( pPage->leaf ){
34357     /* The table is completely empty */
34358     TRACE(("BALANCE: empty table %d\n", pPage->pgno));
34359   }else{
34360     /* The root page is empty but has one child.  Transfer the
34361     ** information from that one child into the root page if it 
34362     ** will fit.  This reduces the depth of the tree by one.
34363     **
34364     ** If the root page is page 1, it has less space available than
34365     ** its child (due to the 100 byte header that occurs at the beginning
34366     ** of the database fle), so it might not be able to hold all of the 
34367     ** information currently contained in the child.  If this is the 
34368     ** case, then do not do the transfer.  Leave page 1 empty except
34369     ** for the right-pointer to the child page.  The child page becomes
34370     ** the virtual root of the tree.
34371     */
34372     pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
34373     assert( pgnoChild>0 );
34374     assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
34375     rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
34376     if( rc ) goto end_shallow_balance;
34377     if( pPage->pgno==1 ){
34378       rc = sqlite3BtreeInitPage(pChild, pPage);
34379       if( rc ) goto end_shallow_balance;
34380       assert( pChild->nOverflow==0 );
34381       if( pChild->nFree>=100 ){
34382         /* The child information will fit on the root page, so do the
34383         ** copy */
34384         int i;
34385         zeroPage(pPage, pChild->aData[0]);
34386         for(i=0; i<pChild->nCell; i++){
34387           apCell[i] = findCell(pChild,i);
34388           szCell[i] = cellSizePtr(pChild, apCell[i]);
34389         }
34390         assemblePage(pPage, pChild->nCell, apCell, szCell);
34391         /* Copy the right-pointer of the child to the parent. */
34392         put4byte(&pPage->aData[pPage->hdrOffset+8], 
34393             get4byte(&pChild->aData[pChild->hdrOffset+8]));
34394         freePage(pChild);
34395         TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
34396       }else{
34397         /* The child has more information that will fit on the root.
34398         ** The tree is already balanced.  Do nothing. */
34399         TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
34400       }
34401     }else{
34402       memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
34403       pPage->isInit = 0;
34404       pPage->pParent = 0;
34405       rc = sqlite3BtreeInitPage(pPage, 0);
34406       assert( rc==SQLITE_OK );
34407       freePage(pChild);
34408       TRACE(("BALANCE: transfer child %d into root %d\n",
34409               pChild->pgno, pPage->pgno));
34410     }
34411     rc = reparentChildPages(pPage);
34412     assert( pPage->nOverflow==0 );
34413 #ifndef SQLITE_OMIT_AUTOVACUUM
34414     if( pBt->autoVacuum ){
34415       int i;
34416       for(i=0; i<pPage->nCell; i++){ 
34417         rc = ptrmapPutOvfl(pPage, i);
34418         if( rc!=SQLITE_OK ){
34419           goto end_shallow_balance;
34420         }
34421       }
34422     }
34423 #endif
34424     releasePage(pChild);
34425   }
34426 end_shallow_balance:
34427   sqlite3_free(apCell);
34428   return rc;
34429 }
34430
34431
34432 /*
34433 ** The root page is overfull
34434 **
34435 ** When this happens, Create a new child page and copy the
34436 ** contents of the root into the child.  Then make the root
34437 ** page an empty page with rightChild pointing to the new
34438 ** child.   Finally, call balance_internal() on the new child
34439 ** to cause it to split.
34440 */
34441 static int balance_deeper(MemPage *pPage){
34442   int rc;             /* Return value from subprocedures */
34443   MemPage *pChild;    /* Pointer to a new child page */
34444   Pgno pgnoChild;     /* Page number of the new child page */
34445   BtShared *pBt;         /* The BTree */
34446   int usableSize;     /* Total usable size of a page */
34447   u8 *data;           /* Content of the parent page */
34448   u8 *cdata;          /* Content of the child page */
34449   int hdr;            /* Offset to page header in parent */
34450   int brk;            /* Offset to content of first cell in parent */
34451
34452   assert( pPage->pParent==0 );
34453   assert( pPage->nOverflow>0 );
34454   pBt = pPage->pBt;
34455   assert( sqlite3_mutex_held(pBt->mutex) );
34456   rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
34457   if( rc ) return rc;
34458   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
34459   usableSize = pBt->usableSize;
34460   data = pPage->aData;
34461   hdr = pPage->hdrOffset;
34462   brk = get2byte(&data[hdr+5]);
34463   cdata = pChild->aData;
34464   memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
34465   memcpy(&cdata[brk], &data[brk], usableSize-brk);
34466   assert( pChild->isInit==0 );
34467   rc = sqlite3BtreeInitPage(pChild, pPage);
34468   if( rc ) goto balancedeeper_out;
34469   memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
34470   pChild->nOverflow = pPage->nOverflow;
34471   if( pChild->nOverflow ){
34472     pChild->nFree = 0;
34473   }
34474   assert( pChild->nCell==pPage->nCell );
34475   zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
34476   put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
34477   TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
34478 #ifndef SQLITE_OMIT_AUTOVACUUM
34479   if( pBt->autoVacuum ){
34480     int i;
34481     rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
34482     if( rc ) goto balancedeeper_out;
34483     for(i=0; i<pChild->nCell; i++){
34484       rc = ptrmapPutOvfl(pChild, i);
34485       if( rc!=SQLITE_OK ){
34486         return rc;
34487       }
34488     }
34489   }
34490 #endif
34491   rc = balance_nonroot(pChild);
34492
34493 balancedeeper_out:
34494   releasePage(pChild);
34495   return rc;
34496 }
34497
34498 /*
34499 ** Decide if the page pPage needs to be balanced.  If balancing is
34500 ** required, call the appropriate balancing routine.
34501 */
34502 static int balance(MemPage *pPage, int insert){
34503   int rc = SQLITE_OK;
34504   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34505   if( pPage->pParent==0 ){
34506     rc = sqlite3PagerWrite(pPage->pDbPage);
34507     if( rc==SQLITE_OK && pPage->nOverflow>0 ){
34508       rc = balance_deeper(pPage);
34509     }
34510     if( rc==SQLITE_OK && pPage->nCell==0 ){
34511       rc = balance_shallower(pPage);
34512     }
34513   }else{
34514     if( pPage->nOverflow>0 || 
34515         (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
34516       rc = balance_nonroot(pPage);
34517     }
34518   }
34519   return rc;
34520 }
34521
34522 /*
34523 ** This routine checks all cursors that point to table pgnoRoot.
34524 ** If any of those cursors were opened with wrFlag==0 in a different
34525 ** database connection (a database connection that shares the pager
34526 ** cache with the current connection) and that other connection 
34527 ** is not in the ReadUncommmitted state, then this routine returns 
34528 ** SQLITE_LOCKED.
34529 **
34530 ** In addition to checking for read-locks (where a read-lock 
34531 ** means a cursor opened with wrFlag==0) this routine also moves
34532 ** all write cursors so that they are pointing to the 
34533 ** first Cell on the root page.  This is necessary because an insert 
34534 ** or delete might change the number of cells on a page or delete
34535 ** a page entirely and we do not want to leave any cursors 
34536 ** pointing to non-existant pages or cells.
34537 */
34538 static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
34539   BtCursor *p;
34540   BtShared *pBt = pBtree->pBt;
34541   sqlite3 *db = pBtree->db;
34542   assert( sqlite3BtreeHoldsMutex(pBtree) );
34543   for(p=pBt->pCursor; p; p=p->pNext){
34544     if( p==pExclude ) continue;
34545     if( p->eState!=CURSOR_VALID ) continue;
34546     if( p->pgnoRoot!=pgnoRoot ) continue;
34547     if( p->wrFlag==0 ){
34548       sqlite3 *dbOther = p->pBtree->db;
34549       if( dbOther==0 ||
34550          (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
34551         return SQLITE_LOCKED;
34552       }
34553     }else if( p->pPage->pgno!=p->pgnoRoot ){
34554       moveToRoot(p);
34555     }
34556   }
34557   return SQLITE_OK;
34558 }
34559
34560 /*
34561 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
34562 ** and the data is given by (pData,nData).  The cursor is used only to
34563 ** define what table the record should be inserted into.  The cursor
34564 ** is left pointing at a random location.
34565 **
34566 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
34567 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
34568 */
34569 SQLITE_PRIVATE int sqlite3BtreeInsert(
34570   BtCursor *pCur,                /* Insert data into the table of this cursor */
34571   const void *pKey, i64 nKey,    /* The key of the new record */
34572   const void *pData, int nData,  /* The data of the new record */
34573   int nZero,                     /* Number of extra 0 bytes to append to data */
34574   int appendBias                 /* True if this is likely an append */
34575 ){
34576   int rc;
34577   int loc;
34578   int szNew;
34579   MemPage *pPage;
34580   Btree *p = pCur->pBtree;
34581   BtShared *pBt = p->pBt;
34582   unsigned char *oldCell;
34583   unsigned char *newCell = 0;
34584
34585   assert( cursorHoldsMutex(pCur) );
34586   if( pBt->inTransaction!=TRANS_WRITE ){
34587     /* Must start a transaction before doing an insert */
34588     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
34589     return rc;
34590   }
34591   assert( !pBt->readOnly );
34592   if( !pCur->wrFlag ){
34593     return SQLITE_PERM;   /* Cursor not open for writing */
34594   }
34595   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
34596     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
34597   }
34598   if( pCur->eState==CURSOR_FAULT ){
34599     return pCur->skip;
34600   }
34601
34602   /* Save the positions of any other cursors open on this table */
34603   clearCursorPosition(pCur);
34604   if( 
34605     SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
34606     SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
34607   ){
34608     return rc;
34609   }
34610
34611   pPage = pCur->pPage;
34612   assert( pPage->intKey || nKey>=0 );
34613   assert( pPage->leaf || !pPage->leafData );
34614   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
34615           pCur->pgnoRoot, nKey, nData, pPage->pgno,
34616           loc==0 ? "overwrite" : "new entry"));
34617   assert( pPage->isInit );
34618   newCell = sqlite3_malloc( MX_CELL_SIZE(pBt) );
34619   if( newCell==0 ) return SQLITE_NOMEM;
34620   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
34621   if( rc ) goto end_insert;
34622   assert( szNew==cellSizePtr(pPage, newCell) );
34623   assert( szNew<=MX_CELL_SIZE(pBt) );
34624   if( loc==0 && CURSOR_VALID==pCur->eState ){
34625     u16 szOld;
34626     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
34627     rc = sqlite3PagerWrite(pPage->pDbPage);
34628     if( rc ){
34629       goto end_insert;
34630     }
34631     oldCell = findCell(pPage, pCur->idx);
34632     if( !pPage->leaf ){
34633       memcpy(newCell, oldCell, 4);
34634     }
34635     szOld = cellSizePtr(pPage, oldCell);
34636     rc = clearCell(pPage, oldCell);
34637     if( rc ) goto end_insert;
34638     dropCell(pPage, pCur->idx, szOld);
34639   }else if( loc<0 && pPage->nCell>0 ){
34640     assert( pPage->leaf );
34641     pCur->idx++;
34642     pCur->info.nSize = 0;
34643   }else{
34644     assert( pPage->leaf );
34645   }
34646   rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
34647   if( rc!=SQLITE_OK ) goto end_insert;
34648   rc = balance(pPage, 1);
34649   /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
34650   /* fflush(stdout); */
34651   if( rc==SQLITE_OK ){
34652     moveToRoot(pCur);
34653   }
34654 end_insert:
34655   sqlite3_free(newCell);
34656   return rc;
34657 }
34658
34659 /*
34660 ** Delete the entry that the cursor is pointing to.  The cursor
34661 ** is left pointing at a random location.
34662 */
34663 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
34664   MemPage *pPage = pCur->pPage;
34665   unsigned char *pCell;
34666   int rc;
34667   Pgno pgnoChild = 0;
34668   Btree *p = pCur->pBtree;
34669   BtShared *pBt = p->pBt;
34670
34671   assert( cursorHoldsMutex(pCur) );
34672   assert( pPage->isInit );
34673   if( pBt->inTransaction!=TRANS_WRITE ){
34674     /* Must start a transaction before doing a delete */
34675     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
34676     return rc;
34677   }
34678   assert( !pBt->readOnly );
34679   if( pCur->eState==CURSOR_FAULT ){
34680     return pCur->skip;
34681   }
34682   if( pCur->idx >= pPage->nCell ){
34683     return SQLITE_ERROR;  /* The cursor is not pointing to anything */
34684   }
34685   if( !pCur->wrFlag ){
34686     return SQLITE_PERM;   /* Did not open this cursor for writing */
34687   }
34688   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
34689     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
34690   }
34691
34692   /* Restore the current cursor position (a no-op if the cursor is not in 
34693   ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
34694   ** open on the same table. Then call sqlite3PagerWrite() on the page
34695   ** that the entry will be deleted from.
34696   */
34697   if( 
34698     (rc = restoreOrClearCursorPosition(pCur))!=0 ||
34699     (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
34700     (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
34701   ){
34702     return rc;
34703   }
34704
34705   /* Locate the cell within its page and leave pCell pointing to the
34706   ** data. The clearCell() call frees any overflow pages associated with the
34707   ** cell. The cell itself is still intact.
34708   */
34709   pCell = findCell(pPage, pCur->idx);
34710   if( !pPage->leaf ){
34711     pgnoChild = get4byte(pCell);
34712   }
34713   rc = clearCell(pPage, pCell);
34714   if( rc ){
34715     return rc;
34716   }
34717
34718   if( !pPage->leaf ){
34719     /*
34720     ** The entry we are about to delete is not a leaf so if we do not
34721     ** do something we will leave a hole on an internal page.
34722     ** We have to fill the hole by moving in a cell from a leaf.  The
34723     ** next Cell after the one to be deleted is guaranteed to exist and
34724     ** to be a leaf so we can use it.
34725     */
34726     BtCursor leafCur;
34727     unsigned char *pNext;
34728     int notUsed;
34729     unsigned char *tempCell = 0;
34730     assert( !pPage->leafData );
34731     sqlite3BtreeGetTempCursor(pCur, &leafCur);
34732     rc = sqlite3BtreeNext(&leafCur, &notUsed);
34733     if( rc==SQLITE_OK ){
34734       rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
34735     }
34736     if( rc==SQLITE_OK ){
34737       u16 szNext;
34738       TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
34739          pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
34740       dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
34741       pNext = findCell(leafCur.pPage, leafCur.idx);
34742       szNext = cellSizePtr(leafCur.pPage, pNext);
34743       assert( MX_CELL_SIZE(pBt)>=szNext+4 );
34744       tempCell = sqlite3_malloc( MX_CELL_SIZE(pBt) );
34745       if( tempCell==0 ){
34746         rc = SQLITE_NOMEM;
34747       }
34748       if( rc==SQLITE_OK ){
34749         rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
34750       }
34751       if( rc==SQLITE_OK ){
34752         put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
34753         rc = balance(pPage, 0);
34754       }
34755       if( rc==SQLITE_OK ){
34756         dropCell(leafCur.pPage, leafCur.idx, szNext);
34757         rc = balance(leafCur.pPage, 0);
34758       }
34759     }
34760     sqlite3_free(tempCell);
34761     sqlite3BtreeReleaseTempCursor(&leafCur);
34762   }else{
34763     TRACE(("DELETE: table=%d delete from leaf %d\n",
34764        pCur->pgnoRoot, pPage->pgno));
34765     dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
34766     rc = balance(pPage, 0);
34767   }
34768   if( rc==SQLITE_OK ){
34769     moveToRoot(pCur);
34770   }
34771   return rc;
34772 }
34773
34774 /*
34775 ** Create a new BTree table.  Write into *piTable the page
34776 ** number for the root page of the new table.
34777 **
34778 ** The type of type is determined by the flags parameter.  Only the
34779 ** following values of flags are currently in use.  Other values for
34780 ** flags might not work:
34781 **
34782 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
34783 **     BTREE_ZERODATA                  Used for SQL indices
34784 */
34785 static int btreeCreateTable(Btree *p, int *piTable, int flags){
34786   BtShared *pBt = p->pBt;
34787   MemPage *pRoot;
34788   Pgno pgnoRoot;
34789   int rc;
34790
34791   assert( sqlite3BtreeHoldsMutex(p) );
34792   if( pBt->inTransaction!=TRANS_WRITE ){
34793     /* Must start a transaction first */
34794     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
34795     return rc;
34796   }
34797   assert( !pBt->readOnly );
34798
34799 #ifdef SQLITE_OMIT_AUTOVACUUM
34800   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
34801   if( rc ){
34802     return rc;
34803   }
34804 #else
34805   if( pBt->autoVacuum ){
34806     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
34807     MemPage *pPageMove; /* The page to move to. */
34808
34809     /* Creating a new table may probably require moving an existing database
34810     ** to make room for the new tables root page. In case this page turns
34811     ** out to be an overflow page, delete all overflow page-map caches
34812     ** held by open cursors.
34813     */
34814     invalidateAllOverflowCache(pBt);
34815
34816     /* Read the value of meta[3] from the database to determine where the
34817     ** root page of the new table should go. meta[3] is the largest root-page
34818     ** created so far, so the new root-page is (meta[3]+1).
34819     */
34820     rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
34821     if( rc!=SQLITE_OK ){
34822       return rc;
34823     }
34824     pgnoRoot++;
34825
34826     /* The new root-page may not be allocated on a pointer-map page, or the
34827     ** PENDING_BYTE page.
34828     */
34829     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
34830         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
34831       pgnoRoot++;
34832     }
34833     assert( pgnoRoot>=3 );
34834
34835     /* Allocate a page. The page that currently resides at pgnoRoot will
34836     ** be moved to the allocated page (unless the allocated page happens
34837     ** to reside at pgnoRoot).
34838     */
34839     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
34840     if( rc!=SQLITE_OK ){
34841       return rc;
34842     }
34843
34844     if( pgnoMove!=pgnoRoot ){
34845       /* pgnoRoot is the page that will be used for the root-page of
34846       ** the new table (assuming an error did not occur). But we were
34847       ** allocated pgnoMove. If required (i.e. if it was not allocated
34848       ** by extending the file), the current page at position pgnoMove
34849       ** is already journaled.
34850       */
34851       u8 eType;
34852       Pgno iPtrPage;
34853
34854       releasePage(pPageMove);
34855
34856       /* Move the page currently at pgnoRoot to pgnoMove. */
34857       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
34858       if( rc!=SQLITE_OK ){
34859         return rc;
34860       }
34861       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
34862       if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
34863         releasePage(pRoot);
34864         return rc;
34865       }
34866       assert( eType!=PTRMAP_ROOTPAGE );
34867       assert( eType!=PTRMAP_FREEPAGE );
34868       rc = sqlite3PagerWrite(pRoot->pDbPage);
34869       if( rc!=SQLITE_OK ){
34870         releasePage(pRoot);
34871         return rc;
34872       }
34873       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
34874       releasePage(pRoot);
34875
34876       /* Obtain the page at pgnoRoot */
34877       if( rc!=SQLITE_OK ){
34878         return rc;
34879       }
34880       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
34881       if( rc!=SQLITE_OK ){
34882         return rc;
34883       }
34884       rc = sqlite3PagerWrite(pRoot->pDbPage);
34885       if( rc!=SQLITE_OK ){
34886         releasePage(pRoot);
34887         return rc;
34888       }
34889     }else{
34890       pRoot = pPageMove;
34891     } 
34892
34893     /* Update the pointer-map and meta-data with the new root-page number. */
34894     rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
34895     if( rc ){
34896       releasePage(pRoot);
34897       return rc;
34898     }
34899     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
34900     if( rc ){
34901       releasePage(pRoot);
34902       return rc;
34903     }
34904
34905   }else{
34906     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
34907     if( rc ) return rc;
34908   }
34909 #endif
34910   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
34911   zeroPage(pRoot, flags | PTF_LEAF);
34912   sqlite3PagerUnref(pRoot->pDbPage);
34913   *piTable = (int)pgnoRoot;
34914   return SQLITE_OK;
34915 }
34916 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
34917   int rc;
34918   sqlite3BtreeEnter(p);
34919   p->pBt->db = p->db;
34920   rc = btreeCreateTable(p, piTable, flags);
34921   sqlite3BtreeLeave(p);
34922   return rc;
34923 }
34924
34925 /*
34926 ** Erase the given database page and all its children.  Return
34927 ** the page to the freelist.
34928 */
34929 static int clearDatabasePage(
34930   BtShared *pBt,           /* The BTree that contains the table */
34931   Pgno pgno,            /* Page number to clear */
34932   MemPage *pParent,     /* Parent page.  NULL for the root */
34933   int freePageFlag      /* Deallocate page if true */
34934 ){
34935   MemPage *pPage = 0;
34936   int rc;
34937   unsigned char *pCell;
34938   int i;
34939
34940   assert( sqlite3_mutex_held(pBt->mutex) );
34941   if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
34942     return SQLITE_CORRUPT_BKPT;
34943   }
34944
34945   rc = getAndInitPage(pBt, pgno, &pPage, pParent);
34946   if( rc ) goto cleardatabasepage_out;
34947   for(i=0; i<pPage->nCell; i++){
34948     pCell = findCell(pPage, i);
34949     if( !pPage->leaf ){
34950       rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
34951       if( rc ) goto cleardatabasepage_out;
34952     }
34953     rc = clearCell(pPage, pCell);
34954     if( rc ) goto cleardatabasepage_out;
34955   }
34956   if( !pPage->leaf ){
34957     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
34958     if( rc ) goto cleardatabasepage_out;
34959   }
34960   if( freePageFlag ){
34961     rc = freePage(pPage);
34962   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
34963     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
34964   }
34965
34966 cleardatabasepage_out:
34967   releasePage(pPage);
34968   return rc;
34969 }
34970
34971 /*
34972 ** Delete all information from a single table in the database.  iTable is
34973 ** the page number of the root of the table.  After this routine returns,
34974 ** the root page is empty, but still exists.
34975 **
34976 ** This routine will fail with SQLITE_LOCKED if there are any open
34977 ** read cursors on the table.  Open write cursors are moved to the
34978 ** root of the table.
34979 */
34980 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable){
34981   int rc;
34982   BtShared *pBt = p->pBt;
34983   sqlite3BtreeEnter(p);
34984   pBt->db = p->db;
34985   if( p->inTrans!=TRANS_WRITE ){
34986     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
34987   }else if( (rc = checkReadLocks(p, iTable, 0))!=SQLITE_OK ){
34988     /* nothing to do */
34989   }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
34990     /* nothing to do */
34991   }else{
34992     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
34993   }
34994   sqlite3BtreeLeave(p);
34995   return rc;
34996 }
34997
34998 /*
34999 ** Erase all information in a table and add the root of the table to
35000 ** the freelist.  Except, the root of the principle table (the one on
35001 ** page 1) is never added to the freelist.
35002 **
35003 ** This routine will fail with SQLITE_LOCKED if there are any open
35004 ** cursors on the table.
35005 **
35006 ** If AUTOVACUUM is enabled and the page at iTable is not the last
35007 ** root page in the database file, then the last root page 
35008 ** in the database file is moved into the slot formerly occupied by
35009 ** iTable and that last slot formerly occupied by the last root page
35010 ** is added to the freelist instead of iTable.  In this say, all
35011 ** root pages are kept at the beginning of the database file, which
35012 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
35013 ** page number that used to be the last root page in the file before
35014 ** the move.  If no page gets moved, *piMoved is set to 0.
35015 ** The last root page is recorded in meta[3] and the value of
35016 ** meta[3] is updated by this procedure.
35017 */
35018 static int btreeDropTable(Btree *p, int iTable, int *piMoved){
35019   int rc;
35020   MemPage *pPage = 0;
35021   BtShared *pBt = p->pBt;
35022
35023   assert( sqlite3BtreeHoldsMutex(p) );
35024   if( p->inTrans!=TRANS_WRITE ){
35025     return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
35026   }
35027
35028   /* It is illegal to drop a table if any cursors are open on the
35029   ** database. This is because in auto-vacuum mode the backend may
35030   ** need to move another root-page to fill a gap left by the deleted
35031   ** root page. If an open cursor was using this page a problem would 
35032   ** occur.
35033   */
35034   if( pBt->pCursor ){
35035     return SQLITE_LOCKED;
35036   }
35037
35038   rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
35039   if( rc ) return rc;
35040   rc = sqlite3BtreeClearTable(p, iTable);
35041   if( rc ){
35042     releasePage(pPage);
35043     return rc;
35044   }
35045
35046   *piMoved = 0;
35047
35048   if( iTable>1 ){
35049 #ifdef SQLITE_OMIT_AUTOVACUUM
35050     rc = freePage(pPage);
35051     releasePage(pPage);
35052 #else
35053     if( pBt->autoVacuum ){
35054       Pgno maxRootPgno;
35055       rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
35056       if( rc!=SQLITE_OK ){
35057         releasePage(pPage);
35058         return rc;
35059       }
35060
35061       if( iTable==maxRootPgno ){
35062         /* If the table being dropped is the table with the largest root-page
35063         ** number in the database, put the root page on the free list. 
35064         */
35065         rc = freePage(pPage);
35066         releasePage(pPage);
35067         if( rc!=SQLITE_OK ){
35068           return rc;
35069         }
35070       }else{
35071         /* The table being dropped does not have the largest root-page
35072         ** number in the database. So move the page that does into the 
35073         ** gap left by the deleted root-page.
35074         */
35075         MemPage *pMove;
35076         releasePage(pPage);
35077         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
35078         if( rc!=SQLITE_OK ){
35079           return rc;
35080         }
35081         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
35082         releasePage(pMove);
35083         if( rc!=SQLITE_OK ){
35084           return rc;
35085         }
35086         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
35087         if( rc!=SQLITE_OK ){
35088           return rc;
35089         }
35090         rc = freePage(pMove);
35091         releasePage(pMove);
35092         if( rc!=SQLITE_OK ){
35093           return rc;
35094         }
35095         *piMoved = maxRootPgno;
35096       }
35097
35098       /* Set the new 'max-root-page' value in the database header. This
35099       ** is the old value less one, less one more if that happens to
35100       ** be a root-page number, less one again if that is the
35101       ** PENDING_BYTE_PAGE.
35102       */
35103       maxRootPgno--;
35104       if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
35105         maxRootPgno--;
35106       }
35107       if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
35108         maxRootPgno--;
35109       }
35110       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
35111
35112       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
35113     }else{
35114       rc = freePage(pPage);
35115       releasePage(pPage);
35116     }
35117 #endif
35118   }else{
35119     /* If sqlite3BtreeDropTable was called on page 1. */
35120     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
35121     releasePage(pPage);
35122   }
35123   return rc;  
35124 }
35125 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
35126   int rc;
35127   sqlite3BtreeEnter(p);
35128   p->pBt->db = p->db;
35129   rc = btreeDropTable(p, iTable, piMoved);
35130   sqlite3BtreeLeave(p);
35131   return rc;
35132 }
35133
35134
35135 /*
35136 ** Read the meta-information out of a database file.  Meta[0]
35137 ** is the number of free pages currently in the database.  Meta[1]
35138 ** through meta[15] are available for use by higher layers.  Meta[0]
35139 ** is read-only, the others are read/write.
35140 ** 
35141 ** The schema layer numbers meta values differently.  At the schema
35142 ** layer (and the SetCookie and ReadCookie opcodes) the number of
35143 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
35144 */
35145 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
35146   DbPage *pDbPage;
35147   int rc;
35148   unsigned char *pP1;
35149   BtShared *pBt = p->pBt;
35150
35151   sqlite3BtreeEnter(p);
35152   pBt->db = p->db;
35153
35154   /* Reading a meta-data value requires a read-lock on page 1 (and hence
35155   ** the sqlite_master table. We grab this lock regardless of whether or
35156   ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
35157   ** 1 is treated as a special case by queryTableLock() and lockTable()).
35158   */
35159   rc = queryTableLock(p, 1, READ_LOCK);
35160   if( rc!=SQLITE_OK ){
35161     sqlite3BtreeLeave(p);
35162     return rc;
35163   }
35164
35165   assert( idx>=0 && idx<=15 );
35166   rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
35167   if( rc ){
35168     sqlite3BtreeLeave(p);
35169     return rc;
35170   }
35171   pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
35172   *pMeta = get4byte(&pP1[36 + idx*4]);
35173   sqlite3PagerUnref(pDbPage);
35174
35175   /* If autovacuumed is disabled in this build but we are trying to 
35176   ** access an autovacuumed database, then make the database readonly. 
35177   */
35178 #ifdef SQLITE_OMIT_AUTOVACUUM
35179   if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
35180 #endif
35181
35182   /* Grab the read-lock on page 1. */
35183   rc = lockTable(p, 1, READ_LOCK);
35184   sqlite3BtreeLeave(p);
35185   return rc;
35186 }
35187
35188 /*
35189 ** Write meta-information back into the database.  Meta[0] is
35190 ** read-only and may not be written.
35191 */
35192 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
35193   BtShared *pBt = p->pBt;
35194   unsigned char *pP1;
35195   int rc;
35196   assert( idx>=1 && idx<=15 );
35197   sqlite3BtreeEnter(p);
35198   pBt->db = p->db;
35199   if( p->inTrans!=TRANS_WRITE ){
35200     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
35201   }else{
35202     assert( pBt->pPage1!=0 );
35203     pP1 = pBt->pPage1->aData;
35204     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
35205     if( rc==SQLITE_OK ){
35206       put4byte(&pP1[36 + idx*4], iMeta);
35207 #ifndef SQLITE_OMIT_AUTOVACUUM
35208       if( idx==7 ){
35209         assert( pBt->autoVacuum || iMeta==0 );
35210         assert( iMeta==0 || iMeta==1 );
35211         pBt->incrVacuum = iMeta;
35212       }
35213 #endif
35214     }
35215   }
35216   sqlite3BtreeLeave(p);
35217   return rc;
35218 }
35219
35220 /*
35221 ** Return the flag byte at the beginning of the page that the cursor
35222 ** is currently pointing to.
35223 */
35224 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
35225   /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
35226   ** restoreOrClearCursorPosition() here.
35227   */
35228   MemPage *pPage;
35229   restoreOrClearCursorPosition(pCur);
35230   pPage = pCur->pPage;
35231   assert( cursorHoldsMutex(pCur) );
35232   assert( pPage->pBt==pCur->pBt );
35233   return pPage ? pPage->aData[pPage->hdrOffset] : 0;
35234 }
35235
35236
35237 /*
35238 ** Return the pager associated with a BTree.  This routine is used for
35239 ** testing and debugging only.
35240 */
35241 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
35242   return p->pBt->pPager;
35243 }
35244
35245 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
35246 /*
35247 ** Append a message to the error message string.
35248 */
35249 static void checkAppendMsg(
35250   IntegrityCk *pCheck,
35251   char *zMsg1,
35252   const char *zFormat,
35253   ...
35254 ){
35255   va_list ap;
35256   char *zMsg2;
35257   if( !pCheck->mxErr ) return;
35258   pCheck->mxErr--;
35259   pCheck->nErr++;
35260   va_start(ap, zFormat);
35261   zMsg2 = sqlite3VMPrintf(0, zFormat, ap);
35262   va_end(ap);
35263   if( zMsg1==0 ) zMsg1 = "";
35264   if( pCheck->zErrMsg ){
35265     char *zOld = pCheck->zErrMsg;
35266     pCheck->zErrMsg = 0;
35267     sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
35268     sqlite3_free(zOld);
35269   }else{
35270     sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
35271   }
35272   sqlite3_free(zMsg2);
35273 }
35274 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
35275
35276 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
35277 /*
35278 ** Add 1 to the reference count for page iPage.  If this is the second
35279 ** reference to the page, add an error message to pCheck->zErrMsg.
35280 ** Return 1 if there are 2 ore more references to the page and 0 if
35281 ** if this is the first reference to the page.
35282 **
35283 ** Also check that the page number is in bounds.
35284 */
35285 static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
35286   if( iPage==0 ) return 1;
35287   if( iPage>pCheck->nPage || iPage<0 ){
35288     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
35289     return 1;
35290   }
35291   if( pCheck->anRef[iPage]==1 ){
35292     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
35293     return 1;
35294   }
35295   return  (pCheck->anRef[iPage]++)>1;
35296 }
35297
35298 #ifndef SQLITE_OMIT_AUTOVACUUM
35299 /*
35300 ** Check that the entry in the pointer-map for page iChild maps to 
35301 ** page iParent, pointer type ptrType. If not, append an error message
35302 ** to pCheck.
35303 */
35304 static void checkPtrmap(
35305   IntegrityCk *pCheck,   /* Integrity check context */
35306   Pgno iChild,           /* Child page number */
35307   u8 eType,              /* Expected pointer map type */
35308   Pgno iParent,          /* Expected pointer map parent page number */
35309   char *zContext         /* Context description (used for error msg) */
35310 ){
35311   int rc;
35312   u8 ePtrmapType;
35313   Pgno iPtrmapParent;
35314
35315   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
35316   if( rc!=SQLITE_OK ){
35317     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
35318     return;
35319   }
35320
35321   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
35322     checkAppendMsg(pCheck, zContext, 
35323       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
35324       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
35325   }
35326 }
35327 #endif
35328
35329 /*
35330 ** Check the integrity of the freelist or of an overflow page list.
35331 ** Verify that the number of pages on the list is N.
35332 */
35333 static void checkList(
35334   IntegrityCk *pCheck,  /* Integrity checking context */
35335   int isFreeList,       /* True for a freelist.  False for overflow page list */
35336   int iPage,            /* Page number for first page in the list */
35337   int N,                /* Expected number of pages in the list */
35338   char *zContext        /* Context for error messages */
35339 ){
35340   int i;
35341   int expected = N;
35342   int iFirst = iPage;
35343   while( N-- > 0 && pCheck->mxErr ){
35344     DbPage *pOvflPage;
35345     unsigned char *pOvflData;
35346     if( iPage<1 ){
35347       checkAppendMsg(pCheck, zContext,
35348          "%d of %d pages missing from overflow list starting at %d",
35349           N+1, expected, iFirst);
35350       break;
35351     }
35352     if( checkRef(pCheck, iPage, zContext) ) break;
35353     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
35354       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
35355       break;
35356     }
35357     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
35358     if( isFreeList ){
35359       int n = get4byte(&pOvflData[4]);
35360 #ifndef SQLITE_OMIT_AUTOVACUUM
35361       if( pCheck->pBt->autoVacuum ){
35362         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
35363       }
35364 #endif
35365       if( n>pCheck->pBt->usableSize/4-8 ){
35366         checkAppendMsg(pCheck, zContext,
35367            "freelist leaf count too big on page %d", iPage);
35368         N--;
35369       }else{
35370         for(i=0; i<n; i++){
35371           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
35372 #ifndef SQLITE_OMIT_AUTOVACUUM
35373           if( pCheck->pBt->autoVacuum ){
35374             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
35375           }
35376 #endif
35377           checkRef(pCheck, iFreePage, zContext);
35378         }
35379         N -= n;
35380       }
35381     }
35382 #ifndef SQLITE_OMIT_AUTOVACUUM
35383     else{
35384       /* If this database supports auto-vacuum and iPage is not the last
35385       ** page in this overflow list, check that the pointer-map entry for
35386       ** the following page matches iPage.
35387       */
35388       if( pCheck->pBt->autoVacuum && N>0 ){
35389         i = get4byte(pOvflData);
35390         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
35391       }
35392     }
35393 #endif
35394     iPage = get4byte(pOvflData);
35395     sqlite3PagerUnref(pOvflPage);
35396   }
35397 }
35398 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
35399
35400 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
35401 /*
35402 ** Do various sanity checks on a single page of a tree.  Return
35403 ** the tree depth.  Root pages return 0.  Parents of root pages
35404 ** return 1, and so forth.
35405 ** 
35406 ** These checks are done:
35407 **
35408 **      1.  Make sure that cells and freeblocks do not overlap
35409 **          but combine to completely cover the page.
35410 **  NO  2.  Make sure cell keys are in order.
35411 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
35412 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
35413 **      5.  Check the integrity of overflow pages.
35414 **      6.  Recursively call checkTreePage on all children.
35415 **      7.  Verify that the depth of all children is the same.
35416 **      8.  Make sure this page is at least 33% full or else it is
35417 **          the root of the tree.
35418 */
35419 static int checkTreePage(
35420   IntegrityCk *pCheck,  /* Context for the sanity check */
35421   int iPage,            /* Page number of the page to check */
35422   MemPage *pParent,     /* Parent page */
35423   char *zParentContext  /* Parent context */
35424 ){
35425   MemPage *pPage;
35426   int i, rc, depth, d2, pgno, cnt;
35427   int hdr, cellStart;
35428   int nCell;
35429   u8 *data;
35430   BtShared *pBt;
35431   int usableSize;
35432   char zContext[100];
35433   char *hit;
35434
35435   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
35436
35437   /* Check that the page exists
35438   */
35439   pBt = pCheck->pBt;
35440   usableSize = pBt->usableSize;
35441   if( iPage==0 ) return 0;
35442   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
35443   if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
35444     checkAppendMsg(pCheck, zContext,
35445        "unable to get the page. error code=%d", rc);
35446     return 0;
35447   }
35448   if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
35449     checkAppendMsg(pCheck, zContext, 
35450                    "sqlite3BtreeInitPage() returns error code %d", rc);
35451     releasePage(pPage);
35452     return 0;
35453   }
35454
35455   /* Check out all the cells.
35456   */
35457   depth = 0;
35458   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
35459     u8 *pCell;
35460     int sz;
35461     CellInfo info;
35462
35463     /* Check payload overflow pages
35464     */
35465     sqlite3_snprintf(sizeof(zContext), zContext,
35466              "On tree page %d cell %d: ", iPage, i);
35467     pCell = findCell(pPage,i);
35468     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
35469     sz = info.nData;
35470     if( !pPage->intKey ) sz += info.nKey;
35471     assert( sz==info.nPayload );
35472     if( sz>info.nLocal ){
35473       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
35474       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
35475 #ifndef SQLITE_OMIT_AUTOVACUUM
35476       if( pBt->autoVacuum ){
35477         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
35478       }
35479 #endif
35480       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
35481     }
35482
35483     /* Check sanity of left child page.
35484     */
35485     if( !pPage->leaf ){
35486       pgno = get4byte(pCell);
35487 #ifndef SQLITE_OMIT_AUTOVACUUM
35488       if( pBt->autoVacuum ){
35489         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
35490       }
35491 #endif
35492       d2 = checkTreePage(pCheck,pgno,pPage,zContext);
35493       if( i>0 && d2!=depth ){
35494         checkAppendMsg(pCheck, zContext, "Child page depth differs");
35495       }
35496       depth = d2;
35497     }
35498   }
35499   if( !pPage->leaf ){
35500     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
35501     sqlite3_snprintf(sizeof(zContext), zContext, 
35502                      "On page %d at right child: ", iPage);
35503 #ifndef SQLITE_OMIT_AUTOVACUUM
35504     if( pBt->autoVacuum ){
35505       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
35506     }
35507 #endif
35508     checkTreePage(pCheck, pgno, pPage, zContext);
35509   }
35510  
35511   /* Check for complete coverage of the page
35512   */
35513   data = pPage->aData;
35514   hdr = pPage->hdrOffset;
35515   hit = sqlite3MallocZero( usableSize );
35516   if( hit ){
35517     memset(hit, 1, get2byte(&data[hdr+5]));
35518     nCell = get2byte(&data[hdr+3]);
35519     cellStart = hdr + 12 - 4*pPage->leaf;
35520     for(i=0; i<nCell; i++){
35521       int pc = get2byte(&data[cellStart+i*2]);
35522       u16 size = cellSizePtr(pPage, &data[pc]);
35523       int j;
35524       if( (pc+size-1)>=usableSize || pc<0 ){
35525         checkAppendMsg(pCheck, 0, 
35526             "Corruption detected in cell %d on page %d",i,iPage,0);
35527       }else{
35528         for(j=pc+size-1; j>=pc; j--) hit[j]++;
35529       }
35530     }
35531     for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; 
35532            cnt++){
35533       int size = get2byte(&data[i+2]);
35534       int j;
35535       if( (i+size-1)>=usableSize || i<0 ){
35536         checkAppendMsg(pCheck, 0,  
35537             "Corruption detected in cell %d on page %d",i,iPage,0);
35538       }else{
35539         for(j=i+size-1; j>=i; j--) hit[j]++;
35540       }
35541       i = get2byte(&data[i]);
35542     }
35543     for(i=cnt=0; i<usableSize; i++){
35544       if( hit[i]==0 ){
35545         cnt++;
35546       }else if( hit[i]>1 ){
35547         checkAppendMsg(pCheck, 0,
35548           "Multiple uses for byte %d of page %d", i, iPage);
35549         break;
35550       }
35551     }
35552     if( cnt!=data[hdr+7] ){
35553       checkAppendMsg(pCheck, 0, 
35554           "Fragmented space is %d byte reported as %d on page %d",
35555           cnt, data[hdr+7], iPage);
35556     }
35557   }
35558   sqlite3_free(hit);
35559
35560   releasePage(pPage);
35561   return depth+1;
35562 }
35563 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
35564
35565 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
35566 /*
35567 ** This routine does a complete check of the given BTree file.  aRoot[] is
35568 ** an array of pages numbers were each page number is the root page of
35569 ** a table.  nRoot is the number of entries in aRoot.
35570 **
35571 ** If everything checks out, this routine returns NULL.  If something is
35572 ** amiss, an error message is written into memory obtained from malloc()
35573 ** and a pointer to that error message is returned.  The calling function
35574 ** is responsible for freeing the error message when it is done.
35575 */
35576 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
35577   Btree *p,     /* The btree to be checked */
35578   int *aRoot,   /* An array of root pages numbers for individual trees */
35579   int nRoot,    /* Number of entries in aRoot[] */
35580   int mxErr,    /* Stop reporting errors after this many */
35581   int *pnErr    /* Write number of errors seen to this variable */
35582 ){
35583   int i;
35584   int nRef;
35585   IntegrityCk sCheck;
35586   BtShared *pBt = p->pBt;
35587
35588   sqlite3BtreeEnter(p);
35589   pBt->db = p->db;
35590   nRef = sqlite3PagerRefcount(pBt->pPager);
35591   if( lockBtreeWithRetry(p)!=SQLITE_OK ){
35592     sqlite3BtreeLeave(p);
35593     return sqlite3StrDup("Unable to acquire a read lock on the database");
35594   }
35595   sCheck.pBt = pBt;
35596   sCheck.pPager = pBt->pPager;
35597   sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
35598   sCheck.mxErr = mxErr;
35599   sCheck.nErr = 0;
35600   *pnErr = 0;
35601 #ifndef SQLITE_OMIT_AUTOVACUUM
35602   if( pBt->nTrunc!=0 ){
35603     sCheck.nPage = pBt->nTrunc;
35604   }
35605 #endif
35606   if( sCheck.nPage==0 ){
35607     unlockBtreeIfUnused(pBt);
35608     sqlite3BtreeLeave(p);
35609     return 0;
35610   }
35611   sCheck.anRef = sqlite3_malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
35612   if( !sCheck.anRef ){
35613     unlockBtreeIfUnused(pBt);
35614     *pnErr = 1;
35615     sqlite3BtreeLeave(p);
35616     return sqlite3MPrintf(p->db, "Unable to malloc %d bytes", 
35617         (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
35618   }
35619   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
35620   i = PENDING_BYTE_PAGE(pBt);
35621   if( i<=sCheck.nPage ){
35622     sCheck.anRef[i] = 1;
35623   }
35624   sCheck.zErrMsg = 0;
35625
35626   /* Check the integrity of the freelist
35627   */
35628   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
35629             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
35630
35631   /* Check all the tables.
35632   */
35633   for(i=0; i<nRoot && sCheck.mxErr; i++){
35634     if( aRoot[i]==0 ) continue;
35635 #ifndef SQLITE_OMIT_AUTOVACUUM
35636     if( pBt->autoVacuum && aRoot[i]>1 ){
35637       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
35638     }
35639 #endif
35640     checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
35641   }
35642
35643   /* Make sure every page in the file is referenced
35644   */
35645   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
35646 #ifdef SQLITE_OMIT_AUTOVACUUM
35647     if( sCheck.anRef[i]==0 ){
35648       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
35649     }
35650 #else
35651     /* If the database supports auto-vacuum, make sure no tables contain
35652     ** references to pointer-map pages.
35653     */
35654     if( sCheck.anRef[i]==0 && 
35655        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
35656       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
35657     }
35658     if( sCheck.anRef[i]!=0 && 
35659        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
35660       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
35661     }
35662 #endif
35663   }
35664
35665   /* Make sure this analysis did not leave any unref() pages
35666   */
35667   unlockBtreeIfUnused(pBt);
35668   if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
35669     checkAppendMsg(&sCheck, 0, 
35670       "Outstanding page count goes from %d to %d during this analysis",
35671       nRef, sqlite3PagerRefcount(pBt->pPager)
35672     );
35673   }
35674
35675   /* Clean  up and report errors.
35676   */
35677   sqlite3BtreeLeave(p);
35678   sqlite3_free(sCheck.anRef);
35679   *pnErr = sCheck.nErr;
35680   return sCheck.zErrMsg;
35681 }
35682 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
35683
35684 /*
35685 ** Return the full pathname of the underlying database file.
35686 **
35687 ** The pager filename is invariant as long as the pager is
35688 ** open so it is safe to access without the BtShared mutex.
35689 */
35690 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
35691   assert( p->pBt->pPager!=0 );
35692   return sqlite3PagerFilename(p->pBt->pPager);
35693 }
35694
35695 /*
35696 ** Return the pathname of the directory that contains the database file.
35697 **
35698 ** The pager directory name is invariant as long as the pager is
35699 ** open so it is safe to access without the BtShared mutex.
35700 */
35701 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
35702   assert( p->pBt->pPager!=0 );
35703   return sqlite3PagerDirname(p->pBt->pPager);
35704 }
35705
35706 /*
35707 ** Return the pathname of the journal file for this database. The return
35708 ** value of this routine is the same regardless of whether the journal file
35709 ** has been created or not.
35710 **
35711 ** The pager journal filename is invariant as long as the pager is
35712 ** open so it is safe to access without the BtShared mutex.
35713 */
35714 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
35715   assert( p->pBt->pPager!=0 );
35716   return sqlite3PagerJournalname(p->pBt->pPager);
35717 }
35718
35719 #ifndef SQLITE_OMIT_VACUUM
35720 /*
35721 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
35722 ** must be active for both files.
35723 **
35724 ** The size of file pBtFrom may be reduced by this operation.
35725 ** If anything goes wrong, the transaction on pBtFrom is rolled back.
35726 */
35727 static int btreeCopyFile(Btree *pTo, Btree *pFrom){
35728   int rc = SQLITE_OK;
35729   Pgno i, nPage, nToPage, iSkip;
35730
35731   BtShared *pBtTo = pTo->pBt;
35732   BtShared *pBtFrom = pFrom->pBt;
35733   pBtTo->db = pTo->db;
35734   pBtFrom->db = pFrom->db;
35735   
35736
35737   if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
35738     return SQLITE_ERROR;
35739   }
35740   if( pBtTo->pCursor ) return SQLITE_BUSY;
35741   nToPage = sqlite3PagerPagecount(pBtTo->pPager);
35742   nPage = sqlite3PagerPagecount(pBtFrom->pPager);
35743   iSkip = PENDING_BYTE_PAGE(pBtTo);
35744   for(i=1; rc==SQLITE_OK && i<=nPage; i++){
35745     DbPage *pDbPage;
35746     if( i==iSkip ) continue;
35747     rc = sqlite3PagerGet(pBtFrom->pPager, i, &pDbPage);
35748     if( rc ) break;
35749     rc = sqlite3PagerOverwrite(pBtTo->pPager, i, sqlite3PagerGetData(pDbPage));
35750     sqlite3PagerUnref(pDbPage);
35751   }
35752
35753   /* If the file is shrinking, journal the pages that are being truncated
35754   ** so that they can be rolled back if the commit fails.
35755   */
35756   for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
35757     DbPage *pDbPage;
35758     if( i==iSkip ) continue;
35759     rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
35760     if( rc ) break;
35761     rc = sqlite3PagerWrite(pDbPage);
35762     sqlite3PagerDontWrite(pDbPage);
35763     /* Yeah.  It seems wierd to call DontWrite() right after Write().  But
35764     ** that is because the names of those procedures do not exactly 
35765     ** represent what they do.  Write() really means "put this page in the
35766     ** rollback journal and mark it as dirty so that it will be written
35767     ** to the database file later."  DontWrite() undoes the second part of
35768     ** that and prevents the page from being written to the database.  The
35769     ** page is still on the rollback journal, though.  And that is the whole
35770     ** point of this loop: to put pages on the rollback journal. */
35771     sqlite3PagerUnref(pDbPage);
35772   }
35773   if( !rc && nPage<nToPage ){
35774     rc = sqlite3PagerTruncate(pBtTo->pPager, nPage);
35775   }
35776
35777   if( rc ){
35778     sqlite3BtreeRollback(pTo);
35779   }
35780   return rc;  
35781 }
35782 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
35783   int rc;
35784   sqlite3BtreeEnter(pTo);
35785   sqlite3BtreeEnter(pFrom);
35786   rc = btreeCopyFile(pTo, pFrom);
35787   sqlite3BtreeLeave(pFrom);
35788   sqlite3BtreeLeave(pTo);
35789   return rc;
35790 }
35791
35792 #endif /* SQLITE_OMIT_VACUUM */
35793
35794 /*
35795 ** Return non-zero if a transaction is active.
35796 */
35797 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
35798   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
35799   return (p && (p->inTrans==TRANS_WRITE));
35800 }
35801
35802 /*
35803 ** Return non-zero if a statement transaction is active.
35804 */
35805 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
35806   assert( sqlite3BtreeHoldsMutex(p) );
35807   return (p->pBt && p->pBt->inStmt);
35808 }
35809
35810 /*
35811 ** Return non-zero if a read (or write) transaction is active.
35812 */
35813 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
35814   assert( sqlite3_mutex_held(p->db->mutex) );
35815   return (p && (p->inTrans!=TRANS_NONE));
35816 }
35817
35818 /*
35819 ** This function returns a pointer to a blob of memory associated with
35820 ** a single shared-btree. The memory is used by client code for its own
35821 ** purposes (for example, to store a high-level schema associated with 
35822 ** the shared-btree). The btree layer manages reference counting issues.
35823 **
35824 ** The first time this is called on a shared-btree, nBytes bytes of memory
35825 ** are allocated, zeroed, and returned to the caller. For each subsequent 
35826 ** call the nBytes parameter is ignored and a pointer to the same blob
35827 ** of memory returned. 
35828 **
35829 ** Just before the shared-btree is closed, the function passed as the 
35830 ** xFree argument when the memory allocation was made is invoked on the 
35831 ** blob of allocated memory. This function should not call sqlite3_free()
35832 ** on the memory, the btree layer does that.
35833 */
35834 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
35835   BtShared *pBt = p->pBt;
35836   sqlite3BtreeEnter(p);
35837   if( !pBt->pSchema ){
35838     pBt->pSchema = sqlite3MallocZero(nBytes);
35839     pBt->xFreeSchema = xFree;
35840   }
35841   sqlite3BtreeLeave(p);
35842   return pBt->pSchema;
35843 }
35844
35845 /*
35846 ** Return true if another user of the same shared btree as the argument
35847 ** handle holds an exclusive lock on the sqlite_master table.
35848 */
35849 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
35850   int rc;
35851   assert( sqlite3_mutex_held(p->db->mutex) );
35852   sqlite3BtreeEnter(p);
35853   rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
35854   sqlite3BtreeLeave(p);
35855   return rc;
35856 }
35857
35858
35859 #ifndef SQLITE_OMIT_SHARED_CACHE
35860 /*
35861 ** Obtain a lock on the table whose root page is iTab.  The
35862 ** lock is a write lock if isWritelock is true or a read lock
35863 ** if it is false.
35864 */
35865 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
35866   int rc = SQLITE_OK;
35867   u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
35868   sqlite3BtreeEnter(p);
35869   rc = queryTableLock(p, iTab, lockType);
35870   if( rc==SQLITE_OK ){
35871     rc = lockTable(p, iTab, lockType);
35872   }
35873   sqlite3BtreeLeave(p);
35874   return rc;
35875 }
35876 #endif
35877
35878 #ifndef SQLITE_OMIT_INCRBLOB
35879 /*
35880 ** Argument pCsr must be a cursor opened for writing on an 
35881 ** INTKEY table currently pointing at a valid table entry. 
35882 ** This function modifies the data stored as part of that entry.
35883 ** Only the data content may only be modified, it is not possible
35884 ** to change the length of the data stored.
35885 */
35886 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
35887   assert( cursorHoldsMutex(pCsr) );
35888   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
35889   assert(pCsr->isIncrblobHandle);
35890   if( pCsr->eState>=CURSOR_REQUIRESEEK ){
35891     if( pCsr->eState==CURSOR_FAULT ){
35892       return pCsr->skip;
35893     }else{
35894       return SQLITE_ABORT;
35895     }
35896   }
35897
35898   /* Check some preconditions: 
35899   **   (a) the cursor is open for writing,
35900   **   (b) there is no read-lock on the table being modified and
35901   **   (c) the cursor points at a valid row of an intKey table.
35902   */
35903   if( !pCsr->wrFlag ){
35904     return SQLITE_READONLY;
35905   }
35906   assert( !pCsr->pBt->readOnly 
35907           && pCsr->pBt->inTransaction==TRANS_WRITE );
35908   if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
35909     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
35910   }
35911   if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
35912     return SQLITE_ERROR;
35913   }
35914
35915   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
35916 }
35917
35918 /* 
35919 ** Set a flag on this cursor to cache the locations of pages from the 
35920 ** overflow list for the current row. This is used by cursors opened
35921 ** for incremental blob IO only.
35922 **
35923 ** This function sets a flag only. The actual page location cache
35924 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
35925 ** accessPayload() (the worker function for sqlite3BtreeData() and
35926 ** sqlite3BtreePutData()).
35927 */
35928 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
35929   assert( cursorHoldsMutex(pCur) );
35930   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
35931   assert(!pCur->isIncrblobHandle);
35932   assert(!pCur->aOverflow);
35933   pCur->isIncrblobHandle = 1;
35934 }
35935 #endif
35936
35937 /************** End of btree.c ***********************************************/
35938 /************** Begin file vdbefifo.c ****************************************/
35939 /*
35940 ** 2005 June 16
35941 **
35942 ** The author disclaims copyright to this source code.  In place of
35943 ** a legal notice, here is a blessing:
35944 **
35945 **    May you do good and not evil.
35946 **    May you find forgiveness for yourself and forgive others.
35947 **    May you share freely, never taking more than you give.
35948 **
35949 *************************************************************************
35950 ** This file implements a FIFO queue of rowids used for processing
35951 ** UPDATE and DELETE statements.
35952 */
35953
35954 /*
35955 ** Constants FIFOSIZE_FIRST and FIFOSIZE_MAX are the initial
35956 ** number of entries in a fifo page and the maximum number of
35957 ** entries in a fifo page.
35958 */
35959 #define FIFOSIZE_FIRST (((128-sizeof(FifoPage))/8)+1)
35960 #ifdef SQLITE_MALLOC_SOFT_LIMIT
35961 # define FIFOSIZE_MAX   (((SQLITE_MALLOC_SOFT_LIMIT-sizeof(FifoPage))/8)+1)
35962 #else
35963 # define FIFOSIZE_MAX   (((262144-sizeof(FifoPage))/8)+1)
35964 #endif
35965
35966 /*
35967 ** Allocate a new FifoPage and return a pointer to it.  Return NULL if
35968 ** we run out of memory.  Leave space on the page for nEntry entries.
35969 */
35970 static FifoPage *allocateFifoPage(int nEntry){
35971   FifoPage *pPage;
35972   if( nEntry>FIFOSIZE_MAX ){
35973     nEntry = FIFOSIZE_MAX;
35974   }
35975   pPage = sqlite3_malloc( sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
35976   if( pPage ){
35977     pPage->nSlot = nEntry;
35978     pPage->iWrite = 0;
35979     pPage->iRead = 0;
35980     pPage->pNext = 0;
35981   }
35982   return pPage;
35983 }
35984
35985 /*
35986 ** Initialize a Fifo structure.
35987 */
35988 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo *pFifo){
35989   memset(pFifo, 0, sizeof(*pFifo));
35990 }
35991
35992 /*
35993 ** Push a single 64-bit integer value into the Fifo.  Return SQLITE_OK
35994 ** normally.   SQLITE_NOMEM is returned if we are unable to allocate
35995 ** memory.
35996 */
35997 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
35998   FifoPage *pPage;
35999   pPage = pFifo->pLast;
36000   if( pPage==0 ){
36001     pPage = pFifo->pLast = pFifo->pFirst = allocateFifoPage(FIFOSIZE_FIRST);
36002     if( pPage==0 ){
36003       return SQLITE_NOMEM;
36004     }
36005   }else if( pPage->iWrite>=pPage->nSlot ){
36006     pPage->pNext = allocateFifoPage(pFifo->nEntry);
36007     if( pPage->pNext==0 ){
36008       return SQLITE_NOMEM;
36009     }
36010     pPage = pFifo->pLast = pPage->pNext;
36011   }
36012   pPage->aSlot[pPage->iWrite++] = val;
36013   pFifo->nEntry++;
36014   return SQLITE_OK;
36015 }
36016
36017 /*
36018 ** Extract a single 64-bit integer value from the Fifo.  The integer
36019 ** extracted is the one least recently inserted.  If the Fifo is empty
36020 ** return SQLITE_DONE.
36021 */
36022 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
36023   FifoPage *pPage;
36024   if( pFifo->nEntry==0 ){
36025     return SQLITE_DONE;
36026   }
36027   assert( pFifo->nEntry>0 );
36028   pPage = pFifo->pFirst;
36029   assert( pPage!=0 );
36030   assert( pPage->iWrite>pPage->iRead );
36031   assert( pPage->iWrite<=pPage->nSlot );
36032   assert( pPage->iRead<pPage->nSlot );
36033   assert( pPage->iRead>=0 );
36034   *pVal = pPage->aSlot[pPage->iRead++];
36035   pFifo->nEntry--;
36036   if( pPage->iRead>=pPage->iWrite ){
36037     pFifo->pFirst = pPage->pNext;
36038     sqlite3_free(pPage);
36039     if( pFifo->nEntry==0 ){
36040       assert( pFifo->pLast==pPage );
36041       pFifo->pLast = 0;
36042     }else{
36043       assert( pFifo->pFirst!=0 );
36044     }
36045   }else{
36046     assert( pFifo->nEntry>0 );
36047   }
36048   return SQLITE_OK;
36049 }
36050
36051 /*
36052 ** Delete all information from a Fifo object.   Free all memory held
36053 ** by the Fifo.
36054 */
36055 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo *pFifo){
36056   FifoPage *pPage, *pNextPage;
36057   for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
36058     pNextPage = pPage->pNext;
36059     sqlite3_free(pPage);
36060   }
36061   sqlite3VdbeFifoInit(pFifo);
36062 }
36063
36064 /************** End of vdbefifo.c ********************************************/
36065 /************** Begin file vdbemem.c *****************************************/
36066 /*
36067 ** 2004 May 26
36068 **
36069 ** The author disclaims copyright to this source code.  In place of
36070 ** a legal notice, here is a blessing:
36071 **
36072 **    May you do good and not evil.
36073 **    May you find forgiveness for yourself and forgive others.
36074 **    May you share freely, never taking more than you give.
36075 **
36076 *************************************************************************
36077 **
36078 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
36079 ** stores a single value in the VDBE.  Mem is an opaque structure visible
36080 ** only within the VDBE.  Interface routines refer to a Mem using the
36081 ** name sqlite_value
36082 */
36083
36084 /*
36085 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
36086 ** P if required.
36087 */
36088 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
36089
36090 /*
36091 ** If pMem is an object with a valid string representation, this routine
36092 ** ensures the internal encoding for the string representation is
36093 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
36094 **
36095 ** If pMem is not a string object, or the encoding of the string
36096 ** representation is already stored using the requested encoding, then this
36097 ** routine is a no-op.
36098 **
36099 ** SQLITE_OK is returned if the conversion is successful (or not required).
36100 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
36101 ** between formats.
36102 */
36103 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
36104   int rc;
36105   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
36106     return SQLITE_OK;
36107   }
36108   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36109 #ifdef SQLITE_OMIT_UTF16
36110   return SQLITE_ERROR;
36111 #else
36112
36113   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
36114   ** then the encoding of the value may not have changed.
36115   */
36116   rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
36117   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
36118   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
36119   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
36120   return rc;
36121 #endif
36122 }
36123
36124 /*
36125 ** Make sure pMem->z points to a writable allocation of at least 
36126 ** n bytes.
36127 **
36128 ** If the memory cell currently contains string or blob data
36129 ** and the third argument passed to this function is true, the 
36130 ** current content of the cell is preserved. Otherwise, it may
36131 ** be discarded.  
36132 **
36133 ** This function sets the MEM_Dyn flag and clears any xDel callback.
36134 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
36135 ** not set, Mem.n is zeroed.
36136 */
36137 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
36138   int f = pMem->flags;
36139
36140   assert( (f & (MEM_Dyn|MEM_Static|MEM_Ephem))==0 
36141        || (f & (MEM_Dyn|MEM_Static|MEM_Ephem))==MEM_Dyn 
36142        || (f & (MEM_Dyn|MEM_Static|MEM_Ephem))==MEM_Ephem 
36143        || (f & (MEM_Dyn|MEM_Static|MEM_Ephem))==MEM_Static 
36144   );
36145
36146   if( ((f&MEM_Dyn)==0 || pMem->xDel || sqlite3MallocSize(pMem->z)<n) ){
36147
36148     /* Allocate the new buffer. The minimum allocation size is 32 bytes. */
36149     char *z = 0;
36150     if( n>0 ){
36151       if( preserve && (f&MEM_Dyn) && !pMem->xDel ){
36152         z = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
36153         pMem->z = 0;
36154         preserve = 0;
36155       }else{
36156         z = sqlite3DbMallocRaw(pMem->db, (n>32?n:32));
36157       }
36158       if( !z ){
36159         return SQLITE_NOMEM;
36160       }
36161     }
36162
36163     /* If the value is currently a string or blob and the preserve flag
36164     ** is true, copy the content to the new buffer. 
36165     */
36166     if( pMem->flags&(MEM_Blob|MEM_Str) && preserve ){
36167       int nCopy = (pMem->n>n?n:pMem->n);
36168       memcpy(z, pMem->z, nCopy);
36169     }
36170  
36171     /* Release the old buffer. */
36172     sqlite3VdbeMemRelease(pMem);
36173
36174     pMem->z = z;
36175     pMem->flags |= MEM_Dyn;
36176     pMem->flags &= ~(MEM_Ephem|MEM_Static);
36177     pMem->xDel = 0;
36178   }
36179   return SQLITE_OK;
36180 }
36181
36182 /*
36183 ** Make the given Mem object MEM_Dyn.
36184 **
36185 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
36186 */
36187 SQLITE_PRIVATE int sqlite3VdbeMemDynamicify(Mem *pMem){
36188   int f;
36189   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36190   expandBlob(pMem);
36191   f = pMem->flags;
36192   if( (f&(MEM_Str|MEM_Blob)) && ((f&MEM_Dyn)==0 || pMem->xDel) ){
36193     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
36194       return SQLITE_NOMEM;
36195     }
36196     pMem->z[pMem->n] = 0;
36197     pMem->z[pMem->n+1] = 0;
36198     pMem->flags |= MEM_Term;
36199   }
36200
36201   return SQLITE_OK;
36202 }
36203
36204 /*
36205 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
36206 ** blob stored in dynamically allocated space.
36207 */
36208 #ifndef SQLITE_OMIT_INCRBLOB
36209 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
36210   if( pMem->flags & MEM_Zero ){
36211     int nByte;
36212     assert( pMem->flags&MEM_Blob );
36213     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36214
36215     /* Set nByte to the number of bytes required to store the expanded blob. */
36216     nByte = pMem->n + pMem->u.i;
36217     if( nByte<=0 ){
36218       nByte = 1;
36219     }
36220     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
36221       return SQLITE_NOMEM;
36222     }
36223
36224     memset(&pMem->z[pMem->n], 0, pMem->u.i);
36225     pMem->n += pMem->u.i;
36226     pMem->flags &= ~(MEM_Zero|MEM_Term);
36227   }
36228   return SQLITE_OK;
36229 }
36230 #endif
36231
36232
36233 /*
36234 ** Make the given Mem object either MEM_Short or MEM_Dyn so that bytes
36235 ** of the Mem.z[] array can be modified.
36236 **
36237 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
36238 */
36239 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
36240   return sqlite3VdbeMemDynamicify(pMem);
36241 }
36242
36243 /*
36244 ** Make sure the given Mem is \u0000 terminated.
36245 */
36246 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
36247   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36248   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
36249     return SQLITE_OK;   /* Nothing to do */
36250   }
36251   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
36252     return SQLITE_NOMEM;
36253   }
36254   pMem->z[pMem->n] = 0;
36255   pMem->z[pMem->n+1] = 0;
36256   pMem->flags |= MEM_Term;
36257   return SQLITE_OK;
36258 }
36259
36260 /*
36261 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
36262 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
36263 ** is a no-op.
36264 **
36265 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
36266 **
36267 ** A MEM_Null value will never be passed to this function. This function is
36268 ** used for converting values to text for returning to the user (i.e. via
36269 ** sqlite3_value_text()), or for ensuring that values to be used as btree
36270 ** keys are strings. In the former case a NULL pointer is returned the
36271 ** user and the later is an internal programming error.
36272 */
36273 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
36274   int rc = SQLITE_OK;
36275   int fg = pMem->flags;
36276   const int nByte = 32;
36277
36278   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36279   assert( !(fg&MEM_Zero) );
36280   assert( !(fg&(MEM_Str|MEM_Blob)) );
36281   assert( fg&(MEM_Int|MEM_Real) );
36282
36283   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
36284     return SQLITE_NOMEM;
36285   }
36286
36287   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
36288   ** string representation of the value. Then, if the required encoding
36289   ** is UTF-16le or UTF-16be do a translation.
36290   ** 
36291   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
36292   */
36293   if( fg & MEM_Int ){
36294     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
36295   }else{
36296     assert( fg & MEM_Real );
36297     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
36298   }
36299   pMem->n = strlen(pMem->z);
36300   pMem->enc = SQLITE_UTF8;
36301   pMem->flags |= MEM_Str|MEM_Term;
36302   sqlite3VdbeChangeEncoding(pMem, enc);
36303   return rc;
36304 }
36305
36306 /*
36307 ** Memory cell pMem contains the context of an aggregate function.
36308 ** This routine calls the finalize method for that function.  The
36309 ** result of the aggregate is stored back into pMem.
36310 **
36311 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
36312 ** otherwise.
36313 */
36314 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
36315   int rc = SQLITE_OK;
36316   if( pFunc && pFunc->xFinalize ){
36317     sqlite3_context ctx;
36318     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
36319     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36320     ctx.s.flags = MEM_Null;
36321     ctx.s.db = pMem->db;
36322     ctx.pMem = pMem;
36323     ctx.pFunc = pFunc;
36324     ctx.isError = 0;
36325     pFunc->xFinalize(&ctx);
36326     if( pMem->z ){
36327       sqlite3_free( pMem->z );
36328     }
36329     *pMem = ctx.s;
36330     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
36331   }
36332   return rc;
36333 }
36334
36335 /*
36336 ** Release any memory held by the Mem. This may leave the Mem in an
36337 ** inconsistent state, for example with (Mem.z==0) and
36338 ** (Mem.type==SQLITE_TEXT).
36339 */
36340 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
36341   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
36342   if( p->flags & (MEM_Dyn|MEM_Agg) ){
36343     if( p->xDel ){
36344       if( p->flags & MEM_Agg ){
36345         sqlite3VdbeMemFinalize(p, p->u.pDef);
36346         assert( (p->flags & MEM_Agg)==0 );
36347         sqlite3VdbeMemRelease(p);
36348       }else{
36349         p->xDel((void *)p->z);
36350       }
36351     }else{
36352       sqlite3_free(p->z);
36353     }
36354     p->z = 0;
36355     p->xDel = 0;
36356   }
36357 }
36358
36359 /*
36360 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
36361 ** If the double is too large, return 0x8000000000000000.
36362 **
36363 ** Most systems appear to do this simply by assigning
36364 ** variables and without the extra range tests.  But
36365 ** there are reports that windows throws an expection
36366 ** if the floating point value is out of range. (See ticket #2880.)
36367 ** Because we do not completely understand the problem, we will
36368 ** take the conservative approach and always do range tests
36369 ** before attempting the conversion.
36370 */
36371 static i64 doubleToInt64(double r){
36372   /*
36373   ** Many compilers we encounter do not define constants for the
36374   ** minimum and maximum 64-bit integers, or they define them
36375   ** inconsistently.  And many do not understand the "LL" notation.
36376   ** So we define our own static constants here using nothing
36377   ** larger than a 32-bit integer constant.
36378   */
36379   static const i64 maxInt = (((i64)0x7fffffff)<<32)|0xffffffff;
36380   static const i64 minInt = ((i64)0x80000000)<<32;
36381
36382   if( r<(double)minInt ){
36383     return minInt;
36384   }else if( r>(double)maxInt ){
36385     return minInt;
36386   }else{
36387     return (i64)r;
36388   }
36389 }
36390
36391 /*
36392 ** Return some kind of integer value which is the best we can do
36393 ** at representing the value that *pMem describes as an integer.
36394 ** If pMem is an integer, then the value is exact.  If pMem is
36395 ** a floating-point then the value returned is the integer part.
36396 ** If pMem is a string or blob, then we make an attempt to convert
36397 ** it into a integer and return that.  If pMem is NULL, return 0.
36398 **
36399 ** If pMem is a string, its encoding might be changed.
36400 */
36401 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
36402   int flags;
36403   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36404   flags = pMem->flags;
36405   if( flags & MEM_Int ){
36406     return pMem->u.i;
36407   }else if( flags & MEM_Real ){
36408     return doubleToInt64(pMem->r);
36409   }else if( flags & (MEM_Str|MEM_Blob) ){
36410     i64 value;
36411     pMem->flags |= MEM_Str;
36412     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
36413        || sqlite3VdbeMemNulTerminate(pMem) ){
36414       return 0;
36415     }
36416     assert( pMem->z );
36417     sqlite3Atoi64(pMem->z, &value);
36418     return value;
36419   }else{
36420     return 0;
36421   }
36422 }
36423
36424 /*
36425 ** Return the best representation of pMem that we can get into a
36426 ** double.  If pMem is already a double or an integer, return its
36427 ** value.  If it is a string or blob, try to convert it to a double.
36428 ** If it is a NULL, return 0.0.
36429 */
36430 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
36431   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36432   if( pMem->flags & MEM_Real ){
36433     return pMem->r;
36434   }else if( pMem->flags & MEM_Int ){
36435     return (double)pMem->u.i;
36436   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
36437     double val = 0.0;
36438     pMem->flags |= MEM_Str;
36439     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
36440        || sqlite3VdbeMemNulTerminate(pMem) ){
36441       return 0.0;
36442     }
36443     assert( pMem->z );
36444     sqlite3AtoF(pMem->z, &val);
36445     return val;
36446   }else{
36447     return 0.0;
36448   }
36449 }
36450
36451 /*
36452 ** The MEM structure is already a MEM_Real.  Try to also make it a
36453 ** MEM_Int if we can.
36454 */
36455 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
36456   assert( pMem->flags & MEM_Real );
36457   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36458
36459   pMem->u.i = doubleToInt64(pMem->r);
36460   if( pMem->r==(double)pMem->u.i ){
36461     pMem->flags |= MEM_Int;
36462   }
36463 }
36464
36465 static void setTypeFlag(Mem *pMem, int f){
36466   MemSetTypeFlag(pMem, f);
36467 }
36468
36469 /*
36470 ** Convert pMem to type integer.  Invalidate any prior representations.
36471 */
36472 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
36473   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36474   pMem->u.i = sqlite3VdbeIntValue(pMem);
36475   setTypeFlag(pMem, MEM_Int);
36476   return SQLITE_OK;
36477 }
36478
36479 /*
36480 ** Convert pMem so that it is of type MEM_Real.
36481 ** Invalidate any prior representations.
36482 */
36483 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
36484   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36485   pMem->r = sqlite3VdbeRealValue(pMem);
36486   setTypeFlag(pMem, MEM_Real);
36487   return SQLITE_OK;
36488 }
36489
36490 /*
36491 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
36492 ** Invalidate any prior representations.
36493 */
36494 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
36495   double r1, r2;
36496   i64 i;
36497   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
36498   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
36499   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36500   r1 = sqlite3VdbeRealValue(pMem);
36501   i = doubleToInt64(r1);
36502   r2 = (double)i;
36503   if( r1==r2 ){
36504     sqlite3VdbeMemIntegerify(pMem);
36505   }else{
36506     pMem->r = r1;
36507     setTypeFlag(pMem, MEM_Real);
36508   }
36509   return SQLITE_OK;
36510 }
36511
36512 /*
36513 ** Delete any previous value and set the value stored in *pMem to NULL.
36514 */
36515 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
36516   setTypeFlag(pMem, MEM_Null);
36517   pMem->type = SQLITE_NULL;
36518 }
36519
36520 /*
36521 ** Delete any previous value and set the value to be a BLOB of length
36522 ** n containing all zeros.
36523 */
36524 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
36525   sqlite3VdbeMemRelease(pMem);
36526   setTypeFlag(pMem, MEM_Blob);
36527   pMem->flags = MEM_Blob|MEM_Zero;
36528   pMem->type = SQLITE_BLOB;
36529   pMem->n = 0;
36530   if( n<0 ) n = 0;
36531   pMem->u.i = n;
36532   pMem->enc = SQLITE_UTF8;
36533 }
36534
36535 /*
36536 ** Delete any previous value and set the value stored in *pMem to val,
36537 ** manifest type INTEGER.
36538 */
36539 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
36540   sqlite3VdbeMemRelease(pMem);
36541   pMem->u.i = val;
36542   pMem->flags = MEM_Int;
36543   pMem->type = SQLITE_INTEGER;
36544 }
36545
36546 /*
36547 ** Delete any previous value and set the value stored in *pMem to val,
36548 ** manifest type REAL.
36549 */
36550 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
36551   if( sqlite3_isnan(val) ){
36552     sqlite3VdbeMemSetNull(pMem);
36553   }else{
36554     sqlite3VdbeMemRelease(pMem);
36555     pMem->r = val;
36556     pMem->flags = MEM_Real;
36557     pMem->type = SQLITE_FLOAT;
36558   }
36559 }
36560
36561 /*
36562 ** Return true if the Mem object contains a TEXT or BLOB that is
36563 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
36564 */
36565 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
36566   if( p->flags & (MEM_Str|MEM_Blob) ){
36567     int n = p->n;
36568     if( p->flags & MEM_Zero ){
36569       n += p->u.i;
36570     }
36571     return n>SQLITE_MAX_LENGTH;
36572   }
36573   return 0; 
36574 }
36575
36576 /*
36577 ** Make an shallow copy of pFrom into pTo.  Prior contents of
36578 ** pTo are freed.  The pFrom->z field is not duplicated.  If
36579 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
36580 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
36581 */
36582 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
36583   sqlite3VdbeMemRelease(pTo);
36584   memcpy(pTo, pFrom, sizeof(*pFrom));
36585   pTo->xDel = 0;
36586   if( pTo->flags&MEM_Dyn ){
36587     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
36588     assert( srcType==MEM_Ephem || srcType==MEM_Static );
36589     pTo->flags |= srcType;
36590   }
36591 }
36592
36593 /*
36594 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
36595 ** freed before the copy is made.
36596 */
36597 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
36598   int rc = SQLITE_OK;
36599   char *zBuf = 0;
36600
36601   /* If cell pTo currently has a reusable buffer, save a pointer to it
36602   ** in local variable zBuf. This function attempts to avoid freeing
36603   ** this buffer.
36604   */
36605   if( pTo->flags&MEM_Dyn ){
36606     if( pTo->xDel ){
36607       sqlite3VdbeMemRelease(pTo);
36608     }else{
36609       zBuf = pTo->z;
36610     }
36611   }
36612
36613   /* Copy the contents of *pFrom to *pTo */
36614   memcpy(pTo, pFrom, sizeof(*pFrom));
36615
36616   if( pTo->flags&(MEM_Str|MEM_Blob) && pTo->flags&MEM_Static ){
36617     /* pFrom contained a pointer to a static string. In this case,
36618     ** free any dynamically allocated buffer associated with pTo.
36619     */
36620     sqlite3_free(zBuf);
36621   }else{
36622     char *zData = pTo->z;
36623
36624     pTo->z = zBuf;
36625     pTo->flags &= ~(MEM_Static|MEM_Ephem);
36626     pTo->flags |= MEM_Dyn;
36627     pTo->xDel = 0;
36628  
36629     if( pTo->flags&(MEM_Str|MEM_Blob) ){
36630       if( sqlite3VdbeMemGrow(pTo, pTo->n+2, 0) ){
36631         pTo->n = 0;
36632         rc = SQLITE_NOMEM;
36633       }else{
36634         memcpy(pTo->z, zData, pTo->n);
36635         pTo->z[pTo->n] = '\0';
36636         pTo->z[pTo->n+1] = '\0';
36637         pTo->flags |= MEM_Term;
36638       }
36639     }
36640   }
36641   return rc;
36642 }
36643
36644 /*
36645 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
36646 ** freed. If pFrom contains ephemeral data, a copy is made.
36647 **
36648 ** pFrom contains an SQL NULL when this routine returns.
36649 */
36650 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
36651   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
36652   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
36653   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
36654   if( pTo->flags & MEM_Dyn ){
36655     sqlite3VdbeMemRelease(pTo);
36656   }
36657   memcpy(pTo, pFrom, sizeof(Mem));
36658   pFrom->flags = MEM_Null;
36659   pFrom->xDel = 0;
36660 }
36661
36662 /*
36663 ** Change the value of a Mem to be a string or a BLOB.
36664 **
36665 ** The memory management strategy depends on the value of the xDel
36666 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
36667 ** string is copied into a (possibly existing) buffer managed by the 
36668 ** Mem structure. Otherwise, any existing buffer is freed and the
36669 ** pointer copied.
36670 */
36671 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
36672   Mem *pMem,          /* Memory cell to set to string value */
36673   const char *z,      /* String pointer */
36674   int n,              /* Bytes in string, or negative */
36675   u8 enc,             /* Encoding of z.  0 for BLOBs */
36676   void (*xDel)(void*) /* Destructor function */
36677 ){
36678   int nByte = n;      /* New value for pMem->n */
36679   int flags = 0;      /* New value for pMem->flags */
36680
36681   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
36682
36683   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
36684   if( !z ){
36685     sqlite3VdbeMemSetNull(pMem);
36686     return SQLITE_OK;
36687   }
36688
36689   flags = (enc==0?MEM_Blob:MEM_Str);
36690   if( nByte<0 ){
36691     assert( enc!=0 );
36692     if( enc==SQLITE_UTF8 ){
36693       for(nByte=0; z[nByte]; nByte++){}
36694     }else{
36695       for(nByte=0; z[nByte] | z[nByte+1]; nByte+=2){}
36696     }
36697     flags |= MEM_Term;
36698   }
36699
36700   /* The following block sets the new values of Mem.z and Mem.xDel. It
36701   ** also sets a flag in local variable "flags" to indicate the memory
36702   ** management (one of MEM_Dyn or MEM_Static).
36703   */
36704   if( xDel==SQLITE_TRANSIENT ){
36705     int nAlloc = nByte;
36706     if( flags&MEM_Term ){
36707       nAlloc += (enc==SQLITE_UTF8?1:2);
36708     }
36709     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
36710       return SQLITE_NOMEM;
36711     }
36712     memcpy(pMem->z, z, nAlloc);
36713     flags |= MEM_Dyn;
36714   }else{
36715     sqlite3VdbeMemRelease(pMem);
36716     pMem->z = (char *)z;
36717     pMem->xDel = xDel;
36718     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
36719   }
36720
36721   pMem->n = nByte;
36722   pMem->flags = flags;
36723   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
36724   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
36725
36726 #ifndef SQLITE_OMIT_UTF16
36727   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
36728     return SQLITE_NOMEM;
36729   }
36730 #endif
36731
36732   return SQLITE_OK;
36733 }
36734
36735 /*
36736 ** Compare the values contained by the two memory cells, returning
36737 ** negative, zero or positive if pMem1 is less than, equal to, or greater
36738 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
36739 ** and reals) sorted numerically, followed by text ordered by the collating
36740 ** sequence pColl and finally blob's ordered by memcmp().
36741 **
36742 ** Two NULL values are considered equal by this function.
36743 */
36744 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
36745   int rc;
36746   int f1, f2;
36747   int combined_flags;
36748
36749   /* Interchange pMem1 and pMem2 if the collating sequence specifies
36750   ** DESC order.
36751   */
36752   f1 = pMem1->flags;
36753   f2 = pMem2->flags;
36754   combined_flags = f1|f2;
36755  
36756   /* If one value is NULL, it is less than the other. If both values
36757   ** are NULL, return 0.
36758   */
36759   if( combined_flags&MEM_Null ){
36760     return (f2&MEM_Null) - (f1&MEM_Null);
36761   }
36762
36763   /* If one value is a number and the other is not, the number is less.
36764   ** If both are numbers, compare as reals if one is a real, or as integers
36765   ** if both values are integers.
36766   */
36767   if( combined_flags&(MEM_Int|MEM_Real) ){
36768     if( !(f1&(MEM_Int|MEM_Real)) ){
36769       return 1;
36770     }
36771     if( !(f2&(MEM_Int|MEM_Real)) ){
36772       return -1;
36773     }
36774     if( (f1 & f2 & MEM_Int)==0 ){
36775       double r1, r2;
36776       if( (f1&MEM_Real)==0 ){
36777         r1 = pMem1->u.i;
36778       }else{
36779         r1 = pMem1->r;
36780       }
36781       if( (f2&MEM_Real)==0 ){
36782         r2 = pMem2->u.i;
36783       }else{
36784         r2 = pMem2->r;
36785       }
36786       if( r1<r2 ) return -1;
36787       if( r1>r2 ) return 1;
36788       return 0;
36789     }else{
36790       assert( f1&MEM_Int );
36791       assert( f2&MEM_Int );
36792       if( pMem1->u.i < pMem2->u.i ) return -1;
36793       if( pMem1->u.i > pMem2->u.i ) return 1;
36794       return 0;
36795     }
36796   }
36797
36798   /* If one value is a string and the other is a blob, the string is less.
36799   ** If both are strings, compare using the collating functions.
36800   */
36801   if( combined_flags&MEM_Str ){
36802     if( (f1 & MEM_Str)==0 ){
36803       return 1;
36804     }
36805     if( (f2 & MEM_Str)==0 ){
36806       return -1;
36807     }
36808
36809     assert( pMem1->enc==pMem2->enc );
36810     assert( pMem1->enc==SQLITE_UTF8 || 
36811             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
36812
36813     /* The collation sequence must be defined at this point, even if
36814     ** the user deletes the collation sequence after the vdbe program is
36815     ** compiled (this was not always the case).
36816     */
36817     assert( !pColl || pColl->xCmp );
36818
36819     if( pColl ){
36820       if( pMem1->enc==pColl->enc ){
36821         /* The strings are already in the correct encoding.  Call the
36822         ** comparison function directly */
36823         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
36824       }else{
36825         u8 origEnc = pMem1->enc;
36826         const void *v1, *v2;
36827         int n1, n2;
36828         /* Convert the strings into the encoding that the comparison
36829         ** function expects */
36830         v1 = sqlite3ValueText((sqlite3_value*)pMem1, pColl->enc);
36831         n1 = v1==0 ? 0 : pMem1->n;
36832         assert( n1==sqlite3ValueBytes((sqlite3_value*)pMem1, pColl->enc) );
36833         v2 = sqlite3ValueText((sqlite3_value*)pMem2, pColl->enc);
36834         n2 = v2==0 ? 0 : pMem2->n;
36835         assert( n2==sqlite3ValueBytes((sqlite3_value*)pMem2, pColl->enc) );
36836         /* Do the comparison */
36837         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
36838         /* Convert the strings back into the database encoding */
36839         sqlite3ValueText((sqlite3_value*)pMem1, origEnc);
36840         sqlite3ValueText((sqlite3_value*)pMem2, origEnc);
36841         return rc;
36842       }
36843     }
36844     /* If a NULL pointer was passed as the collate function, fall through
36845     ** to the blob case and use memcmp().  */
36846   }
36847  
36848   /* Both values must be blobs.  Compare using memcmp().  */
36849   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
36850   if( rc==0 ){
36851     rc = pMem1->n - pMem2->n;
36852   }
36853   return rc;
36854 }
36855
36856 /*
36857 ** Move data out of a btree key or data field and into a Mem structure.
36858 ** The data or key is taken from the entry that pCur is currently pointing
36859 ** to.  offset and amt determine what portion of the data or key to retrieve.
36860 ** key is true to get the key or false to get data.  The result is written
36861 ** into the pMem element.
36862 **
36863 ** The pMem structure is assumed to be uninitialized.  Any prior content
36864 ** is overwritten without being freed.
36865 **
36866 ** If this routine fails for any reason (malloc returns NULL or unable
36867 ** to read from the disk) then the pMem is left in an inconsistent state.
36868 */
36869 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
36870   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
36871   int offset,       /* Offset from the start of data to return bytes from. */
36872   int amt,          /* Number of bytes to return. */
36873   int key,          /* If true, retrieve from the btree key, not data. */
36874   Mem *pMem         /* OUT: Return data in this Mem structure. */
36875 ){
36876   char *zData;       /* Data from the btree layer */
36877   int available = 0; /* Number of bytes available on the local btree page */
36878   sqlite3 *db;       /* Database connection */
36879   int rc = SQLITE_OK;
36880
36881   db = sqlite3BtreeCursorDb(pCur);
36882   assert( sqlite3_mutex_held(db->mutex) );
36883   if( key ){
36884     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
36885   }else{
36886     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
36887   }
36888   assert( zData!=0 );
36889
36890   if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
36891     sqlite3VdbeMemRelease(pMem);
36892     pMem->z = &zData[offset];
36893     pMem->flags = MEM_Blob|MEM_Ephem;
36894   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
36895     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
36896     pMem->enc = 0;
36897     pMem->type = SQLITE_BLOB;
36898     if( key ){
36899       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
36900     }else{
36901       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
36902     }
36903     pMem->z[amt] = 0;
36904     pMem->z[amt+1] = 0;
36905     if( rc!=SQLITE_OK ){
36906       sqlite3VdbeMemRelease(pMem);
36907     }
36908   }
36909   pMem->n = amt;
36910
36911   return rc;
36912 }
36913
36914 #if 0
36915 /*
36916 ** Perform various checks on the memory cell pMem. An assert() will
36917 ** fail if pMem is internally inconsistent.
36918 */
36919 SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
36920   int flags = pMem->flags;
36921   assert( flags!=0 );  /* Must define some type */
36922   if( flags & (MEM_Str|MEM_Blob) ){
36923     int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
36924     assert( x!=0 );            /* Strings must define a string subtype */
36925     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
36926     assert( pMem->z!=0 );      /* Strings must have a value */
36927     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
36928     assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
36929     assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
36930     /* No destructor unless there is MEM_Dyn */
36931     assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
36932
36933     if( (flags & MEM_Str) ){
36934       assert( pMem->enc==SQLITE_UTF8 || 
36935               pMem->enc==SQLITE_UTF16BE ||
36936               pMem->enc==SQLITE_UTF16LE 
36937       );
36938       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
36939       ** must be the length of the string.  (Later:)  If the database file
36940       ** has been corrupted, '\000' characters might have been inserted
36941       ** into the middle of the string.  In that case, the strlen() might
36942       ** be less.
36943       */
36944       if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){ 
36945         assert( strlen(pMem->z)<=pMem->n );
36946         assert( pMem->z[pMem->n]==0 );
36947       }
36948     }
36949   }else{
36950     /* Cannot define a string subtype for non-string objects */
36951     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
36952     assert( pMem->xDel==0 );
36953   }
36954   /* MEM_Null excludes all other types */
36955   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
36956           || (pMem->flags&MEM_Null)==0 );
36957   /* If the MEM is both real and integer, the values are equal */
36958   assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) 
36959           || pMem->r==pMem->u.i );
36960 }
36961 #endif
36962
36963 /* This function is only available internally, it is not part of the
36964 ** external API. It works in a similar way to sqlite3_value_text(),
36965 ** except the data returned is in the encoding specified by the second
36966 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
36967 ** SQLITE_UTF8.
36968 **
36969 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
36970 ** If that is the case, then the result must be aligned on an even byte
36971 ** boundary.
36972 */
36973 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
36974   if( !pVal ) return 0;
36975
36976   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
36977   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
36978
36979   if( pVal->flags&MEM_Null ){
36980     return 0;
36981   }
36982   assert( (MEM_Blob>>3) == MEM_Str );
36983   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
36984   expandBlob(pVal);
36985   if( pVal->flags&MEM_Str ){
36986     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
36987     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&(sqlite3_intptr_t)pVal->z) ){
36988       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
36989       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
36990         return 0;
36991       }
36992     }
36993     sqlite3VdbeMemNulTerminate(pVal);
36994   }else{
36995     assert( (pVal->flags&MEM_Blob)==0 );
36996     sqlite3VdbeMemStringify(pVal, enc);
36997     assert( 0==(1&(sqlite3_intptr_t)pVal->z) );
36998   }
36999   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
37000               || pVal->db->mallocFailed );
37001   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
37002     return pVal->z;
37003   }else{
37004     return 0;
37005   }
37006 }
37007
37008 /*
37009 ** Create a new sqlite3_value object.
37010 */
37011 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
37012   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
37013   if( p ){
37014     p->flags = MEM_Null;
37015     p->type = SQLITE_NULL;
37016     p->db = db;
37017   }
37018   return p;
37019 }
37020
37021 /*
37022 ** Create a new sqlite3_value object, containing the value of pExpr.
37023 **
37024 ** This only works for very simple expressions that consist of one constant
37025 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
37026 ** be converted directly into a value, then the value is allocated and
37027 ** a pointer written to *ppVal. The caller is responsible for deallocating
37028 ** the value by passing it to sqlite3ValueFree() later on. If the expression
37029 ** cannot be converted to a value, then *ppVal is set to NULL.
37030 */
37031 SQLITE_PRIVATE int sqlite3ValueFromExpr(
37032   sqlite3 *db,              /* The database connection */
37033   Expr *pExpr,              /* The expression to evaluate */
37034   u8 enc,                   /* Encoding to use */
37035   u8 affinity,              /* Affinity to use */
37036   sqlite3_value **ppVal     /* Write the new value here */
37037 ){
37038   int op;
37039   char *zVal = 0;
37040   sqlite3_value *pVal = 0;
37041
37042   if( !pExpr ){
37043     *ppVal = 0;
37044     return SQLITE_OK;
37045   }
37046   op = pExpr->op;
37047
37048   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
37049     zVal = sqlite3StrNDup((char*)pExpr->token.z, pExpr->token.n);
37050     pVal = sqlite3ValueNew(db);
37051     if( !zVal || !pVal ) goto no_mem;
37052     sqlite3Dequote(zVal);
37053     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, sqlite3_free);
37054     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
37055       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
37056     }else{
37057       sqlite3ValueApplyAffinity(pVal, affinity, enc);
37058     }
37059   }else if( op==TK_UMINUS ) {
37060     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
37061       pVal->u.i = -1 * pVal->u.i;
37062       pVal->r = -1.0 * pVal->r;
37063     }
37064   }
37065 #ifndef SQLITE_OMIT_BLOB_LITERAL
37066   else if( op==TK_BLOB ){
37067     int nVal;
37068     assert( pExpr->token.n>=3 );
37069     assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
37070     assert( pExpr->token.z[1]=='\'' );
37071     assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
37072     pVal = sqlite3ValueNew(db);
37073     nVal = pExpr->token.n - 3;
37074     zVal = (char*)pExpr->token.z + 2;
37075     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
37076                          0, sqlite3_free);
37077   }
37078 #endif
37079
37080   *ppVal = pVal;
37081   return SQLITE_OK;
37082
37083 no_mem:
37084   db->mallocFailed = 1;
37085   sqlite3_free(zVal);
37086   sqlite3ValueFree(pVal);
37087   *ppVal = 0;
37088   return SQLITE_NOMEM;
37089 }
37090
37091 /*
37092 ** Change the string value of an sqlite3_value object
37093 */
37094 SQLITE_PRIVATE void sqlite3ValueSetStr(
37095   sqlite3_value *v,     /* Value to be set */
37096   int n,                /* Length of string z */
37097   const void *z,        /* Text of the new string */
37098   u8 enc,               /* Encoding to use */
37099   void (*xDel)(void*)   /* Destructor for the string */
37100 ){
37101   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
37102 }
37103
37104 /*
37105 ** Free an sqlite3_value object
37106 */
37107 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
37108   if( !v ) return;
37109   sqlite3VdbeMemRelease((Mem *)v);
37110   sqlite3_free(v);
37111 }
37112
37113 /*
37114 ** Return the number of bytes in the sqlite3_value object assuming
37115 ** that it uses the encoding "enc"
37116 */
37117 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
37118   Mem *p = (Mem*)pVal;
37119   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
37120     if( p->flags & MEM_Zero ){
37121       return p->n+p->u.i;
37122     }else{
37123       return p->n;
37124     }
37125   }
37126   return 0;
37127 }
37128
37129 /************** End of vdbemem.c *********************************************/
37130 /************** Begin file vdbeaux.c *****************************************/
37131 /*
37132 ** 2003 September 6
37133 **
37134 ** The author disclaims copyright to this source code.  In place of
37135 ** a legal notice, here is a blessing:
37136 **
37137 **    May you do good and not evil.
37138 **    May you find forgiveness for yourself and forgive others.
37139 **    May you share freely, never taking more than you give.
37140 **
37141 *************************************************************************
37142 ** This file contains code used for creating, destroying, and populating
37143 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
37144 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
37145 ** But that file was getting too big so this subroutines were split out.
37146 */
37147
37148
37149
37150 /*
37151 ** When debugging the code generator in a symbolic debugger, one can
37152 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
37153 ** as they are added to the instruction stream.
37154 */
37155 #ifdef SQLITE_DEBUG
37156 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
37157 #endif
37158
37159
37160 /*
37161 ** Create a new virtual database engine.
37162 */
37163 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
37164   Vdbe *p;
37165   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
37166   if( p==0 ) return 0;
37167   p->db = db;
37168   if( db->pVdbe ){
37169     db->pVdbe->pPrev = p;
37170   }
37171   p->pNext = db->pVdbe;
37172   p->pPrev = 0;
37173   db->pVdbe = p;
37174   p->magic = VDBE_MAGIC_INIT;
37175   return p;
37176 }
37177
37178 /*
37179 ** Remember the SQL string for a prepared statement.
37180 */
37181 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
37182   if( p==0 ) return;
37183   assert( p->zSql==0 );
37184   p->zSql = sqlite3DbStrNDup(p->db, z, n);
37185 }
37186
37187 /*
37188 ** Return the SQL associated with a prepared statement
37189 */
37190 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
37191   return ((Vdbe *)pStmt)->zSql;
37192 }
37193
37194 /*
37195 ** Swap all content between two VDBE structures.
37196 */
37197 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
37198   Vdbe tmp, *pTmp;
37199   char *zTmp;
37200   int nTmp;
37201   tmp = *pA;
37202   *pA = *pB;
37203   *pB = tmp;
37204   pTmp = pA->pNext;
37205   pA->pNext = pB->pNext;
37206   pB->pNext = pTmp;
37207   pTmp = pA->pPrev;
37208   pA->pPrev = pB->pPrev;
37209   pB->pPrev = pTmp;
37210   zTmp = pA->zSql;
37211   pA->zSql = pB->zSql;
37212   pB->zSql = zTmp;
37213   nTmp = pA->nSql;
37214   pA->nSql = pB->nSql;
37215   pB->nSql = nTmp;
37216 }
37217
37218 #ifdef SQLITE_DEBUG
37219 /*
37220 ** Turn tracing on or off
37221 */
37222 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
37223   p->trace = trace;
37224 }
37225 #endif
37226
37227 /*
37228 ** Resize the Vdbe.aOp array so that it contains at least N
37229 ** elements.
37230 **
37231 ** If an out-of-memory error occurs while resizing the array,
37232 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
37233 ** any opcodes already allocated can be correctly deallocated
37234 ** along with the rest of the Vdbe).
37235 */
37236 static void resizeOpArray(Vdbe *p, int N){
37237   VdbeOp *pNew;
37238   int oldSize = p->nOpAlloc;
37239   pNew = sqlite3DbRealloc(p->db, p->aOp, N*sizeof(Op));
37240   if( pNew ){
37241     p->nOpAlloc = N;
37242     p->aOp = pNew;
37243     if( N>oldSize ){
37244       memset(&p->aOp[oldSize], 0, (N-oldSize)*sizeof(Op));
37245     }
37246   }
37247 }
37248
37249 /*
37250 ** Add a new instruction to the list of instructions current in the
37251 ** VDBE.  Return the address of the new instruction.
37252 **
37253 ** Parameters:
37254 **
37255 **    p               Pointer to the VDBE
37256 **
37257 **    op              The opcode for this instruction
37258 **
37259 **    p1, p2, p3      Operands
37260 **
37261 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
37262 ** the sqlite3VdbeChangeP4() function to change the value of the P4
37263 ** operand.
37264 */
37265 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
37266   int i;
37267   VdbeOp *pOp;
37268
37269   i = p->nOp;
37270   assert( p->magic==VDBE_MAGIC_INIT );
37271   if( p->nOpAlloc<=i ){
37272     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
37273     if( p->db->mallocFailed ){
37274       return 0;
37275     }
37276   }
37277   p->nOp++;
37278   pOp = &p->aOp[i];
37279   pOp->opcode = op;
37280   pOp->p1 = p1;
37281   pOp->p2 = p2;
37282   pOp->p3 = p3;
37283   pOp->p4.p = 0;
37284   pOp->p4type = P4_NOTUSED;
37285   p->expired = 0;
37286 #ifdef SQLITE_DEBUG
37287   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
37288 #endif
37289   return i;
37290 }
37291 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
37292   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
37293 }
37294 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
37295   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
37296 }
37297 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
37298   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
37299 }
37300
37301
37302 /*
37303 ** Add an opcode that includes the p4 value as a pointer.
37304 */
37305 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
37306   Vdbe *p,            /* Add the opcode to this VM */
37307   int op,             /* The new opcode */
37308   int p1,             /* The P1 operand */
37309   int p2,             /* The P2 operand */
37310   int p3,             /* The P3 operand */
37311   const char *zP4,    /* The P4 operand */
37312   int p4type          /* P4 operand type */
37313 ){
37314   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
37315   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
37316   return addr;
37317 }
37318
37319 /*
37320 ** Create a new symbolic label for an instruction that has yet to be
37321 ** coded.  The symbolic label is really just a negative number.  The
37322 ** label can be used as the P2 value of an operation.  Later, when
37323 ** the label is resolved to a specific address, the VDBE will scan
37324 ** through its operation list and change all values of P2 which match
37325 ** the label into the resolved address.
37326 **
37327 ** The VDBE knows that a P2 value is a label because labels are
37328 ** always negative and P2 values are suppose to be non-negative.
37329 ** Hence, a negative P2 value is a label that has yet to be resolved.
37330 **
37331 ** Zero is returned if a malloc() fails.
37332 */
37333 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
37334   int i;
37335   i = p->nLabel++;
37336   assert( p->magic==VDBE_MAGIC_INIT );
37337   if( i>=p->nLabelAlloc ){
37338     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
37339     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
37340                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
37341   }
37342   if( p->aLabel ){
37343     p->aLabel[i] = -1;
37344   }
37345   return -1-i;
37346 }
37347
37348 /*
37349 ** Resolve label "x" to be the address of the next instruction to
37350 ** be inserted.  The parameter "x" must have been obtained from
37351 ** a prior call to sqlite3VdbeMakeLabel().
37352 */
37353 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
37354   int j = -1-x;
37355   assert( p->magic==VDBE_MAGIC_INIT );
37356   assert( j>=0 && j<p->nLabel );
37357   if( p->aLabel ){
37358     p->aLabel[j] = p->nOp;
37359   }
37360 }
37361
37362 /*
37363 ** Loop through the program looking for P2 values that are negative
37364 ** on jump instructions.  Each such value is a label.  Resolve the
37365 ** label by setting the P2 value to its correct non-zero value.
37366 **
37367 ** This routine is called once after all opcodes have been inserted.
37368 **
37369 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
37370 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
37371 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
37372 **
37373 ** This routine also does the following optimization:  It scans for
37374 ** instructions that might cause a statement rollback.  Such instructions
37375 ** are:
37376 **
37377 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
37378 **   *  OP_Destroy
37379 **   *  OP_VUpdate
37380 **   *  OP_VRename
37381 **
37382 ** If no such instruction is found, then every Statement instruction 
37383 ** is changed to a Noop.  In this way, we avoid creating the statement 
37384 ** journal file unnecessarily.
37385 */
37386 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
37387   int i;
37388   int nMaxArgs = 0;
37389   Op *pOp;
37390   int *aLabel = p->aLabel;
37391   int doesStatementRollback = 0;
37392   int hasStatementBegin = 0;
37393   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
37394     u8 opcode = pOp->opcode;
37395
37396     if( opcode==OP_Function ){
37397       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
37398     }else if( opcode==OP_AggStep 
37399 #ifndef SQLITE_OMIT_VIRTUALTABLE
37400         || opcode==OP_VUpdate
37401 #endif
37402     ){
37403       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
37404     }
37405     if( opcode==OP_Halt ){
37406       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
37407         doesStatementRollback = 1;
37408       }
37409     }else if( opcode==OP_Statement ){
37410       hasStatementBegin = 1;
37411     }else if( opcode==OP_Destroy ){
37412       doesStatementRollback = 1;
37413 #ifndef SQLITE_OMIT_VIRTUALTABLE
37414     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
37415       doesStatementRollback = 1;
37416     }else if( opcode==OP_VFilter ){
37417       int n;
37418       assert( p->nOp - i >= 3 );
37419       assert( pOp[-1].opcode==OP_Integer );
37420       n = pOp[-1].p1;
37421       if( n>nMaxArgs ) nMaxArgs = n;
37422 #endif
37423     }
37424
37425     if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
37426       assert( -1-pOp->p2<p->nLabel );
37427       pOp->p2 = aLabel[-1-pOp->p2];
37428     }
37429   }
37430   sqlite3_free(p->aLabel);
37431   p->aLabel = 0;
37432
37433   *pMaxFuncArgs = nMaxArgs;
37434
37435   /* If we never rollback a statement transaction, then statement
37436   ** transactions are not needed.  So change every OP_Statement
37437   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
37438   ** which can be expensive on some platforms.
37439   */
37440   if( hasStatementBegin && !doesStatementRollback ){
37441     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
37442       if( pOp->opcode==OP_Statement ){
37443         pOp->opcode = OP_Noop;
37444       }
37445     }
37446   }
37447 }
37448
37449 /*
37450 ** Return the address of the next instruction to be inserted.
37451 */
37452 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
37453   assert( p->magic==VDBE_MAGIC_INIT );
37454   return p->nOp;
37455 }
37456
37457 /*
37458 ** Add a whole list of operations to the operation stack.  Return the
37459 ** address of the first operation added.
37460 */
37461 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
37462   int addr;
37463   assert( p->magic==VDBE_MAGIC_INIT );
37464   if( p->nOp + nOp > p->nOpAlloc ){
37465     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
37466     assert( p->nOp+nOp<=p->nOpAlloc || p->db->mallocFailed );
37467   }
37468   if( p->db->mallocFailed ){
37469     return 0;
37470   }
37471   addr = p->nOp;
37472   if( nOp>0 ){
37473     int i;
37474     VdbeOpList const *pIn = aOp;
37475     for(i=0; i<nOp; i++, pIn++){
37476       int p2 = pIn->p2;
37477       VdbeOp *pOut = &p->aOp[i+addr];
37478       pOut->opcode = pIn->opcode;
37479       pOut->p1 = pIn->p1;
37480       if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
37481         pOut->p2 = addr + ADDR(p2);
37482       }else{
37483         pOut->p2 = p2;
37484       }
37485       pOut->p3 = pIn->p3;
37486       pOut->p4type = P4_NOTUSED;
37487       pOut->p4.p = 0;
37488       pOut->p5 = 0;
37489 #ifdef SQLITE_DEBUG
37490       if( sqlite3VdbeAddopTrace ){
37491         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
37492       }
37493 #endif
37494     }
37495     p->nOp += nOp;
37496   }
37497   return addr;
37498 }
37499
37500 /*
37501 ** Change the value of the P1 operand for a specific instruction.
37502 ** This routine is useful when a large program is loaded from a
37503 ** static array using sqlite3VdbeAddOpList but we want to make a
37504 ** few minor changes to the program.
37505 */
37506 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
37507   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
37508   if( p && addr>=0 && p->nOp>addr && p->aOp ){
37509     p->aOp[addr].p1 = val;
37510   }
37511 }
37512
37513 /*
37514 ** Change the value of the P2 operand for a specific instruction.
37515 ** This routine is useful for setting a jump destination.
37516 */
37517 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
37518   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
37519   if( p && addr>=0 && p->nOp>addr && p->aOp ){
37520     p->aOp[addr].p2 = val;
37521   }
37522 }
37523
37524 /*
37525 ** Change the value of the P3 operand for a specific instruction.
37526 */
37527 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
37528   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
37529   if( p && addr>=0 && p->nOp>addr && p->aOp ){
37530     p->aOp[addr].p3 = val;
37531   }
37532 }
37533
37534 /*
37535 ** Change the value of the P5 operand for the most recently
37536 ** added operation.
37537 */
37538 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
37539   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
37540   if( p && p->aOp ){
37541     assert( p->nOp>0 );
37542     p->aOp[p->nOp-1].p5 = val;
37543   }
37544 }
37545
37546 /*
37547 ** Change the P2 operand of instruction addr so that it points to
37548 ** the address of the next instruction to be coded.
37549 */
37550 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
37551   sqlite3VdbeChangeP2(p, addr, p->nOp);
37552 }
37553
37554
37555 /*
37556 ** If the input FuncDef structure is ephemeral, then free it.  If
37557 ** the FuncDef is not ephermal, then do nothing.
37558 */
37559 static void freeEphemeralFunction(FuncDef *pDef){
37560   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
37561     sqlite3_free(pDef);
37562   }
37563 }
37564
37565 /*
37566 ** Delete a P4 value if necessary.
37567 */
37568 static void freeP4(int p4type, void *p3){
37569   if( p3 ){
37570     switch( p4type ){
37571       case P4_REAL:
37572       case P4_INT64:
37573       case P4_MPRINTF:
37574       case P4_DYNAMIC:
37575       case P4_KEYINFO:
37576       case P4_KEYINFO_HANDOFF: {
37577         sqlite3_free(p3);
37578         break;
37579       }
37580       case P4_VDBEFUNC: {
37581         VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
37582         freeEphemeralFunction(pVdbeFunc->pFunc);
37583         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
37584         sqlite3_free(pVdbeFunc);
37585         break;
37586       }
37587       case P4_FUNCDEF: {
37588         freeEphemeralFunction((FuncDef*)p3);
37589         break;
37590       }
37591       case P4_MEM: {
37592         sqlite3ValueFree((sqlite3_value*)p3);
37593         break;
37594       }
37595     }
37596   }
37597 }
37598
37599
37600 /*
37601 ** Change N opcodes starting at addr to No-ops.
37602 */
37603 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
37604   if( p && p->aOp ){
37605     VdbeOp *pOp = &p->aOp[addr];
37606     while( N-- ){
37607       freeP4(pOp->p4type, pOp->p4.p);
37608       memset(pOp, 0, sizeof(pOp[0]));
37609       pOp->opcode = OP_Noop;
37610       pOp++;
37611     }
37612   }
37613 }
37614
37615 /*
37616 ** Change the value of the P4 operand for a specific instruction.
37617 ** This routine is useful when a large program is loaded from a
37618 ** static array using sqlite3VdbeAddOpList but we want to make a
37619 ** few minor changes to the program.
37620 **
37621 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
37622 ** the string is made into memory obtained from sqlite3_malloc().
37623 ** A value of n==0 means copy bytes of zP4 up to and including the
37624 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
37625 **
37626 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
37627 ** A copy is made of the KeyInfo structure into memory obtained from
37628 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
37629 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
37630 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
37631 ** caller should not free the allocation, it will be freed when the Vdbe is
37632 ** finalized.
37633 ** 
37634 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
37635 ** to a string or structure that is guaranteed to exist for the lifetime of
37636 ** the Vdbe. In these cases we can just copy the pointer.
37637 **
37638 ** If addr<0 then change P4 on the most recently inserted instruction.
37639 */
37640 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
37641   Op *pOp;
37642   assert( p!=0 );
37643   assert( p->magic==VDBE_MAGIC_INIT );
37644   if( p->aOp==0 || p->db->mallocFailed ){
37645     if (n != P4_KEYINFO) {
37646       freeP4(n, (void*)*(char**)&zP4);
37647     }
37648     return;
37649   }
37650   assert( addr<p->nOp );
37651   if( addr<0 ){
37652     addr = p->nOp - 1;
37653     if( addr<0 ) return;
37654   }
37655   pOp = &p->aOp[addr];
37656   freeP4(pOp->p4type, pOp->p4.p);
37657   pOp->p4.p = 0;
37658   if( n==P4_INT32 ){
37659     /* Note: this cast is safe, because the origin data point was an int
37660     ** that was cast to a (const char *). */
37661     pOp->p4.i = (int)(sqlite3_intptr_t)zP4;
37662     pOp->p4type = n;
37663   }else if( zP4==0 ){
37664     pOp->p4.p = 0;
37665     pOp->p4type = P4_NOTUSED;
37666   }else if( n==P4_KEYINFO ){
37667     KeyInfo *pKeyInfo;
37668     int nField, nByte;
37669
37670     nField = ((KeyInfo*)zP4)->nField;
37671     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
37672     pKeyInfo = sqlite3_malloc( nByte );
37673     pOp->p4.pKeyInfo = pKeyInfo;
37674     if( pKeyInfo ){
37675       memcpy(pKeyInfo, zP4, nByte);
37676       /* In the current implementation, P4_KEYINFO is only ever used on
37677       ** KeyInfo structures that have no aSortOrder component.  Elements
37678       ** with an aSortOrder always use P4_KEYINFO_HANDOFF.  So we do not
37679       ** need to bother with duplicating the aSortOrder. */
37680       assert( pKeyInfo->aSortOrder==0 );
37681 #if 0
37682       aSortOrder = pKeyInfo->aSortOrder;
37683       if( aSortOrder ){
37684         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
37685         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
37686       }
37687 #endif
37688       pOp->p4type = P4_KEYINFO;
37689     }else{
37690       p->db->mallocFailed = 1;
37691       pOp->p4type = P4_NOTUSED;
37692     }
37693   }else if( n==P4_KEYINFO_HANDOFF ){
37694     pOp->p4.p = (void*)zP4;
37695     pOp->p4type = P4_KEYINFO;
37696   }else if( n<0 ){
37697     pOp->p4.p = (void*)zP4;
37698     pOp->p4type = n;
37699   }else{
37700     if( n==0 ) n = strlen(zP4);
37701     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
37702     pOp->p4type = P4_DYNAMIC;
37703   }
37704 }
37705
37706 #ifndef NDEBUG
37707 /*
37708 ** Change the comment on the the most recently coded instruction.
37709 */
37710 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
37711   va_list ap;
37712   assert( p->nOp>0 || p->aOp==0 );
37713   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
37714   if( p->nOp ){
37715     char **pz = &p->aOp[p->nOp-1].zComment;
37716     va_start(ap, zFormat);
37717     sqlite3_free(*pz);
37718     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
37719     va_end(ap);
37720   }
37721 }
37722 #endif
37723
37724 /*
37725 ** Return the opcode for a given address.
37726 */
37727 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
37728   assert( p->magic==VDBE_MAGIC_INIT );
37729   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
37730   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
37731 }
37732
37733 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
37734      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
37735 /*
37736 ** Compute a string that describes the P4 parameter for an opcode.
37737 ** Use zTemp for any required temporary buffer space.
37738 */
37739 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
37740   char *zP4 = zTemp;
37741   assert( nTemp>=20 );
37742   switch( pOp->p4type ){
37743     case P4_KEYINFO: {
37744       int i, j;
37745       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
37746       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
37747       i = strlen(zTemp);
37748       for(j=0; j<pKeyInfo->nField; j++){
37749         CollSeq *pColl = pKeyInfo->aColl[j];
37750         if( pColl ){
37751           int n = strlen(pColl->zName);
37752           if( i+n>nTemp-6 ){
37753             memcpy(&zTemp[i],",...",4);
37754             break;
37755           }
37756           zTemp[i++] = ',';
37757           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
37758             zTemp[i++] = '-';
37759           }
37760           memcpy(&zTemp[i], pColl->zName,n+1);
37761           i += n;
37762         }else if( i+4<nTemp-6 ){
37763           memcpy(&zTemp[i],",nil",4);
37764           i += 4;
37765         }
37766       }
37767       zTemp[i++] = ')';
37768       zTemp[i] = 0;
37769       assert( i<nTemp );
37770       break;
37771     }
37772     case P4_COLLSEQ: {
37773       CollSeq *pColl = pOp->p4.pColl;
37774       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
37775       break;
37776     }
37777     case P4_FUNCDEF: {
37778       FuncDef *pDef = pOp->p4.pFunc;
37779       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
37780       break;
37781     }
37782     case P4_INT64: {
37783       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
37784       break;
37785     }
37786     case P4_INT32: {
37787       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
37788       break;
37789     }
37790     case P4_REAL: {
37791       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
37792       break;
37793     }
37794     case P4_MEM: {
37795       Mem *pMem = pOp->p4.pMem;
37796       assert( (pMem->flags & MEM_Null)==0 );
37797       if( pMem->flags & MEM_Str ){
37798         zP4 = pMem->z;
37799       }else if( pMem->flags & MEM_Int ){
37800         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
37801       }else if( pMem->flags & MEM_Real ){
37802         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
37803       }
37804       break;
37805     }
37806 #ifndef SQLITE_OMIT_VIRTUALTABLE
37807     case P4_VTAB: {
37808       sqlite3_vtab *pVtab = pOp->p4.pVtab;
37809       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
37810       break;
37811     }
37812 #endif
37813     default: {
37814       zP4 = pOp->p4.z;
37815       if( zP4==0 ){
37816         zP4 = zTemp;
37817         zTemp[0] = 0;
37818       }
37819     }
37820   }
37821   assert( zP4!=0 );
37822   return zP4;
37823 }
37824 #endif
37825
37826 /*
37827 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
37828 **
37829 */
37830 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
37831   int mask;
37832   assert( i>=0 && i<p->db->nDb );
37833   assert( i<sizeof(p->btreeMask)*8 );
37834   mask = 1<<i;
37835   if( (p->btreeMask & mask)==0 ){
37836     p->btreeMask |= mask;
37837     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
37838   }
37839 }
37840
37841
37842 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
37843 /*
37844 ** Print a single opcode.  This routine is used for debugging only.
37845 */
37846 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
37847   char *zP4;
37848   char zPtr[50];
37849   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
37850   if( pOut==0 ) pOut = stdout;
37851   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
37852   fprintf(pOut, zFormat1, pc, 
37853       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
37854 #ifdef SQLITE_DEBUG
37855       pOp->zComment ? pOp->zComment : ""
37856 #else
37857       ""
37858 #endif
37859   );
37860   fflush(pOut);
37861 }
37862 #endif
37863
37864 /*
37865 ** Release an array of N Mem elements
37866 */
37867 static void releaseMemArray(Mem *p, int N){
37868   if( p && N ){
37869     sqlite3 *db = p->db;
37870     int malloc_failed = db->mallocFailed;
37871     while( N-->0 ){
37872       assert( N<2 || p[0].db==p[1].db );
37873       sqlite3VdbeMemRelease(p);
37874       p++->flags = MEM_Null;
37875     }
37876     db->mallocFailed = malloc_failed;
37877   }
37878 }
37879
37880 #ifndef SQLITE_OMIT_EXPLAIN
37881 /*
37882 ** Give a listing of the program in the virtual machine.
37883 **
37884 ** The interface is the same as sqlite3VdbeExec().  But instead of
37885 ** running the code, it invokes the callback once for each instruction.
37886 ** This feature is used to implement "EXPLAIN".
37887 **
37888 ** When p->explain==1, each instruction is listed.  When
37889 ** p->explain==2, only OP_Explain instructions are listed and these
37890 ** are shown in a different format.  p->explain==2 is used to implement
37891 ** EXPLAIN QUERY PLAN.
37892 */
37893 SQLITE_PRIVATE int sqlite3VdbeList(
37894   Vdbe *p                   /* The VDBE */
37895 ){
37896   sqlite3 *db = p->db;
37897   int i;
37898   int rc = SQLITE_OK;
37899   Mem *pMem = p->pResultSet = &p->aMem[1];
37900
37901   assert( p->explain );
37902   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
37903   assert( db->magic==SQLITE_MAGIC_BUSY );
37904   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
37905
37906   /* Even though this opcode does not use dynamic strings for
37907   ** the result, result columns may become dynamic if the user calls
37908   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
37909   */
37910   releaseMemArray(pMem, p->nMem);
37911
37912   do{
37913     i = p->pc++;
37914   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
37915   if( i>=p->nOp ){
37916     p->rc = SQLITE_OK;
37917     rc = SQLITE_DONE;
37918   }else if( db->u1.isInterrupted ){
37919     p->rc = SQLITE_INTERRUPT;
37920     rc = SQLITE_ERROR;
37921     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
37922   }else{
37923     char *z;
37924     Op *pOp = &p->aOp[i];
37925     if( p->explain==1 ){
37926       pMem->flags = MEM_Int;
37927       pMem->type = SQLITE_INTEGER;
37928       pMem->u.i = i;                                /* Program counter */
37929       pMem++;
37930   
37931       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
37932       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
37933       assert( pMem->z!=0 );
37934       pMem->n = strlen(pMem->z);
37935       pMem->type = SQLITE_TEXT;
37936       pMem->enc = SQLITE_UTF8;
37937       pMem++;
37938     }
37939
37940     pMem->flags = MEM_Int;
37941     pMem->u.i = pOp->p1;                          /* P1 */
37942     pMem->type = SQLITE_INTEGER;
37943     pMem++;
37944
37945     pMem->flags = MEM_Int;
37946     pMem->u.i = pOp->p2;                          /* P2 */
37947     pMem->type = SQLITE_INTEGER;
37948     pMem++;
37949
37950     if( p->explain==1 ){
37951       pMem->flags = MEM_Int;
37952       pMem->u.i = pOp->p3;                          /* P3 */
37953       pMem->type = SQLITE_INTEGER;
37954       pMem++;
37955     }
37956
37957     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
37958       p->db->mallocFailed = 1;
37959       return SQLITE_NOMEM;
37960     }
37961     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
37962     z = displayP4(pOp, pMem->z, 32);
37963     if( z!=pMem->z ){
37964       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
37965     }else{
37966       assert( pMem->z!=0 );
37967       pMem->n = strlen(pMem->z);
37968       pMem->enc = SQLITE_UTF8;
37969     }
37970     pMem->type = SQLITE_TEXT;
37971     pMem++;
37972
37973     if( p->explain==1 ){
37974       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
37975         p->db->mallocFailed = 1;
37976         return SQLITE_NOMEM;
37977       }
37978       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
37979       pMem->n = 2;
37980       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
37981       pMem->type = SQLITE_TEXT;
37982       pMem->enc = SQLITE_UTF8;
37983       pMem++;
37984   
37985 #ifdef SQLITE_DEBUG
37986       if( pOp->zComment ){
37987         pMem->flags = MEM_Str|MEM_Term;
37988         pMem->z = pOp->zComment;
37989         pMem->n = strlen(pMem->z);
37990         pMem->enc = SQLITE_UTF8;
37991       }else
37992 #endif
37993       {
37994         pMem->flags = MEM_Null;                       /* Comment */
37995         pMem->type = SQLITE_NULL;
37996       }
37997     }
37998
37999     p->nResColumn = 8 - 5*(p->explain-1);
38000     p->rc = SQLITE_OK;
38001     rc = SQLITE_ROW;
38002   }
38003   return rc;
38004 }
38005 #endif /* SQLITE_OMIT_EXPLAIN */
38006
38007 #ifdef SQLITE_DEBUG
38008 /*
38009 ** Print the SQL that was used to generate a VDBE program.
38010 */
38011 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
38012   int nOp = p->nOp;
38013   VdbeOp *pOp;
38014   if( nOp<1 ) return;
38015   pOp = &p->aOp[0];
38016   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
38017     const char *z = pOp->p4.z;
38018     while( isspace(*(u8*)z) ) z++;
38019     printf("SQL: [%s]\n", z);
38020   }
38021 }
38022 #endif
38023
38024 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
38025 /*
38026 ** Print an IOTRACE message showing SQL content.
38027 */
38028 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
38029   int nOp = p->nOp;
38030   VdbeOp *pOp;
38031   if( sqlite3IoTrace==0 ) return;
38032   if( nOp<1 ) return;
38033   pOp = &p->aOp[0];
38034   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
38035     int i, j;
38036     char z[1000];
38037     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
38038     for(i=0; isspace((unsigned char)z[i]); i++){}
38039     for(j=0; z[i]; i++){
38040       if( isspace((unsigned char)z[i]) ){
38041         if( z[i-1]!=' ' ){
38042           z[j++] = ' ';
38043         }
38044       }else{
38045         z[j++] = z[i];
38046       }
38047     }
38048     z[j] = 0;
38049     sqlite3IoTrace("SQL %s\n", z);
38050   }
38051 }
38052 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
38053
38054
38055 /*
38056 ** Prepare a virtual machine for execution.  This involves things such
38057 ** as allocating stack space and initializing the program counter.
38058 ** After the VDBE has be prepped, it can be executed by one or more
38059 ** calls to sqlite3VdbeExec().  
38060 **
38061 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
38062 ** VDBE_MAGIC_RUN.
38063 */
38064 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
38065   Vdbe *p,                       /* The VDBE */
38066   int nVar,                      /* Number of '?' see in the SQL statement */
38067   int nMem,                      /* Number of memory cells to allocate */
38068   int nCursor,                   /* Number of cursors to allocate */
38069   int isExplain                  /* True if the EXPLAIN keywords is present */
38070 ){
38071   int n;
38072   sqlite3 *db = p->db;
38073
38074   assert( p!=0 );
38075   assert( p->magic==VDBE_MAGIC_INIT );
38076
38077   /* There should be at least one opcode.
38078   */
38079   assert( p->nOp>0 );
38080
38081   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
38082    * is because the call to resizeOpArray() below may shrink the
38083    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
38084    * state.
38085    */
38086   p->magic = VDBE_MAGIC_RUN;
38087
38088   /*
38089   ** Allocation space for registers.
38090   */
38091   if( p->aMem==0 ){
38092     int nArg;       /* Maximum number of args passed to a user function. */
38093     resolveP2Values(p, &nArg);
38094     resizeOpArray(p, p->nOp);
38095     assert( nVar>=0 );
38096     if( isExplain && nMem<10 ){
38097       p->nMem = nMem = 10;
38098     }
38099     p->aMem = sqlite3DbMallocZero(db,
38100         nMem*sizeof(Mem)               /* aMem */
38101       + nVar*sizeof(Mem)               /* aVar */
38102       + nArg*sizeof(Mem*)              /* apArg */
38103       + nVar*sizeof(char*)             /* azVar */
38104       + nCursor*sizeof(Cursor*) + 1    /* apCsr */
38105     );
38106     if( !db->mallocFailed ){
38107       p->aMem--;             /* aMem[] goes from 1..nMem */
38108       p->nMem = nMem;        /*       not from 0..nMem-1 */
38109       p->aVar = &p->aMem[nMem+1];
38110       p->nVar = nVar;
38111       p->okVar = 0;
38112       p->apArg = (Mem**)&p->aVar[nVar];
38113       p->azVar = (char**)&p->apArg[nArg];
38114       p->apCsr = (Cursor**)&p->azVar[nVar];
38115       p->nCursor = nCursor;
38116       for(n=0; n<nVar; n++){
38117         p->aVar[n].flags = MEM_Null;
38118         p->aVar[n].db = db;
38119       }
38120       for(n=1; n<=nMem; n++){
38121         p->aMem[n].flags = MEM_Null;
38122         p->aMem[n].db = db;
38123       }
38124     }
38125   }
38126 #ifdef SQLITE_DEBUG
38127   for(n=1; n<p->nMem; n++){
38128     assert( p->aMem[n].db==db );
38129     assert( p->aMem[n].flags==MEM_Null );
38130   }
38131 #endif
38132
38133   p->pc = -1;
38134   p->rc = SQLITE_OK;
38135   p->uniqueCnt = 0;
38136   p->returnDepth = 0;
38137   p->errorAction = OE_Abort;
38138   p->explain |= isExplain;
38139   p->magic = VDBE_MAGIC_RUN;
38140   p->nChange = 0;
38141   p->cacheCtr = 1;
38142   p->minWriteFileFormat = 255;
38143   p->openedStatement = 0;
38144 #ifdef VDBE_PROFILE
38145   {
38146     int i;
38147     for(i=0; i<p->nOp; i++){
38148       p->aOp[i].cnt = 0;
38149       p->aOp[i].cycles = 0;
38150     }
38151   }
38152 #endif
38153 }
38154
38155 /*
38156 ** Close a VDBE cursor and release all the resources that cursor happens
38157 ** to hold.
38158 */
38159 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
38160   if( pCx==0 ){
38161     return;
38162   }
38163   if( pCx->pCursor ){
38164     sqlite3BtreeCloseCursor(pCx->pCursor);
38165   }
38166   if( pCx->pBt ){
38167     sqlite3BtreeClose(pCx->pBt);
38168   }
38169 #ifndef SQLITE_OMIT_VIRTUALTABLE
38170   if( pCx->pVtabCursor ){
38171     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
38172     const sqlite3_module *pModule = pCx->pModule;
38173     p->inVtabMethod = 1;
38174     (void)sqlite3SafetyOff(p->db);
38175     pModule->xClose(pVtabCursor);
38176     (void)sqlite3SafetyOn(p->db);
38177     p->inVtabMethod = 0;
38178   }
38179 #endif
38180   sqlite3_free(pCx->pData);
38181   sqlite3_free(pCx->aType);
38182   sqlite3_free(pCx);
38183 }
38184
38185 /*
38186 ** Close all cursors except for VTab cursors that are currently
38187 ** in use.
38188 */
38189 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
38190   int i;
38191   if( p->apCsr==0 ) return;
38192   for(i=0; i<p->nCursor; i++){
38193     Cursor *pC = p->apCsr[i];
38194     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
38195       sqlite3VdbeFreeCursor(p, pC);
38196       p->apCsr[i] = 0;
38197     }
38198   }
38199 }
38200
38201 /*
38202 ** Clean up the VM after execution.
38203 **
38204 ** This routine will automatically close any cursors, lists, and/or
38205 ** sorters that were left open.  It also deletes the values of
38206 ** variables in the aVar[] array.
38207 */
38208 static void Cleanup(Vdbe *p){
38209   int i;
38210   closeAllCursorsExceptActiveVtabs(p);
38211   for(i=1; i<=p->nMem; i++){
38212     MemSetTypeFlag(&p->aMem[i], MEM_Null);
38213   }
38214   releaseMemArray(&p->aMem[1], p->nMem);
38215   sqlite3VdbeFifoClear(&p->sFifo);
38216   if( p->contextStack ){
38217     for(i=0; i<p->contextStackTop; i++){
38218       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
38219     }
38220     sqlite3_free(p->contextStack);
38221   }
38222   p->contextStack = 0;
38223   p->contextStackDepth = 0;
38224   p->contextStackTop = 0;
38225   sqlite3_free(p->zErrMsg);
38226   p->zErrMsg = 0;
38227   p->pResultSet = 0;
38228 }
38229
38230 /*
38231 ** Set the number of result columns that will be returned by this SQL
38232 ** statement. This is now set at compile time, rather than during
38233 ** execution of the vdbe program so that sqlite3_column_count() can
38234 ** be called on an SQL statement before sqlite3_step().
38235 */
38236 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
38237   Mem *pColName;
38238   int n;
38239
38240   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
38241   sqlite3_free(p->aColName);
38242   n = nResColumn*COLNAME_N;
38243   p->nResColumn = nResColumn;
38244   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(p->db, sizeof(Mem)*n );
38245   if( p->aColName==0 ) return;
38246   while( n-- > 0 ){
38247     pColName->flags = MEM_Null;
38248     pColName->db = p->db;
38249     pColName++;
38250   }
38251 }
38252
38253 /*
38254 ** Set the name of the idx'th column to be returned by the SQL statement.
38255 ** zName must be a pointer to a nul terminated string.
38256 **
38257 ** This call must be made after a call to sqlite3VdbeSetNumCols().
38258 **
38259 ** If N==P4_STATIC  it means that zName is a pointer to a constant static
38260 ** string and we can just copy the pointer. If it is P4_DYNAMIC, then 
38261 ** the string is freed using sqlite3_free() when the vdbe is finished with
38262 ** it. Otherwise, N bytes of zName are copied.
38263 */
38264 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
38265   int rc;
38266   Mem *pColName;
38267   assert( idx<p->nResColumn );
38268   assert( var<COLNAME_N );
38269   if( p->db->mallocFailed ) return SQLITE_NOMEM;
38270   assert( p->aColName!=0 );
38271   pColName = &(p->aColName[idx+var*p->nResColumn]);
38272   if( N==P4_DYNAMIC || N==P4_STATIC ){
38273     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
38274   }else{
38275     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
38276   }
38277   if( rc==SQLITE_OK && N==P4_DYNAMIC ){
38278     pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
38279     pColName->xDel = 0;
38280   }
38281   return rc;
38282 }
38283
38284 /*
38285 ** A read or write transaction may or may not be active on database handle
38286 ** db. If a transaction is active, commit it. If there is a
38287 ** write-transaction spanning more than one database file, this routine
38288 ** takes care of the master journal trickery.
38289 */
38290 static int vdbeCommit(sqlite3 *db){
38291   int i;
38292   int nTrans = 0;  /* Number of databases with an active write-transaction */
38293   int rc = SQLITE_OK;
38294   int needXcommit = 0;
38295
38296   /* Before doing anything else, call the xSync() callback for any
38297   ** virtual module tables written in this transaction. This has to
38298   ** be done before determining whether a master journal file is 
38299   ** required, as an xSync() callback may add an attached database
38300   ** to the transaction.
38301   */
38302   rc = sqlite3VtabSync(db, rc);
38303   if( rc!=SQLITE_OK ){
38304     return rc;
38305   }
38306
38307   /* This loop determines (a) if the commit hook should be invoked and
38308   ** (b) how many database files have open write transactions, not 
38309   ** including the temp database. (b) is important because if more than 
38310   ** one database file has an open write transaction, a master journal
38311   ** file is required for an atomic commit.
38312   */ 
38313   for(i=0; i<db->nDb; i++){ 
38314     Btree *pBt = db->aDb[i].pBt;
38315     if( sqlite3BtreeIsInTrans(pBt) ){
38316       needXcommit = 1;
38317       if( i!=1 ) nTrans++;
38318     }
38319   }
38320
38321   /* If there are any write-transactions at all, invoke the commit hook */
38322   if( needXcommit && db->xCommitCallback ){
38323     (void)sqlite3SafetyOff(db);
38324     rc = db->xCommitCallback(db->pCommitArg);
38325     (void)sqlite3SafetyOn(db);
38326     if( rc ){
38327       return SQLITE_CONSTRAINT;
38328     }
38329   }
38330
38331   /* The simple case - no more than one database file (not counting the
38332   ** TEMP database) has a transaction active.   There is no need for the
38333   ** master-journal.
38334   **
38335   ** If the return value of sqlite3BtreeGetFilename() is a zero length
38336   ** string, it means the main database is :memory:.  In that case we do
38337   ** not support atomic multi-file commits, so use the simple case then
38338   ** too.
38339   */
38340   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
38341     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
38342       Btree *pBt = db->aDb[i].pBt;
38343       if( pBt ){
38344         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
38345       }
38346     }
38347
38348     /* Do the commit only if all databases successfully complete phase 1. 
38349     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
38350     ** IO error while deleting or truncating a journal file. It is unlikely,
38351     ** but could happen. In this case abandon processing and return the error.
38352     */
38353     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
38354       Btree *pBt = db->aDb[i].pBt;
38355       if( pBt ){
38356         rc = sqlite3BtreeCommitPhaseTwo(pBt);
38357       }
38358     }
38359     if( rc==SQLITE_OK ){
38360       sqlite3VtabCommit(db);
38361     }
38362   }
38363
38364   /* The complex case - There is a multi-file write-transaction active.
38365   ** This requires a master journal file to ensure the transaction is
38366   ** committed atomicly.
38367   */
38368 #ifndef SQLITE_OMIT_DISKIO
38369   else{
38370     sqlite3_vfs *pVfs = db->pVfs;
38371     int needSync = 0;
38372     char *zMaster = 0;   /* File-name for the master journal */
38373     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
38374     sqlite3_file *pMaster = 0;
38375     i64 offset = 0;
38376
38377     /* Select a master journal file name */
38378     do {
38379       u32 random;
38380       sqlite3_free(zMaster);
38381       sqlite3Randomness(sizeof(random), &random);
38382       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
38383       if( !zMaster ){
38384         return SQLITE_NOMEM;
38385       }
38386     }while( sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS) );
38387
38388     /* Open the master journal. */
38389     rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
38390         SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
38391         SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
38392     );
38393     if( rc!=SQLITE_OK ){
38394       sqlite3_free(zMaster);
38395       return rc;
38396     }
38397  
38398     /* Write the name of each database file in the transaction into the new
38399     ** master journal file. If an error occurs at this point close
38400     ** and delete the master journal file. All the individual journal files
38401     ** still have 'null' as the master journal pointer, so they will roll
38402     ** back independently if a failure occurs.
38403     */
38404     for(i=0; i<db->nDb; i++){
38405       Btree *pBt = db->aDb[i].pBt;
38406       if( i==1 ) continue;   /* Ignore the TEMP database */
38407       if( sqlite3BtreeIsInTrans(pBt) ){
38408         char const *zFile = sqlite3BtreeGetJournalname(pBt);
38409         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
38410         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
38411           needSync = 1;
38412         }
38413         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
38414         offset += strlen(zFile)+1;
38415         if( rc!=SQLITE_OK ){
38416           sqlite3OsCloseFree(pMaster);
38417           sqlite3OsDelete(pVfs, zMaster, 0);
38418           sqlite3_free(zMaster);
38419           return rc;
38420         }
38421       }
38422     }
38423
38424     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
38425     ** flag is set this is not required.
38426     */
38427     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
38428     if( (needSync 
38429      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
38430      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
38431       sqlite3OsCloseFree(pMaster);
38432       sqlite3OsDelete(pVfs, zMaster, 0);
38433       sqlite3_free(zMaster);
38434       return rc;
38435     }
38436
38437     /* Sync all the db files involved in the transaction. The same call
38438     ** sets the master journal pointer in each individual journal. If
38439     ** an error occurs here, do not delete the master journal file.
38440     **
38441     ** If the error occurs during the first call to
38442     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
38443     ** master journal file will be orphaned. But we cannot delete it,
38444     ** in case the master journal file name was written into the journal
38445     ** file before the failure occured.
38446     */
38447     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
38448       Btree *pBt = db->aDb[i].pBt;
38449       if( pBt ){
38450         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
38451       }
38452     }
38453     sqlite3OsCloseFree(pMaster);
38454     if( rc!=SQLITE_OK ){
38455       sqlite3_free(zMaster);
38456       return rc;
38457     }
38458
38459     /* Delete the master journal file. This commits the transaction. After
38460     ** doing this the directory is synced again before any individual
38461     ** transaction files are deleted.
38462     */
38463     rc = sqlite3OsDelete(pVfs, zMaster, 1);
38464     sqlite3_free(zMaster);
38465     zMaster = 0;
38466     if( rc ){
38467       return rc;
38468     }
38469
38470     /* All files and directories have already been synced, so the following
38471     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
38472     ** deleting or truncating journals. If something goes wrong while
38473     ** this is happening we don't really care. The integrity of the
38474     ** transaction is already guaranteed, but some stray 'cold' journals
38475     ** may be lying around. Returning an error code won't help matters.
38476     */
38477     disable_simulated_io_errors();
38478     for(i=0; i<db->nDb; i++){ 
38479       Btree *pBt = db->aDb[i].pBt;
38480       if( pBt ){
38481         sqlite3BtreeCommitPhaseTwo(pBt);
38482       }
38483     }
38484     enable_simulated_io_errors();
38485
38486     sqlite3VtabCommit(db);
38487   }
38488 #endif
38489
38490   return rc;
38491 }
38492
38493 /* 
38494 ** This routine checks that the sqlite3.activeVdbeCnt count variable
38495 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
38496 ** currently active. An assertion fails if the two counts do not match.
38497 ** This is an internal self-check only - it is not an essential processing
38498 ** step.
38499 **
38500 ** This is a no-op if NDEBUG is defined.
38501 */
38502 #ifndef NDEBUG
38503 static void checkActiveVdbeCnt(sqlite3 *db){
38504   Vdbe *p;
38505   int cnt = 0;
38506   p = db->pVdbe;
38507   while( p ){
38508     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
38509       cnt++;
38510     }
38511     p = p->pNext;
38512   }
38513   assert( cnt==db->activeVdbeCnt );
38514 }
38515 #else
38516 #define checkActiveVdbeCnt(x)
38517 #endif
38518
38519 /*
38520 ** For every Btree that in database connection db which 
38521 ** has been modified, "trip" or invalidate each cursor in
38522 ** that Btree might have been modified so that the cursor
38523 ** can never be used again.  This happens when a rollback
38524 *** occurs.  We have to trip all the other cursors, even
38525 ** cursor from other VMs in different database connections,
38526 ** so that none of them try to use the data at which they
38527 ** were pointing and which now may have been changed due
38528 ** to the rollback.
38529 **
38530 ** Remember that a rollback can delete tables complete and
38531 ** reorder rootpages.  So it is not sufficient just to save
38532 ** the state of the cursor.  We have to invalidate the cursor
38533 ** so that it is never used again.
38534 */
38535 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
38536   int i;
38537   for(i=0; i<db->nDb; i++){
38538     Btree *p = db->aDb[i].pBt;
38539     if( p && sqlite3BtreeIsInTrans(p) ){
38540       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
38541     }
38542   }
38543 }
38544
38545 /*
38546 ** This routine is called the when a VDBE tries to halt.  If the VDBE
38547 ** has made changes and is in autocommit mode, then commit those
38548 ** changes.  If a rollback is needed, then do the rollback.
38549 **
38550 ** This routine is the only way to move the state of a VM from
38551 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
38552 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
38553 **
38554 ** Return an error code.  If the commit could not complete because of
38555 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
38556 ** means the close did not happen and needs to be repeated.
38557 */
38558 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
38559   sqlite3 *db = p->db;
38560   int i;
38561   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
38562   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
38563
38564   /* This function contains the logic that determines if a statement or
38565   ** transaction will be committed or rolled back as a result of the
38566   ** execution of this virtual machine. 
38567   **
38568   ** If any of the following errors occur:
38569   **
38570   **     SQLITE_NOMEM
38571   **     SQLITE_IOERR
38572   **     SQLITE_FULL
38573   **     SQLITE_INTERRUPT
38574   **
38575   ** Then the internal cache might have been left in an inconsistent
38576   ** state.  We need to rollback the statement transaction, if there is
38577   ** one, or the complete transaction if there is no statement transaction.
38578   */
38579
38580   if( p->db->mallocFailed ){
38581     p->rc = SQLITE_NOMEM;
38582   }
38583   closeAllCursorsExceptActiveVtabs(p);
38584   if( p->magic!=VDBE_MAGIC_RUN ){
38585     return SQLITE_OK;
38586   }
38587   checkActiveVdbeCnt(db);
38588
38589   /* No commit or rollback needed if the program never started */
38590   if( p->pc>=0 ){
38591     int mrc;   /* Primary error code from p->rc */
38592
38593     /* Lock all btrees used by the statement */
38594     sqlite3BtreeMutexArrayEnter(&p->aMutex);
38595
38596     /* Check for one of the special errors */
38597     mrc = p->rc & 0xff;
38598     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
38599                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
38600     if( isSpecialError ){
38601       /* This loop does static analysis of the query to see which of the
38602       ** following three categories it falls into:
38603       **
38604       **     Read-only
38605       **     Query with statement journal
38606       **     Query without statement journal
38607       **
38608       ** We could do something more elegant than this static analysis (i.e.
38609       ** store the type of query as part of the compliation phase), but 
38610       ** handling malloc() or IO failure is a fairly obscure edge case so 
38611       ** this is probably easier. Todo: Might be an opportunity to reduce 
38612       ** code size a very small amount though...
38613       */
38614       int notReadOnly = 0;
38615       int isStatement = 0;
38616       assert(p->aOp || p->nOp==0);
38617       for(i=0; i<p->nOp; i++){ 
38618         switch( p->aOp[i].opcode ){
38619           case OP_Transaction:
38620             notReadOnly |= p->aOp[i].p2;
38621             break;
38622           case OP_Statement:
38623             isStatement = 1;
38624             break;
38625         }
38626       }
38627
38628    
38629       /* If the query was read-only, we need do no rollback at all. Otherwise,
38630       ** proceed with the special handling.
38631       */
38632       if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
38633         if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
38634           xFunc = sqlite3BtreeRollbackStmt;
38635           p->rc = SQLITE_BUSY;
38636         } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
38637           xFunc = sqlite3BtreeRollbackStmt;
38638         }else{
38639           /* We are forced to roll back the active transaction. Before doing
38640           ** so, abort any other statements this handle currently has active.
38641           */
38642           invalidateCursorsOnModifiedBtrees(db);
38643           sqlite3RollbackAll(db);
38644           db->autoCommit = 1;
38645         }
38646       }
38647     }
38648   
38649     /* If the auto-commit flag is set and this is the only active vdbe, then
38650     ** we do either a commit or rollback of the current transaction. 
38651     **
38652     ** Note: This block also runs if one of the special errors handled 
38653     ** above has occured. 
38654     */
38655     if( db->autoCommit && db->activeVdbeCnt==1 ){
38656       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
38657         /* The auto-commit flag is true, and the vdbe program was 
38658         ** successful or hit an 'OR FAIL' constraint. This means a commit 
38659         ** is required.
38660         */
38661         int rc = vdbeCommit(db);
38662         if( rc==SQLITE_BUSY ){
38663           sqlite3BtreeMutexArrayLeave(&p->aMutex);
38664           return SQLITE_BUSY;
38665         }else if( rc!=SQLITE_OK ){
38666           p->rc = rc;
38667           sqlite3RollbackAll(db);
38668         }else{
38669           sqlite3CommitInternalChanges(db);
38670         }
38671       }else{
38672         sqlite3RollbackAll(db);
38673       }
38674     }else if( !xFunc ){
38675       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
38676         if( p->openedStatement ){
38677           xFunc = sqlite3BtreeCommitStmt;
38678         } 
38679       }else if( p->errorAction==OE_Abort ){
38680         xFunc = sqlite3BtreeRollbackStmt;
38681       }else{
38682         invalidateCursorsOnModifiedBtrees(db);
38683         sqlite3RollbackAll(db);
38684         db->autoCommit = 1;
38685       }
38686     }
38687   
38688     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
38689     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
38690     ** and the return code is still SQLITE_OK, set the return code to the new
38691     ** error value.
38692     */
38693     assert(!xFunc ||
38694       xFunc==sqlite3BtreeCommitStmt ||
38695       xFunc==sqlite3BtreeRollbackStmt
38696     );
38697     for(i=0; xFunc && i<db->nDb; i++){ 
38698       int rc;
38699       Btree *pBt = db->aDb[i].pBt;
38700       if( pBt ){
38701         rc = xFunc(pBt);
38702         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
38703           p->rc = rc;
38704           sqlite3SetString(&p->zErrMsg, 0);
38705         }
38706       }
38707     }
38708   
38709     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
38710     ** set the change counter. 
38711     */
38712     if( p->changeCntOn && p->pc>=0 ){
38713       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
38714         sqlite3VdbeSetChanges(db, p->nChange);
38715       }else{
38716         sqlite3VdbeSetChanges(db, 0);
38717       }
38718       p->nChange = 0;
38719     }
38720   
38721     /* Rollback or commit any schema changes that occurred. */
38722     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
38723       sqlite3ResetInternalSchema(db, 0);
38724       db->flags = (db->flags | SQLITE_InternChanges);
38725     }
38726
38727     /* Release the locks */
38728     sqlite3BtreeMutexArrayLeave(&p->aMutex);
38729   }
38730
38731   /* We have successfully halted and closed the VM.  Record this fact. */
38732   if( p->pc>=0 ){
38733     db->activeVdbeCnt--;
38734   }
38735   p->magic = VDBE_MAGIC_HALT;
38736   checkActiveVdbeCnt(db);
38737   if( p->db->mallocFailed ){
38738     p->rc = SQLITE_NOMEM;
38739   }
38740   checkActiveVdbeCnt(db);
38741
38742   return SQLITE_OK;
38743 }
38744
38745
38746 /*
38747 ** Each VDBE holds the result of the most recent sqlite3_step() call
38748 ** in p->rc.  This routine sets that result back to SQLITE_OK.
38749 */
38750 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
38751   p->rc = SQLITE_OK;
38752 }
38753
38754 /*
38755 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
38756 ** Write any error messages into *pzErrMsg.  Return the result code.
38757 **
38758 ** After this routine is run, the VDBE should be ready to be executed
38759 ** again.
38760 **
38761 ** To look at it another way, this routine resets the state of the
38762 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
38763 ** VDBE_MAGIC_INIT.
38764 */
38765 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
38766   sqlite3 *db;
38767   db = p->db;
38768
38769   /* If the VM did not run to completion or if it encountered an
38770   ** error, then it might not have been halted properly.  So halt
38771   ** it now.
38772   */
38773   (void)sqlite3SafetyOn(db);
38774   sqlite3VdbeHalt(p);
38775   (void)sqlite3SafetyOff(db);
38776
38777   /* If the VDBE has be run even partially, then transfer the error code
38778   ** and error message from the VDBE into the main database structure.  But
38779   ** if the VDBE has just been set to run but has not actually executed any
38780   ** instructions yet, leave the main database error information unchanged.
38781   */
38782   if( p->pc>=0 ){
38783     if( p->zErrMsg ){
38784       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,sqlite3_free);
38785       db->errCode = p->rc;
38786       p->zErrMsg = 0;
38787     }else if( p->rc ){
38788       sqlite3Error(db, p->rc, 0);
38789     }else{
38790       sqlite3Error(db, SQLITE_OK, 0);
38791     }
38792   }else if( p->rc && p->expired ){
38793     /* The expired flag was set on the VDBE before the first call
38794     ** to sqlite3_step(). For consistency (since sqlite3_step() was
38795     ** called), set the database error in this case as well.
38796     */
38797     sqlite3Error(db, p->rc, 0);
38798     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3_free);
38799     p->zErrMsg = 0;
38800   }
38801
38802   /* Reclaim all memory used by the VDBE
38803   */
38804   Cleanup(p);
38805
38806   /* Save profiling information from this VDBE run.
38807   */
38808 #ifdef VDBE_PROFILE
38809   {
38810     FILE *out = fopen("vdbe_profile.out", "a");
38811     if( out ){
38812       int i;
38813       fprintf(out, "---- ");
38814       for(i=0; i<p->nOp; i++){
38815         fprintf(out, "%02x", p->aOp[i].opcode);
38816       }
38817       fprintf(out, "\n");
38818       for(i=0; i<p->nOp; i++){
38819         fprintf(out, "%6d %10lld %8lld ",
38820            p->aOp[i].cnt,
38821            p->aOp[i].cycles,
38822            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
38823         );
38824         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
38825       }
38826       fclose(out);
38827     }
38828   }
38829 #endif
38830   p->magic = VDBE_MAGIC_INIT;
38831   p->aborted = 0;
38832   return p->rc & db->errMask;
38833 }
38834  
38835 /*
38836 ** Clean up and delete a VDBE after execution.  Return an integer which is
38837 ** the result code.  Write any error message text into *pzErrMsg.
38838 */
38839 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
38840   int rc = SQLITE_OK;
38841   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
38842     rc = sqlite3VdbeReset(p);
38843     assert( (rc & p->db->errMask)==rc );
38844   }else if( p->magic!=VDBE_MAGIC_INIT ){
38845     return SQLITE_MISUSE;
38846   }
38847   sqlite3VdbeDelete(p);
38848   return rc;
38849 }
38850
38851 /*
38852 ** Call the destructor for each auxdata entry in pVdbeFunc for which
38853 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
38854 ** are always destroyed.  To destroy all auxdata entries, call this
38855 ** routine with mask==0.
38856 */
38857 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
38858   int i;
38859   for(i=0; i<pVdbeFunc->nAux; i++){
38860     struct AuxData *pAux = &pVdbeFunc->apAux[i];
38861     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
38862       if( pAux->xDelete ){
38863         pAux->xDelete(pAux->pAux);
38864       }
38865       pAux->pAux = 0;
38866     }
38867   }
38868 }
38869
38870 /*
38871 ** Delete an entire VDBE.
38872 */
38873 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
38874   int i;
38875   if( p==0 ) return;
38876   Cleanup(p);
38877   if( p->pPrev ){
38878     p->pPrev->pNext = p->pNext;
38879   }else{
38880     assert( p->db->pVdbe==p );
38881     p->db->pVdbe = p->pNext;
38882   }
38883   if( p->pNext ){
38884     p->pNext->pPrev = p->pPrev;
38885   }
38886   if( p->aOp ){
38887     Op *pOp = p->aOp;
38888     for(i=0; i<p->nOp; i++, pOp++){
38889       freeP4(pOp->p4type, pOp->p4.p);
38890 #ifdef SQLITE_DEBUG
38891       sqlite3_free(pOp->zComment);
38892 #endif     
38893     }
38894     sqlite3_free(p->aOp);
38895   }
38896   releaseMemArray(p->aVar, p->nVar);
38897   sqlite3_free(p->aLabel);
38898   if( p->aMem ){
38899     sqlite3_free(&p->aMem[1]);
38900   }
38901   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
38902   sqlite3_free(p->aColName);
38903   sqlite3_free(p->zSql);
38904   p->magic = VDBE_MAGIC_DEAD;
38905   sqlite3_free(p);
38906 }
38907
38908 /*
38909 ** If a MoveTo operation is pending on the given cursor, then do that
38910 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
38911 ** routine does nothing and returns SQLITE_OK.
38912 */
38913 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor *p){
38914   if( p->deferredMoveto ){
38915     int res, rc;
38916 #ifdef SQLITE_TEST
38917     extern int sqlite3_search_count;
38918 #endif
38919     assert( p->isTable );
38920     rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
38921     if( rc ) return rc;
38922     *p->pIncrKey = 0;
38923     p->lastRowid = keyToInt(p->movetoTarget);
38924     p->rowidIsValid = res==0;
38925     if( res<0 ){
38926       rc = sqlite3BtreeNext(p->pCursor, &res);
38927       if( rc ) return rc;
38928     }
38929 #ifdef SQLITE_TEST
38930     sqlite3_search_count++;
38931 #endif
38932     p->deferredMoveto = 0;
38933     p->cacheStatus = CACHE_STALE;
38934   }
38935   return SQLITE_OK;
38936 }
38937
38938 /*
38939 ** The following functions:
38940 **
38941 ** sqlite3VdbeSerialType()
38942 ** sqlite3VdbeSerialTypeLen()
38943 ** sqlite3VdbeSerialRead()
38944 ** sqlite3VdbeSerialLen()
38945 ** sqlite3VdbeSerialWrite()
38946 **
38947 ** encapsulate the code that serializes values for storage in SQLite
38948 ** data and index records. Each serialized value consists of a
38949 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
38950 ** integer, stored as a varint.
38951 **
38952 ** In an SQLite index record, the serial type is stored directly before
38953 ** the blob of data that it corresponds to. In a table record, all serial
38954 ** types are stored at the start of the record, and the blobs of data at
38955 ** the end. Hence these functions allow the caller to handle the
38956 ** serial-type and data blob seperately.
38957 **
38958 ** The following table describes the various storage classes for data:
38959 **
38960 **   serial type        bytes of data      type
38961 **   --------------     ---------------    ---------------
38962 **      0                     0            NULL
38963 **      1                     1            signed integer
38964 **      2                     2            signed integer
38965 **      3                     3            signed integer
38966 **      4                     4            signed integer
38967 **      5                     6            signed integer
38968 **      6                     8            signed integer
38969 **      7                     8            IEEE float
38970 **      8                     0            Integer constant 0
38971 **      9                     0            Integer constant 1
38972 **     10,11                               reserved for expansion
38973 **    N>=12 and even       (N-12)/2        BLOB
38974 **    N>=13 and odd        (N-13)/2        text
38975 **
38976 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
38977 ** of SQLite will not understand those serial types.
38978 */
38979
38980 /*
38981 ** Return the serial-type for the value stored in pMem.
38982 */
38983 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
38984   int flags = pMem->flags;
38985   int n;
38986
38987   if( flags&MEM_Null ){
38988     return 0;
38989   }
38990   if( flags&MEM_Int ){
38991     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
38992 #   define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
38993     i64 i = pMem->u.i;
38994     u64 u;
38995     if( file_format>=4 && (i&1)==i ){
38996       return 8+i;
38997     }
38998     u = i<0 ? -i : i;
38999     if( u<=127 ) return 1;
39000     if( u<=32767 ) return 2;
39001     if( u<=8388607 ) return 3;
39002     if( u<=2147483647 ) return 4;
39003     if( u<=MAX_6BYTE ) return 5;
39004     return 6;
39005   }
39006   if( flags&MEM_Real ){
39007     return 7;
39008   }
39009   assert( flags&(MEM_Str|MEM_Blob) );
39010   n = pMem->n;
39011   if( flags & MEM_Zero ){
39012     n += pMem->u.i;
39013   }
39014   assert( n>=0 );
39015   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
39016 }
39017
39018 /*
39019 ** Return the length of the data corresponding to the supplied serial-type.
39020 */
39021 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
39022   if( serial_type>=12 ){
39023     return (serial_type-12)/2;
39024   }else{
39025     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
39026     return aSize[serial_type];
39027   }
39028 }
39029
39030 /*
39031 ** If we are on an architecture with mixed-endian floating 
39032 ** points (ex: ARM7) then swap the lower 4 bytes with the 
39033 ** upper 4 bytes.  Return the result.
39034 **
39035 ** For most architectures, this is a no-op.
39036 **
39037 ** (later):  It is reported to me that the mixed-endian problem
39038 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
39039 ** that early versions of GCC stored the two words of a 64-bit
39040 ** float in the wrong order.  And that error has been propagated
39041 ** ever since.  The blame is not necessarily with GCC, though.
39042 ** GCC might have just copying the problem from a prior compiler.
39043 ** I am also told that newer versions of GCC that follow a different
39044 ** ABI get the byte order right.
39045 **
39046 ** Developers using SQLite on an ARM7 should compile and run their
39047 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
39048 ** enabled, some asserts below will ensure that the byte order of
39049 ** floating point values is correct.
39050 **
39051 ** (2007-08-30)  Frank van Vugt has studied this problem closely
39052 ** and has send his findings to the SQLite developers.  Frank
39053 ** writes that some Linux kernels offer floating point hardware
39054 ** emulation that uses only 32-bit mantissas instead of a full 
39055 ** 48-bits as required by the IEEE standard.  (This is the
39056 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
39057 ** byte swapping becomes very complicated.  To avoid problems,
39058 ** the necessary byte swapping is carried out using a 64-bit integer
39059 ** rather than a 64-bit float.  Frank assures us that the code here
39060 ** works for him.  We, the developers, have no way to independently
39061 ** verify this, but Frank seems to know what he is talking about
39062 ** so we trust him.
39063 */
39064 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
39065 static u64 floatSwap(u64 in){
39066   union {
39067     u64 r;
39068     u32 i[2];
39069   } u;
39070   u32 t;
39071
39072   u.r = in;
39073   t = u.i[0];
39074   u.i[0] = u.i[1];
39075   u.i[1] = t;
39076   return u.r;
39077 }
39078 # define swapMixedEndianFloat(X)  X = floatSwap(X)
39079 #else
39080 # define swapMixedEndianFloat(X)
39081 #endif
39082
39083 /*
39084 ** Write the serialized data blob for the value stored in pMem into 
39085 ** buf. It is assumed that the caller has allocated sufficient space.
39086 ** Return the number of bytes written.
39087 **
39088 ** nBuf is the amount of space left in buf[].  nBuf must always be
39089 ** large enough to hold the entire field.  Except, if the field is
39090 ** a blob with a zero-filled tail, then buf[] might be just the right
39091 ** size to hold everything except for the zero-filled tail.  If buf[]
39092 ** is only big enough to hold the non-zero prefix, then only write that
39093 ** prefix into buf[].  But if buf[] is large enough to hold both the
39094 ** prefix and the tail then write the prefix and set the tail to all
39095 ** zeros.
39096 **
39097 ** Return the number of bytes actually written into buf[].  The number
39098 ** of bytes in the zero-filled tail is included in the return value only
39099 ** if those bytes were zeroed in buf[].
39100 */ 
39101 SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
39102   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
39103   int len;
39104
39105   /* Integer and Real */
39106   if( serial_type<=7 && serial_type>0 ){
39107     u64 v;
39108     int i;
39109     if( serial_type==7 ){
39110       assert( sizeof(v)==sizeof(pMem->r) );
39111       memcpy(&v, &pMem->r, sizeof(v));
39112       swapMixedEndianFloat(v);
39113     }else{
39114       v = pMem->u.i;
39115     }
39116     len = i = sqlite3VdbeSerialTypeLen(serial_type);
39117     assert( len<=nBuf );
39118     while( i-- ){
39119       buf[i] = (v&0xFF);
39120       v >>= 8;
39121     }
39122     return len;
39123   }
39124
39125   /* String or blob */
39126   if( serial_type>=12 ){
39127     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
39128              == sqlite3VdbeSerialTypeLen(serial_type) );
39129     assert( pMem->n<=nBuf );
39130     len = pMem->n;
39131     memcpy(buf, pMem->z, len);
39132     if( pMem->flags & MEM_Zero ){
39133       len += pMem->u.i;
39134       if( len>nBuf ){
39135         len = nBuf;
39136       }
39137       memset(&buf[pMem->n], 0, len-pMem->n);
39138     }
39139     return len;
39140   }
39141
39142   /* NULL or constants 0 or 1 */
39143   return 0;
39144 }
39145
39146 /*
39147 ** Deserialize the data blob pointed to by buf as serial type serial_type
39148 ** and store the result in pMem.  Return the number of bytes read.
39149 */ 
39150 SQLITE_PRIVATE int sqlite3VdbeSerialGet(
39151   const unsigned char *buf,     /* Buffer to deserialize from */
39152   u32 serial_type,              /* Serial type to deserialize */
39153   Mem *pMem                     /* Memory cell to write value into */
39154 ){
39155   switch( serial_type ){
39156     case 10:   /* Reserved for future use */
39157     case 11:   /* Reserved for future use */
39158     case 0: {  /* NULL */
39159       pMem->flags = MEM_Null;
39160       break;
39161     }
39162     case 1: { /* 1-byte signed integer */
39163       pMem->u.i = (signed char)buf[0];
39164       pMem->flags = MEM_Int;
39165       return 1;
39166     }
39167     case 2: { /* 2-byte signed integer */
39168       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
39169       pMem->flags = MEM_Int;
39170       return 2;
39171     }
39172     case 3: { /* 3-byte signed integer */
39173       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
39174       pMem->flags = MEM_Int;
39175       return 3;
39176     }
39177     case 4: { /* 4-byte signed integer */
39178       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
39179       pMem->flags = MEM_Int;
39180       return 4;
39181     }
39182     case 5: { /* 6-byte signed integer */
39183       u64 x = (((signed char)buf[0])<<8) | buf[1];
39184       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
39185       x = (x<<32) | y;
39186       pMem->u.i = *(i64*)&x;
39187       pMem->flags = MEM_Int;
39188       return 6;
39189     }
39190     case 6:   /* 8-byte signed integer */
39191     case 7: { /* IEEE floating point */
39192       u64 x;
39193       u32 y;
39194 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
39195       /* Verify that integers and floating point values use the same
39196       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
39197       ** defined that 64-bit floating point values really are mixed
39198       ** endian.
39199       */
39200       static const u64 t1 = ((u64)0x3ff00000)<<32;
39201       static const double r1 = 1.0;
39202       u64 t2 = t1;
39203       swapMixedEndianFloat(t2);
39204       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
39205 #endif
39206
39207       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
39208       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
39209       x = (x<<32) | y;
39210       if( serial_type==6 ){
39211         pMem->u.i = *(i64*)&x;
39212         pMem->flags = MEM_Int;
39213       }else{
39214         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
39215         swapMixedEndianFloat(x);
39216         memcpy(&pMem->r, &x, sizeof(x));
39217         pMem->flags = MEM_Real;
39218       }
39219       return 8;
39220     }
39221     case 8:    /* Integer 0 */
39222     case 9: {  /* Integer 1 */
39223       pMem->u.i = serial_type-8;
39224       pMem->flags = MEM_Int;
39225       return 0;
39226     }
39227     default: {
39228       int len = (serial_type-12)/2;
39229       pMem->z = (char *)buf;
39230       pMem->n = len;
39231       pMem->xDel = 0;
39232       if( serial_type&0x01 ){
39233         pMem->flags = MEM_Str | MEM_Ephem;
39234       }else{
39235         pMem->flags = MEM_Blob | MEM_Ephem;
39236       }
39237       return len;
39238     }
39239   }
39240   return 0;
39241 }
39242
39243 /*
39244 ** The header of a record consists of a sequence variable-length integers.
39245 ** These integers are almost always small and are encoded as a single byte.
39246 ** The following macro takes advantage this fact to provide a fast decode
39247 ** of the integers in a record header.  It is faster for the common case
39248 ** where the integer is a single byte.  It is a little slower when the
39249 ** integer is two or more bytes.  But overall it is faster.
39250 **
39251 ** The following expressions are equivalent:
39252 **
39253 **     x = sqlite3GetVarint32( A, &B );
39254 **
39255 **     x = GetVarint( A, B );
39256 **
39257 */
39258 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
39259
39260 /*
39261 ** This function compares the two table rows or index records specified by 
39262 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
39263 ** or positive integer if {nKey1, pKey1} is less than, equal to or 
39264 ** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
39265 ** composed by the OP_MakeRecord opcode of the VDBE.
39266 **
39267 ** Key1 and Key2 do not have to contain the same number of fields.
39268 ** But if the lengths differ, Key2 must be the shorter of the two.
39269 */
39270 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
39271   void *userData,
39272   int nKey1, const void *pKey1, 
39273   int nKey2, const void *pKey2
39274 ){
39275   KeyInfo *pKeyInfo = (KeyInfo*)userData;
39276   u32 d1, d2;          /* Offset into aKey[] of next data element */
39277   u32 idx1, idx2;      /* Offset into aKey[] of next header element */
39278   u32 szHdr1, szHdr2;  /* Number of bytes in header */
39279   int i = 0;
39280   int nField;
39281   int rc = 0;
39282   const unsigned char *aKey1 = (const unsigned char *)pKey1;
39283   const unsigned char *aKey2 = (const unsigned char *)pKey2;
39284
39285   Mem mem1;
39286   Mem mem2;
39287   mem1.enc = pKeyInfo->enc;
39288   mem1.db = pKeyInfo->db;
39289   mem1.flags = 0;
39290   mem2.enc = pKeyInfo->enc;
39291   mem2.db = pKeyInfo->db;
39292   mem2.flags = 0;
39293   
39294   idx1 = GetVarint(aKey1, szHdr1);
39295   d1 = szHdr1;
39296   idx2 = GetVarint(aKey2, szHdr2);
39297   d2 = szHdr2;
39298   nField = pKeyInfo->nField;
39299   while( idx1<szHdr1 && idx2<szHdr2 ){
39300     u32 serial_type1;
39301     u32 serial_type2;
39302
39303     /* Read the serial types for the next element in each key. */
39304     idx1 += GetVarint( aKey1+idx1, serial_type1 );
39305     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
39306     idx2 += GetVarint( aKey2+idx2, serial_type2 );
39307     if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
39308
39309     /* Extract the values to be compared.
39310     */
39311     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
39312     d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
39313
39314     /* Do the comparison
39315     */
39316     rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
39317     if( mem1.flags&MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
39318     if( mem2.flags&MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
39319     if( rc!=0 ){
39320       break;
39321     }
39322     i++;
39323   }
39324
39325   /* One of the keys ran out of fields, but all the fields up to that point
39326   ** were equal. If the incrKey flag is true, then the second key is
39327   ** treated as larger.
39328   */
39329   if( rc==0 ){
39330     if( pKeyInfo->incrKey ){
39331       rc = -1;
39332     }else if( !pKeyInfo->prefixIsEqual ){
39333       if( d1<nKey1 ){
39334         rc = 1;
39335       }else if( d2<nKey2 ){
39336         rc = -1;  /* Only occurs on a corrupt database file */
39337       }
39338     }
39339   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
39340                && pKeyInfo->aSortOrder[i] ){
39341     rc = -rc;
39342   }
39343
39344   return rc;
39345 }
39346
39347 /*
39348 ** The argument is an index entry composed using the OP_MakeRecord opcode.
39349 ** The last entry in this record should be an integer (specifically
39350 ** an integer rowid).  This routine returns the number of bytes in
39351 ** that integer.
39352 */
39353 SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8 *aKey){
39354   u32 szHdr;        /* Size of the header */
39355   u32 typeRowid;    /* Serial type of the rowid */
39356
39357   sqlite3GetVarint32(aKey, &szHdr);
39358   sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
39359   return sqlite3VdbeSerialTypeLen(typeRowid);
39360 }
39361   
39362
39363 /*
39364 ** pCur points at an index entry created using the OP_MakeRecord opcode.
39365 ** Read the rowid (the last field in the record) and store it in *rowid.
39366 ** Return SQLITE_OK if everything works, or an error code otherwise.
39367 */
39368 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
39369   i64 nCellKey = 0;
39370   int rc;
39371   u32 szHdr;        /* Size of the header */
39372   u32 typeRowid;    /* Serial type of the rowid */
39373   u32 lenRowid;     /* Size of the rowid */
39374   Mem m, v;
39375
39376   sqlite3BtreeKeySize(pCur, &nCellKey);
39377   if( nCellKey<=0 ){
39378     return SQLITE_CORRUPT_BKPT;
39379   }
39380   m.flags = 0;
39381   m.db = 0;
39382   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
39383   if( rc ){
39384     return rc;
39385   }
39386   sqlite3GetVarint32((u8*)m.z, &szHdr);
39387   sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
39388   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
39389   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
39390   *rowid = v.u.i;
39391   sqlite3VdbeMemRelease(&m);
39392   return SQLITE_OK;
39393 }
39394
39395 /*
39396 ** Compare the key of the index entry that cursor pC is point to against
39397 ** the key string in pKey (of length nKey).  Write into *pRes a number
39398 ** that is negative, zero, or positive if pC is less than, equal to,
39399 ** or greater than pKey.  Return SQLITE_OK on success.
39400 **
39401 ** pKey is either created without a rowid or is truncated so that it
39402 ** omits the rowid at the end.  The rowid at the end of the index entry
39403 ** is ignored as well.
39404 */
39405 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
39406   Cursor *pC,                 /* The cursor to compare against */
39407   int nKey, const u8 *pKey,   /* The key to compare */
39408   int *res                    /* Write the comparison result here */
39409 ){
39410   i64 nCellKey = 0;
39411   int rc;
39412   BtCursor *pCur = pC->pCursor;
39413   int lenRowid;
39414   Mem m;
39415
39416   sqlite3BtreeKeySize(pCur, &nCellKey);
39417   if( nCellKey<=0 ){
39418     *res = 0;
39419     return SQLITE_OK;
39420   }
39421   m.db = 0;
39422   m.flags = 0;
39423   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
39424   if( rc ){
39425     return rc;
39426   }
39427   lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
39428   *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
39429   sqlite3VdbeMemRelease(&m);
39430   return SQLITE_OK;
39431 }
39432
39433 /*
39434 ** This routine sets the value to be returned by subsequent calls to
39435 ** sqlite3_changes() on the database handle 'db'. 
39436 */
39437 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
39438   assert( sqlite3_mutex_held(db->mutex) );
39439   db->nChange = nChange;
39440   db->nTotalChange += nChange;
39441 }
39442
39443 /*
39444 ** Set a flag in the vdbe to update the change counter when it is finalised
39445 ** or reset.
39446 */
39447 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
39448   v->changeCntOn = 1;
39449 }
39450
39451 /*
39452 ** Mark every prepared statement associated with a database connection
39453 ** as expired.
39454 **
39455 ** An expired statement means that recompilation of the statement is
39456 ** recommend.  Statements expire when things happen that make their
39457 ** programs obsolete.  Removing user-defined functions or collating
39458 ** sequences, or changing an authorization function are the types of
39459 ** things that make prepared statements obsolete.
39460 */
39461 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
39462   Vdbe *p;
39463   for(p = db->pVdbe; p; p=p->pNext){
39464     p->expired = 1;
39465   }
39466 }
39467
39468 /*
39469 ** Return the database associated with the Vdbe.
39470 */
39471 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
39472   return v->db;
39473 }
39474
39475 /************** End of vdbeaux.c *********************************************/
39476 /************** Begin file vdbeapi.c *****************************************/
39477 /*
39478 ** 2004 May 26
39479 **
39480 ** The author disclaims copyright to this source code.  In place of
39481 ** a legal notice, here is a blessing:
39482 **
39483 **    May you do good and not evil.
39484 **    May you find forgiveness for yourself and forgive others.
39485 **    May you share freely, never taking more than you give.
39486 **
39487 *************************************************************************
39488 **
39489 ** This file contains code use to implement APIs that are part of the
39490 ** VDBE.
39491 */
39492
39493 /*
39494 ** Return TRUE (non-zero) of the statement supplied as an argument needs
39495 ** to be recompiled.  A statement needs to be recompiled whenever the
39496 ** execution environment changes in a way that would alter the program
39497 ** that sqlite3_prepare() generates.  For example, if new functions or
39498 ** collating sequences are registered or if an authorizer function is
39499 ** added or changed.
39500 */
39501 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
39502   Vdbe *p = (Vdbe*)pStmt;
39503   return p==0 || p->expired;
39504 }
39505
39506 /*
39507 ** The following routine destroys a virtual machine that is created by
39508 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
39509 ** success/failure code that describes the result of executing the virtual
39510 ** machine.
39511 **
39512 ** This routine sets the error code and string returned by
39513 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
39514 */
39515 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
39516   int rc;
39517   if( pStmt==0 ){
39518     rc = SQLITE_OK;
39519   }else{
39520     Vdbe *v = (Vdbe*)pStmt;
39521 #ifndef SQLITE_MUTEX_NOOP
39522     sqlite3_mutex *mutex = v->db->mutex;
39523 #endif
39524     sqlite3_mutex_enter(mutex);
39525     rc = sqlite3VdbeFinalize(v);
39526     sqlite3_mutex_leave(mutex);
39527   }
39528   return rc;
39529 }
39530
39531 /*
39532 ** Terminate the current execution of an SQL statement and reset it
39533 ** back to its starting state so that it can be reused. A success code from
39534 ** the prior execution is returned.
39535 **
39536 ** This routine sets the error code and string returned by
39537 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
39538 */
39539 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
39540   int rc;
39541   if( pStmt==0 ){
39542     rc = SQLITE_OK;
39543   }else{
39544     Vdbe *v = (Vdbe*)pStmt;
39545     sqlite3_mutex_enter(v->db->mutex);
39546     rc = sqlite3VdbeReset(v);
39547     sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
39548     assert( (rc & (v->db->errMask))==rc );
39549     sqlite3_mutex_leave(v->db->mutex);
39550   }
39551   return rc;
39552 }
39553
39554 /*
39555 ** Set all the parameters in the compiled SQL statement to NULL.
39556 */
39557 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
39558   int i;
39559   int rc = SQLITE_OK;
39560 #ifndef SQLITE_MUTEX_NOOP
39561   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
39562 #endif
39563   sqlite3_mutex_enter(mutex);
39564   for(i=1; rc==SQLITE_OK && i<=sqlite3_bind_parameter_count(pStmt); i++){
39565     rc = sqlite3_bind_null(pStmt, i);
39566   }
39567   sqlite3_mutex_leave(mutex);
39568   return rc;
39569 }
39570
39571
39572 /**************************** sqlite3_value_  *******************************
39573 ** The following routines extract information from a Mem or sqlite3_value
39574 ** structure.
39575 */
39576 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
39577   Mem *p = (Mem*)pVal;
39578   if( p->flags & (MEM_Blob|MEM_Str) ){
39579     sqlite3VdbeMemExpandBlob(p);
39580     p->flags &= ~MEM_Str;
39581     p->flags |= MEM_Blob;
39582     return p->z;
39583   }else{
39584     return sqlite3_value_text(pVal);
39585   }
39586 }
39587 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
39588   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
39589 }
39590 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
39591   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
39592 }
39593 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
39594   return sqlite3VdbeRealValue((Mem*)pVal);
39595 }
39596 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
39597   return sqlite3VdbeIntValue((Mem*)pVal);
39598 }
39599 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
39600   return sqlite3VdbeIntValue((Mem*)pVal);
39601 }
39602 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
39603   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
39604 }
39605 #ifndef SQLITE_OMIT_UTF16
39606 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
39607   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
39608 }
39609 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
39610   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
39611 }
39612 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
39613   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
39614 }
39615 #endif /* SQLITE_OMIT_UTF16 */
39616 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
39617   return pVal->type;
39618 }
39619
39620 /**************************** sqlite3_result_  *******************************
39621 ** The following routines are used by user-defined functions to specify
39622 ** the function result.
39623 */
39624 SQLITE_API void sqlite3_result_blob(
39625   sqlite3_context *pCtx, 
39626   const void *z, 
39627   int n, 
39628   void (*xDel)(void *)
39629 ){
39630   assert( n>=0 );
39631   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39632   sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
39633 }
39634 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
39635   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39636   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
39637 }
39638 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
39639   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39640   pCtx->isError = SQLITE_ERROR;
39641   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
39642 }
39643 #ifndef SQLITE_OMIT_UTF16
39644 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
39645   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39646   pCtx->isError = SQLITE_ERROR;
39647   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
39648 }
39649 #endif
39650 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
39651   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39652   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
39653 }
39654 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
39655   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39656   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
39657 }
39658 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
39659   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39660   sqlite3VdbeMemSetNull(&pCtx->s);
39661 }
39662 SQLITE_API void sqlite3_result_text(
39663   sqlite3_context *pCtx, 
39664   const char *z, 
39665   int n,
39666   void (*xDel)(void *)
39667 ){
39668   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39669   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
39670 }
39671 #ifndef SQLITE_OMIT_UTF16
39672 SQLITE_API void sqlite3_result_text16(
39673   sqlite3_context *pCtx, 
39674   const void *z, 
39675   int n, 
39676   void (*xDel)(void *)
39677 ){
39678   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39679   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
39680 }
39681 SQLITE_API void sqlite3_result_text16be(
39682   sqlite3_context *pCtx, 
39683   const void *z, 
39684   int n, 
39685   void (*xDel)(void *)
39686 ){
39687   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39688   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
39689 }
39690 SQLITE_API void sqlite3_result_text16le(
39691   sqlite3_context *pCtx, 
39692   const void *z, 
39693   int n, 
39694   void (*xDel)(void *)
39695 ){
39696   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39697   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
39698 }
39699 #endif /* SQLITE_OMIT_UTF16 */
39700 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
39701   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39702   sqlite3VdbeMemCopy(&pCtx->s, pValue);
39703 }
39704 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
39705   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39706   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
39707 }
39708 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
39709   pCtx->isError = errCode;
39710 }
39711
39712 /* Force an SQLITE_TOOBIG error. */
39713 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
39714   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39715   sqlite3VdbeMemSetZeroBlob(&pCtx->s, SQLITE_MAX_LENGTH+1);
39716 }
39717
39718 /* An SQLITE_NOMEM error. */
39719 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
39720   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39721   sqlite3VdbeMemSetNull(&pCtx->s);
39722   pCtx->isError = SQLITE_NOMEM;
39723   pCtx->s.db->mallocFailed = 1;
39724 }
39725
39726 /*
39727 ** Execute the statement pStmt, either until a row of data is ready, the
39728 ** statement is completely executed or an error occurs.
39729 **
39730 ** This routine implements the bulk of the logic behind the sqlite_step()
39731 ** API.  The only thing omitted is the automatic recompile if a 
39732 ** schema change has occurred.  That detail is handled by the
39733 ** outer sqlite3_step() wrapper procedure.
39734 */
39735 static int sqlite3Step(Vdbe *p){
39736   sqlite3 *db;
39737   int rc;
39738
39739   assert(p);
39740   if( p->magic!=VDBE_MAGIC_RUN ){
39741     return SQLITE_MISUSE;
39742   }
39743
39744   /* Assert that malloc() has not failed */
39745   db = p->db;
39746   assert( !db->mallocFailed );
39747
39748   if( p->aborted ){
39749     return SQLITE_ABORT;
39750   }
39751   if( p->pc<=0 && p->expired ){
39752     if( p->rc==SQLITE_OK ){
39753       p->rc = SQLITE_SCHEMA;
39754     }
39755     rc = SQLITE_ERROR;
39756     goto end_of_step;
39757   }
39758   if( sqlite3SafetyOn(db) ){
39759     p->rc = SQLITE_MISUSE;
39760     return SQLITE_MISUSE;
39761   }
39762   if( p->pc<0 ){
39763     /* If there are no other statements currently running, then
39764     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
39765     ** from interrupting a statement that has not yet started.
39766     */
39767     if( db->activeVdbeCnt==0 ){
39768       db->u1.isInterrupted = 0;
39769     }
39770
39771 #ifndef SQLITE_OMIT_TRACE
39772     if( db->xProfile && !db->init.busy ){
39773       double rNow;
39774       sqlite3OsCurrentTime(db->pVfs, &rNow);
39775       p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
39776     }
39777 #endif
39778
39779     db->activeVdbeCnt++;
39780     p->pc = 0;
39781   }
39782 #ifndef SQLITE_OMIT_EXPLAIN
39783   if( p->explain ){
39784     rc = sqlite3VdbeList(p);
39785   }else
39786 #endif /* SQLITE_OMIT_EXPLAIN */
39787   {
39788     rc = sqlite3VdbeExec(p);
39789   }
39790
39791   if( sqlite3SafetyOff(db) ){
39792     rc = SQLITE_MISUSE;
39793   }
39794
39795 #ifndef SQLITE_OMIT_TRACE
39796   /* Invoke the profile callback if there is one
39797   */
39798   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0
39799            && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){
39800     double rNow;
39801     u64 elapseTime;
39802
39803     sqlite3OsCurrentTime(db->pVfs, &rNow);
39804     elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
39805     db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime);
39806   }
39807 #endif
39808
39809   sqlite3Error(p->db, rc, 0);
39810   p->rc = sqlite3ApiExit(p->db, p->rc);
39811 end_of_step:
39812   assert( (rc&0xff)==rc );
39813   if( p->zSql && (rc&0xff)<SQLITE_ROW ){
39814     /* This behavior occurs if sqlite3_prepare_v2() was used to build
39815     ** the prepared statement.  Return error codes directly */
39816     sqlite3Error(p->db, p->rc, 0);
39817     return p->rc;
39818   }else{
39819     /* This is for legacy sqlite3_prepare() builds and when the code
39820     ** is SQLITE_ROW or SQLITE_DONE */
39821     return rc;
39822   }
39823 }
39824
39825 /*
39826 ** This is the top-level implementation of sqlite3_step().  Call
39827 ** sqlite3Step() to do most of the work.  If a schema error occurs,
39828 ** call sqlite3Reprepare() and try again.
39829 */
39830 #ifdef SQLITE_OMIT_PARSER
39831 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
39832   int rc = SQLITE_MISUSE;
39833   if( pStmt ){
39834     Vdbe *v;
39835     v = (Vdbe*)pStmt;
39836     sqlite3_mutex_enter(v->db->mutex);
39837     rc = sqlite3Step(v);
39838     sqlite3_mutex_leave(v->db->mutex);
39839   }
39840   return rc;
39841 }
39842 #else
39843 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
39844   int rc = SQLITE_MISUSE;
39845   if( pStmt ){
39846     int cnt = 0;
39847     Vdbe *v = (Vdbe*)pStmt;
39848     sqlite3 *db = v->db;
39849     sqlite3_mutex_enter(db->mutex);
39850     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
39851            && cnt++ < 5
39852            && sqlite3Reprepare(v) ){
39853       sqlite3_reset(pStmt);
39854       v->expired = 0;
39855     }
39856     if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
39857       /* This case occurs after failing to recompile an sql statement. 
39858       ** The error message from the SQL compiler has already been loaded 
39859       ** into the database handle. This block copies the error message 
39860       ** from the database handle into the statement and sets the statement
39861       ** program counter to 0 to ensure that when the statement is 
39862       ** finalized or reset the parser error message is available via
39863       ** sqlite3_errmsg() and sqlite3_errcode().
39864       */
39865       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
39866       sqlite3_free(v->zErrMsg);
39867       if( !db->mallocFailed ){
39868         v->zErrMsg = sqlite3DbStrDup(db, zErr);
39869       } else {
39870         v->zErrMsg = 0;
39871         v->rc = SQLITE_NOMEM;
39872       }
39873     }
39874     rc = sqlite3ApiExit(db, rc);
39875     sqlite3_mutex_leave(db->mutex);
39876   }
39877   return rc;
39878 }
39879 #endif
39880
39881 /*
39882 ** Extract the user data from a sqlite3_context structure and return a
39883 ** pointer to it.
39884 */
39885 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
39886   assert( p && p->pFunc );
39887   return p->pFunc->pUserData;
39888 }
39889
39890 /*
39891 ** The following is the implementation of an SQL function that always
39892 ** fails with an error message stating that the function is used in the
39893 ** wrong context.  The sqlite3_overload_function() API might construct
39894 ** SQL function that use this routine so that the functions will exist
39895 ** for name resolution but are actually overloaded by the xFindFunction
39896 ** method of virtual tables.
39897 */
39898 SQLITE_PRIVATE void sqlite3InvalidFunction(
39899   sqlite3_context *context,  /* The function calling context */
39900   int argc,                  /* Number of arguments to the function */
39901   sqlite3_value **argv       /* Value of each argument */
39902 ){
39903   const char *zName = context->pFunc->zName;
39904   char *zErr;
39905   zErr = sqlite3MPrintf(0,
39906       "unable to use function %s in the requested context", zName);
39907   sqlite3_result_error(context, zErr, -1);
39908   sqlite3_free(zErr);
39909 }
39910
39911 /*
39912 ** Allocate or return the aggregate context for a user function.  A new
39913 ** context is allocated on the first call.  Subsequent calls return the
39914 ** same context that was returned on prior calls.
39915 */
39916 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
39917   Mem *pMem;
39918   assert( p && p->pFunc && p->pFunc->xStep );
39919   assert( sqlite3_mutex_held(p->s.db->mutex) );
39920   pMem = p->pMem;
39921   if( (pMem->flags & MEM_Agg)==0 ){
39922     if( nByte==0 ){
39923       assert( pMem->flags==MEM_Null );
39924       pMem->z = 0;
39925     }else{
39926       pMem->flags = MEM_Agg;
39927       pMem->xDel = sqlite3_free;
39928       pMem->u.pDef = p->pFunc;
39929       pMem->z = sqlite3DbMallocZero(p->s.db, nByte);
39930     }
39931   }
39932   return (void*)pMem->z;
39933 }
39934
39935 /*
39936 ** Return the auxilary data pointer, if any, for the iArg'th argument to
39937 ** the user-function defined by pCtx.
39938 */
39939 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
39940   VdbeFunc *pVdbeFunc;
39941
39942   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39943   pVdbeFunc = pCtx->pVdbeFunc;
39944   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
39945     return 0;
39946   }
39947   return pVdbeFunc->apAux[iArg].pAux;
39948 }
39949
39950 /*
39951 ** Set the auxilary data pointer and delete function, for the iArg'th
39952 ** argument to the user-function defined by pCtx. Any previous value is
39953 ** deleted by calling the delete function specified when it was set.
39954 */
39955 SQLITE_API void sqlite3_set_auxdata(
39956   sqlite3_context *pCtx, 
39957   int iArg, 
39958   void *pAux, 
39959   void (*xDelete)(void*)
39960 ){
39961   struct AuxData *pAuxData;
39962   VdbeFunc *pVdbeFunc;
39963   if( iArg<0 ) goto failed;
39964
39965   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
39966   pVdbeFunc = pCtx->pVdbeFunc;
39967   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
39968     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
39969     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
39970     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
39971     if( !pVdbeFunc ){
39972       goto failed;
39973     }
39974     pCtx->pVdbeFunc = pVdbeFunc;
39975     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
39976     pVdbeFunc->nAux = iArg+1;
39977     pVdbeFunc->pFunc = pCtx->pFunc;
39978   }
39979
39980   pAuxData = &pVdbeFunc->apAux[iArg];
39981   if( pAuxData->pAux && pAuxData->xDelete ){
39982     pAuxData->xDelete(pAuxData->pAux);
39983   }
39984   pAuxData->pAux = pAux;
39985   pAuxData->xDelete = xDelete;
39986   return;
39987
39988 failed:
39989   if( xDelete ){
39990     xDelete(pAux);
39991   }
39992 }
39993
39994 /*
39995 ** Return the number of times the Step function of a aggregate has been 
39996 ** called.
39997 **
39998 ** This function is deprecated.  Do not use it for new code.  It is
39999 ** provide only to avoid breaking legacy code.  New aggregate function
40000 ** implementations should keep their own counts within their aggregate
40001 ** context.
40002 */
40003 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
40004   assert( p && p->pFunc && p->pFunc->xStep );
40005   return p->pMem->n;
40006 }
40007
40008 /*
40009 ** Return the number of columns in the result set for the statement pStmt.
40010 */
40011 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
40012   Vdbe *pVm = (Vdbe *)pStmt;
40013   return pVm ? pVm->nResColumn : 0;
40014 }
40015
40016 /*
40017 ** Return the number of values available from the current row of the
40018 ** currently executing statement pStmt.
40019 */
40020 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
40021   Vdbe *pVm = (Vdbe *)pStmt;
40022   if( pVm==0 || pVm->pResultSet==0 ) return 0;
40023   return pVm->nResColumn;
40024 }
40025
40026
40027 /*
40028 ** Check to see if column iCol of the given statement is valid.  If
40029 ** it is, return a pointer to the Mem for the value of that column.
40030 ** If iCol is not valid, return a pointer to a Mem which has a value
40031 ** of NULL.
40032 */
40033 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
40034   Vdbe *pVm;
40035   int vals;
40036   Mem *pOut;
40037
40038   pVm = (Vdbe *)pStmt;
40039   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
40040     sqlite3_mutex_enter(pVm->db->mutex);
40041     vals = sqlite3_data_count(pStmt);
40042     pOut = &pVm->pResultSet[i];
40043   }else{
40044     static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL };
40045     if( pVm->db ){
40046       sqlite3_mutex_enter(pVm->db->mutex);
40047       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
40048     }
40049     pOut = (Mem*)&nullMem;
40050   }
40051   return pOut;
40052 }
40053
40054 /*
40055 ** This function is called after invoking an sqlite3_value_XXX function on a 
40056 ** column value (i.e. a value returned by evaluating an SQL expression in the
40057 ** select list of a SELECT statement) that may cause a malloc() failure. If 
40058 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
40059 ** code of statement pStmt set to SQLITE_NOMEM.
40060 **
40061 ** Specifically, this is called from within:
40062 **
40063 **     sqlite3_column_int()
40064 **     sqlite3_column_int64()
40065 **     sqlite3_column_text()
40066 **     sqlite3_column_text16()
40067 **     sqlite3_column_real()
40068 **     sqlite3_column_bytes()
40069 **     sqlite3_column_bytes16()
40070 **
40071 ** But not for sqlite3_column_blob(), which never calls malloc().
40072 */
40073 static void columnMallocFailure(sqlite3_stmt *pStmt)
40074 {
40075   /* If malloc() failed during an encoding conversion within an
40076   ** sqlite3_column_XXX API, then set the return code of the statement to
40077   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
40078   ** and _finalize() will return NOMEM.
40079   */
40080   Vdbe *p = (Vdbe *)pStmt;
40081   if( p ){
40082     p->rc = sqlite3ApiExit(p->db, p->rc);
40083     sqlite3_mutex_leave(p->db->mutex);
40084   }
40085 }
40086
40087 /**************************** sqlite3_column_  *******************************
40088 ** The following routines are used to access elements of the current row
40089 ** in the result set.
40090 */
40091 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
40092   const void *val;
40093   val = sqlite3_value_blob( columnMem(pStmt,i) );
40094   /* Even though there is no encoding conversion, value_blob() might
40095   ** need to call malloc() to expand the result of a zeroblob() 
40096   ** expression. 
40097   */
40098   columnMallocFailure(pStmt);
40099   return val;
40100 }
40101 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
40102   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
40103   columnMallocFailure(pStmt);
40104   return val;
40105 }
40106 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
40107   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
40108   columnMallocFailure(pStmt);
40109   return val;
40110 }
40111 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
40112   double val = sqlite3_value_double( columnMem(pStmt,i) );
40113   columnMallocFailure(pStmt);
40114   return val;
40115 }
40116 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
40117   int val = sqlite3_value_int( columnMem(pStmt,i) );
40118   columnMallocFailure(pStmt);
40119   return val;
40120 }
40121 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
40122   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
40123   columnMallocFailure(pStmt);
40124   return val;
40125 }
40126 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
40127   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
40128   columnMallocFailure(pStmt);
40129   return val;
40130 }
40131 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
40132   sqlite3_value *pOut = columnMem(pStmt, i);
40133   columnMallocFailure(pStmt);
40134   return pOut;
40135 }
40136 #ifndef SQLITE_OMIT_UTF16
40137 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
40138   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
40139   columnMallocFailure(pStmt);
40140   return val;
40141 }
40142 #endif /* SQLITE_OMIT_UTF16 */
40143 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
40144   int iType = sqlite3_value_type( columnMem(pStmt,i) );
40145   columnMallocFailure(pStmt);
40146   return iType;
40147 }
40148
40149 /* The following function is experimental and subject to change or
40150 ** removal */
40151 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
40152 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
40153 **}
40154 */
40155
40156 /*
40157 ** Convert the N-th element of pStmt->pColName[] into a string using
40158 ** xFunc() then return that string.  If N is out of range, return 0.
40159 **
40160 ** There are up to 5 names for each column.  useType determines which
40161 ** name is returned.  Here are the names:
40162 **
40163 **    0      The column name as it should be displayed for output
40164 **    1      The datatype name for the column
40165 **    2      The name of the database that the column derives from
40166 **    3      The name of the table that the column derives from
40167 **    4      The name of the table column that the result column derives from
40168 **
40169 ** If the result is not a simple column reference (if it is an expression
40170 ** or a constant) then useTypes 2, 3, and 4 return NULL.
40171 */
40172 static const void *columnName(
40173   sqlite3_stmt *pStmt,
40174   int N,
40175   const void *(*xFunc)(Mem*),
40176   int useType
40177 ){
40178   const void *ret = 0;
40179   Vdbe *p = (Vdbe *)pStmt;
40180   int n;
40181   
40182
40183   if( p!=0 ){
40184     n = sqlite3_column_count(pStmt);
40185     if( N<n && N>=0 ){
40186       N += useType*n;
40187       sqlite3_mutex_enter(p->db->mutex);
40188       ret = xFunc(&p->aColName[N]);
40189
40190       /* A malloc may have failed inside of the xFunc() call. If this
40191       ** is the case, clear the mallocFailed flag and return NULL.
40192       */
40193       if( p->db && p->db->mallocFailed ){
40194         p->db->mallocFailed = 0;
40195         ret = 0;
40196       }
40197       sqlite3_mutex_leave(p->db->mutex);
40198     }
40199   }
40200   return ret;
40201 }
40202
40203 /*
40204 ** Return the name of the Nth column of the result set returned by SQL
40205 ** statement pStmt.
40206 */
40207 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
40208   return columnName(
40209       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
40210 }
40211 #ifndef SQLITE_OMIT_UTF16
40212 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
40213   return columnName(
40214       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
40215 }
40216 #endif
40217
40218 /*
40219 ** Return the column declaration type (if applicable) of the 'i'th column
40220 ** of the result set of SQL statement pStmt.
40221 */
40222 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
40223   return columnName(
40224       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
40225 }
40226 #ifndef SQLITE_OMIT_UTF16
40227 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
40228   return columnName(
40229       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
40230 }
40231 #endif /* SQLITE_OMIT_UTF16 */
40232
40233 #ifdef SQLITE_ENABLE_COLUMN_METADATA
40234 /*
40235 ** Return the name of the database from which a result column derives.
40236 ** NULL is returned if the result column is an expression or constant or
40237 ** anything else which is not an unabiguous reference to a database column.
40238 */
40239 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
40240   return columnName(
40241       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
40242 }
40243 #ifndef SQLITE_OMIT_UTF16
40244 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
40245   return columnName(
40246       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
40247 }
40248 #endif /* SQLITE_OMIT_UTF16 */
40249
40250 /*
40251 ** Return the name of the table from which a result column derives.
40252 ** NULL is returned if the result column is an expression or constant or
40253 ** anything else which is not an unabiguous reference to a database column.
40254 */
40255 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
40256   return columnName(
40257       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
40258 }
40259 #ifndef SQLITE_OMIT_UTF16
40260 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
40261   return columnName(
40262       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
40263 }
40264 #endif /* SQLITE_OMIT_UTF16 */
40265
40266 /*
40267 ** Return the name of the table column from which a result column derives.
40268 ** NULL is returned if the result column is an expression or constant or
40269 ** anything else which is not an unabiguous reference to a database column.
40270 */
40271 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
40272   return columnName(
40273       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
40274 }
40275 #ifndef SQLITE_OMIT_UTF16
40276 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
40277   return columnName(
40278       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
40279 }
40280 #endif /* SQLITE_OMIT_UTF16 */
40281 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
40282
40283
40284 /******************************* sqlite3_bind_  ***************************
40285 ** 
40286 ** Routines used to attach values to wildcards in a compiled SQL statement.
40287 */
40288 /*
40289 ** Unbind the value bound to variable i in virtual machine p. This is the 
40290 ** the same as binding a NULL value to the column. If the "i" parameter is
40291 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
40292 **
40293 ** The error code stored in database p->db is overwritten with the return
40294 ** value in any case.
40295 */
40296 static int vdbeUnbind(Vdbe *p, int i){
40297   Mem *pVar;
40298   if( p==0 || p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
40299     if( p ) sqlite3Error(p->db, SQLITE_MISUSE, 0);
40300     return SQLITE_MISUSE;
40301   }
40302   if( i<1 || i>p->nVar ){
40303     sqlite3Error(p->db, SQLITE_RANGE, 0);
40304     return SQLITE_RANGE;
40305   }
40306   i--;
40307   pVar = &p->aVar[i];
40308   sqlite3VdbeMemRelease(pVar);
40309   pVar->flags = MEM_Null;
40310   sqlite3Error(p->db, SQLITE_OK, 0);
40311   return SQLITE_OK;
40312 }
40313
40314 /*
40315 ** Bind a text or BLOB value.
40316 */
40317 static int bindText(
40318   sqlite3_stmt *pStmt,   /* The statement to bind against */
40319   int i,                 /* Index of the parameter to bind */
40320   const void *zData,     /* Pointer to the data to be bound */
40321   int nData,             /* Number of bytes of data to be bound */
40322   void (*xDel)(void*),   /* Destructor for the data */
40323   int encoding           /* Encoding for the data */
40324 ){
40325   Vdbe *p = (Vdbe *)pStmt;
40326   Mem *pVar;
40327   int rc;
40328
40329   if( p==0 ){
40330     return SQLITE_MISUSE;
40331   }
40332   sqlite3_mutex_enter(p->db->mutex);
40333   rc = vdbeUnbind(p, i);
40334   if( rc==SQLITE_OK && zData!=0 ){
40335     pVar = &p->aVar[i-1];
40336     rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
40337     if( rc==SQLITE_OK && encoding!=0 ){
40338       rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
40339     }
40340     sqlite3Error(p->db, rc, 0);
40341     rc = sqlite3ApiExit(p->db, rc);
40342   }
40343   sqlite3_mutex_leave(p->db->mutex);
40344   return rc;
40345 }
40346
40347
40348 /*
40349 ** Bind a blob value to an SQL statement variable.
40350 */
40351 SQLITE_API int sqlite3_bind_blob(
40352   sqlite3_stmt *pStmt, 
40353   int i, 
40354   const void *zData, 
40355   int nData, 
40356   void (*xDel)(void*)
40357 ){
40358   return bindText(pStmt, i, zData, nData, xDel, 0);
40359 }
40360 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
40361   int rc;
40362   Vdbe *p = (Vdbe *)pStmt;
40363   sqlite3_mutex_enter(p->db->mutex);
40364   rc = vdbeUnbind(p, i);
40365   if( rc==SQLITE_OK ){
40366     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
40367   }
40368   sqlite3_mutex_leave(p->db->mutex);
40369   return rc;
40370 }
40371 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
40372   return sqlite3_bind_int64(p, i, (i64)iValue);
40373 }
40374 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
40375   int rc;
40376   Vdbe *p = (Vdbe *)pStmt;
40377   sqlite3_mutex_enter(p->db->mutex);
40378   rc = vdbeUnbind(p, i);
40379   if( rc==SQLITE_OK ){
40380     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
40381   }
40382   sqlite3_mutex_leave(p->db->mutex);
40383   return rc;
40384 }
40385 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
40386   int rc;
40387   Vdbe *p = (Vdbe*)pStmt;
40388   sqlite3_mutex_enter(p->db->mutex);
40389   rc = vdbeUnbind(p, i);
40390   sqlite3_mutex_leave(p->db->mutex);
40391   return rc;
40392 }
40393 SQLITE_API int sqlite3_bind_text( 
40394   sqlite3_stmt *pStmt, 
40395   int i, 
40396   const char *zData, 
40397   int nData, 
40398   void (*xDel)(void*)
40399 ){
40400   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
40401 }
40402 #ifndef SQLITE_OMIT_UTF16
40403 SQLITE_API int sqlite3_bind_text16(
40404   sqlite3_stmt *pStmt, 
40405   int i, 
40406   const void *zData, 
40407   int nData, 
40408   void (*xDel)(void*)
40409 ){
40410   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
40411 }
40412 #endif /* SQLITE_OMIT_UTF16 */
40413 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
40414   int rc;
40415   Vdbe *p = (Vdbe *)pStmt;
40416   sqlite3_mutex_enter(p->db->mutex);
40417   rc = vdbeUnbind(p, i);
40418   if( rc==SQLITE_OK ){
40419     rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
40420   }
40421   rc = sqlite3ApiExit(p->db, rc);
40422   sqlite3_mutex_leave(p->db->mutex);
40423   return rc;
40424 }
40425 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
40426   int rc;
40427   Vdbe *p = (Vdbe *)pStmt;
40428   sqlite3_mutex_enter(p->db->mutex);
40429   rc = vdbeUnbind(p, i);
40430   if( rc==SQLITE_OK ){
40431     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
40432   }
40433   sqlite3_mutex_leave(p->db->mutex);
40434   return rc;
40435 }
40436
40437 /*
40438 ** Return the number of wildcards that can be potentially bound to.
40439 ** This routine is added to support DBD::SQLite.  
40440 */
40441 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
40442   Vdbe *p = (Vdbe*)pStmt;
40443   return p ? p->nVar : 0;
40444 }
40445
40446 /*
40447 ** Create a mapping from variable numbers to variable names
40448 ** in the Vdbe.azVar[] array, if such a mapping does not already
40449 ** exist.
40450 */
40451 static void createVarMap(Vdbe *p){
40452   if( !p->okVar ){
40453     sqlite3_mutex_enter(p->db->mutex);
40454     if( !p->okVar ){
40455       int j;
40456       Op *pOp;
40457       for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
40458         if( pOp->opcode==OP_Variable ){
40459           assert( pOp->p1>0 && pOp->p1<=p->nVar );
40460           p->azVar[pOp->p1-1] = pOp->p4.z;
40461         }
40462       }
40463       p->okVar = 1;
40464     }
40465     sqlite3_mutex_leave(p->db->mutex);
40466   }
40467 }
40468
40469 /*
40470 ** Return the name of a wildcard parameter.  Return NULL if the index
40471 ** is out of range or if the wildcard is unnamed.
40472 **
40473 ** The result is always UTF-8.
40474 */
40475 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
40476   Vdbe *p = (Vdbe*)pStmt;
40477   if( p==0 || i<1 || i>p->nVar ){
40478     return 0;
40479   }
40480   createVarMap(p);
40481   return p->azVar[i-1];
40482 }
40483
40484 /*
40485 ** Given a wildcard parameter name, return the index of the variable
40486 ** with that name.  If there is no variable with the given name,
40487 ** return 0.
40488 */
40489 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
40490   Vdbe *p = (Vdbe*)pStmt;
40491   int i;
40492   if( p==0 ){
40493     return 0;
40494   }
40495   createVarMap(p); 
40496   if( zName ){
40497     for(i=0; i<p->nVar; i++){
40498       const char *z = p->azVar[i];
40499       if( z && strcmp(z,zName)==0 ){
40500         return i+1;
40501       }
40502     }
40503   }
40504   return 0;
40505 }
40506
40507 /*
40508 ** Transfer all bindings from the first statement over to the second.
40509 ** If the two statements contain a different number of bindings, then
40510 ** an SQLITE_ERROR is returned.
40511 */
40512 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
40513   Vdbe *pFrom = (Vdbe*)pFromStmt;
40514   Vdbe *pTo = (Vdbe*)pToStmt;
40515   int i, rc = SQLITE_OK;
40516   if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
40517     || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
40518     || pTo->db!=pFrom->db ){
40519     return SQLITE_MISUSE;
40520   }
40521   if( pFrom->nVar!=pTo->nVar ){
40522     return SQLITE_ERROR;
40523   }
40524   sqlite3_mutex_enter(pTo->db->mutex);
40525   for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
40526     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
40527   }
40528   sqlite3_mutex_leave(pTo->db->mutex);
40529   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40530   return rc;
40531 }
40532
40533 /*
40534 ** Return the sqlite3* database handle to which the prepared statement given
40535 ** in the argument belongs.  This is the same database handle that was
40536 ** the first argument to the sqlite3_prepare() that was used to create
40537 ** the statement in the first place.
40538 */
40539 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
40540   return pStmt ? ((Vdbe*)pStmt)->db : 0;
40541 }
40542
40543 /************** End of vdbeapi.c *********************************************/
40544 /************** Begin file vdbe.c ********************************************/
40545 /*
40546 ** 2001 September 15
40547 **
40548 ** The author disclaims copyright to this source code.  In place of
40549 ** a legal notice, here is a blessing:
40550 **
40551 **    May you do good and not evil.
40552 **    May you find forgiveness for yourself and forgive others.
40553 **    May you share freely, never taking more than you give.
40554 **
40555 *************************************************************************
40556 ** The code in this file implements execution method of the 
40557 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
40558 ** handles housekeeping details such as creating and deleting
40559 ** VDBE instances.  This file is solely interested in executing
40560 ** the VDBE program.
40561 **
40562 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
40563 ** to a VDBE.
40564 **
40565 ** The SQL parser generates a program which is then executed by
40566 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
40567 ** similar in form to assembly language.  The program consists of
40568 ** a linear sequence of operations.  Each operation has an opcode 
40569 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
40570 ** is a null-terminated string.  Operand P5 is an unsigned character.
40571 ** Few opcodes use all 5 operands.
40572 **
40573 ** Computation results are stored on a set of registers numbered beginning
40574 ** with 1 and going up to Vdbe.nMem.  Each register can store
40575 ** either an integer, a null-terminated string, a floating point
40576 ** number, or the SQL "NULL" value.  An inplicit conversion from one
40577 ** type to the other occurs as necessary.
40578 ** 
40579 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
40580 ** function which does the work of interpreting a VDBE program.
40581 ** But other routines are also provided to help in building up
40582 ** a program instruction by instruction.
40583 **
40584 ** Various scripts scan this source file in order to generate HTML
40585 ** documentation, headers files, or other derived files.  The formatting
40586 ** of the code in this file is, therefore, important.  See other comments
40587 ** in this file for details.  If in doubt, do not deviate from existing
40588 ** commenting and indentation practices when changing or adding code.
40589 **
40590 ** $Id: vdbe.c,v 1.711 2008/03/17 17:18:38 drh Exp $
40591 */
40592
40593 /*
40594 ** The following global variable is incremented every time a cursor
40595 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
40596 ** procedures use this information to make sure that indices are
40597 ** working correctly.  This variable has no function other than to
40598 ** help verify the correct operation of the library.
40599 */
40600 #ifdef SQLITE_TEST
40601 SQLITE_API int sqlite3_search_count = 0;
40602 #endif
40603
40604 /*
40605 ** When this global variable is positive, it gets decremented once before
40606 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
40607 ** field of the sqlite3 structure is set in order to simulate and interrupt.
40608 **
40609 ** This facility is used for testing purposes only.  It does not function
40610 ** in an ordinary build.
40611 */
40612 #ifdef SQLITE_TEST
40613 SQLITE_API int sqlite3_interrupt_count = 0;
40614 #endif
40615
40616 /*
40617 ** The next global variable is incremented each type the OP_Sort opcode
40618 ** is executed.  The test procedures use this information to make sure that
40619 ** sorting is occurring or not occuring at appropriate times.   This variable
40620 ** has no function other than to help verify the correct operation of the
40621 ** library.
40622 */
40623 #ifdef SQLITE_TEST
40624 SQLITE_API int sqlite3_sort_count = 0;
40625 #endif
40626
40627 /*
40628 ** The next global variable records the size of the largest MEM_Blob
40629 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
40630 ** use this information to make sure that the zero-blob functionality
40631 ** is working correctly.   This variable has no function other than to
40632 ** help verify the correct operation of the library.
40633 */
40634 #ifdef SQLITE_TEST
40635 SQLITE_API int sqlite3_max_blobsize = 0;
40636 static void updateMaxBlobsize(Mem *p){
40637   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
40638     sqlite3_max_blobsize = p->n;
40639   }
40640 }
40641 #endif
40642
40643 /*
40644 ** Test a register to see if it exceeds the current maximum blob size.
40645 ** If it does, record the new maximum blob size.
40646 */
40647 #ifdef SQLITE_TEST
40648 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
40649 #else
40650 # define UPDATE_MAX_BLOBSIZE(P)
40651 #endif
40652
40653 /*
40654 ** Release the memory associated with a register.  This
40655 ** leaves the Mem.flags field in an inconsistent state.
40656 */
40657 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
40658
40659 /*
40660 ** Convert the given register into a string if it isn't one
40661 ** already. Return non-zero if a malloc() fails.
40662 */
40663 #define Stringify(P, enc) \
40664    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
40665      { goto no_mem; }
40666
40667 /*
40668 ** The header of a record consists of a sequence variable-length integers.
40669 ** These integers are almost always small and are encoded as a single byte.
40670 ** The following macro takes advantage this fact to provide a fast decode
40671 ** of the integers in a record header.  It is faster for the common case
40672 ** where the integer is a single byte.  It is a little slower when the
40673 ** integer is two or more bytes.  But overall it is faster.
40674 **
40675 ** The following expressions are equivalent:
40676 **
40677 **     x = sqlite3GetVarint32( A, &B );
40678 **
40679 **     x = GetVarint( A, B );
40680 **
40681 */
40682 #define GetVarint(A,B)  ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
40683
40684 /*
40685 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
40686 ** a pointer to a dynamically allocated string where some other entity
40687 ** is responsible for deallocating that string.  Because the register
40688 ** does not control the string, it might be deleted without the register
40689 ** knowing it.
40690 **
40691 ** This routine converts an ephemeral string into a dynamically allocated
40692 ** string that the register itself controls.  In other words, it
40693 ** converts an MEM_Ephem string into an MEM_Dyn string.
40694 */
40695 #define Deephemeralize(P) \
40696    if( ((P)->flags&MEM_Ephem)!=0 \
40697        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
40698
40699 /*
40700 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
40701 ** P if required.
40702 */
40703 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
40704
40705 /*
40706 ** Argument pMem points at a regiser that will be passed to a
40707 ** user-defined function or returned to the user as the result of a query.
40708 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
40709 ** register variables.  This routine sets the pMem->enc and pMem->type
40710 ** variables used by the sqlite3_value_*() routines.
40711 */
40712 #define storeTypeInfo(A,B) _storeTypeInfo(A)
40713 static void _storeTypeInfo(Mem *pMem){
40714   int flags = pMem->flags;
40715   if( flags & MEM_Null ){
40716     pMem->type = SQLITE_NULL;
40717   }
40718   else if( flags & MEM_Int ){
40719     pMem->type = SQLITE_INTEGER;
40720   }
40721   else if( flags & MEM_Real ){
40722     pMem->type = SQLITE_FLOAT;
40723   }
40724   else if( flags & MEM_Str ){
40725     pMem->type = SQLITE_TEXT;
40726   }else{
40727     pMem->type = SQLITE_BLOB;
40728   }
40729 }
40730
40731 /*
40732 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
40733 ** created by mkopcodeh.awk during compilation.  Data is obtained
40734 ** from the comments following the "case OP_xxxx:" statements in
40735 ** this file.  
40736 */
40737 static unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
40738
40739 /*
40740 ** Return true if an opcode has any of the OPFLG_xxx properties
40741 ** specified by mask.
40742 */
40743 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
40744   assert( opcode>0 && opcode<sizeof(opcodeProperty) );
40745   return (opcodeProperty[opcode]&mask)!=0;
40746 }
40747
40748 /*
40749 ** Allocate cursor number iCur.  Return a pointer to it.  Return NULL
40750 ** if we run out of memory.
40751 */
40752 static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
40753   Cursor *pCx;
40754   assert( iCur<p->nCursor );
40755   if( p->apCsr[iCur] ){
40756     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
40757   }
40758   p->apCsr[iCur] = pCx = sqlite3MallocZero( sizeof(Cursor) );
40759   if( pCx ){
40760     pCx->iDb = iDb;
40761   }
40762   return pCx;
40763 }
40764
40765 /*
40766 ** Try to convert a value into a numeric representation if we can
40767 ** do so without loss of information.  In other words, if the string
40768 ** looks like a number, convert it into a number.  If it does not
40769 ** look like a number, leave it alone.
40770 */
40771 static void applyNumericAffinity(Mem *pRec){
40772   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
40773     int realnum;
40774     sqlite3VdbeMemNulTerminate(pRec);
40775     if( (pRec->flags&MEM_Str)
40776          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
40777       i64 value;
40778       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
40779       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
40780         pRec->u.i = value;
40781         MemSetTypeFlag(pRec, MEM_Int);
40782       }else{
40783         sqlite3VdbeMemRealify(pRec);
40784       }
40785     }
40786   }
40787 }
40788
40789 /*
40790 ** Processing is determine by the affinity parameter:
40791 **
40792 ** SQLITE_AFF_INTEGER:
40793 ** SQLITE_AFF_REAL:
40794 ** SQLITE_AFF_NUMERIC:
40795 **    Try to convert pRec to an integer representation or a 
40796 **    floating-point representation if an integer representation
40797 **    is not possible.  Note that the integer representation is
40798 **    always preferred, even if the affinity is REAL, because
40799 **    an integer representation is more space efficient on disk.
40800 **
40801 ** SQLITE_AFF_TEXT:
40802 **    Convert pRec to a text representation.
40803 **
40804 ** SQLITE_AFF_NONE:
40805 **    No-op.  pRec is unchanged.
40806 */
40807 static void applyAffinity(
40808   Mem *pRec,          /* The value to apply affinity to */
40809   char affinity,      /* The affinity to be applied */
40810   u8 enc              /* Use this text encoding */
40811 ){
40812   if( affinity==SQLITE_AFF_TEXT ){
40813     /* Only attempt the conversion to TEXT if there is an integer or real
40814     ** representation (blob and NULL do not get converted) but no string
40815     ** representation.
40816     */
40817     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
40818       sqlite3VdbeMemStringify(pRec, enc);
40819     }
40820     pRec->flags &= ~(MEM_Real|MEM_Int);
40821   }else if( affinity!=SQLITE_AFF_NONE ){
40822     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
40823              || affinity==SQLITE_AFF_NUMERIC );
40824     applyNumericAffinity(pRec);
40825     if( pRec->flags & MEM_Real ){
40826       sqlite3VdbeIntegerAffinity(pRec);
40827     }
40828   }
40829 }
40830
40831 /*
40832 ** Try to convert the type of a function argument or a result column
40833 ** into a numeric representation.  Use either INTEGER or REAL whichever
40834 ** is appropriate.  But only do the conversion if it is possible without
40835 ** loss of information and return the revised type of the argument.
40836 **
40837 ** This is an EXPERIMENTAL api and is subject to change or removal.
40838 */
40839 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
40840   Mem *pMem = (Mem*)pVal;
40841   applyNumericAffinity(pMem);
40842   storeTypeInfo(pMem, 0);
40843   return pMem->type;
40844 }
40845
40846 /*
40847 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
40848 ** not the internal Mem* type.
40849 */
40850 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
40851   sqlite3_value *pVal, 
40852   u8 affinity, 
40853   u8 enc
40854 ){
40855   applyAffinity((Mem *)pVal, affinity, enc);
40856 }
40857
40858 #ifdef SQLITE_DEBUG
40859 /*
40860 ** Write a nice string representation of the contents of cell pMem
40861 ** into buffer zBuf, length nBuf.
40862 */
40863 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
40864   char *zCsr = zBuf;
40865   int f = pMem->flags;
40866
40867   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
40868
40869   if( f&MEM_Blob ){
40870     int i;
40871     char c;
40872     if( f & MEM_Dyn ){
40873       c = 'z';
40874       assert( (f & (MEM_Static|MEM_Ephem))==0 );
40875     }else if( f & MEM_Static ){
40876       c = 't';
40877       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
40878     }else if( f & MEM_Ephem ){
40879       c = 'e';
40880       assert( (f & (MEM_Static|MEM_Dyn))==0 );
40881     }else{
40882       c = 's';
40883     }
40884
40885     sqlite3_snprintf(100, zCsr, "%c", c);
40886     zCsr += strlen(zCsr);
40887     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
40888     zCsr += strlen(zCsr);
40889     for(i=0; i<16 && i<pMem->n; i++){
40890       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
40891       zCsr += strlen(zCsr);
40892     }
40893     for(i=0; i<16 && i<pMem->n; i++){
40894       char z = pMem->z[i];
40895       if( z<32 || z>126 ) *zCsr++ = '.';
40896       else *zCsr++ = z;
40897     }
40898
40899     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
40900     zCsr += strlen(zCsr);
40901     if( f & MEM_Zero ){
40902       sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
40903       zCsr += strlen(zCsr);
40904     }
40905     *zCsr = '\0';
40906   }else if( f & MEM_Str ){
40907     int j, k;
40908     zBuf[0] = ' ';
40909     if( f & MEM_Dyn ){
40910       zBuf[1] = 'z';
40911       assert( (f & (MEM_Static|MEM_Ephem))==0 );
40912     }else if( f & MEM_Static ){
40913       zBuf[1] = 't';
40914       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
40915     }else if( f & MEM_Ephem ){
40916       zBuf[1] = 'e';
40917       assert( (f & (MEM_Static|MEM_Dyn))==0 );
40918     }else{
40919       zBuf[1] = 's';
40920     }
40921     k = 2;
40922     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
40923     k += strlen(&zBuf[k]);
40924     zBuf[k++] = '[';
40925     for(j=0; j<15 && j<pMem->n; j++){
40926       u8 c = pMem->z[j];
40927       if( c>=0x20 && c<0x7f ){
40928         zBuf[k++] = c;
40929       }else{
40930         zBuf[k++] = '.';
40931       }
40932     }
40933     zBuf[k++] = ']';
40934     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
40935     k += strlen(&zBuf[k]);
40936     zBuf[k++] = 0;
40937   }
40938 }
40939 #endif
40940
40941 #ifdef SQLITE_DEBUG
40942 /*
40943 ** Print the value of a register for tracing purposes:
40944 */
40945 static void memTracePrint(FILE *out, Mem *p){
40946   if( p->flags & MEM_Null ){
40947     fprintf(out, " NULL");
40948   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
40949     fprintf(out, " si:%lld", p->u.i);
40950   }else if( p->flags & MEM_Int ){
40951     fprintf(out, " i:%lld", p->u.i);
40952   }else if( p->flags & MEM_Real ){
40953     fprintf(out, " r:%g", p->r);
40954   }else{
40955     char zBuf[200];
40956     sqlite3VdbeMemPrettyPrint(p, zBuf);
40957     fprintf(out, " ");
40958     fprintf(out, "%s", zBuf);
40959   }
40960 }
40961 static void registerTrace(FILE *out, int iReg, Mem *p){
40962   fprintf(out, "REG[%d] = ", iReg);
40963   memTracePrint(out, p);
40964   fprintf(out, "\n");
40965 }
40966 #endif
40967
40968 #ifdef SQLITE_DEBUG
40969 #  define REGISTER_TRACE(R,M) if(p->trace&&R>0)registerTrace(p->trace,R,M)
40970 #else
40971 #  define REGISTER_TRACE(R,M)
40972 #endif
40973
40974
40975 #ifdef VDBE_PROFILE
40976 /*
40977 ** The following routine only works on pentium-class processors.
40978 ** It uses the RDTSC opcode to read the cycle count value out of the
40979 ** processor and returns that value.  This can be used for high-res
40980 ** profiling.
40981 */
40982 __inline__ unsigned long long int hwtime(void){
40983   unsigned long long int x;
40984   __asm__("rdtsc\n\t"
40985           "mov %%edx, %%ecx\n\t"
40986           :"=A" (x));
40987   return x;
40988 }
40989 #endif
40990
40991 /*
40992 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
40993 ** sqlite3_interrupt() routine has been called.  If it has been, then
40994 ** processing of the VDBE program is interrupted.
40995 **
40996 ** This macro added to every instruction that does a jump in order to
40997 ** implement a loop.  This test used to be on every single instruction,
40998 ** but that meant we more testing that we needed.  By only testing the
40999 ** flag on jump instructions, we get a (small) speed improvement.
41000 */
41001 #define CHECK_FOR_INTERRUPT \
41002    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
41003
41004
41005 /*
41006 ** Execute as much of a VDBE program as we can then return.
41007 **
41008 ** sqlite3VdbeMakeReady() must be called before this routine in order to
41009 ** close the program with a final OP_Halt and to set up the callbacks
41010 ** and the error message pointer.
41011 **
41012 ** Whenever a row or result data is available, this routine will either
41013 ** invoke the result callback (if there is one) or return with
41014 ** SQLITE_ROW.
41015 **
41016 ** If an attempt is made to open a locked database, then this routine
41017 ** will either invoke the busy callback (if there is one) or it will
41018 ** return SQLITE_BUSY.
41019 **
41020 ** If an error occurs, an error message is written to memory obtained
41021 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
41022 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
41023 **
41024 ** If the callback ever returns non-zero, then the program exits
41025 ** immediately.  There will be no error message but the p->rc field is
41026 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
41027 **
41028 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
41029 ** routine to return SQLITE_ERROR.
41030 **
41031 ** Other fatal errors return SQLITE_ERROR.
41032 **
41033 ** After this routine has finished, sqlite3VdbeFinalize() should be
41034 ** used to clean up the mess that was left behind.
41035 */
41036 SQLITE_PRIVATE int sqlite3VdbeExec(
41037   Vdbe *p                    /* The VDBE */
41038 ){
41039   int pc;                    /* The program counter */
41040   Op *pOp;                   /* Current operation */
41041   int rc = SQLITE_OK;        /* Value to return */
41042   sqlite3 *db = p->db;       /* The database */
41043   u8 encoding = ENC(db);     /* The database encoding */
41044   Mem *pIn1, *pIn2, *pIn3;   /* Input operands */
41045   Mem *pOut;                 /* Output operand */
41046   u8 opProperty;
41047 #ifdef VDBE_PROFILE
41048   unsigned long long start;  /* CPU clock count at start of opcode */
41049   int origPc;                /* Program counter at start of opcode */
41050 #endif
41051 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
41052   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
41053 #endif
41054
41055   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
41056   assert( db->magic==SQLITE_MAGIC_BUSY );
41057   sqlite3BtreeMutexArrayEnter(&p->aMutex);
41058   if( p->rc==SQLITE_NOMEM ){
41059     /* This happens if a malloc() inside a call to sqlite3_column_text() or
41060     ** sqlite3_column_text16() failed.  */
41061     goto no_mem;
41062   }
41063   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
41064   p->rc = SQLITE_OK;
41065   assert( p->explain==0 );
41066   p->pResultSet = 0;
41067   db->busyHandler.nBusy = 0;
41068   CHECK_FOR_INTERRUPT;
41069   sqlite3VdbeIOTraceSql(p);
41070 #ifdef SQLITE_DEBUG
41071   if( p->pc==0 && ((p->db->flags & SQLITE_VdbeListing)!=0
41072     || sqlite3OsAccess(db->pVfs, "vdbe_explain", SQLITE_ACCESS_EXISTS))
41073   ){
41074     int i;
41075     printf("VDBE Program Listing:\n");
41076     sqlite3VdbePrintSql(p);
41077     for(i=0; i<p->nOp; i++){
41078       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
41079     }
41080   }
41081   if( sqlite3OsAccess(db->pVfs, "vdbe_trace", SQLITE_ACCESS_EXISTS) ){
41082     p->trace = stdout;
41083   }
41084 #endif
41085   for(pc=p->pc; rc==SQLITE_OK; pc++){
41086     assert( pc>=0 && pc<p->nOp );
41087     if( db->mallocFailed ) goto no_mem;
41088 #ifdef VDBE_PROFILE
41089     origPc = pc;
41090     start = hwtime();
41091 #endif
41092     pOp = &p->aOp[pc];
41093
41094     /* Only allow tracing if SQLITE_DEBUG is defined.
41095     */
41096 #ifdef SQLITE_DEBUG
41097     if( p->trace ){
41098       if( pc==0 ){
41099         printf("VDBE Execution Trace:\n");
41100         sqlite3VdbePrintSql(p);
41101       }
41102       sqlite3VdbePrintOp(p->trace, pc, pOp);
41103     }
41104     if( p->trace==0 && pc==0 
41105      && sqlite3OsAccess(db->pVfs, "vdbe_sqltrace", SQLITE_ACCESS_EXISTS) ){
41106       sqlite3VdbePrintSql(p);
41107     }
41108 #endif
41109       
41110
41111     /* Check to see if we need to simulate an interrupt.  This only happens
41112     ** if we have a special test build.
41113     */
41114 #ifdef SQLITE_TEST
41115     if( sqlite3_interrupt_count>0 ){
41116       sqlite3_interrupt_count--;
41117       if( sqlite3_interrupt_count==0 ){
41118         sqlite3_interrupt(db);
41119       }
41120     }
41121 #endif
41122
41123 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
41124     /* Call the progress callback if it is configured and the required number
41125     ** of VDBE ops have been executed (either since this invocation of
41126     ** sqlite3VdbeExec() or since last time the progress callback was called).
41127     ** If the progress callback returns non-zero, exit the virtual machine with
41128     ** a return code SQLITE_ABORT.
41129     */
41130     if( db->xProgress ){
41131       if( db->nProgressOps==nProgressOps ){
41132         int prc;
41133         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
41134         prc =db->xProgress(db->pProgressArg);
41135         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
41136         if( prc!=0 ){
41137           rc = SQLITE_INTERRUPT;
41138           goto vdbe_error_halt;
41139         }
41140         nProgressOps = 0;
41141       }
41142       nProgressOps++;
41143     }
41144 #endif
41145
41146     /* Do common setup processing for any opcode that is marked
41147     ** with the "out2-prerelease" tag.  Such opcodes have a single
41148     ** output which is specified by the P2 parameter.  The P2 register
41149     ** is initialized to a NULL.
41150     */
41151     opProperty = opcodeProperty[pOp->opcode];
41152     if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
41153       assert( pOp->p2>0 );
41154       assert( pOp->p2<=p->nMem );
41155       pOut = &p->aMem[pOp->p2];
41156       sqlite3VdbeMemRelease(pOut);
41157       pOut->flags = MEM_Null;
41158     }else
41159  
41160     /* Do common setup for opcodes marked with one of the following
41161     ** combinations of properties.
41162     **
41163     **           in1
41164     **           in1 in2
41165     **           in1 in2 out3
41166     **           in1 in3
41167     **
41168     ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
41169     ** registers for inputs.  Variable pOut points to the output register.
41170     */
41171     if( (opProperty & OPFLG_IN1)!=0 ){
41172       assert( pOp->p1>0 );
41173       assert( pOp->p1<=p->nMem );
41174       pIn1 = &p->aMem[pOp->p1];
41175       REGISTER_TRACE(pOp->p1, pIn1);
41176       if( (opProperty & OPFLG_IN2)!=0 ){
41177         assert( pOp->p2>0 );
41178         assert( pOp->p2<=p->nMem );
41179         pIn2 = &p->aMem[pOp->p2];
41180         REGISTER_TRACE(pOp->p2, pIn2);
41181         if( (opProperty & OPFLG_OUT3)!=0 ){
41182           assert( pOp->p3>0 );
41183           assert( pOp->p3<=p->nMem );
41184           pOut = &p->aMem[pOp->p3];
41185         }
41186       }else if( (opProperty & OPFLG_IN3)!=0 ){
41187         assert( pOp->p3>0 );
41188         assert( pOp->p3<=p->nMem );
41189         pIn3 = &p->aMem[pOp->p3];
41190         REGISTER_TRACE(pOp->p3, pIn3);
41191       }
41192     }else if( (opProperty & OPFLG_IN2)!=0 ){
41193       assert( pOp->p2>0 );
41194       assert( pOp->p2<=p->nMem );
41195       pIn2 = &p->aMem[pOp->p2];
41196       REGISTER_TRACE(pOp->p2, pIn2);
41197     }else if( (opProperty & OPFLG_IN3)!=0 ){
41198       assert( pOp->p3>0 );
41199       assert( pOp->p3<=p->nMem );
41200       pIn3 = &p->aMem[pOp->p3];
41201       REGISTER_TRACE(pOp->p3, pIn3);
41202     }
41203
41204     switch( pOp->opcode ){
41205
41206 /*****************************************************************************
41207 ** What follows is a massive switch statement where each case implements a
41208 ** separate instruction in the virtual machine.  If we follow the usual
41209 ** indentation conventions, each case should be indented by 6 spaces.  But
41210 ** that is a lot of wasted space on the left margin.  So the code within
41211 ** the switch statement will break with convention and be flush-left. Another
41212 ** big comment (similar to this one) will mark the point in the code where
41213 ** we transition back to normal indentation.
41214 **
41215 ** The formatting of each case is important.  The makefile for SQLite
41216 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
41217 ** file looking for lines that begin with "case OP_".  The opcodes.h files
41218 ** will be filled with #defines that give unique integer values to each
41219 ** opcode and the opcodes.c file is filled with an array of strings where
41220 ** each string is the symbolic name for the corresponding opcode.  If the
41221 ** case statement is followed by a comment of the form "/# same as ... #/"
41222 ** that comment is used to determine the particular value of the opcode.
41223 **
41224 ** Other keywords in the comment that follows each case are used to
41225 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
41226 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
41227 ** the mkopcodeh.awk script for additional information.
41228 **
41229 ** Documentation about VDBE opcodes is generated by scanning this file
41230 ** for lines of that contain "Opcode:".  That line and all subsequent
41231 ** comment lines are used in the generation of the opcode.html documentation
41232 ** file.
41233 **
41234 ** SUMMARY:
41235 **
41236 **     Formatting is important to scripts that scan this file.
41237 **     Do not deviate from the formatting style currently in use.
41238 **
41239 *****************************************************************************/
41240
41241 /* Opcode:  Goto * P2 * * *
41242 **
41243 ** An unconditional jump to address P2.
41244 ** The next instruction executed will be 
41245 ** the one at index P2 from the beginning of
41246 ** the program.
41247 */
41248 case OP_Goto: {             /* jump */
41249   CHECK_FOR_INTERRUPT;
41250   pc = pOp->p2 - 1;
41251   break;
41252 }
41253
41254 /* Opcode:  Gosub * P2 * * *
41255 **
41256 ** Push the current address plus 1 onto the return address stack
41257 ** and then jump to address P2.
41258 **
41259 ** The return address stack is of limited depth.  If too many
41260 ** OP_Gosub operations occur without intervening OP_Returns, then
41261 ** the return address stack will fill up and processing will abort
41262 ** with a fatal error.
41263 */
41264 case OP_Gosub: {            /* jump */
41265   assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
41266   p->returnStack[p->returnDepth++] = pc+1;
41267   pc = pOp->p2 - 1;
41268   break;
41269 }
41270
41271 /* Opcode:  Return * * * * *
41272 **
41273 ** Jump immediately to the next instruction after the last unreturned
41274 ** OP_Gosub.  If an OP_Return has occurred for all OP_Gosubs, then
41275 ** processing aborts with a fatal error.
41276 */
41277 case OP_Return: {
41278   assert( p->returnDepth>0 );
41279   p->returnDepth--;
41280   pc = p->returnStack[p->returnDepth] - 1;
41281   break;
41282 }
41283
41284 /* Opcode:  Halt P1 P2 * P4 *
41285 **
41286 ** Exit immediately.  All open cursors, Fifos, etc are closed
41287 ** automatically.
41288 **
41289 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
41290 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
41291 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
41292 ** whether or not to rollback the current transaction.  Do not rollback
41293 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
41294 ** then back out all changes that have occurred during this execution of the
41295 ** VDBE, but do not rollback the transaction. 
41296 **
41297 ** If P4 is not null then it is an error message string.
41298 **
41299 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
41300 ** every program.  So a jump past the last instruction of the program
41301 ** is the same as executing Halt.
41302 */
41303 case OP_Halt: {
41304   p->rc = pOp->p1;
41305   p->pc = pc;
41306   p->errorAction = pOp->p2;
41307   if( pOp->p4.z ){
41308     sqlite3SetString(&p->zErrMsg, pOp->p4.z, (char*)0);
41309   }
41310   rc = sqlite3VdbeHalt(p);
41311   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
41312   if( rc==SQLITE_BUSY ){
41313     p->rc = rc = SQLITE_BUSY;
41314   }else{
41315     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
41316   }
41317   goto vdbe_return;
41318 }
41319
41320 /* Opcode: Integer P1 P2 * * *
41321 **
41322 ** The 32-bit integer value P1 is written into register P2.
41323 */
41324 case OP_Integer: {         /* out2-prerelease */
41325   pOut->flags = MEM_Int;
41326   pOut->u.i = pOp->p1;
41327   break;
41328 }
41329
41330 /* Opcode: Int64 * P2 * P4 *
41331 **
41332 ** P4 is a pointer to a 64-bit integer value.
41333 ** Write that value into register P2.
41334 */
41335 case OP_Int64: {           /* out2-prerelease */
41336   assert( pOp->p4.pI64!=0 );
41337   pOut->flags = MEM_Int;
41338   pOut->u.i = *pOp->p4.pI64;
41339   break;
41340 }
41341
41342 /* Opcode: Real * P2 * P4 *
41343 **
41344 ** P4 is a pointer to a 64-bit floating point value.
41345 ** Write that value into register P2.
41346 */
41347 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
41348   pOut->flags = MEM_Real;
41349   pOut->r = *pOp->p4.pReal;
41350   break;
41351 }
41352
41353 /* Opcode: String8 * P2 * P4 *
41354 **
41355 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
41356 ** into an OP_String before it is executed for the first time.
41357 */
41358 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
41359   assert( pOp->p4.z!=0 );
41360   pOp->opcode = OP_String;
41361   pOp->p1 = strlen(pOp->p4.z);
41362
41363 #ifndef SQLITE_OMIT_UTF16
41364   if( encoding!=SQLITE_UTF8 ){
41365     sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
41366     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
41367     if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pOut) ) goto no_mem;
41368     pOut->flags &= ~(MEM_Dyn);
41369     pOut->flags |= MEM_Static;
41370     if( pOp->p4type==P4_DYNAMIC ){
41371       sqlite3_free(pOp->p4.z);
41372     }
41373     pOp->p4type = P4_DYNAMIC;
41374     pOp->p4.z = pOut->z;
41375     pOp->p1 = pOut->n;
41376     if( pOp->p1>SQLITE_MAX_LENGTH ){
41377       goto too_big;
41378     }
41379     UPDATE_MAX_BLOBSIZE(pOut);
41380     break;
41381   }
41382 #endif
41383   if( pOp->p1>SQLITE_MAX_LENGTH ){
41384     goto too_big;
41385   }
41386   /* Fall through to the next case, OP_String */
41387 }
41388   
41389 /* Opcode: String P1 P2 * P4 *
41390 **
41391 ** The string value P4 of length P1 (bytes) is stored in register P2.
41392 */
41393 case OP_String: {          /* out2-prerelease */
41394   assert( pOp->p4.z!=0 );
41395   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
41396   pOut->z = pOp->p4.z;
41397   pOut->n = pOp->p1;
41398   pOut->enc = encoding;
41399   UPDATE_MAX_BLOBSIZE(pOut);
41400   break;
41401 }
41402
41403 /* Opcode: Null * P2 * * *
41404 **
41405 ** Write a NULL into register P2.
41406 */
41407 case OP_Null: {           /* out2-prerelease */
41408   break;
41409 }
41410
41411
41412 #ifndef SQLITE_OMIT_BLOB_LITERAL
41413 /* Opcode: Blob P1 P2 * P4
41414 **
41415 ** P4 points to a blob of data P1 bytes long.  Store this
41416 ** blob in register P2. This instruction is not coded directly
41417 ** by the compiler. Instead, the compiler layer specifies
41418 ** an OP_HexBlob opcode, with the hex string representation of
41419 ** the blob as P4. This opcode is transformed to an OP_Blob
41420 ** the first time it is executed.
41421 */
41422 case OP_Blob: {                /* out2-prerelease */
41423   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
41424   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
41425   pOut->enc = encoding;
41426   UPDATE_MAX_BLOBSIZE(pOut);
41427   break;
41428 }
41429 #endif /* SQLITE_OMIT_BLOB_LITERAL */
41430
41431 /* Opcode: Variable P1 P2 * * *
41432 **
41433 ** The value of variable P1 is written into register P2. A variable is
41434 ** an unknown in the original SQL string as handed to sqlite3_compile().
41435 ** Any occurance of the '?' character in the original SQL is considered
41436 ** a variable.  Variables in the SQL string are number from left to
41437 ** right beginning with 1.  The values of variables are set using the
41438 ** sqlite3_bind() API.
41439 */
41440 case OP_Variable: {           /* out2-prerelease */
41441   int j = pOp->p1 - 1;
41442   Mem *pVar;
41443   assert( j>=0 && j<p->nVar );
41444
41445   pVar = &p->aVar[j];
41446   if( sqlite3VdbeMemTooBig(pVar) ){
41447     goto too_big;
41448   }
41449   sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
41450   UPDATE_MAX_BLOBSIZE(pOut);
41451   break;
41452 }
41453
41454 /* Opcode: Move P1 P2 * * *
41455 **
41456 ** Move the value in register P1 over into register P2.  Register P1
41457 ** is left holding a NULL.  It is an error for P1 and P2 to be the
41458 ** same register.
41459 */
41460 /* Opcode: Copy P1 P2 * * *
41461 **
41462 ** Make a copy of register P1 into register P2.
41463 **
41464 ** This instruction makes a deep copy of the value.  A duplicate
41465 ** is made of any string or blob constant.  See also OP_SCopy.
41466 */
41467 /* Opcode: SCopy P1 P2 * * *
41468 **
41469 ** Make a shallow copy of register P1 into register P2.
41470 **
41471 ** This instruction makes a shallow copy of the value.  If the value
41472 ** is a string or blob, then the copy is only a pointer to the
41473 ** original and hence if the original changes so will the copy.
41474 ** Worse, if the original is deallocated, the copy becomes invalid.
41475 ** Thus the program must guarantee that the original will not change
41476 ** during the lifetime of the copy.  Use OP_Copy to make a complete
41477 ** copy.
41478 */
41479 case OP_Move:
41480 case OP_Copy:
41481 case OP_SCopy: {
41482   assert( pOp->p1>0 );
41483   assert( pOp->p1<=p->nMem );
41484   pIn1 = &p->aMem[pOp->p1];
41485   REGISTER_TRACE(pOp->p1, pIn1);
41486   assert( pOp->p2>0 );
41487   assert( pOp->p2<=p->nMem );
41488   pOut = &p->aMem[pOp->p2];
41489   assert( pOut!=pIn1 );
41490   if( pOp->opcode==OP_Move ){
41491     sqlite3VdbeMemMove(pOut, pIn1);
41492   }else{
41493     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
41494     if( pOp->opcode==OP_Copy ){
41495       Deephemeralize(pOut);
41496     }
41497   }
41498   REGISTER_TRACE(pOp->p2, pOut);
41499   break;
41500 }
41501
41502 /* Opcode: ResultRow P1 P2 * * *
41503 **
41504 ** The registers P1 throught P1+P2-1 contain a single row of
41505 ** results. This opcode causes the sqlite3_step() call to terminate
41506 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
41507 ** structure to provide access to the top P1 values as the result
41508 ** row.
41509 */
41510 case OP_ResultRow: {
41511   Mem *pMem;
41512   int i;
41513   assert( p->nResColumn==pOp->p2 );
41514   assert( pOp->p1>0 );
41515   assert( pOp->p1+pOp->p2<=p->nMem );
41516
41517   /* Invalidate all ephemeral cursor row caches */
41518   p->cacheCtr = (p->cacheCtr + 2)|1;
41519
41520   /* Make sure the results of the current row are \000 terminated
41521   ** and have an assigned type.  The results are deephemeralized as
41522   ** as side effect.
41523   */
41524   pMem = p->pResultSet = &p->aMem[pOp->p1];
41525   for(i=0; i<pOp->p2; i++){
41526     sqlite3VdbeMemNulTerminate(&pMem[i]);
41527     storeTypeInfo(&pMem[i], encoding);
41528   }
41529   if( db->mallocFailed ) goto no_mem;
41530
41531   /* Return SQLITE_ROW
41532   */
41533   p->nCallback++;
41534   p->pc = pc + 1;
41535   rc = SQLITE_ROW;
41536   goto vdbe_return;
41537 }
41538
41539 /* Opcode: Concat P1 P2 P3 * *
41540 **
41541 ** Add the text in register P1 onto the end of the text in
41542 ** register P2 and store the result in register P3.
41543 ** If either the P1 or P2 text are NULL then store NULL in P3.
41544 **
41545 **   P3 = P2 || P1
41546 **
41547 ** It is illegal for P1 and P3 to be the same register. Sometimes,
41548 ** if P3 is the same register as P2, the implementation is able
41549 ** to avoid a memcpy().
41550 */
41551 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
41552   i64 nByte;
41553
41554   assert( pIn1!=pOut );
41555   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
41556     sqlite3VdbeMemSetNull(pOut);
41557     break;
41558   }
41559   ExpandBlob(pIn1);
41560   Stringify(pIn1, encoding);
41561   ExpandBlob(pIn2);
41562   Stringify(pIn2, encoding);
41563   nByte = pIn1->n + pIn2->n;
41564   if( nByte>SQLITE_MAX_LENGTH ){
41565     goto too_big;
41566   }
41567   MemSetTypeFlag(pOut, MEM_Str);
41568   if( sqlite3VdbeMemGrow(pOut, nByte+2, pOut==pIn2) ){
41569     goto no_mem;
41570   }
41571   if( pOut!=pIn2 ){
41572     memcpy(pOut->z, pIn2->z, pIn2->n);
41573   }
41574   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
41575   pOut->z[nByte] = 0;
41576   pOut->z[nByte+1] = 0;
41577   pOut->flags |= MEM_Term;
41578   pOut->n = nByte;
41579   pOut->enc = encoding;
41580   UPDATE_MAX_BLOBSIZE(pOut);
41581   break;
41582 }
41583
41584 /* Opcode: Add P1 P2 P3 * *
41585 **
41586 ** Add the value in register P1 to the value in register P2
41587 ** and store the result in regiser P3.
41588 ** If either input is NULL, the result is NULL.
41589 */
41590 /* Opcode: Multiply P1 P2 P3 * *
41591 **
41592 **
41593 ** Multiply the value in regiser P1 by the value in regiser P2
41594 ** and store the result in register P3.
41595 ** If either input is NULL, the result is NULL.
41596 */
41597 /* Opcode: Subtract P1 P2 P3 * *
41598 **
41599 ** Subtract the value in register P1 from the value in register P2
41600 ** and store the result in register P3.
41601 ** If either input is NULL, the result is NULL.
41602 */
41603 /* Opcode: Divide P1 P2 P3 * *
41604 **
41605 ** Divide the value in register P1 by the value in register P2
41606 ** and store the result in register P3.  If the value in register P2
41607 ** is zero, then the result is NULL.
41608 ** If either input is NULL, the result is NULL.
41609 */
41610 /* Opcode: Remainder P1 P2 P3 * *
41611 **
41612 ** Compute the remainder after integer division of the value in
41613 ** register P1 by the value in register P2 and store the result in P3. 
41614 ** If the value in register P2 is zero the result is NULL.
41615 ** If either operand is NULL, the result is NULL.
41616 */
41617 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
41618 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
41619 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
41620 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
41621 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
41622   int flags;
41623   flags = pIn1->flags | pIn2->flags;
41624   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
41625   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
41626     i64 a, b;
41627     a = pIn1->u.i;
41628     b = pIn2->u.i;
41629     switch( pOp->opcode ){
41630       case OP_Add:         b += a;       break;
41631       case OP_Subtract:    b -= a;       break;
41632       case OP_Multiply:    b *= a;       break;
41633       case OP_Divide: {
41634         if( a==0 ) goto arithmetic_result_is_null;
41635         /* Dividing the largest possible negative 64-bit integer (1<<63) by 
41636         ** -1 returns an integer to large to store in a 64-bit data-type. On
41637         ** some architectures, the value overflows to (1<<63). On others,
41638         ** a SIGFPE is issued. The following statement normalizes this
41639         ** behaviour so that all architectures behave as if integer 
41640         ** overflow occured.
41641         */
41642         if( a==-1 && b==(((i64)1)<<63) ) a = 1;
41643         b /= a;
41644         break;
41645       }
41646       default: {
41647         if( a==0 ) goto arithmetic_result_is_null;
41648         if( a==-1 ) a = 1;
41649         b %= a;
41650         break;
41651       }
41652     }
41653     pOut->u.i = b;
41654     MemSetTypeFlag(pOut, MEM_Int);
41655   }else{
41656     double a, b;
41657     a = sqlite3VdbeRealValue(pIn1);
41658     b = sqlite3VdbeRealValue(pIn2);
41659     switch( pOp->opcode ){
41660       case OP_Add:         b += a;       break;
41661       case OP_Subtract:    b -= a;       break;
41662       case OP_Multiply:    b *= a;       break;
41663       case OP_Divide: {
41664         if( a==0.0 ) goto arithmetic_result_is_null;
41665         b /= a;
41666         break;
41667       }
41668       default: {
41669         i64 ia = (i64)a;
41670         i64 ib = (i64)b;
41671         if( ia==0 ) goto arithmetic_result_is_null;
41672         if( ia==-1 ) ia = 1;
41673         b = ib % ia;
41674         break;
41675       }
41676     }
41677     if( sqlite3_isnan(b) ){
41678       goto arithmetic_result_is_null;
41679     }
41680     pOut->r = b;
41681     MemSetTypeFlag(pOut, MEM_Real);
41682     if( (flags & MEM_Real)==0 ){
41683       sqlite3VdbeIntegerAffinity(pOut);
41684     }
41685   }
41686   break;
41687
41688 arithmetic_result_is_null:
41689   sqlite3VdbeMemSetNull(pOut);
41690   break;
41691 }
41692
41693 /* Opcode: CollSeq * * P4
41694 **
41695 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
41696 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
41697 ** be returned. This is used by the built-in min(), max() and nullif()
41698 ** functions.
41699 **
41700 ** The interface used by the implementation of the aforementioned functions
41701 ** to retrieve the collation sequence set by this opcode is not available
41702 ** publicly, only to user functions defined in func.c.
41703 */
41704 case OP_CollSeq: {
41705   assert( pOp->p4type==P4_COLLSEQ );
41706   break;
41707 }
41708
41709 /* Opcode: Function P1 P2 P3 P4 P5
41710 **
41711 ** Invoke a user function (P4 is a pointer to a Function structure that
41712 ** defines the function) with P5 arguments taken from register P2 and
41713 ** successors.  The result of the function is stored in register P3.
41714 ** Register P3 must not be one of the function inputs.
41715 **
41716 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
41717 ** function was determined to be constant at compile time. If the first
41718 ** argument was constant then bit 0 of P1 is set. This is used to determine
41719 ** whether meta data associated with a user function argument using the
41720 ** sqlite3_set_auxdata() API may be safely retained until the next
41721 ** invocation of this opcode.
41722 **
41723 ** See also: AggStep and AggFinal
41724 */
41725 case OP_Function: {
41726   int i;
41727   Mem *pArg;
41728   sqlite3_context ctx;
41729   sqlite3_value **apVal;
41730   int n = pOp->p5;
41731
41732   apVal = p->apArg;
41733   assert( apVal || n==0 );
41734
41735   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
41736   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
41737   pArg = &p->aMem[pOp->p2];
41738   for(i=0; i<n; i++, pArg++){
41739     apVal[i] = pArg;
41740     storeTypeInfo(pArg, encoding);
41741     REGISTER_TRACE(pOp->p2, pArg);
41742   }
41743
41744   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
41745   if( pOp->p4type==P4_FUNCDEF ){
41746     ctx.pFunc = pOp->p4.pFunc;
41747     ctx.pVdbeFunc = 0;
41748   }else{
41749     ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
41750     ctx.pFunc = ctx.pVdbeFunc->pFunc;
41751   }
41752
41753   assert( pOp->p3>0 && pOp->p3<=p->nMem );
41754   pOut = &p->aMem[pOp->p3];
41755   ctx.s.flags = MEM_Null;
41756   ctx.s.db = 0;
41757
41758   /* The output cell may already have a buffer allocated. Move
41759   ** the pointer to ctx.s so in case the user-function can use
41760   ** the already allocated buffer instead of allocating a new one.
41761   */
41762   sqlite3VdbeMemMove(&ctx.s, pOut);
41763   MemSetTypeFlag(&ctx.s, MEM_Null);
41764
41765   ctx.isError = 0;
41766   if( ctx.pFunc->needCollSeq ){
41767     assert( pOp>p->aOp );
41768     assert( pOp[-1].p4type==P4_COLLSEQ );
41769     assert( pOp[-1].opcode==OP_CollSeq );
41770     ctx.pColl = pOp[-1].p4.pColl;
41771   }
41772   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
41773   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
41774   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
41775   if( db->mallocFailed ){
41776     /* Even though a malloc() has failed, the implementation of the
41777     ** user function may have called an sqlite3_result_XXX() function
41778     ** to return a value. The following call releases any resources
41779     ** associated with such a value.
41780     **
41781     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
41782     ** fails also (the if(...) statement above). But if people are
41783     ** misusing sqlite, they have bigger problems than a leaked value.
41784     */
41785     sqlite3VdbeMemRelease(&ctx.s);
41786     goto no_mem;
41787   }
41788
41789   /* If any auxilary data functions have been called by this user function,
41790   ** immediately call the destructor for any non-static values.
41791   */
41792   if( ctx.pVdbeFunc ){
41793     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
41794     pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
41795     pOp->p4type = P4_VDBEFUNC;
41796   }
41797
41798   /* If the function returned an error, throw an exception */
41799   if( ctx.isError ){
41800     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
41801     rc = ctx.isError;
41802   }
41803
41804   /* Copy the result of the function into register P3 */
41805   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
41806   sqlite3VdbeMemMove(pOut, &ctx.s);
41807   if( sqlite3VdbeMemTooBig(pOut) ){
41808     goto too_big;
41809   }
41810   REGISTER_TRACE(pOp->p3, pOut);
41811   UPDATE_MAX_BLOBSIZE(pOut);
41812   break;
41813 }
41814
41815 /* Opcode: BitAnd P1 P2 P3 * *
41816 **
41817 ** Take the bit-wise AND of the values in register P1 and P2 and
41818 ** store the result in register P3.
41819 ** If either input is NULL, the result is NULL.
41820 */
41821 /* Opcode: BitOr P1 P2 P3 * *
41822 **
41823 ** Take the bit-wise OR of the values in register P1 and P2 and
41824 ** store the result in register P3.
41825 ** If either input is NULL, the result is NULL.
41826 */
41827 /* Opcode: ShiftLeft P1 P2 P3 * *
41828 **
41829 ** Shift the integer value in register P2 to the left by the
41830 ** number of bits specified by the integer in regiser P1.
41831 ** Store the result in register P3.
41832 ** If either input is NULL, the result is NULL.
41833 */
41834 /* Opcode: ShiftRight P1 P2 P3 * *
41835 **
41836 ** Shift the integer value in register P2 to the right by the
41837 ** number of bits specified by the integer in register P1.
41838 ** Store the result in register P3.
41839 ** If either input is NULL, the result is NULL.
41840 */
41841 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
41842 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
41843 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
41844 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
41845   i64 a, b;
41846
41847   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
41848     sqlite3VdbeMemSetNull(pOut);
41849     break;
41850   }
41851   a = sqlite3VdbeIntValue(pIn2);
41852   b = sqlite3VdbeIntValue(pIn1);
41853   switch( pOp->opcode ){
41854     case OP_BitAnd:      a &= b;     break;
41855     case OP_BitOr:       a |= b;     break;
41856     case OP_ShiftLeft:   a <<= b;    break;
41857     default:  assert( pOp->opcode==OP_ShiftRight );
41858                          a >>= b;    break;
41859   }
41860   pOut->u.i = a;
41861   MemSetTypeFlag(pOut, MEM_Int);
41862   break;
41863 }
41864
41865 /* Opcode: AddImm  P1 P2 * * *
41866 ** 
41867 ** Add the constant P2 the value in register P1.
41868 ** The result is always an integer.
41869 **
41870 ** To force any register to be an integer, just add 0.
41871 */
41872 case OP_AddImm: {            /* in1 */
41873   sqlite3VdbeMemIntegerify(pIn1);
41874   pIn1->u.i += pOp->p2;
41875   break;
41876 }
41877
41878 /* Opcode: ForceInt P1 P2 P3 * *
41879 **
41880 ** Convert value in register P1 into an integer.  If the value 
41881 ** in P1 is not numeric (meaning that is is a NULL or a string that
41882 ** does not look like an integer or floating point number) then
41883 ** jump to P2.  If the value in P1 is numeric then
41884 ** convert it into the least integer that is greater than or equal to its
41885 ** current value if P3==0, or to the least integer that is strictly
41886 ** greater than its current value if P3==1.
41887 */
41888 case OP_ForceInt: {            /* jump, in1 */
41889   i64 v;
41890   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
41891   if( (pIn1->flags & (MEM_Int|MEM_Real))==0 ){
41892     pc = pOp->p2 - 1;
41893     break;
41894   }
41895   if( pIn1->flags & MEM_Int ){
41896     v = pIn1->u.i + (pOp->p3!=0);
41897   }else{
41898     assert( pIn1->flags & MEM_Real );
41899     v = (sqlite3_int64)pIn1->r;
41900     if( pIn1->r>(double)v ) v++;
41901     if( pOp->p3 && pIn1->r==(double)v ) v++;
41902   }
41903   pIn1->u.i = v;
41904   MemSetTypeFlag(pIn1, MEM_Int);
41905   break;
41906 }
41907
41908 /* Opcode: MustBeInt P1 P2 * * *
41909 ** 
41910 ** Force the value in register P1 to be an integer.  If the value
41911 ** in P1 is not an integer and cannot be converted into an integer
41912 ** without data loss, then jump immediately to P2, or if P2==0
41913 ** raise an SQLITE_MISMATCH exception.
41914 */
41915 case OP_MustBeInt: {            /* jump, in1 */
41916   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
41917   if( (pIn1->flags & MEM_Int)==0 ){
41918     if( pOp->p2==0 ){
41919       rc = SQLITE_MISMATCH;
41920       goto abort_due_to_error;
41921     }else{
41922       pc = pOp->p2 - 1;
41923     }
41924   }else{
41925     MemSetTypeFlag(pIn1, MEM_Int);
41926   }
41927   break;
41928 }
41929
41930 /* Opcode: RealAffinity P1 * * * *
41931 **
41932 ** If register P1 holds an integer convert it to a real value.
41933 **
41934 ** This opcode is used when extracting information from a column that
41935 ** has REAL affinity.  Such column values may still be stored as
41936 ** integers, for space efficiency, but after extraction we want them
41937 ** to have only a real value.
41938 */
41939 case OP_RealAffinity: {                  /* in1 */
41940   if( pIn1->flags & MEM_Int ){
41941     sqlite3VdbeMemRealify(pIn1);
41942   }
41943   break;
41944 }
41945
41946 #ifndef SQLITE_OMIT_CAST
41947 /* Opcode: ToText P1 * * * *
41948 **
41949 ** Force the value in register P1 to be text.
41950 ** If the value is numeric, convert it to a string using the
41951 ** equivalent of printf().  Blob values are unchanged and
41952 ** are afterwards simply interpreted as text.
41953 **
41954 ** A NULL value is not changed by this routine.  It remains NULL.
41955 */
41956 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
41957   if( pIn1->flags & MEM_Null ) break;
41958   assert( MEM_Str==(MEM_Blob>>3) );
41959   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
41960   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
41961   rc = ExpandBlob(pIn1);
41962   assert( pIn1->flags & MEM_Str || db->mallocFailed );
41963   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
41964   UPDATE_MAX_BLOBSIZE(pIn1);
41965   break;
41966 }
41967
41968 /* Opcode: ToBlob P1 * * * *
41969 **
41970 ** Force the value in register P1 to be a BLOB.
41971 ** If the value is numeric, convert it to a string first.
41972 ** Strings are simply reinterpreted as blobs with no change
41973 ** to the underlying data.
41974 **
41975 ** A NULL value is not changed by this routine.  It remains NULL.
41976 */
41977 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
41978   if( pIn1->flags & MEM_Null ) break;
41979   if( (pIn1->flags & MEM_Blob)==0 ){
41980     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
41981     assert( pIn1->flags & MEM_Str || db->mallocFailed );
41982   }
41983   MemSetTypeFlag(pIn1, MEM_Blob);
41984   UPDATE_MAX_BLOBSIZE(pIn1);
41985   break;
41986 }
41987
41988 /* Opcode: ToNumeric P1 * * * *
41989 **
41990 ** Force the value in register P1 to be numeric (either an
41991 ** integer or a floating-point number.)
41992 ** If the value is text or blob, try to convert it to an using the
41993 ** equivalent of atoi() or atof() and store 0 if no such conversion 
41994 ** is possible.
41995 **
41996 ** A NULL value is not changed by this routine.  It remains NULL.
41997 */
41998 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
41999   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
42000     sqlite3VdbeMemNumerify(pIn1);
42001   }
42002   break;
42003 }
42004 #endif /* SQLITE_OMIT_CAST */
42005
42006 /* Opcode: ToInt P1 * * * *
42007 **
42008 ** Force the value in register P1 be an integer.  If
42009 ** The value is currently a real number, drop its fractional part.
42010 ** If the value is text or blob, try to convert it to an integer using the
42011 ** equivalent of atoi() and store 0 if no such conversion is possible.
42012 **
42013 ** A NULL value is not changed by this routine.  It remains NULL.
42014 */
42015 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
42016   if( (pIn1->flags & MEM_Null)==0 ){
42017     sqlite3VdbeMemIntegerify(pIn1);
42018   }
42019   break;
42020 }
42021
42022 #ifndef SQLITE_OMIT_CAST
42023 /* Opcode: ToReal P1 * * * *
42024 **
42025 ** Force the value in register P1 to be a floating point number.
42026 ** If The value is currently an integer, convert it.
42027 ** If the value is text or blob, try to convert it to an integer using the
42028 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
42029 **
42030 ** A NULL value is not changed by this routine.  It remains NULL.
42031 */
42032 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
42033   if( (pIn1->flags & MEM_Null)==0 ){
42034     sqlite3VdbeMemRealify(pIn1);
42035   }
42036   break;
42037 }
42038 #endif /* SQLITE_OMIT_CAST */
42039
42040 /* Opcode: Lt P1 P2 P3 P4 P5
42041 **
42042 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
42043 ** jump to address P2.  
42044 **
42045 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
42046 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
42047 ** bit is clear then fall thru if either operand is NULL.
42048 **
42049 ** If the SQLITE_NULLEQUAL bit of P5 is set then treat NULL operands
42050 ** as being equal to one another.  Normally NULLs are not equal to 
42051 ** anything including other NULLs.
42052 **
42053 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
42054 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
42055 ** to coerce both inputs according to this affinity before the
42056 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
42057 ** affinity is used. Note that the affinity conversions are stored
42058 ** back into the input registers P1 and P3.  So this opcode can cause
42059 ** persistent changes to registers P1 and P3.
42060 **
42061 ** Once any conversions have taken place, and neither value is NULL, 
42062 ** the values are compared. If both values are blobs then memcmp() is
42063 ** used to determine the results of the comparison.  If both values
42064 ** are text, then the appropriate collating function specified in
42065 ** P4 is  used to do the comparison.  If P4 is not specified then
42066 ** memcmp() is used to compare text string.  If both values are
42067 ** numeric, then a numeric comparison is used. If the two values
42068 ** are of different types, then numbers are considered less than
42069 ** strings and strings are considered less than blobs.
42070 **
42071 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
42072 ** store a boolean result (either 0, or 1, or NULL) in register P2.
42073 */
42074 /* Opcode: Ne P1 P2 P3 P4 P5
42075 **
42076 ** This works just like the Lt opcode except that the jump is taken if
42077 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
42078 ** additional information.
42079 */
42080 /* Opcode: Eq P1 P2 P3 P4 P5
42081 **
42082 ** This works just like the Lt opcode except that the jump is taken if
42083 ** the operands in registers P1 and P3 are equal.
42084 ** See the Lt opcode for additional information.
42085 */
42086 /* Opcode: Le P1 P2 P3 P4 P5
42087 **
42088 ** This works just like the Lt opcode except that the jump is taken if
42089 ** the content of register P3 is less than or equal to the content of
42090 ** register P1.  See the Lt opcode for additional information.
42091 */
42092 /* Opcode: Gt P1 P2 P3 P4 P5
42093 **
42094 ** This works just like the Lt opcode except that the jump is taken if
42095 ** the content of register P3 is greater than the content of
42096 ** register P1.  See the Lt opcode for additional information.
42097 */
42098 /* Opcode: Ge P1 P2 P3 P4 P5
42099 **
42100 ** This works just like the Lt opcode except that the jump is taken if
42101 ** the content of register P3 is greater than or equal to the content of
42102 ** register P1.  See the Lt opcode for additional information.
42103 */
42104 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
42105 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
42106 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
42107 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
42108 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
42109 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
42110   int flags;
42111   int res;
42112   char affinity;
42113   Mem x1, x3;
42114
42115   flags = pIn1->flags|pIn3->flags;
42116
42117   if( flags&MEM_Null ){
42118     if( (pOp->p5 & SQLITE_NULLEQUAL)!=0 ){
42119       /*
42120       ** When SQLITE_NULLEQUAL set and either operand is NULL
42121       ** then both operands are converted to integers prior to being 
42122       ** passed down into the normal comparison logic below.  
42123       ** NULL operands are converted to zero and non-NULL operands
42124       ** are converted to 1.  Thus, for example, with SQLITE_NULLEQUAL
42125       ** set,  NULL==NULL is true whereas it would normally NULL.
42126       ** Similarly,  NULL!=123 is true.
42127       */
42128       x1.flags = MEM_Int;
42129       x1.u.i = (pIn1->flags & MEM_Null)==0;
42130       pIn1 = &x1;
42131       x3.flags = MEM_Int;
42132       x3.u.i = (pIn3->flags & MEM_Null)==0;
42133       pIn3 = &x3;
42134     }else{
42135       /* If the SQLITE_NULLEQUAL bit is clear and either operand is NULL then
42136       ** the result is always NULL.  The jump is taken if the 
42137       ** SQLITE_JUMPIFNULL bit is set.
42138       */
42139       if( pOp->p5 & SQLITE_STOREP2 ){
42140         pOut = &p->aMem[pOp->p2];
42141         MemSetTypeFlag(pOut, MEM_Null);
42142         REGISTER_TRACE(pOp->p2, pOut);
42143       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
42144         pc = pOp->p2-1;
42145       }
42146       break;
42147     }
42148   }
42149
42150   affinity = pOp->p5 & SQLITE_AFF_MASK;
42151   if( affinity ){
42152     applyAffinity(pIn1, affinity, encoding);
42153     applyAffinity(pIn3, affinity, encoding);
42154   }
42155
42156   assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
42157   ExpandBlob(pIn1);
42158   ExpandBlob(pIn3);
42159   res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
42160   switch( pOp->opcode ){
42161     case OP_Eq:    res = res==0;     break;
42162     case OP_Ne:    res = res!=0;     break;
42163     case OP_Lt:    res = res<0;      break;
42164     case OP_Le:    res = res<=0;     break;
42165     case OP_Gt:    res = res>0;      break;
42166     default:       res = res>=0;     break;
42167   }
42168
42169   if( pOp->p5 & SQLITE_STOREP2 ){
42170     pOut = &p->aMem[pOp->p2];
42171     MemSetTypeFlag(pOut, MEM_Int);
42172     pOut->u.i = res;
42173     REGISTER_TRACE(pOp->p2, pOut);
42174   }else if( res ){
42175     pc = pOp->p2-1;
42176   }
42177   break;
42178 }
42179
42180 /* Opcode: And P1 P2 P3 * *
42181 **
42182 ** Take the logical AND of the values in registers P1 and P2 and
42183 ** write the result into register P3.
42184 **
42185 ** If either P1 or P2 is 0 (false) then the result is 0 even if
42186 ** the other input is NULL.  A NULL and true or two NULLs give
42187 ** a NULL output.
42188 */
42189 /* Opcode: Or P1 P2 P3 * *
42190 **
42191 ** Take the logical OR of the values in register P1 and P2 and
42192 ** store the answer in register P3.
42193 **
42194 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
42195 ** even if the other input is NULL.  A NULL and false or two NULLs
42196 ** give a NULL output.
42197 */
42198 case OP_And:              /* same as TK_AND, in1, in2, out3 */
42199 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
42200   int v1, v2;    /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
42201
42202   if( pIn1->flags & MEM_Null ){
42203     v1 = 2;
42204   }else{
42205     v1 = sqlite3VdbeIntValue(pIn1)!=0;
42206   }
42207   if( pIn2->flags & MEM_Null ){
42208     v2 = 2;
42209   }else{
42210     v2 = sqlite3VdbeIntValue(pIn2)!=0;
42211   }
42212   if( pOp->opcode==OP_And ){
42213     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
42214     v1 = and_logic[v1*3+v2];
42215   }else{
42216     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
42217     v1 = or_logic[v1*3+v2];
42218   }
42219   if( v1==2 ){
42220     MemSetTypeFlag(pOut, MEM_Null);
42221   }else{
42222     pOut->u.i = v1;
42223     MemSetTypeFlag(pOut, MEM_Int);
42224   }
42225   break;
42226 }
42227
42228 /* Opcode: Not P1 * * * *
42229 **
42230 ** Interpret the value in register P1 as a boolean value.  Replace it
42231 ** with its complement.  If the value in register P1 is NULL its value
42232 ** is unchanged.
42233 */
42234 case OP_Not: {                /* same as TK_NOT, in1 */
42235   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
42236   sqlite3VdbeMemIntegerify(pIn1);
42237   pIn1->u.i = !pIn1->u.i;
42238   assert( pIn1->flags&MEM_Int );
42239   break;
42240 }
42241
42242 /* Opcode: BitNot P1 * * * *
42243 **
42244 ** Interpret the content of register P1 as an integer.  Replace it
42245 ** with its ones-complement.  If the value is originally NULL, leave
42246 ** it unchanged.
42247 */
42248 case OP_BitNot: {             /* same as TK_BITNOT, in1 */
42249   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
42250   sqlite3VdbeMemIntegerify(pIn1);
42251   pIn1->u.i = ~pIn1->u.i;
42252   assert( pIn1->flags&MEM_Int );
42253   break;
42254 }
42255
42256 /* Opcode: If P1 P2 P3 * *
42257 **
42258 ** Jump to P2 if the value in register P1 is true.  The value is
42259 ** is considered true if it is numeric and non-zero.  If the value
42260 ** in P1 is NULL then take the jump if P3 is true.
42261 */
42262 /* Opcode: IfNot P1 P2 P3 * *
42263 **
42264 ** Jump to P2 if the value in register P1 is False.  The value is
42265 ** is considered true if it has a numeric value of zero.  If the value
42266 ** in P1 is NULL then take the jump if P3 is true.
42267 */
42268 case OP_If:                 /* jump, in1 */
42269 case OP_IfNot: {            /* jump, in1 */
42270   int c;
42271   if( pIn1->flags & MEM_Null ){
42272     c = pOp->p3;
42273   }else{
42274 #ifdef SQLITE_OMIT_FLOATING_POINT
42275     c = sqlite3VdbeIntValue(pIn1);
42276 #else
42277     c = sqlite3VdbeRealValue(pIn1)!=0.0;
42278 #endif
42279     if( pOp->opcode==OP_IfNot ) c = !c;
42280   }
42281   if( c ){
42282     pc = pOp->p2-1;
42283   }
42284   break;
42285 }
42286
42287 /* Opcode: IsNull P1 P2 P3 * *
42288 **
42289 ** Jump to P2 if the value in register P1 is NULL.  If P3 is greater
42290 ** than zero, then check all values reg(P1), reg(P1+1), 
42291 ** reg(P1+2), ..., reg(P1+P3-1).
42292 */
42293 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
42294   int n = pOp->p3;
42295   assert( pOp->p3==0 || pOp->p1>0 );
42296   do{
42297     if( (pIn1->flags & MEM_Null)!=0 ){
42298       pc = pOp->p2 - 1;
42299       break;
42300     }
42301     pIn1++;
42302   }while( --n > 0 );
42303   break;
42304 }
42305
42306 /* Opcode: NotNull P1 P2 * * *
42307 **
42308 ** Jump to P2 if the value in register P1 is not NULL.  
42309 */
42310 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
42311   if( (pIn1->flags & MEM_Null)==0 ){
42312     pc = pOp->p2 - 1;
42313   }
42314   break;
42315 }
42316
42317 /* Opcode: SetNumColumns P1 P2 * * *
42318 **
42319 ** Before the OP_Column opcode can be executed on a cursor, this
42320 ** opcode must be called to set the number of fields in the table.
42321 **
42322 ** This opcode sets the number of columns for cursor P1 to P2.
42323 **
42324 ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
42325 ** before this op-code.
42326 */
42327 case OP_SetNumColumns: {
42328   Cursor *pC;
42329   assert( (pOp->p1)<p->nCursor );
42330   assert( p->apCsr[pOp->p1]!=0 );
42331   pC = p->apCsr[pOp->p1];
42332   pC->nField = pOp->p2;
42333   break;
42334 }
42335
42336 /* Opcode: Column P1 P2 P3 P4 *
42337 **
42338 ** Interpret the data that cursor P1 points to as a structure built using
42339 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
42340 ** information about the format of the data.)  Extract the P2-th column
42341 ** from this record.  If there are less that (P2+1) 
42342 ** values in the record, extract a NULL.
42343 **
42344 ** The value extracted is stored in register P3.
42345 **
42346 ** If the KeyAsData opcode has previously executed on this cursor, then the
42347 ** field might be extracted from the key rather than the data.
42348 **
42349 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
42350 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
42351 ** the result.
42352 */
42353 case OP_Column: {
42354   u32 payloadSize;   /* Number of bytes in the record */
42355   int p1 = pOp->p1;  /* P1 value of the opcode */
42356   int p2 = pOp->p2;  /* column number to retrieve */
42357   Cursor *pC = 0;    /* The VDBE cursor */
42358   char *zRec;        /* Pointer to complete record-data */
42359   BtCursor *pCrsr;   /* The BTree cursor */
42360   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
42361   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
42362   u32 nField;        /* number of fields in the record */
42363   int len;           /* The length of the serialized data for the column */
42364   int i;             /* Loop counter */
42365   char *zData;       /* Part of the record being decoded */
42366   Mem *pDest;        /* Where to write the extracted value */
42367   Mem sMem;          /* For storing the record being decoded */
42368
42369   sMem.flags = 0;
42370   sMem.db = 0;
42371   assert( p1<p->nCursor );
42372   assert( pOp->p3>0 && pOp->p3<=p->nMem );
42373   pDest = &p->aMem[pOp->p3];
42374   MemSetTypeFlag(pDest, MEM_Null);
42375
42376   /* This block sets the variable payloadSize to be the total number of
42377   ** bytes in the record.
42378   **
42379   ** zRec is set to be the complete text of the record if it is available.
42380   ** The complete record text is always available for pseudo-tables
42381   ** If the record is stored in a cursor, the complete record text
42382   ** might be available in the  pC->aRow cache.  Or it might not be.
42383   ** If the data is unavailable,  zRec is set to NULL.
42384   **
42385   ** We also compute the number of columns in the record.  For cursors,
42386   ** the number of columns is stored in the Cursor.nField element.
42387   */
42388   pC = p->apCsr[p1];
42389   assert( pC!=0 );
42390 #ifndef SQLITE_OMIT_VIRTUALTABLE
42391   assert( pC->pVtabCursor==0 );
42392 #endif
42393   if( pC->pCursor!=0 ){
42394     /* The record is stored in a B-Tree */
42395     rc = sqlite3VdbeCursorMoveto(pC);
42396     if( rc ) goto abort_due_to_error;
42397     zRec = 0;
42398     pCrsr = pC->pCursor;
42399     if( pC->nullRow ){
42400       payloadSize = 0;
42401     }else if( pC->cacheStatus==p->cacheCtr ){
42402       payloadSize = pC->payloadSize;
42403       zRec = (char*)pC->aRow;
42404     }else if( pC->isIndex ){
42405       i64 payloadSize64;
42406       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
42407       payloadSize = payloadSize64;
42408     }else{
42409       sqlite3BtreeDataSize(pCrsr, &payloadSize);
42410     }
42411     nField = pC->nField;
42412   }else{
42413     assert( pC->pseudoTable );
42414     /* The record is the sole entry of a pseudo-table */
42415     payloadSize = pC->nData;
42416     zRec = pC->pData;
42417     pC->cacheStatus = CACHE_STALE;
42418     assert( payloadSize==0 || zRec!=0 );
42419     nField = pC->nField;
42420     pCrsr = 0;
42421   }
42422
42423   /* If payloadSize is 0, then just store a NULL */
42424   if( payloadSize==0 ){
42425     assert( pDest->flags&MEM_Null );
42426     goto op_column_out;
42427   }
42428   if( payloadSize>SQLITE_MAX_LENGTH ){
42429     goto too_big;
42430   }
42431
42432   assert( p2<nField );
42433
42434   /* Read and parse the table header.  Store the results of the parse
42435   ** into the record header cache fields of the cursor.
42436   */
42437   if( pC->cacheStatus==p->cacheCtr ){
42438     aType = pC->aType;
42439     aOffset = pC->aOffset;
42440   }else{
42441     u8 *zIdx;        /* Index into header */
42442     u8 *zEndHdr;     /* Pointer to first byte after the header */
42443     u32 offset;      /* Offset into the data */
42444     int szHdrSz;     /* Size of the header size field at start of record */
42445     int avail;       /* Number of bytes of available data */
42446
42447     aType = pC->aType;
42448     if( aType==0 ){
42449       pC->aType = aType = sqlite3DbMallocRaw(db, 2*nField*sizeof(aType) );
42450     }
42451     if( aType==0 ){
42452       goto no_mem;
42453     }
42454     pC->aOffset = aOffset = &aType[nField];
42455     pC->payloadSize = payloadSize;
42456     pC->cacheStatus = p->cacheCtr;
42457
42458     /* Figure out how many bytes are in the header */
42459     if( zRec ){
42460       zData = zRec;
42461     }else{
42462       if( pC->isIndex ){
42463         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
42464       }else{
42465         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
42466       }
42467       /* If KeyFetch()/DataFetch() managed to get the entire payload,
42468       ** save the payload in the pC->aRow cache.  That will save us from
42469       ** having to make additional calls to fetch the content portion of
42470       ** the record.
42471       */
42472       if( avail>=payloadSize ){
42473         zRec = zData;
42474         pC->aRow = (u8*)zData;
42475       }else{
42476         pC->aRow = 0;
42477       }
42478     }
42479     /* The following assert is true in all cases accept when
42480     ** the database file has been corrupted externally.
42481     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
42482     szHdrSz = GetVarint((u8*)zData, offset);
42483
42484     /* The KeyFetch() or DataFetch() above are fast and will get the entire
42485     ** record header in most cases.  But they will fail to get the complete
42486     ** record header if the record header does not fit on a single page
42487     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
42488     ** acquire the complete header text.
42489     */
42490     if( !zRec && avail<offset ){
42491       sMem.flags = 0;
42492       sMem.db = 0;
42493       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
42494       if( rc!=SQLITE_OK ){
42495         goto op_column_out;
42496       }
42497       zData = sMem.z;
42498     }
42499     zEndHdr = (u8 *)&zData[offset];
42500     zIdx = (u8 *)&zData[szHdrSz];
42501
42502     /* Scan the header and use it to fill in the aType[] and aOffset[]
42503     ** arrays.  aType[i] will contain the type integer for the i-th
42504     ** column and aOffset[i] will contain the offset from the beginning
42505     ** of the record to the start of the data for the i-th column
42506     */
42507     for(i=0; i<nField; i++){
42508       if( zIdx<zEndHdr ){
42509         aOffset[i] = offset;
42510         zIdx += GetVarint(zIdx, aType[i]);
42511         offset += sqlite3VdbeSerialTypeLen(aType[i]);
42512       }else{
42513         /* If i is less that nField, then there are less fields in this
42514         ** record than SetNumColumns indicated there are columns in the
42515         ** table. Set the offset for any extra columns not present in
42516         ** the record to 0. This tells code below to store a NULL
42517         ** instead of deserializing a value from the record.
42518         */
42519         aOffset[i] = 0;
42520       }
42521     }
42522     Release(&sMem);
42523     sMem.flags = MEM_Null;
42524
42525     /* If we have read more header data than was contained in the header,
42526     ** or if the end of the last field appears to be past the end of the
42527     ** record, then we must be dealing with a corrupt database.
42528     */
42529     if( zIdx>zEndHdr || offset>payloadSize ){
42530       rc = SQLITE_CORRUPT_BKPT;
42531       goto op_column_out;
42532     }
42533   }
42534
42535   /* Get the column information. If aOffset[p2] is non-zero, then 
42536   ** deserialize the value from the record. If aOffset[p2] is zero,
42537   ** then there are not enough fields in the record to satisfy the
42538   ** request.  In this case, set the value NULL or to P4 if P4 is
42539   ** a pointer to a Mem object.
42540   */
42541   if( aOffset[p2] ){
42542     assert( rc==SQLITE_OK );
42543     if( zRec ){
42544       if( pDest->flags&MEM_Dyn ){
42545         sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], &sMem);
42546         sMem.db = db; 
42547         sqlite3VdbeMemCopy(pDest, &sMem);
42548         assert( !(sMem.flags&MEM_Dyn) );
42549       }else{
42550         sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
42551       }
42552     }else{
42553       len = sqlite3VdbeSerialTypeLen(aType[p2]);
42554       sqlite3VdbeMemMove(&sMem, pDest);
42555       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
42556       if( rc!=SQLITE_OK ){
42557         goto op_column_out;
42558       }
42559       zData = sMem.z;
42560       sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
42561     }
42562     pDest->enc = encoding;
42563   }else{
42564     if( pOp->p4type==P4_MEM ){
42565       sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
42566     }else{
42567       assert( pDest->flags&MEM_Null );
42568     }
42569   }
42570
42571   /* If we dynamically allocated space to hold the data (in the
42572   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
42573   ** dynamically allocated space over to the pDest structure.
42574   ** This prevents a memory copy.
42575   */
42576   if( (sMem.flags & MEM_Dyn)!=0 ){
42577     assert( !sMem.xDel );
42578     assert( !(pDest->flags & MEM_Dyn) );
42579     assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
42580     pDest->flags &= ~(MEM_Ephem|MEM_Static);
42581     pDest->flags |= MEM_Dyn|MEM_Term;
42582     pDest->z = sMem.z;
42583   }
42584
42585   rc = sqlite3VdbeMemMakeWriteable(pDest);
42586
42587 op_column_out:
42588   UPDATE_MAX_BLOBSIZE(pDest);
42589   REGISTER_TRACE(pOp->p3, pDest);
42590   break;
42591 }
42592
42593 /* Opcode: MakeRecord P1 P2 P3 P4 *
42594 **
42595 ** Convert P2 registers beginning with P1 into a single entry
42596 ** suitable for use as a data record in a database table or as a key
42597 ** in an index.  The details of the format are irrelavant as long as
42598 ** the OP_Column opcode can decode the record later and as long as the
42599 ** sqlite3VdbeRecordCompare function will correctly compare two encoded
42600 ** records.  Refer to source code comments for the details of the record
42601 ** format.
42602 **
42603 ** P4 may be a string that is P1 characters long.  The nth character of the
42604 ** string indicates the column affinity that should be used for the nth
42605 ** field of the index key.
42606 **
42607 ** The mapping from character to affinity is given by the SQLITE_AFF_
42608 ** macros defined in sqliteInt.h.
42609 **
42610 ** If P4 is NULL then all index fields have the affinity NONE.
42611 */
42612 case OP_MakeRecord: {
42613   /* Assuming the record contains N fields, the record format looks
42614   ** like this:
42615   **
42616   ** ------------------------------------------------------------------------
42617   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
42618   ** ------------------------------------------------------------------------
42619   **
42620   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
42621   ** and so froth.
42622   **
42623   ** Each type field is a varint representing the serial type of the 
42624   ** corresponding data element (see sqlite3VdbeSerialType()). The
42625   ** hdr-size field is also a varint which is the offset from the beginning
42626   ** of the record to data0.
42627   */
42628   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
42629   Mem *pRec;             /* The new record */
42630   u64 nData = 0;         /* Number of bytes of data space */
42631   int nHdr = 0;          /* Number of bytes of header space */
42632   u64 nByte = 0;         /* Data space required for this record */
42633   int nZero = 0;         /* Number of zero bytes at the end of the record */
42634   int nVarint;           /* Number of bytes in a varint */
42635   u32 serial_type;       /* Type field */
42636   Mem *pData0;           /* First field to be combined into the record */
42637   Mem *pLast;            /* Last field of the record */
42638   int nField;            /* Number of fields in the record */
42639   char *zAffinity;       /* The affinity string for the record */
42640   int file_format;       /* File format to use for encoding */
42641   int i;                 /* Space used in zNewRecord[] */
42642
42643   nField = pOp->p1;
42644   zAffinity = pOp->p4.z;
42645   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
42646   pData0 = &p->aMem[nField];
42647   nField = pOp->p2;
42648   pLast = &pData0[nField-1];
42649   file_format = p->minWriteFileFormat;
42650
42651   /* Loop through the elements that will make up the record to figure
42652   ** out how much space is required for the new record.
42653   */
42654   for(pRec=pData0; pRec<=pLast; pRec++){
42655     int len;
42656     if( zAffinity ){
42657       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
42658     }
42659     if( pRec->flags&MEM_Zero && pRec->n>0 ){
42660       sqlite3VdbeMemExpandBlob(pRec);
42661     }
42662     serial_type = sqlite3VdbeSerialType(pRec, file_format);
42663     len = sqlite3VdbeSerialTypeLen(serial_type);
42664     nData += len;
42665     nHdr += sqlite3VarintLen(serial_type);
42666     if( pRec->flags & MEM_Zero ){
42667       /* Only pure zero-filled BLOBs can be input to this Opcode.
42668       ** We do not allow blobs with a prefix and a zero-filled tail. */
42669       nZero += pRec->u.i;
42670     }else if( len ){
42671       nZero = 0;
42672     }
42673   }
42674
42675   /* Add the initial header varint and total the size */
42676   nHdr += nVarint = sqlite3VarintLen(nHdr);
42677   if( nVarint<sqlite3VarintLen(nHdr) ){
42678     nHdr++;
42679   }
42680   nByte = nHdr+nData-nZero;
42681   if( nByte>SQLITE_MAX_LENGTH ){
42682     goto too_big;
42683   }
42684
42685   /* Make sure the output register has a buffer large enough to store 
42686   ** the new record. The output register (pOp->p3) is not allowed to
42687   ** be one of the input registers (because the following call to
42688   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
42689   */
42690   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
42691   pOut = &p->aMem[pOp->p3];
42692   if( sqlite3VdbeMemGrow(pOut, nByte, 0) ){
42693     goto no_mem;
42694   }
42695   zNewRecord = (u8 *)pOut->z;
42696
42697   /* Write the record */
42698   i = sqlite3PutVarint(zNewRecord, nHdr);
42699   for(pRec=pData0; pRec<=pLast; pRec++){
42700     serial_type = sqlite3VdbeSerialType(pRec, file_format);
42701     i += sqlite3PutVarint(&zNewRecord[i], serial_type);      /* serial type */
42702   }
42703   for(pRec=pData0; pRec<=pLast; pRec++){  /* serial data */
42704     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
42705   }
42706   assert( i==nByte );
42707
42708   assert( pOp->p3>0 && pOp->p3<=p->nMem );
42709   pOut->n = nByte;
42710   pOut->flags = MEM_Blob | MEM_Dyn;
42711   pOut->xDel = 0;
42712   if( nZero ){
42713     pOut->u.i = nZero;
42714     pOut->flags |= MEM_Zero;
42715   }
42716   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
42717   REGISTER_TRACE(pOp->p3, pOut);
42718   UPDATE_MAX_BLOBSIZE(pOut);
42719   break;
42720 }
42721
42722 /* Opcode: Statement P1 * * * *
42723 **
42724 ** Begin an individual statement transaction which is part of a larger
42725 ** BEGIN..COMMIT transaction.  This is needed so that the statement
42726 ** can be rolled back after an error without having to roll back the
42727 ** entire transaction.  The statement transaction will automatically
42728 ** commit when the VDBE halts.
42729 **
42730 ** The statement is begun on the database file with index P1.  The main
42731 ** database file has an index of 0 and the file used for temporary tables
42732 ** has an index of 1.
42733 */
42734 case OP_Statement: {
42735   if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
42736     int i = pOp->p1;
42737     Btree *pBt;
42738     assert( i>=0 && i<db->nDb );
42739     assert( db->aDb[i].pBt!=0 );
42740     pBt = db->aDb[i].pBt;
42741     assert( sqlite3BtreeIsInTrans(pBt) );
42742     assert( (p->btreeMask & (1<<i))!=0 );
42743     if( !sqlite3BtreeIsInStmt(pBt) ){
42744       rc = sqlite3BtreeBeginStmt(pBt);
42745       p->openedStatement = 1;
42746     }
42747   }
42748   break;
42749 }
42750
42751 /* Opcode: AutoCommit P1 P2 * * *
42752 **
42753 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
42754 ** back any currently active btree transactions. If there are any active
42755 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
42756 **
42757 ** This instruction causes the VM to halt.
42758 */
42759 case OP_AutoCommit: {
42760   u8 i = pOp->p1;
42761   u8 rollback = pOp->p2;
42762
42763   assert( i==1 || i==0 );
42764   assert( i==1 || rollback==0 );
42765
42766   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
42767
42768   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
42769     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
42770     ** still running, and a transaction is active, return an error indicating
42771     ** that the other VMs must complete first. 
42772     */
42773     sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit", 
42774         " transaction - SQL statements in progress", (char*)0);
42775     rc = SQLITE_ERROR;
42776   }else if( i!=db->autoCommit ){
42777     if( pOp->p2 ){
42778       assert( i==1 );
42779       sqlite3RollbackAll(db);
42780       db->autoCommit = 1;
42781     }else{
42782       db->autoCommit = i;
42783       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
42784         p->pc = pc;
42785         db->autoCommit = 1-i;
42786         p->rc = rc = SQLITE_BUSY;
42787         goto vdbe_return;
42788       }
42789     }
42790     if( p->rc==SQLITE_OK ){
42791       rc = SQLITE_DONE;
42792     }else{
42793       rc = SQLITE_ERROR;
42794     }
42795     goto vdbe_return;
42796   }else{
42797     sqlite3SetString(&p->zErrMsg,
42798         (!i)?"cannot start a transaction within a transaction":(
42799         (rollback)?"cannot rollback - no transaction is active":
42800                    "cannot commit - no transaction is active"), (char*)0);
42801          
42802     rc = SQLITE_ERROR;
42803   }
42804   break;
42805 }
42806
42807 /* Opcode: Transaction P1 P2 * * *
42808 **
42809 ** Begin a transaction.  The transaction ends when a Commit or Rollback
42810 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
42811 ** transaction might also be rolled back if an error is encountered.
42812 **
42813 ** P1 is the index of the database file on which the transaction is
42814 ** started.  Index 0 is the main database file and index 1 is the
42815 ** file used for temporary tables.  Indices of 2 or more are used for
42816 ** attached databases.
42817 **
42818 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
42819 ** obtained on the database file when a write-transaction is started.  No
42820 ** other process can start another write transaction while this transaction is
42821 ** underway.  Starting a write transaction also creates a rollback journal. A
42822 ** write transaction must be started before any changes can be made to the
42823 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
42824 ** on the file.
42825 **
42826 ** If P2 is zero, then a read-lock is obtained on the database file.
42827 */
42828 case OP_Transaction: {
42829   int i = pOp->p1;
42830   Btree *pBt;
42831
42832   assert( i>=0 && i<db->nDb );
42833   assert( (p->btreeMask & (1<<i))!=0 );
42834   pBt = db->aDb[i].pBt;
42835
42836   if( pBt ){
42837     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
42838     if( rc==SQLITE_BUSY ){
42839       p->pc = pc;
42840       p->rc = rc = SQLITE_BUSY;
42841       goto vdbe_return;
42842     }
42843     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
42844       goto abort_due_to_error;
42845     }
42846   }
42847   break;
42848 }
42849
42850 /* Opcode: ReadCookie P1 P2 P3 * *
42851 **
42852 ** Read cookie number P3 from database P1 and write it into register P2.
42853 ** P3==0 is the schema version.  P3==1 is the database format.
42854 ** P3==2 is the recommended pager cache size, and so forth.  P1==0 is
42855 ** the main database file and P1==1 is the database file used to store
42856 ** temporary tables.
42857 **
42858 ** If P1 is negative, then this is a request to read the size of a
42859 ** databases free-list. P3 must be set to 1 in this case. The actual
42860 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
42861 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
42862 **
42863 ** There must be a read-lock on the database (either a transaction
42864 ** must be started or there must be an open cursor) before
42865 ** executing this instruction.
42866 */
42867 case OP_ReadCookie: {               /* out2-prerelease */
42868   int iMeta;
42869   int iDb = pOp->p1;
42870   int iCookie = pOp->p3;
42871
42872   assert( pOp->p3<SQLITE_N_BTREE_META );
42873   if( iDb<0 ){
42874     iDb = (-1*(iDb+1));
42875     iCookie *= -1;
42876   }
42877   assert( iDb>=0 && iDb<db->nDb );
42878   assert( db->aDb[iDb].pBt!=0 );
42879   assert( (p->btreeMask & (1<<iDb))!=0 );
42880   /* The indexing of meta values at the schema layer is off by one from
42881   ** the indexing in the btree layer.  The btree considers meta[0] to
42882   ** be the number of free pages in the database (a read-only value)
42883   ** and meta[1] to be the schema cookie.  The schema layer considers
42884   ** meta[1] to be the schema cookie.  So we have to shift the index
42885   ** by one in the following statement.
42886   */
42887   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
42888   pOut->u.i = iMeta;
42889   MemSetTypeFlag(pOut, MEM_Int);
42890   break;
42891 }
42892
42893 /* Opcode: SetCookie P1 P2 P3 * *
42894 **
42895 ** Write the content of register P3 (interpreted as an integer)
42896 ** into cookie number P2 of database P1.
42897 ** P2==0 is the schema version.  P2==1 is the database format.
42898 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
42899 ** the main database file and P1==1 is the database file used to store
42900 ** temporary tables.
42901 **
42902 ** A transaction must be started before executing this opcode.
42903 */
42904 case OP_SetCookie: {       /* in3 */
42905   Db *pDb;
42906   assert( pOp->p2<SQLITE_N_BTREE_META );
42907   assert( pOp->p1>=0 && pOp->p1<db->nDb );
42908   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
42909   pDb = &db->aDb[pOp->p1];
42910   assert( pDb->pBt!=0 );
42911   sqlite3VdbeMemIntegerify(pIn3);
42912   /* See note about index shifting on OP_ReadCookie */
42913   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
42914   if( pOp->p2==0 ){
42915     /* When the schema cookie changes, record the new cookie internally */
42916     pDb->pSchema->schema_cookie = pIn3->u.i;
42917     db->flags |= SQLITE_InternChanges;
42918   }else if( pOp->p2==1 ){
42919     /* Record changes in the file format */
42920     pDb->pSchema->file_format = pIn3->u.i;
42921   }
42922   if( pOp->p1==1 ){
42923     /* Invalidate all prepared statements whenever the TEMP database
42924     ** schema is changed.  Ticket #1644 */
42925     sqlite3ExpirePreparedStatements(db);
42926   }
42927   break;
42928 }
42929
42930 /* Opcode: VerifyCookie P1 P2 *
42931 **
42932 ** Check the value of global database parameter number 0 (the
42933 ** schema version) and make sure it is equal to P2.  
42934 ** P1 is the database number which is 0 for the main database file
42935 ** and 1 for the file holding temporary tables and some higher number
42936 ** for auxiliary databases.
42937 **
42938 ** The cookie changes its value whenever the database schema changes.
42939 ** This operation is used to detect when that the cookie has changed
42940 ** and that the current process needs to reread the schema.
42941 **
42942 ** Either a transaction needs to have been started or an OP_Open needs
42943 ** to be executed (to establish a read lock) before this opcode is
42944 ** invoked.
42945 */
42946 case OP_VerifyCookie: {
42947   int iMeta;
42948   Btree *pBt;
42949   assert( pOp->p1>=0 && pOp->p1<db->nDb );
42950   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
42951   pBt = db->aDb[pOp->p1].pBt;
42952   if( pBt ){
42953     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
42954   }else{
42955     rc = SQLITE_OK;
42956     iMeta = 0;
42957   }
42958   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
42959     sqlite3_free(p->zErrMsg);
42960     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
42961     /* If the schema-cookie from the database file matches the cookie 
42962     ** stored with the in-memory representation of the schema, do
42963     ** not reload the schema from the database file.
42964     **
42965     ** If virtual-tables are in use, this is not just an optimisation.
42966     ** Often, v-tables store their data in other SQLite tables, which
42967     ** are queried from within xNext() and other v-table methods using
42968     ** prepared queries. If such a query is out-of-date, we do not want to
42969     ** discard the database schema, as the user code implementing the
42970     ** v-table would have to be ready for the sqlite3_vtab structure itself
42971     ** to be invalidated whenever sqlite3_step() is called from within 
42972     ** a v-table method.
42973     */
42974     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
42975       sqlite3ResetInternalSchema(db, pOp->p1);
42976     }
42977
42978     sqlite3ExpirePreparedStatements(db);
42979     rc = SQLITE_SCHEMA;
42980   }
42981   break;
42982 }
42983
42984 /* Opcode: OpenRead P1 P2 P3 P4 P5
42985 **
42986 ** Open a read-only cursor for the database table whose root page is
42987 ** P2 in a database file.  The database file is determined by P3. 
42988 ** P3==0 means the main database, P3==1 means the database used for 
42989 ** temporary tables, and P3>1 means used the corresponding attached
42990 ** database.  Give the new cursor an identifier of P1.  The P1
42991 ** values need not be contiguous but all P1 values should be small integers.
42992 ** It is an error for P1 to be negative.
42993 **
42994 ** If P5!=0 then use the content of register P2 as the root page, not
42995 ** the value of P2 itself.
42996 **
42997 ** There will be a read lock on the database whenever there is an
42998 ** open cursor.  If the database was unlocked prior to this instruction
42999 ** then a read lock is acquired as part of this instruction.  A read
43000 ** lock allows other processes to read the database but prohibits
43001 ** any other process from modifying the database.  The read lock is
43002 ** released when all cursors are closed.  If this instruction attempts
43003 ** to get a read lock but fails, the script terminates with an
43004 ** SQLITE_BUSY error code.
43005 **
43006 ** The P4 value is a pointer to a KeyInfo structure that defines the
43007 ** content and collating sequence of indices.  P4 is NULL for cursors
43008 ** that are not pointing to indices.
43009 **
43010 ** See also OpenWrite.
43011 */
43012 /* Opcode: OpenWrite P1 P2 P3 P4 P5
43013 **
43014 ** Open a read/write cursor named P1 on the table or index whose root
43015 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
43016 ** root page.
43017 **
43018 ** The P4 value is a pointer to a KeyInfo structure that defines the
43019 ** content and collating sequence of indices.  P4 is NULL for cursors
43020 ** that are not pointing to indices.
43021 **
43022 ** This instruction works just like OpenRead except that it opens the cursor
43023 ** in read/write mode.  For a given table, there can be one or more read-only
43024 ** cursors or a single read/write cursor but not both.
43025 **
43026 ** See also OpenRead.
43027 */
43028 case OP_OpenRead:
43029 case OP_OpenWrite: {
43030   int i = pOp->p1;
43031   int p2 = pOp->p2;
43032   int iDb = pOp->p3;
43033   int wrFlag;
43034   Btree *pX;
43035   Cursor *pCur;
43036   Db *pDb;
43037   
43038   assert( iDb>=0 && iDb<db->nDb );
43039   assert( (p->btreeMask & (1<<iDb))!=0 );
43040   pDb = &db->aDb[iDb];
43041   pX = pDb->pBt;
43042   assert( pX!=0 );
43043   if( pOp->opcode==OP_OpenWrite ){
43044     wrFlag = 1;
43045     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
43046       p->minWriteFileFormat = pDb->pSchema->file_format;
43047     }
43048   }else{
43049     wrFlag = 0;
43050   }
43051   if( pOp->p5 ){
43052     assert( p2>0 );
43053     assert( p2<=p->nMem );
43054     pIn2 = &p->aMem[p2];
43055     sqlite3VdbeMemIntegerify(pIn2);
43056     p2 = pIn2->u.i;
43057     assert( p2>=2 );
43058   }
43059   assert( i>=0 );
43060   pCur = allocateCursor(p, i, iDb);
43061   if( pCur==0 ) goto no_mem;
43062   pCur->nullRow = 1;
43063   /* We always provide a key comparison function.  If the table being
43064   ** opened is of type INTKEY, the comparision function will be ignored. */
43065   rc = sqlite3BtreeCursor(pX, p2, wrFlag,
43066            sqlite3VdbeRecordCompare, pOp->p4.p,
43067            &pCur->pCursor);
43068   if( pOp->p4type==P4_KEYINFO ){
43069     pCur->pKeyInfo = pOp->p4.pKeyInfo;
43070     pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
43071     pCur->pKeyInfo->enc = ENC(p->db);
43072   }else{
43073     pCur->pKeyInfo = 0;
43074     pCur->pIncrKey = &pCur->bogusIncrKey;
43075   }
43076   switch( rc ){
43077     case SQLITE_BUSY: {
43078       p->pc = pc;
43079       p->rc = rc = SQLITE_BUSY;
43080       goto vdbe_return;
43081     }
43082     case SQLITE_OK: {
43083       int flags = sqlite3BtreeFlags(pCur->pCursor);
43084       /* Sanity checking.  Only the lower four bits of the flags byte should
43085       ** be used.  Bit 3 (mask 0x08) is unpreditable.  The lower 3 bits
43086       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
43087       ** 2 (zerodata for indices).  If these conditions are not met it can
43088       ** only mean that we are dealing with a corrupt database file
43089       */
43090       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
43091         rc = SQLITE_CORRUPT_BKPT;
43092         goto abort_due_to_error;
43093       }
43094       pCur->isTable = (flags & BTREE_INTKEY)!=0;
43095       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
43096       /* If P4==0 it means we are expected to open a table.  If P4!=0 then
43097       ** we expect to be opening an index.  If this is not what happened,
43098       ** then the database is corrupt
43099       */
43100       if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
43101        || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
43102         rc = SQLITE_CORRUPT_BKPT;
43103         goto abort_due_to_error;
43104       }
43105       break;
43106     }
43107     case SQLITE_EMPTY: {
43108       pCur->isTable = pOp->p4type!=P4_KEYINFO;
43109       pCur->isIndex = !pCur->isTable;
43110       rc = SQLITE_OK;
43111       break;
43112     }
43113     default: {
43114       goto abort_due_to_error;
43115     }
43116   }
43117   break;
43118 }
43119
43120 /* Opcode: OpenEphemeral P1 P2 * P4 *
43121 **
43122 ** Open a new cursor P1 to a transient table.
43123 ** The cursor is always opened read/write even if 
43124 ** the main database is read-only.  The transient or virtual
43125 ** table is deleted automatically when the cursor is closed.
43126 **
43127 ** P2 is the number of columns in the virtual table.
43128 ** The cursor points to a BTree table if P4==0 and to a BTree index
43129 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
43130 ** that defines the format of keys in the index.
43131 **
43132 ** This opcode was once called OpenTemp.  But that created
43133 ** confusion because the term "temp table", might refer either
43134 ** to a TEMP table at the SQL level, or to a table opened by
43135 ** this opcode.  Then this opcode was call OpenVirtual.  But
43136 ** that created confusion with the whole virtual-table idea.
43137 */
43138 case OP_OpenEphemeral: {
43139   int i = pOp->p1;
43140   Cursor *pCx;
43141   static const int openFlags = 
43142       SQLITE_OPEN_READWRITE |
43143       SQLITE_OPEN_CREATE |
43144       SQLITE_OPEN_EXCLUSIVE |
43145       SQLITE_OPEN_DELETEONCLOSE |
43146       SQLITE_OPEN_TRANSIENT_DB;
43147
43148   assert( i>=0 );
43149   pCx = allocateCursor(p, i, -1);
43150   if( pCx==0 ) goto no_mem;
43151   pCx->nullRow = 1;
43152   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
43153                            &pCx->pBt);
43154   if( rc==SQLITE_OK ){
43155     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
43156   }
43157   if( rc==SQLITE_OK ){
43158     /* If a transient index is required, create it by calling
43159     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
43160     ** opening it. If a transient table is required, just use the
43161     ** automatically created table with root-page 1 (an INTKEY table).
43162     */
43163     if( pOp->p4.pKeyInfo ){
43164       int pgno;
43165       assert( pOp->p4type==P4_KEYINFO );
43166       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
43167       if( rc==SQLITE_OK ){
43168         assert( pgno==MASTER_ROOT+1 );
43169         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
43170             pOp->p4.z, &pCx->pCursor);
43171         pCx->pKeyInfo = pOp->p4.pKeyInfo;
43172         pCx->pKeyInfo->enc = ENC(p->db);
43173         pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
43174       }
43175       pCx->isTable = 0;
43176     }else{
43177       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
43178       pCx->isTable = 1;
43179       pCx->pIncrKey = &pCx->bogusIncrKey;
43180     }
43181   }
43182   pCx->nField = pOp->p2;
43183   pCx->isIndex = !pCx->isTable;
43184   break;
43185 }
43186
43187 /* Opcode: OpenPseudo P1 * * * *
43188 **
43189 ** Open a new cursor that points to a fake table that contains a single
43190 ** row of data.  Any attempt to write a second row of data causes the
43191 ** first row to be deleted.  All data is deleted when the cursor is
43192 ** closed.
43193 **
43194 ** A pseudo-table created by this opcode is useful for holding the
43195 ** NEW or OLD tables in a trigger.  Also used to hold the a single
43196 ** row output from the sorter so that the row can be decomposed into
43197 ** individual columns using the OP_Column opcode.
43198 */
43199 case OP_OpenPseudo: {
43200   int i = pOp->p1;
43201   Cursor *pCx;
43202   assert( i>=0 );
43203   pCx = allocateCursor(p, i, -1);
43204   if( pCx==0 ) goto no_mem;
43205   pCx->nullRow = 1;
43206   pCx->pseudoTable = 1;
43207   pCx->pIncrKey = &pCx->bogusIncrKey;
43208   pCx->isTable = 1;
43209   pCx->isIndex = 0;
43210   break;
43211 }
43212
43213 /* Opcode: Close P1 * * * *
43214 **
43215 ** Close a cursor previously opened as P1.  If P1 is not
43216 ** currently open, this instruction is a no-op.
43217 */
43218 case OP_Close: {
43219   int i = pOp->p1;
43220   assert( i>=0 && i<p->nCursor );
43221   sqlite3VdbeFreeCursor(p, p->apCsr[i]);
43222   p->apCsr[i] = 0;
43223   break;
43224 }
43225
43226 /* Opcode: MoveGe P1 P2 P3 * *
43227 **
43228 ** Use the value in register P3 as a key.  Reposition
43229 ** cursor P1 so that it points to the smallest entry that is greater
43230 ** than or equal to the key in register P3.
43231 ** If there are no records greater than or equal to the key and P2 
43232 ** is not zero, then jump to P2.
43233 **
43234 ** A special feature of this opcode (and different from the
43235 ** related OP_MoveGt, OP_MoveLt, and OP_MoveLe) is that if P2 is
43236 ** zero and P1 is an SQL table (a b-tree with integer keys) then
43237 ** the seek is deferred until it is actually needed.  It might be
43238 ** the case that the cursor is never accessed.  By deferring the
43239 ** seek, we avoid unnecessary seeks.
43240 **
43241 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
43242 */
43243 /* Opcode: MoveGt P1 P2 P3 * *
43244 **
43245 ** Use the value in register P3 as a key.  Reposition
43246 ** cursor P1 so that it points to the smallest entry that is greater
43247 ** than the key in register P3.
43248 ** If there are no records greater than the key 
43249 ** then jump to P2.
43250 **
43251 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
43252 */
43253 /* Opcode: MoveLt P1 P2 P3 * * 
43254 **
43255 ** Use the value in register P3 as a key.  Reposition
43256 ** cursor P1 so that it points to the largest entry that is less
43257 ** than the key in register P3.
43258 ** If there are no records less than the key
43259 ** then jump to P2.
43260 **
43261 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
43262 */
43263 /* Opcode: MoveLe P1 P2 P3 * *
43264 **
43265 ** Use the value in register P3 as a key.  Reposition
43266 ** cursor P1 so that it points to the largest entry that is less than
43267 ** or equal to the key.
43268 ** If there are no records less than or eqal to the key
43269 ** then jump to P2.
43270 **
43271 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
43272 */
43273 case OP_MoveLt:         /* jump, in3 */
43274 case OP_MoveLe:         /* jump, in3 */
43275 case OP_MoveGe:         /* jump, in3 */
43276 case OP_MoveGt: {       /* jump, in3 */
43277   int i = pOp->p1;
43278   Cursor *pC;
43279
43280   assert( i>=0 && i<p->nCursor );
43281   pC = p->apCsr[i];
43282   assert( pC!=0 );
43283   if( pC->pCursor!=0 ){
43284     int res, oc;
43285     oc = pOp->opcode;
43286     pC->nullRow = 0;
43287     *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
43288     if( pC->isTable ){
43289       i64 iKey = sqlite3VdbeIntValue(pIn3);
43290       if( pOp->p2==0 ){
43291         assert( pOp->opcode==OP_MoveGe );
43292         pC->movetoTarget = iKey;
43293         pC->rowidIsValid = 0;
43294         pC->deferredMoveto = 1;
43295         break;
43296       }
43297       rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
43298       if( rc!=SQLITE_OK ){
43299         goto abort_due_to_error;
43300       }
43301       pC->lastRowid = iKey;
43302       pC->rowidIsValid = res==0;
43303     }else{
43304       assert( pIn3->flags & MEM_Blob );
43305       ExpandBlob(pIn3);
43306       rc = sqlite3BtreeMoveto(pC->pCursor, pIn3->z, pIn3->n, 0, &res);
43307       if( rc!=SQLITE_OK ){
43308         goto abort_due_to_error;
43309       }
43310       pC->rowidIsValid = 0;
43311     }
43312     pC->deferredMoveto = 0;
43313     pC->cacheStatus = CACHE_STALE;
43314     *pC->pIncrKey = 0;
43315 #ifdef SQLITE_TEST
43316     sqlite3_search_count++;
43317 #endif
43318     if( oc==OP_MoveGe || oc==OP_MoveGt ){
43319       if( res<0 ){
43320         rc = sqlite3BtreeNext(pC->pCursor, &res);
43321         if( rc!=SQLITE_OK ) goto abort_due_to_error;
43322         pC->rowidIsValid = 0;
43323       }else{
43324         res = 0;
43325       }
43326     }else{
43327       assert( oc==OP_MoveLt || oc==OP_MoveLe );
43328       if( res>=0 ){
43329         rc = sqlite3BtreePrevious(pC->pCursor, &res);
43330         if( rc!=SQLITE_OK ) goto abort_due_to_error;
43331         pC->rowidIsValid = 0;
43332       }else{
43333         /* res might be negative because the table is empty.  Check to
43334         ** see if this is the case.
43335         */
43336         res = sqlite3BtreeEof(pC->pCursor);
43337       }
43338     }
43339     assert( pOp->p2>0 );
43340     if( res ){
43341       pc = pOp->p2 - 1;
43342     }
43343   }
43344   break;
43345 }
43346
43347 /* Opcode: Found P1 P2 P3 * *
43348 **
43349 ** Register P3 holds a blob constructed by MakeRecord.  P1 is an index.
43350 ** If an entry that matches the value in register p3 exists in P1 then
43351 ** jump to P2.  If the P3 value does not match any entry in P1
43352 ** then fall thru.  The P1 cursor is left pointing at the matching entry
43353 ** if it exists.
43354 **
43355 ** This instruction is used to implement the IN operator where the
43356 ** left-hand side is a SELECT statement.  P1 may be a true index, or it
43357 ** may be a temporary index that holds the results of the SELECT
43358 ** statement.   This instruction is also used to implement the
43359 ** DISTINCT keyword in SELECT statements.
43360 **
43361 ** This instruction checks if index P1 contains a record for which 
43362 ** the first N serialised values exactly match the N serialised values
43363 ** in the record in register P3, where N is the total number of values in
43364 ** the P3 record (the P3 record is a prefix of the P1 record). 
43365 **
43366 ** See also: NotFound, MoveTo, IsUnique, NotExists
43367 */
43368 /* Opcode: NotFound P1 P2 P3 * *
43369 **
43370 ** Register P3 holds a blob constructed by MakeRecord.  P1 is
43371 ** an index.  If no entry exists in P1 that matches the blob then jump
43372 ** to P2.  If an entry does existing, fall through.  The cursor is left
43373 ** pointing to the entry that matches.
43374 **
43375 ** See also: Found, MoveTo, NotExists, IsUnique
43376 */
43377 case OP_NotFound:       /* jump, in3 */
43378 case OP_Found: {        /* jump, in3 */
43379   int i = pOp->p1;
43380   int alreadyExists = 0;
43381   Cursor *pC;
43382   assert( i>=0 && i<p->nCursor );
43383   assert( p->apCsr[i]!=0 );
43384   if( (pC = p->apCsr[i])->pCursor!=0 ){
43385     int res;
43386     assert( pC->isTable==0 );
43387     assert( pIn3->flags & MEM_Blob );
43388     if( pOp->opcode==OP_Found ){
43389       pC->pKeyInfo->prefixIsEqual = 1;
43390     }
43391     rc = sqlite3BtreeMoveto(pC->pCursor, pIn3->z, pIn3->n, 0, &res);
43392     pC->pKeyInfo->prefixIsEqual = 0;
43393     if( rc!=SQLITE_OK ){
43394       break;
43395     }
43396     alreadyExists = (res==0);
43397     pC->deferredMoveto = 0;
43398     pC->cacheStatus = CACHE_STALE;
43399   }
43400   if( pOp->opcode==OP_Found ){
43401     if( alreadyExists ) pc = pOp->p2 - 1;
43402   }else{
43403     if( !alreadyExists ) pc = pOp->p2 - 1;
43404   }
43405   break;
43406 }
43407
43408 /* Opcode: IsUnique P1 P2 P3 P4 *
43409 **
43410 ** The P3 register contains an integer record number.  Call this
43411 ** record number R.  The P4 register contains an index key created
43412 ** using MakeIdxRec.  Call it K.
43413 **
43414 ** P1 is an index.  So it has no data and its key consists of a
43415 ** record generated by OP_MakeRecord where the last field is the 
43416 ** rowid of the entry that the index refers to.
43417 ** 
43418 ** This instruction asks if there is an entry in P1 where the
43419 ** fields matches K but the rowid is different from R.
43420 ** If there is no such entry, then there is an immediate
43421 ** jump to P2.  If any entry does exist where the index string
43422 ** matches K but the record number is not R, then the record
43423 ** number for that entry is written into P3 and control
43424 ** falls through to the next instruction.
43425 **
43426 ** See also: NotFound, NotExists, Found
43427 */
43428 case OP_IsUnique: {        /* jump, in3 */
43429   int i = pOp->p1;
43430   Cursor *pCx;
43431   BtCursor *pCrsr;
43432   Mem *pK;
43433   i64 R;
43434
43435   /* Pop the value R off the top of the stack
43436   */
43437   assert( pOp->p4type==P4_INT32 );
43438   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
43439   pK = &p->aMem[pOp->p4.i];
43440   sqlite3VdbeMemIntegerify(pIn3);
43441   R = pIn3->u.i;
43442   assert( i>=0 && i<p->nCursor );
43443   pCx = p->apCsr[i];
43444   assert( pCx!=0 );
43445   pCrsr = pCx->pCursor;
43446   if( pCrsr!=0 ){
43447     int res;
43448     i64 v;         /* The record number on the P1 entry that matches K */
43449     char *zKey;    /* The value of K */
43450     int nKey;      /* Number of bytes in K */
43451     int len;       /* Number of bytes in K without the rowid at the end */
43452     int szRowid;   /* Size of the rowid column at the end of zKey */
43453
43454     /* Make sure K is a string and make zKey point to K
43455     */
43456     assert( pK->flags & MEM_Blob );
43457     zKey = pK->z;
43458     nKey = pK->n;
43459
43460     szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
43461     len = nKey-szRowid;
43462
43463     /* Search for an entry in P1 where all but the last four bytes match K.
43464     ** If there is no such entry, jump immediately to P2.
43465     */
43466     assert( pCx->deferredMoveto==0 );
43467     pCx->cacheStatus = CACHE_STALE;
43468     rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
43469     if( rc!=SQLITE_OK ){
43470       goto abort_due_to_error;
43471     }
43472     if( res<0 ){
43473       rc = sqlite3BtreeNext(pCrsr, &res);
43474       if( res ){
43475         pc = pOp->p2 - 1;
43476         break;
43477       }
43478     }
43479     rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res); 
43480     if( rc!=SQLITE_OK ) goto abort_due_to_error;
43481     if( res>0 ){
43482       pc = pOp->p2 - 1;
43483       break;
43484     }
43485
43486     /* At this point, pCrsr is pointing to an entry in P1 where all but
43487     ** the final entry (the rowid) matches K.  Check to see if the
43488     ** final rowid column is different from R.  If it equals R then jump
43489     ** immediately to P2.
43490     */
43491     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
43492     if( rc!=SQLITE_OK ){
43493       goto abort_due_to_error;
43494     }
43495     if( v==R ){
43496       pc = pOp->p2 - 1;
43497       break;
43498     }
43499
43500     /* The final varint of the key is different from R.  Store it back
43501     ** into register R3.  (The record number of an entry that violates
43502     ** a UNIQUE constraint.)
43503     */
43504     pIn3->u.i = v;
43505     assert( pIn3->flags&MEM_Int );
43506   }
43507   break;
43508 }
43509
43510 /* Opcode: NotExists P1 P2 P3 * *
43511 **
43512 ** Use the content of register P3 as a integer key.  If a record 
43513 ** with that key does not exist in table of P1, then jump to P2. 
43514 ** If the record does exist, then fall thru.  The cursor is left 
43515 ** pointing to the record if it exists.
43516 **
43517 ** The difference between this operation and NotFound is that this
43518 ** operation assumes the key is an integer and that P1 is a table whereas
43519 ** NotFound assumes key is a blob constructed from MakeRecord and
43520 ** P1 is an index.
43521 **
43522 ** See also: Found, MoveTo, NotFound, IsUnique
43523 */
43524 case OP_NotExists: {        /* jump, in3 */
43525   int i = pOp->p1;
43526   Cursor *pC;
43527   BtCursor *pCrsr;
43528   assert( i>=0 && i<p->nCursor );
43529   assert( p->apCsr[i]!=0 );
43530   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
43531     int res;
43532     u64 iKey;
43533     assert( pIn3->flags & MEM_Int );
43534     assert( p->apCsr[i]->isTable );
43535     iKey = intToKey(pIn3->u.i);
43536     rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
43537     pC->lastRowid = pIn3->u.i;
43538     pC->rowidIsValid = res==0;
43539     pC->nullRow = 0;
43540     pC->cacheStatus = CACHE_STALE;
43541     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
43542     ** processing is about to abort so we really do not care whether or not
43543     ** the following jump is taken.  (In other words, do not stress over
43544     ** the error that valgrind sometimes shows on the next statement when
43545     ** running ioerr.test and similar failure-recovery test scripts.) */
43546     if( res!=0 ){
43547       pc = pOp->p2 - 1;
43548       assert( pC->rowidIsValid==0 );
43549     }
43550   }
43551   break;
43552 }
43553
43554 /* Opcode: Sequence P1 P2 * * *
43555 **
43556 ** Find the next available sequence number for cursor P1.
43557 ** Write the sequence number into register P2.
43558 ** The sequence number on the cursor is incremented after this
43559 ** instruction.  
43560 */
43561 case OP_Sequence: {           /* out2-prerelease */
43562   int i = pOp->p1;
43563   assert( i>=0 && i<p->nCursor );
43564   assert( p->apCsr[i]!=0 );
43565   pOut->u.i = p->apCsr[i]->seqCount++;
43566   MemSetTypeFlag(pOut, MEM_Int);
43567   break;
43568 }
43569
43570
43571 /* Opcode: NewRowid P1 P2 P3 * *
43572 **
43573 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
43574 ** The record number is not previously used as a key in the database
43575 ** table that cursor P1 points to.  The new record number is written
43576 ** written to register P2.
43577 **
43578 ** If P3>0 then P3 is a register that holds the largest previously
43579 ** generated record number.  No new record numbers are allowed to be less
43580 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
43581 ** error is generated.  The P3 register is updated with the generated
43582 ** record number.  This P3 mechanism is used to help implement the
43583 ** AUTOINCREMENT feature.
43584 */
43585 case OP_NewRowid: {           /* out2-prerelease */
43586   int i = pOp->p1;
43587   i64 v = 0;
43588   Cursor *pC;
43589   assert( i>=0 && i<p->nCursor );
43590   assert( p->apCsr[i]!=0 );
43591   if( (pC = p->apCsr[i])->pCursor==0 ){
43592     /* The zero initialization above is all that is needed */
43593   }else{
43594     /* The next rowid or record number (different terms for the same
43595     ** thing) is obtained in a two-step algorithm.
43596     **
43597     ** First we attempt to find the largest existing rowid and add one
43598     ** to that.  But if the largest existing rowid is already the maximum
43599     ** positive integer, we have to fall through to the second
43600     ** probabilistic algorithm
43601     **
43602     ** The second algorithm is to select a rowid at random and see if
43603     ** it already exists in the table.  If it does not exist, we have
43604     ** succeeded.  If the random rowid does exist, we select a new one
43605     ** and try again, up to 1000 times.
43606     **
43607     ** For a table with less than 2 billion entries, the probability
43608     ** of not finding a unused rowid is about 1.0e-300.  This is a 
43609     ** non-zero probability, but it is still vanishingly small and should
43610     ** never cause a problem.  You are much, much more likely to have a
43611     ** hardware failure than for this algorithm to fail.
43612     **
43613     ** The analysis in the previous paragraph assumes that you have a good
43614     ** source of random numbers.  Is a library function like lrand48()
43615     ** good enough?  Maybe. Maybe not. It's hard to know whether there
43616     ** might be subtle bugs is some implementations of lrand48() that
43617     ** could cause problems. To avoid uncertainty, SQLite uses its own 
43618     ** random number generator based on the RC4 algorithm.
43619     **
43620     ** To promote locality of reference for repetitive inserts, the
43621     ** first few attempts at chosing a random rowid pick values just a little
43622     ** larger than the previous rowid.  This has been shown experimentally
43623     ** to double the speed of the COPY operation.
43624     */
43625     int res, rx=SQLITE_OK, cnt;
43626     i64 x;
43627     cnt = 0;
43628     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
43629           BTREE_INTKEY ){
43630       rc = SQLITE_CORRUPT_BKPT;
43631       goto abort_due_to_error;
43632     }
43633     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
43634     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
43635
43636 #ifdef SQLITE_32BIT_ROWID
43637 #   define MAX_ROWID 0x7fffffff
43638 #else
43639     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
43640     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
43641     ** to provide the constant while making all compilers happy.
43642     */
43643 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
43644 #endif
43645
43646     if( !pC->useRandomRowid ){
43647       if( pC->nextRowidValid ){
43648         v = pC->nextRowid;
43649       }else{
43650         rc = sqlite3BtreeLast(pC->pCursor, &res);
43651         if( rc!=SQLITE_OK ){
43652           goto abort_due_to_error;
43653         }
43654         if( res ){
43655           v = 1;
43656         }else{
43657           sqlite3BtreeKeySize(pC->pCursor, &v);
43658           v = keyToInt(v);
43659           if( v==MAX_ROWID ){
43660             pC->useRandomRowid = 1;
43661           }else{
43662             v++;
43663           }
43664         }
43665       }
43666
43667 #ifndef SQLITE_OMIT_AUTOINCREMENT
43668       if( pOp->p3 ){
43669         Mem *pMem;
43670         assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
43671         pMem = &p->aMem[pOp->p3];
43672         REGISTER_TRACE(pOp->p3, pMem);
43673         sqlite3VdbeMemIntegerify(pMem);
43674         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
43675         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
43676           rc = SQLITE_FULL;
43677           goto abort_due_to_error;
43678         }
43679         if( v<pMem->u.i+1 ){
43680           v = pMem->u.i + 1;
43681         }
43682         pMem->u.i = v;
43683       }
43684 #endif
43685
43686       if( v<MAX_ROWID ){
43687         pC->nextRowidValid = 1;
43688         pC->nextRowid = v+1;
43689       }else{
43690         pC->nextRowidValid = 0;
43691       }
43692     }
43693     if( pC->useRandomRowid ){
43694       assert( pOp->p3==0 );  /* SQLITE_FULL must have occurred prior to this */
43695       v = db->priorNewRowid;
43696       cnt = 0;
43697       do{
43698         if( cnt==0 && (v&0xffffff)==v ){
43699           v++;
43700         }else{
43701           sqlite3Randomness(sizeof(v), &v);
43702           if( cnt<5 ) v &= 0xffffff;
43703         }
43704         if( v==0 ) continue;
43705         x = intToKey(v);
43706         rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
43707         cnt++;
43708       }while( cnt<100 && rx==SQLITE_OK && res==0 );
43709       db->priorNewRowid = v;
43710       if( rx==SQLITE_OK && res==0 ){
43711         rc = SQLITE_FULL;
43712         goto abort_due_to_error;
43713       }
43714     }
43715     pC->rowidIsValid = 0;
43716     pC->deferredMoveto = 0;
43717     pC->cacheStatus = CACHE_STALE;
43718   }
43719   MemSetTypeFlag(pOut, MEM_Int);
43720   pOut->u.i = v;
43721   break;
43722 }
43723
43724 /* Opcode: Insert P1 P2 P3 P4 P5
43725 **
43726 ** Write an entry into the table of cursor P1.  A new entry is
43727 ** created if it doesn't already exist or the data for an existing
43728 ** entry is overwritten.  The data is the value stored register
43729 ** number P2. The key is stored in register P3. The key must
43730 ** be an integer.
43731 **
43732 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
43733 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
43734 ** then rowid is stored for subsequent return by the
43735 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
43736 **
43737 ** Parameter P4 may point to a string containing the table-name, or
43738 ** may be NULL. If it is not NULL, then the update-hook 
43739 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
43740 **
43741 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
43742 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
43743 ** and register P2 becomes ephemeral.  If the cursor is changed, the
43744 ** value of register P2 will then change.  Make sure this does not
43745 ** cause any problems.)
43746 **
43747 ** This instruction only works on tables.  The equivalent instruction
43748 ** for indices is OP_IdxInsert.
43749 */
43750 case OP_Insert: {
43751   Mem *pData = &p->aMem[pOp->p2];
43752   Mem *pKey = &p->aMem[pOp->p3];
43753
43754   i64 iKey;   /* The integer ROWID or key for the record to be inserted */
43755   int i = pOp->p1;
43756   Cursor *pC;
43757   assert( i>=0 && i<p->nCursor );
43758   pC = p->apCsr[i];
43759   assert( pC!=0 );
43760   assert( pC->pCursor!=0 || pC->pseudoTable );
43761   assert( pKey->flags & MEM_Int );
43762   assert( pC->isTable );
43763   REGISTER_TRACE(pOp->p2, pData);
43764   REGISTER_TRACE(pOp->p3, pKey);
43765
43766   iKey = intToKey(pKey->u.i);
43767   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
43768   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
43769   if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
43770     pC->nextRowidValid = 0;
43771   }
43772   if( pData->flags & MEM_Null ){
43773     pData->z = 0;
43774     pData->n = 0;
43775   }else{
43776     assert( pData->flags & (MEM_Blob|MEM_Str) );
43777   }
43778   if( pC->pseudoTable ){
43779     sqlite3_free(pC->pData);
43780     pC->iKey = iKey;
43781     pC->nData = pData->n;
43782     if( pData->flags & MEM_Dyn ){
43783       pC->pData = pData->z;
43784       pData->flags &= ~MEM_Dyn;
43785       pData->flags |= MEM_Ephem;
43786     }else{
43787       pC->pData = sqlite3_malloc( pC->nData+2 );
43788       if( !pC->pData ) goto no_mem;
43789       memcpy(pC->pData, pData->z, pC->nData);
43790       pC->pData[pC->nData] = 0;
43791       pC->pData[pC->nData+1] = 0;
43792     }
43793     pC->nullRow = 0;
43794   }else{
43795     int nZero;
43796     if( pData->flags & MEM_Zero ){
43797       nZero = pData->u.i;
43798     }else{
43799       nZero = 0;
43800     }
43801     rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
43802                             pData->z, pData->n, nZero,
43803                             pOp->p5 & OPFLAG_APPEND);
43804   }
43805   
43806   pC->rowidIsValid = 0;
43807   pC->deferredMoveto = 0;
43808   pC->cacheStatus = CACHE_STALE;
43809
43810   /* Invoke the update-hook if required. */
43811   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
43812     const char *zDb = db->aDb[pC->iDb].zName;
43813     const char *zTbl = pOp->p4.z;
43814     int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
43815     assert( pC->isTable );
43816     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
43817     assert( pC->iDb>=0 );
43818   }
43819   break;
43820 }
43821
43822 /* Opcode: Delete P1 P2 * P4 *
43823 **
43824 ** Delete the record at which the P1 cursor is currently pointing.
43825 **
43826 ** The cursor will be left pointing at either the next or the previous
43827 ** record in the table. If it is left pointing at the next record, then
43828 ** the next Next instruction will be a no-op.  Hence it is OK to delete
43829 ** a record from within an Next loop.
43830 **
43831 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
43832 ** incremented (otherwise not).
43833 **
43834 ** P1 must not be pseudo-table.  It has to be a real table with
43835 ** multiple rows.
43836 **
43837 ** If P4 is not NULL, then it is the name of the table that P1 is
43838 ** pointing to.  The update hook will be invoked, if it exists.
43839 ** If P4 is not NULL then the P1 cursor must have been positioned
43840 ** using OP_NotFound prior to invoking this opcode.
43841 */
43842 case OP_Delete: {
43843   int i = pOp->p1;
43844   i64 iKey;
43845   Cursor *pC;
43846
43847   assert( i>=0 && i<p->nCursor );
43848   pC = p->apCsr[i];
43849   assert( pC!=0 );
43850   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
43851
43852   /* If the update-hook will be invoked, set iKey to the rowid of the
43853   ** row being deleted.
43854   */
43855   if( db->xUpdateCallback && pOp->p4.z ){
43856     assert( pC->isTable );
43857     assert( pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
43858     iKey = pC->lastRowid;
43859   }
43860
43861   rc = sqlite3VdbeCursorMoveto(pC);
43862   if( rc ) goto abort_due_to_error;
43863   rc = sqlite3BtreeDelete(pC->pCursor);
43864   pC->nextRowidValid = 0;
43865   pC->cacheStatus = CACHE_STALE;
43866
43867   /* Invoke the update-hook if required. */
43868   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
43869     const char *zDb = db->aDb[pC->iDb].zName;
43870     const char *zTbl = pOp->p4.z;
43871     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
43872     assert( pC->iDb>=0 );
43873   }
43874   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
43875   break;
43876 }
43877
43878 /* Opcode: ResetCount P1 * *
43879 **
43880 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
43881 ** then the value of the change counter is copied to the database handle
43882 ** change counter (returned by subsequent calls to sqlite3_changes())
43883 ** before it is reset. This is used by trigger programs.
43884 */
43885 case OP_ResetCount: {
43886   if( pOp->p1 ){
43887     sqlite3VdbeSetChanges(db, p->nChange);
43888   }
43889   p->nChange = 0;
43890   break;
43891 }
43892
43893 /* Opcode: RowData P1 P2 * * *
43894 **
43895 ** Write into register P2 the complete row data for cursor P1.
43896 ** There is no interpretation of the data.  
43897 ** It is just copied onto the P2 register exactly as 
43898 ** it is found in the database file.
43899 **
43900 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
43901 ** of a real table, not a pseudo-table.
43902 */
43903 /* Opcode: RowKey P1 P2 * * *
43904 **
43905 ** Write into register P2 the complete row key for cursor P1.
43906 ** There is no interpretation of the data.  
43907 ** The key is copied onto the P3 register exactly as 
43908 ** it is found in the database file.
43909 **
43910 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
43911 ** of a real table, not a pseudo-table.
43912 */
43913 case OP_RowKey:
43914 case OP_RowData: {
43915   int i = pOp->p1;
43916   Cursor *pC;
43917   BtCursor *pCrsr;
43918   u32 n;
43919
43920   pOut = &p->aMem[pOp->p2];
43921
43922   /* Note that RowKey and RowData are really exactly the same instruction */
43923   assert( i>=0 && i<p->nCursor );
43924   pC = p->apCsr[i];
43925   assert( pC->isTable || pOp->opcode==OP_RowKey );
43926   assert( pC->isIndex || pOp->opcode==OP_RowData );
43927   assert( pC!=0 );
43928   assert( pC->nullRow==0 );
43929   assert( pC->pseudoTable==0 );
43930   assert( pC->pCursor!=0 );
43931   pCrsr = pC->pCursor;
43932   rc = sqlite3VdbeCursorMoveto(pC);
43933   if( rc ) goto abort_due_to_error;
43934   if( pC->isIndex ){
43935     i64 n64;
43936     assert( !pC->isTable );
43937     sqlite3BtreeKeySize(pCrsr, &n64);
43938     if( n64>SQLITE_MAX_LENGTH ){
43939       goto too_big;
43940     }
43941     n = n64;
43942   }else{
43943     sqlite3BtreeDataSize(pCrsr, &n);
43944     if( n>SQLITE_MAX_LENGTH ){
43945       goto too_big;
43946     }
43947   }
43948   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
43949     goto no_mem;
43950   }
43951   pOut->n = n;
43952   MemSetTypeFlag(pOut, MEM_Blob);
43953   if( pC->isIndex ){
43954     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
43955   }else{
43956     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
43957   }
43958   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
43959   UPDATE_MAX_BLOBSIZE(pOut);
43960   break;
43961 }
43962
43963 /* Opcode: Rowid P1 P2 * * *
43964 **
43965 ** Store in register P2 an integer which is the key of the table entry that
43966 ** P1 is currently point to.  If p2==0 then push the integer.
43967 */
43968 case OP_Rowid: {                 /* out2-prerelease */
43969   int i = pOp->p1;
43970   Cursor *pC;
43971   i64 v;
43972
43973   assert( i>=0 && i<p->nCursor );
43974   pC = p->apCsr[i];
43975   assert( pC!=0 );
43976   rc = sqlite3VdbeCursorMoveto(pC);
43977   if( rc ) goto abort_due_to_error;
43978   if( pC->rowidIsValid ){
43979     v = pC->lastRowid;
43980   }else if( pC->pseudoTable ){
43981     v = keyToInt(pC->iKey);
43982   }else if( pC->nullRow ){
43983     /* Leave the rowid set to a NULL */
43984     break;
43985   }else{
43986     assert( pC->pCursor!=0 );
43987     sqlite3BtreeKeySize(pC->pCursor, &v);
43988     v = keyToInt(v);
43989   }
43990   pOut->u.i = v;
43991   MemSetTypeFlag(pOut, MEM_Int);
43992   break;
43993 }
43994
43995 /* Opcode: NullRow P1 * * * *
43996 **
43997 ** Move the cursor P1 to a null row.  Any OP_Column operations
43998 ** that occur while the cursor is on the null row will always
43999 ** write a NULL.
44000 */
44001 case OP_NullRow: {
44002   int i = pOp->p1;
44003   Cursor *pC;
44004
44005   assert( i>=0 && i<p->nCursor );
44006   pC = p->apCsr[i];
44007   assert( pC!=0 );
44008   pC->nullRow = 1;
44009   pC->rowidIsValid = 0;
44010   break;
44011 }
44012
44013 /* Opcode: Last P1 P2 * * *
44014 **
44015 ** The next use of the Rowid or Column or Next instruction for P1 
44016 ** will refer to the last entry in the database table or index.
44017 ** If the table or index is empty and P2>0, then jump immediately to P2.
44018 ** If P2 is 0 or if the table or index is not empty, fall through
44019 ** to the following instruction.
44020 */
44021 case OP_Last: {        /* jump */
44022   int i = pOp->p1;
44023   Cursor *pC;
44024   BtCursor *pCrsr;
44025   int res;
44026
44027   assert( i>=0 && i<p->nCursor );
44028   pC = p->apCsr[i];
44029   assert( pC!=0 );
44030   pCrsr = pC->pCursor;
44031   assert( pCrsr!=0 );
44032   rc = sqlite3BtreeLast(pCrsr, &res);
44033   pC->nullRow = res;
44034   pC->deferredMoveto = 0;
44035   pC->cacheStatus = CACHE_STALE;
44036   if( res && pOp->p2>0 ){
44037     pc = pOp->p2 - 1;
44038   }
44039   break;
44040 }
44041
44042
44043 /* Opcode: Sort P1 P2 * * *
44044 **
44045 ** This opcode does exactly the same thing as OP_Rewind except that
44046 ** it increments an undocumented global variable used for testing.
44047 **
44048 ** Sorting is accomplished by writing records into a sorting index,
44049 ** then rewinding that index and playing it back from beginning to
44050 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
44051 ** rewinding so that the global variable will be incremented and
44052 ** regression tests can determine whether or not the optimizer is
44053 ** correctly optimizing out sorts.
44054 */
44055 case OP_Sort: {        /* jump */
44056 #ifdef SQLITE_TEST
44057   sqlite3_sort_count++;
44058   sqlite3_search_count--;
44059 #endif
44060   /* Fall through into OP_Rewind */
44061 }
44062 /* Opcode: Rewind P1 P2 * * *
44063 **
44064 ** The next use of the Rowid or Column or Next instruction for P1 
44065 ** will refer to the first entry in the database table or index.
44066 ** If the table or index is empty and P2>0, then jump immediately to P2.
44067 ** If P2 is 0 or if the table or index is not empty, fall through
44068 ** to the following instruction.
44069 */
44070 case OP_Rewind: {        /* jump */
44071   int i = pOp->p1;
44072   Cursor *pC;
44073   BtCursor *pCrsr;
44074   int res;
44075
44076   assert( i>=0 && i<p->nCursor );
44077   pC = p->apCsr[i];
44078   assert( pC!=0 );
44079   if( (pCrsr = pC->pCursor)!=0 ){
44080     rc = sqlite3BtreeFirst(pCrsr, &res);
44081     pC->atFirst = res==0;
44082     pC->deferredMoveto = 0;
44083     pC->cacheStatus = CACHE_STALE;
44084   }else{
44085     res = 1;
44086   }
44087   pC->nullRow = res;
44088   assert( pOp->p2>0 && pOp->p2<p->nOp );
44089   if( res ){
44090     pc = pOp->p2 - 1;
44091   }
44092   break;
44093 }
44094
44095 /* Opcode: Next P1 P2 * * *
44096 **
44097 ** Advance cursor P1 so that it points to the next key/data pair in its
44098 ** table or index.  If there are no more key/value pairs then fall through
44099 ** to the following instruction.  But if the cursor advance was successful,
44100 ** jump immediately to P2.
44101 **
44102 ** The P1 cursor must be for a real table, not a pseudo-table.
44103 **
44104 ** See also: Prev
44105 */
44106 /* Opcode: Prev P1 P2 * * *
44107 **
44108 ** Back up cursor P1 so that it points to the previous key/data pair in its
44109 ** table or index.  If there is no previous key/value pairs then fall through
44110 ** to the following instruction.  But if the cursor backup was successful,
44111 ** jump immediately to P2.
44112 **
44113 ** The P1 cursor must be for a real table, not a pseudo-table.
44114 */
44115 case OP_Prev:          /* jump */
44116 case OP_Next: {        /* jump */
44117   Cursor *pC;
44118   BtCursor *pCrsr;
44119
44120   CHECK_FOR_INTERRUPT;
44121   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
44122   pC = p->apCsr[pOp->p1];
44123   if( pC==0 ){
44124     break;  /* See ticket #2273 */
44125   }
44126   pCrsr = pC->pCursor;
44127   assert( pCrsr );
44128   if( pC->nullRow==0 ){
44129     int res = 1;
44130     assert( pC->deferredMoveto==0 );
44131     rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
44132                                 sqlite3BtreePrevious(pCrsr, &res);
44133     pC->nullRow = res;
44134     pC->cacheStatus = CACHE_STALE;
44135     if( res==0 ){
44136       pc = pOp->p2 - 1;
44137 #ifdef SQLITE_TEST
44138       sqlite3_search_count++;
44139 #endif
44140     }
44141   }
44142   pC->rowidIsValid = 0;
44143   break;
44144 }
44145
44146 /* Opcode: IdxInsert P1 P2 P3 * *
44147 **
44148 ** Register P2 holds a SQL index key made using the
44149 ** MakeIdxRec instructions.  This opcode writes that key
44150 ** into the index P1.  Data for the entry is nil.
44151 **
44152 ** P3 is a flag that provides a hint to the b-tree layer that this
44153 ** insert is likely to be an append.
44154 **
44155 ** This instruction only works for indices.  The equivalent instruction
44156 ** for tables is OP_Insert.
44157 */
44158 case OP_IdxInsert: {        /* in2 */
44159   int i = pOp->p1;
44160   Cursor *pC;
44161   BtCursor *pCrsr;
44162   assert( i>=0 && i<p->nCursor );
44163   assert( p->apCsr[i]!=0 );
44164   assert( pIn2->flags & MEM_Blob );
44165   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
44166     assert( pC->isTable==0 );
44167     rc = ExpandBlob(pIn2);
44168     if( rc==SQLITE_OK ){
44169       int nKey = pIn2->n;
44170       const char *zKey = pIn2->z;
44171       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
44172       assert( pC->deferredMoveto==0 );
44173       pC->cacheStatus = CACHE_STALE;
44174     }
44175   }
44176   break;
44177 }
44178
44179 /* Opcode: IdxDelete P1 P2 * * *
44180 **
44181 ** The content of register P2 is an index key built using the 
44182 ** MakeIdxRec opcode. This opcode removes that entry from the 
44183 ** index opened by cursor P1.
44184 */
44185 case OP_IdxDelete: {        /* in2 */
44186   int i = pOp->p1;
44187   Cursor *pC;
44188   BtCursor *pCrsr;
44189   assert( pIn2->flags & MEM_Blob );
44190   assert( i>=0 && i<p->nCursor );
44191   assert( p->apCsr[i]!=0 );
44192   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
44193     int res;
44194     rc = sqlite3BtreeMoveto(pCrsr, pIn2->z, pIn2->n, 0, &res);
44195     if( rc==SQLITE_OK && res==0 ){
44196       rc = sqlite3BtreeDelete(pCrsr);
44197     }
44198     assert( pC->deferredMoveto==0 );
44199     pC->cacheStatus = CACHE_STALE;
44200   }
44201   break;
44202 }
44203
44204 /* Opcode: IdxRowid P1 P2 * * *
44205 **
44206 ** Write into register P2 an integer which is the last entry in the record at
44207 ** the end of the index key pointed to by cursor P1.  This integer should be
44208 ** the rowid of the table entry to which this index entry points.
44209 **
44210 ** See also: Rowid, MakeIdxRec.
44211 */
44212 case OP_IdxRowid: {              /* out2-prerelease */
44213   int i = pOp->p1;
44214   BtCursor *pCrsr;
44215   Cursor *pC;
44216
44217   assert( i>=0 && i<p->nCursor );
44218   assert( p->apCsr[i]!=0 );
44219   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
44220     i64 rowid;
44221
44222     assert( pC->deferredMoveto==0 );
44223     assert( pC->isTable==0 );
44224     if( !pC->nullRow ){
44225       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
44226       if( rc!=SQLITE_OK ){
44227         goto abort_due_to_error;
44228       }
44229       MemSetTypeFlag(pOut, MEM_Int);
44230       pOut->u.i = rowid;
44231     }
44232   }
44233   break;
44234 }
44235
44236 /* Opcode: IdxGE P1 P2 P3 * P5
44237 **
44238 ** The value in register P3 is an index entry that omits the ROWID.  Compare
44239 ** this value against the index that P1 is currently pointing to.
44240 ** Ignore the ROWID on the P1 index.
44241 **
44242 ** If the P1 index entry is greater than or equal to the value in 
44243 ** register P3 then jump to P2.  Otherwise fall through to the next 
44244 ** instruction.
44245 **
44246 ** If P5 is non-zero then the value in register P3 is temporarily
44247 ** increased by an epsilon prior to the comparison.  This make the opcode work
44248 ** like IdxGT except that if the key from register P3 is a prefix of
44249 ** the key in the cursor, the result is false whereas it would be
44250 ** true with IdxGT.
44251 */
44252 /* Opcode: IdxLT P1 P2 P3 * P5
44253 **
44254 ** The value in register P3 is an index entry that omits the ROWID.  Compare
44255 ** the this value against the index that P1 is currently pointing to.
44256 ** Ignore the ROWID on the P1 index.
44257 **
44258 ** If the P1 index entry is less than the register P3 value
44259 ** then jump to P2.  Otherwise fall through to the next instruction.
44260 **
44261 ** If P5 is non-zero then the
44262 ** index taken from register P3 is temporarily increased by
44263 ** an epsilon prior to the comparison.  This makes the opcode work
44264 ** like IdxLE.
44265 */
44266 case OP_IdxLT:          /* jump, in3 */
44267 case OP_IdxGE: {        /* jump, in3 */
44268   int i= pOp->p1;
44269   Cursor *pC;
44270
44271   assert( i>=0 && i<p->nCursor );
44272   assert( p->apCsr[i]!=0 );
44273   if( (pC = p->apCsr[i])->pCursor!=0 ){
44274     int res;
44275  
44276     assert( pIn3->flags & MEM_Blob );  /* Created using OP_MakeRecord */
44277     assert( pC->deferredMoveto==0 );
44278     ExpandBlob(pIn3);
44279     assert( pOp->p5==0 || pOp->p5==1 );
44280     *pC->pIncrKey = pOp->p5;
44281     rc = sqlite3VdbeIdxKeyCompare(pC, pIn3->n, (u8*)pIn3->z, &res);
44282     *pC->pIncrKey = 0;
44283     if( rc!=SQLITE_OK ){
44284       break;
44285     }
44286     if( pOp->opcode==OP_IdxLT ){
44287       res = -res;
44288     }else{
44289       assert( pOp->opcode==OP_IdxGE );
44290       res++;
44291     }
44292     if( res>0 ){
44293       pc = pOp->p2 - 1 ;
44294     }
44295   }
44296   break;
44297 }
44298
44299 /* Opcode: Destroy P1 P2 P3 * *
44300 **
44301 ** Delete an entire database table or index whose root page in the database
44302 ** file is given by P1.
44303 **
44304 ** The table being destroyed is in the main database file if P3==0.  If
44305 ** P3==1 then the table to be clear is in the auxiliary database file
44306 ** that is used to store tables create using CREATE TEMPORARY TABLE.
44307 **
44308 ** If AUTOVACUUM is enabled then it is possible that another root page
44309 ** might be moved into the newly deleted root page in order to keep all
44310 ** root pages contiguous at the beginning of the database.  The former
44311 ** value of the root page that moved - its value before the move occurred -
44312 ** is stored in register P2.  If no page 
44313 ** movement was required (because the table being dropped was already 
44314 ** the last one in the database) then a zero is stored in register P2.
44315 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
44316 **
44317 ** See also: Clear
44318 */
44319 case OP_Destroy: {     /* out2-prerelease */
44320   int iMoved;
44321   int iCnt;
44322 #ifndef SQLITE_OMIT_VIRTUALTABLE
44323   Vdbe *pVdbe;
44324   iCnt = 0;
44325   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
44326     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
44327       iCnt++;
44328     }
44329   }
44330 #else
44331   iCnt = db->activeVdbeCnt;
44332 #endif
44333   if( iCnt>1 ){
44334     rc = SQLITE_LOCKED;
44335     p->errorAction = OE_Abort;
44336   }else{
44337     int iDb = pOp->p3;
44338     assert( iCnt==1 );
44339     assert( (p->btreeMask & (1<<iDb))!=0 );
44340     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
44341     MemSetTypeFlag(pOut, MEM_Int);
44342     pOut->u.i = iMoved;
44343 #ifndef SQLITE_OMIT_AUTOVACUUM
44344     if( rc==SQLITE_OK && iMoved!=0 ){
44345       sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
44346     }
44347 #endif
44348   }
44349   break;
44350 }
44351
44352 /* Opcode: Clear P1 P2 *
44353 **
44354 ** Delete all contents of the database table or index whose root page
44355 ** in the database file is given by P1.  But, unlike Destroy, do not
44356 ** remove the table or index from the database file.
44357 **
44358 ** The table being clear is in the main database file if P2==0.  If
44359 ** P2==1 then the table to be clear is in the auxiliary database file
44360 ** that is used to store tables create using CREATE TEMPORARY TABLE.
44361 **
44362 ** See also: Destroy
44363 */
44364 case OP_Clear: {
44365   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
44366   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
44367   break;
44368 }
44369
44370 /* Opcode: CreateTable P1 P2 * * *
44371 **
44372 ** Allocate a new table in the main database file if P1==0 or in the
44373 ** auxiliary database file if P1==1 or in an attached database if
44374 ** P1>1.  Write the root page number of the new table into
44375 ** register P2
44376 **
44377 ** The difference between a table and an index is this:  A table must
44378 ** have a 4-byte integer key and can have arbitrary data.  An index
44379 ** has an arbitrary key but no data.
44380 **
44381 ** See also: CreateIndex
44382 */
44383 /* Opcode: CreateIndex P1 P2 * * *
44384 **
44385 ** Allocate a new index in the main database file if P1==0 or in the
44386 ** auxiliary database file if P1==1 or in an attached database if
44387 ** P1>1.  Write the root page number of the new table into
44388 ** register P2.
44389 **
44390 ** See documentation on OP_CreateTable for additional information.
44391 */
44392 case OP_CreateIndex:            /* out2-prerelease */
44393 case OP_CreateTable: {          /* out2-prerelease */
44394   int pgno;
44395   int flags;
44396   Db *pDb;
44397   assert( pOp->p1>=0 && pOp->p1<db->nDb );
44398   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
44399   pDb = &db->aDb[pOp->p1];
44400   assert( pDb->pBt!=0 );
44401   if( pOp->opcode==OP_CreateTable ){
44402     /* flags = BTREE_INTKEY; */
44403     flags = BTREE_LEAFDATA|BTREE_INTKEY;
44404   }else{
44405     flags = BTREE_ZERODATA;
44406   }
44407   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
44408   if( rc==SQLITE_OK ){
44409     pOut->u.i = pgno;
44410     MemSetTypeFlag(pOut, MEM_Int);
44411   }
44412   break;
44413 }
44414
44415 /* Opcode: ParseSchema P1 P2 * P4 *
44416 **
44417 ** Read and parse all entries from the SQLITE_MASTER table of database P1
44418 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
44419 ** the parsing if P2 is true.  If P2 is false, then this routine is a
44420 ** no-op if the schema is not currently loaded.  In other words, if P2
44421 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
44422 ** schema is already loaded into the symbol table.
44423 **
44424 ** This opcode invokes the parser to create a new virtual machine,
44425 ** then runs the new virtual machine.  It is thus a reentrant opcode.
44426 */
44427 case OP_ParseSchema: {
44428   char *zSql;
44429   int iDb = pOp->p1;
44430   const char *zMaster;
44431   InitData initData;
44432
44433   assert( iDb>=0 && iDb<db->nDb );
44434   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
44435     break;
44436   }
44437   zMaster = SCHEMA_TABLE(iDb);
44438   initData.db = db;
44439   initData.iDb = pOp->p1;
44440   initData.pzErrMsg = &p->zErrMsg;
44441   zSql = sqlite3MPrintf(db,
44442      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
44443      db->aDb[iDb].zName, zMaster, pOp->p4.z);
44444   if( zSql==0 ) goto no_mem;
44445   (void)sqlite3SafetyOff(db);
44446   assert( db->init.busy==0 );
44447   db->init.busy = 1;
44448   assert( !db->mallocFailed );
44449   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
44450   if( rc==SQLITE_ABORT ) rc = initData.rc;
44451   sqlite3_free(zSql);
44452   db->init.busy = 0;
44453   (void)sqlite3SafetyOn(db);
44454   if( rc==SQLITE_NOMEM ){
44455     goto no_mem;
44456   }
44457   break;  
44458 }
44459
44460 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
44461 /* Opcode: LoadAnalysis P1 * * * *
44462 **
44463 ** Read the sqlite_stat1 table for database P1 and load the content
44464 ** of that table into the internal index hash table.  This will cause
44465 ** the analysis to be used when preparing all subsequent queries.
44466 */
44467 case OP_LoadAnalysis: {
44468   int iDb = pOp->p1;
44469   assert( iDb>=0 && iDb<db->nDb );
44470   rc = sqlite3AnalysisLoad(db, iDb);
44471   break;  
44472 }
44473 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
44474
44475 /* Opcode: DropTable P1 * * P4 *
44476 **
44477 ** Remove the internal (in-memory) data structures that describe
44478 ** the table named P4 in database P1.  This is called after a table
44479 ** is dropped in order to keep the internal representation of the
44480 ** schema consistent with what is on disk.
44481 */
44482 case OP_DropTable: {
44483   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
44484   break;
44485 }
44486
44487 /* Opcode: DropIndex P1 * * P4 *
44488 **
44489 ** Remove the internal (in-memory) data structures that describe
44490 ** the index named P4 in database P1.  This is called after an index
44491 ** is dropped in order to keep the internal representation of the
44492 ** schema consistent with what is on disk.
44493 */
44494 case OP_DropIndex: {
44495   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
44496   break;
44497 }
44498
44499 /* Opcode: DropTrigger P1 * * P4 *
44500 **
44501 ** Remove the internal (in-memory) data structures that describe
44502 ** the trigger named P4 in database P1.  This is called after a trigger
44503 ** is dropped in order to keep the internal representation of the
44504 ** schema consistent with what is on disk.
44505 */
44506 case OP_DropTrigger: {
44507   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
44508   break;
44509 }
44510
44511
44512 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
44513 /* Opcode: IntegrityCk P1 P2 P3 * P5
44514 **
44515 ** Do an analysis of the currently open database.  Store in
44516 ** register P1 the text of an error message describing any problems.
44517 ** If no problems are found, store a NULL in register P1.
44518 **
44519 ** The register P3 contains the maximum number of allowed errors.
44520 ** At most reg(P3) errors will be reported.
44521 ** In other words, the analysis stops as soon as reg(P1) errors are 
44522 ** seen.  Reg(P1) is updated with the number of errors remaining.
44523 **
44524 ** The root page numbers of all tables in the database are integer
44525 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
44526 ** total.
44527 **
44528 ** If P5 is not zero, the check is done on the auxiliary database
44529 ** file, not the main database file.
44530 **
44531 ** This opcode is used to implement the integrity_check pragma.
44532 */
44533 case OP_IntegrityCk: {
44534   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
44535   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
44536   int j;          /* Loop counter */
44537   int nErr;       /* Number of errors reported */
44538   char *z;        /* Text of the error report */
44539   Mem *pnErr;     /* Register keeping track of errors remaining */
44540   
44541   nRoot = pOp->p2;
44542   assert( nRoot>0 );
44543   aRoot = sqlite3_malloc( sizeof(int)*(nRoot+1) );
44544   if( aRoot==0 ) goto no_mem;
44545   assert( pOp->p3>0 && pOp->p3<=p->nMem );
44546   pnErr = &p->aMem[pOp->p3];
44547   assert( (pnErr->flags & MEM_Int)!=0 );
44548   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
44549   pIn1 = &p->aMem[pOp->p1];
44550   for(j=0; j<nRoot; j++){
44551     aRoot[j] = sqlite3VdbeIntValue(&pIn1[j]);
44552   }
44553   aRoot[j] = 0;
44554   assert( pOp->p5<db->nDb );
44555   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
44556   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
44557                                  pnErr->u.i, &nErr);
44558   pnErr->u.i -= nErr;
44559   sqlite3VdbeMemSetNull(pIn1);
44560   if( nErr==0 ){
44561     assert( z==0 );
44562   }else{
44563     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
44564   }
44565   UPDATE_MAX_BLOBSIZE(pIn1);
44566   sqlite3VdbeChangeEncoding(pIn1, encoding);
44567   sqlite3_free(aRoot);
44568   break;
44569 }
44570 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44571
44572 /* Opcode: FifoWrite P1 * * * *
44573 **
44574 ** Write the integer from register P1 into the Fifo.
44575 */
44576 case OP_FifoWrite: {        /* in1 */
44577   if( sqlite3VdbeFifoPush(&p->sFifo, sqlite3VdbeIntValue(pIn1))==SQLITE_NOMEM ){
44578     goto no_mem;
44579   }
44580   break;
44581 }
44582
44583 /* Opcode: FifoRead P1 P2 * * *
44584 **
44585 ** Attempt to read a single integer from the Fifo.  Store that
44586 ** integer in register P1.
44587 ** 
44588 ** If the Fifo is empty jump to P2.
44589 */
44590 case OP_FifoRead: {         /* jump */
44591   CHECK_FOR_INTERRUPT;
44592   assert( pOp->p1>0 && pOp->p1<=p->nMem );
44593   pOut = &p->aMem[pOp->p1];
44594   MemSetTypeFlag(pOut, MEM_Int);
44595   if( sqlite3VdbeFifoPop(&p->sFifo, &pOut->u.i)==SQLITE_DONE ){
44596     pc = pOp->p2 - 1;
44597   }
44598   break;
44599 }
44600
44601 #ifndef SQLITE_OMIT_TRIGGER
44602 /* Opcode: ContextPush * * * 
44603 **
44604 ** Save the current Vdbe context such that it can be restored by a ContextPop
44605 ** opcode. The context stores the last insert row id, the last statement change
44606 ** count, and the current statement change count.
44607 */
44608 case OP_ContextPush: {
44609   int i = p->contextStackTop++;
44610   Context *pContext;
44611
44612   assert( i>=0 );
44613   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
44614   if( i>=p->contextStackDepth ){
44615     p->contextStackDepth = i+1;
44616     p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
44617                                           sizeof(Context)*(i+1));
44618     if( p->contextStack==0 ) goto no_mem;
44619   }
44620   pContext = &p->contextStack[i];
44621   pContext->lastRowid = db->lastRowid;
44622   pContext->nChange = p->nChange;
44623   pContext->sFifo = p->sFifo;
44624   sqlite3VdbeFifoInit(&p->sFifo);
44625   break;
44626 }
44627
44628 /* Opcode: ContextPop * * * 
44629 **
44630 ** Restore the Vdbe context to the state it was in when contextPush was last
44631 ** executed. The context stores the last insert row id, the last statement
44632 ** change count, and the current statement change count.
44633 */
44634 case OP_ContextPop: {
44635   Context *pContext = &p->contextStack[--p->contextStackTop];
44636   assert( p->contextStackTop>=0 );
44637   db->lastRowid = pContext->lastRowid;
44638   p->nChange = pContext->nChange;
44639   sqlite3VdbeFifoClear(&p->sFifo);
44640   p->sFifo = pContext->sFifo;
44641   break;
44642 }
44643 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
44644
44645 #ifndef SQLITE_OMIT_AUTOINCREMENT
44646 /* Opcode: MemMax P1 P2 * * *
44647 **
44648 ** Set the value of register P1 to the maximum of its current value
44649 ** and the value in register P2.
44650 **
44651 ** This instruction throws an error if the memory cell is not initially
44652 ** an integer.
44653 */
44654 case OP_MemMax: {        /* in1, in2 */
44655   sqlite3VdbeMemIntegerify(pIn1);
44656   sqlite3VdbeMemIntegerify(pIn2);
44657   if( pIn1->u.i<pIn2->u.i){
44658     pIn1->u.i = pIn2->u.i;
44659   }
44660   break;
44661 }
44662 #endif /* SQLITE_OMIT_AUTOINCREMENT */
44663
44664 /* Opcode: IfPos P1 P2 * * *
44665 **
44666 ** If the value of register P1 is 1 or greater, jump to P2.
44667 **
44668 ** It is illegal to use this instruction on a register that does
44669 ** not contain an integer.  An assertion fault will result if you try.
44670 */
44671 case OP_IfPos: {        /* jump, in1 */
44672   assert( pIn1->flags&MEM_Int );
44673   if( pIn1->u.i>0 ){
44674      pc = pOp->p2 - 1;
44675   }
44676   break;
44677 }
44678
44679 /* Opcode: IfNeg P1 P2 * * *
44680 **
44681 ** If the value of register P1 is less than zero, jump to P2. 
44682 **
44683 ** It is illegal to use this instruction on a register that does
44684 ** not contain an integer.  An assertion fault will result if you try.
44685 */
44686 case OP_IfNeg: {        /* jump, in1 */
44687   assert( pIn1->flags&MEM_Int );
44688   if( pIn1->u.i<0 ){
44689      pc = pOp->p2 - 1;
44690   }
44691   break;
44692 }
44693
44694 /* Opcode: IfZero P1 P2 * * *
44695 **
44696 ** If the value of register P1 is exactly 0, jump to P2. 
44697 **
44698 ** It is illegal to use this instruction on a register that does
44699 ** not contain an integer.  An assertion fault will result if you try.
44700 */
44701 case OP_IfZero: {        /* jump, in1 */
44702   assert( pIn1->flags&MEM_Int );
44703   if( pIn1->u.i==0 ){
44704      pc = pOp->p2 - 1;
44705   }
44706   break;
44707 }
44708
44709 /* Opcode: AggStep * P2 P3 P4 P5
44710 **
44711 ** Execute the step function for an aggregate.  The
44712 ** function has P5 arguments.   P4 is a pointer to the FuncDef
44713 ** structure that specifies the function.  Use register
44714 ** P3 as the accumulator.
44715 **
44716 ** The P5 arguments are taken from register P2 and its
44717 ** successors.
44718 */
44719 case OP_AggStep: {
44720   int n = pOp->p5;
44721   int i;
44722   Mem *pMem, *pRec;
44723   sqlite3_context ctx;
44724   sqlite3_value **apVal;
44725
44726   assert( n>=0 );
44727   pRec = &p->aMem[pOp->p2];
44728   apVal = p->apArg;
44729   assert( apVal || n==0 );
44730   for(i=0; i<n; i++, pRec++){
44731     apVal[i] = pRec;
44732     storeTypeInfo(pRec, encoding);
44733   }
44734   ctx.pFunc = pOp->p4.pFunc;
44735   assert( pOp->p3>0 && pOp->p3<=p->nMem );
44736   ctx.pMem = pMem = &p->aMem[pOp->p3];
44737   pMem->n++;
44738   ctx.s.flags = MEM_Null;
44739   ctx.s.z = 0;
44740   ctx.s.xDel = 0;
44741   ctx.s.db = db;
44742   ctx.isError = 0;
44743   ctx.pColl = 0;
44744   if( ctx.pFunc->needCollSeq ){
44745     assert( pOp>p->aOp );
44746     assert( pOp[-1].p4type==P4_COLLSEQ );
44747     assert( pOp[-1].opcode==OP_CollSeq );
44748     ctx.pColl = pOp[-1].p4.pColl;
44749   }
44750   (ctx.pFunc->xStep)(&ctx, n, apVal);
44751   if( ctx.isError ){
44752     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
44753     rc = ctx.isError;
44754   }
44755   sqlite3VdbeMemRelease(&ctx.s);
44756   break;
44757 }
44758
44759 /* Opcode: AggFinal P1 P2 * P4 *
44760 **
44761 ** Execute the finalizer function for an aggregate.  P1 is
44762 ** the memory location that is the accumulator for the aggregate.
44763 **
44764 ** P2 is the number of arguments that the step function takes and
44765 ** P4 is a pointer to the FuncDef for this function.  The P2
44766 ** argument is not used by this opcode.  It is only there to disambiguate
44767 ** functions that can take varying numbers of arguments.  The
44768 ** P4 argument is only needed for the degenerate case where
44769 ** the step function was not previously called.
44770 */
44771 case OP_AggFinal: {
44772   Mem *pMem;
44773   assert( pOp->p1>0 && pOp->p1<=p->nMem );
44774   pMem = &p->aMem[pOp->p1];
44775   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
44776   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
44777   if( rc==SQLITE_ERROR ){
44778     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
44779   }
44780   UPDATE_MAX_BLOBSIZE(pMem);
44781   if( sqlite3VdbeMemTooBig(pMem) ){
44782     goto too_big;
44783   }
44784   break;
44785 }
44786
44787
44788 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
44789 /* Opcode: Vacuum * * * * *
44790 **
44791 ** Vacuum the entire database.  This opcode will cause other virtual
44792 ** machines to be created and run.  It may not be called from within
44793 ** a transaction.
44794 */
44795 case OP_Vacuum: {
44796   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
44797   rc = sqlite3RunVacuum(&p->zErrMsg, db);
44798   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
44799   break;
44800 }
44801 #endif
44802
44803 #if !defined(SQLITE_OMIT_AUTOVACUUM)
44804 /* Opcode: IncrVacuum P1 P2 * * *
44805 **
44806 ** Perform a single step of the incremental vacuum procedure on
44807 ** the P1 database. If the vacuum has finished, jump to instruction
44808 ** P2. Otherwise, fall through to the next instruction.
44809 */
44810 case OP_IncrVacuum: {        /* jump */
44811   Btree *pBt;
44812
44813   assert( pOp->p1>=0 && pOp->p1<db->nDb );
44814   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
44815   pBt = db->aDb[pOp->p1].pBt;
44816   rc = sqlite3BtreeIncrVacuum(pBt);
44817   if( rc==SQLITE_DONE ){
44818     pc = pOp->p2 - 1;
44819     rc = SQLITE_OK;
44820   }
44821   break;
44822 }
44823 #endif
44824
44825 /* Opcode: Expire P1 * * * *
44826 **
44827 ** Cause precompiled statements to become expired. An expired statement
44828 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
44829 ** (via sqlite3_step()).
44830 ** 
44831 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
44832 ** then only the currently executing statement is affected. 
44833 */
44834 case OP_Expire: {
44835   if( !pOp->p1 ){
44836     sqlite3ExpirePreparedStatements(db);
44837   }else{
44838     p->expired = 1;
44839   }
44840   break;
44841 }
44842
44843 #ifndef SQLITE_OMIT_SHARED_CACHE
44844 /* Opcode: TableLock P1 P2 * P4 *
44845 **
44846 ** Obtain a lock on a particular table. This instruction is only used when
44847 ** the shared-cache feature is enabled. 
44848 **
44849 ** If P1 is not negative, then it is the index of the database
44850 ** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a 
44851 ** write-lock is required. In this case the index of the database is the 
44852 ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
44853 ** required. 
44854 **
44855 ** P2 contains the root-page of the table to lock.
44856 **
44857 ** P4 contains a pointer to the name of the table being locked. This is only
44858 ** used to generate an error message if the lock cannot be obtained.
44859 */
44860 case OP_TableLock: {
44861   int p1 = pOp->p1; 
44862   u8 isWriteLock = (p1<0);
44863   if( isWriteLock ){
44864     p1 = (-1*p1)-1;
44865   }
44866   assert( p1>=0 && p1<db->nDb );
44867   assert( (p->btreeMask & (1<<p1))!=0 );
44868   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
44869   if( rc==SQLITE_LOCKED ){
44870     const char *z = pOp->p4.z;
44871     sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
44872   }
44873   break;
44874 }
44875 #endif /* SQLITE_OMIT_SHARED_CACHE */
44876
44877 #ifndef SQLITE_OMIT_VIRTUALTABLE
44878 /* Opcode: VBegin * * * P4 *
44879 **
44880 ** P4 a pointer to an sqlite3_vtab structure. Call the xBegin method 
44881 ** for that table.
44882 */
44883 case OP_VBegin: {
44884   rc = sqlite3VtabBegin(db, pOp->p4.pVtab);
44885   break;
44886 }
44887 #endif /* SQLITE_OMIT_VIRTUALTABLE */
44888
44889 #ifndef SQLITE_OMIT_VIRTUALTABLE
44890 /* Opcode: VCreate P1 * * P4 *
44891 **
44892 ** P4 is the name of a virtual table in database P1. Call the xCreate method
44893 ** for that table.
44894 */
44895 case OP_VCreate: {
44896   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
44897   break;
44898 }
44899 #endif /* SQLITE_OMIT_VIRTUALTABLE */
44900
44901 #ifndef SQLITE_OMIT_VIRTUALTABLE
44902 /* Opcode: VDestroy P1 * * P4 *
44903 **
44904 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
44905 ** of that table.
44906 */
44907 case OP_VDestroy: {
44908   p->inVtabMethod = 2;
44909   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
44910   p->inVtabMethod = 0;
44911   break;
44912 }
44913 #endif /* SQLITE_OMIT_VIRTUALTABLE */
44914
44915 #ifndef SQLITE_OMIT_VIRTUALTABLE
44916 /* Opcode: VOpen P1 * * P4 *
44917 **
44918 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
44919 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
44920 ** table and stores that cursor in P1.
44921 */
44922 case OP_VOpen: {
44923   Cursor *pCur = 0;
44924   sqlite3_vtab_cursor *pVtabCursor = 0;
44925
44926   sqlite3_vtab *pVtab = pOp->p4.pVtab;
44927   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
44928
44929   assert(pVtab && pModule);
44930   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
44931   rc = pModule->xOpen(pVtab, &pVtabCursor);
44932   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
44933   if( SQLITE_OK==rc ){
44934     /* Initialise sqlite3_vtab_cursor base class */
44935     pVtabCursor->pVtab = pVtab;
44936
44937     /* Initialise vdbe cursor object */
44938     pCur = allocateCursor(p, pOp->p1, -1);
44939     if( pCur ){
44940       pCur->pVtabCursor = pVtabCursor;
44941       pCur->pModule = pVtabCursor->pVtab->pModule;
44942     }else{
44943       db->mallocFailed = 1;
44944       pModule->xClose(pVtabCursor);
44945     }
44946   }
44947   break;
44948 }
44949 #endif /* SQLITE_OMIT_VIRTUALTABLE */
44950
44951 #ifndef SQLITE_OMIT_VIRTUALTABLE
44952 /* Opcode: VFilter P1 P2 P3 P4 *
44953 **
44954 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
44955 ** the filtered result set is empty.
44956 **
44957 ** P4 is either NULL or a string that was generated by the xBestIndex
44958 ** method of the module.  The interpretation of the P4 string is left
44959 ** to the module implementation.
44960 **
44961 ** This opcode invokes the xFilter method on the virtual table specified
44962 ** by P1.  The integer query plan parameter to xFilter is stored in register
44963 ** P3. Register P3+1 stores the argc parameter to be passed to the
44964 ** xFilter method. Registers P3+2..P3+1+argc are the argc additional
44965 ** parametersneath additional parameters which are passed to
44966 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
44967 **
44968 ** A jump is made to P2 if the result set after filtering would be empty.
44969 */
44970 case OP_VFilter: {   /* jump */
44971   int nArg;
44972   int iQuery;
44973   const sqlite3_module *pModule;
44974   Mem *pQuery = &p->aMem[pOp->p3];
44975   Mem *pArgc = &pQuery[1];
44976
44977   Cursor *pCur = p->apCsr[pOp->p1];
44978
44979   REGISTER_TRACE(pOp->p3, pQuery);
44980   assert( pCur->pVtabCursor );
44981   pModule = pCur->pVtabCursor->pVtab->pModule;
44982
44983   /* Grab the index number and argc parameters */
44984   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
44985   nArg = pArgc->u.i;
44986   iQuery = pQuery->u.i;
44987
44988   /* Invoke the xFilter method */
44989   {
44990     int res = 0;
44991     int i;
44992     Mem **apArg = p->apArg;
44993     for(i = 0; i<nArg; i++){
44994       apArg[i] = &pArgc[i+1];
44995       storeTypeInfo(apArg[i], 0);
44996     }
44997
44998     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
44999     p->inVtabMethod = 1;
45000     rc = pModule->xFilter(pCur->pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
45001     p->inVtabMethod = 0;
45002     if( rc==SQLITE_OK ){
45003       res = pModule->xEof(pCur->pVtabCursor);
45004     }
45005     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
45006
45007     if( res ){
45008       pc = pOp->p2 - 1;
45009     }
45010   }
45011   pCur->nullRow = 0;
45012
45013   break;
45014 }
45015 #endif /* SQLITE_OMIT_VIRTUALTABLE */
45016
45017 #ifndef SQLITE_OMIT_VIRTUALTABLE
45018 /* Opcode: VRowid P1 P2 * * *
45019 **
45020 ** Store into register P2  the rowid of
45021 ** the virtual-table that the P1 cursor is pointing to.
45022 */
45023 case OP_VRowid: {             /* out2-prerelease */
45024   const sqlite3_module *pModule;
45025   sqlite_int64 iRow;
45026   Cursor *pCur = p->apCsr[pOp->p1];
45027
45028   assert( pCur->pVtabCursor );
45029   if( pCur->nullRow ){
45030     break;
45031   }
45032   pModule = pCur->pVtabCursor->pVtab->pModule;
45033   assert( pModule->xRowid );
45034   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
45035   rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
45036   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
45037   MemSetTypeFlag(pOut, MEM_Int);
45038   pOut->u.i = iRow;
45039   break;
45040 }
45041 #endif /* SQLITE_OMIT_VIRTUALTABLE */
45042
45043 #ifndef SQLITE_OMIT_VIRTUALTABLE
45044 /* Opcode: VColumn P1 P2 P3 * *
45045 **
45046 ** Store the value of the P2-th column of
45047 ** the row of the virtual-table that the 
45048 ** P1 cursor is pointing to into register P3.
45049 */
45050 case OP_VColumn: {
45051   const sqlite3_module *pModule;
45052   Mem *pDest;
45053   sqlite3_context sContext;
45054
45055   Cursor *pCur = p->apCsr[pOp->p1];
45056   assert( pCur->pVtabCursor );
45057   assert( pOp->p3>0 && pOp->p3<=p->nMem );
45058   pDest = &p->aMem[pOp->p3];
45059   if( pCur->nullRow ){
45060     sqlite3VdbeMemSetNull(pDest);
45061     break;
45062   }
45063   pModule = pCur->pVtabCursor->pVtab->pModule;
45064   assert( pModule->xColumn );
45065   memset(&sContext, 0, sizeof(sContext));
45066
45067   /* The output cell may already have a buffer allocated. Move
45068   ** the current contents to sContext.s so in case the user-function 
45069   ** can use the already allocated buffer instead of allocating a 
45070   ** new one.
45071   */
45072   sqlite3VdbeMemMove(&sContext.s, pDest);
45073   MemSetTypeFlag(&sContext.s, MEM_Null);
45074
45075   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
45076   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
45077
45078   /* Copy the result of the function to the P3 register. We
45079   ** do this regardless of whether or not an error occured to ensure any
45080   ** dynamic allocation in sContext.s (a Mem struct) is  released.
45081   */
45082   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
45083   REGISTER_TRACE(pOp->p3, pDest);
45084   sqlite3VdbeMemMove(pDest, &sContext.s);
45085   UPDATE_MAX_BLOBSIZE(pDest);
45086
45087   if( sqlite3SafetyOn(db) ){
45088     goto abort_due_to_misuse;
45089   }
45090   if( sqlite3VdbeMemTooBig(pDest) ){
45091     goto too_big;
45092   }
45093   break;
45094 }
45095 #endif /* SQLITE_OMIT_VIRTUALTABLE */
45096
45097 #ifndef SQLITE_OMIT_VIRTUALTABLE
45098 /* Opcode: VNext P1 P2 * * *
45099 **
45100 ** Advance virtual table P1 to the next row in its result set and
45101 ** jump to instruction P2.  Or, if the virtual table has reached
45102 ** the end of its result set, then fall through to the next instruction.
45103 */
45104 case OP_VNext: {   /* jump */
45105   const sqlite3_module *pModule;
45106   int res = 0;
45107
45108   Cursor *pCur = p->apCsr[pOp->p1];
45109   assert( pCur->pVtabCursor );
45110   if( pCur->nullRow ){
45111     break;
45112   }
45113   pModule = pCur->pVtabCursor->pVtab->pModule;
45114   assert( pModule->xNext );
45115
45116   /* Invoke the xNext() method of the module. There is no way for the
45117   ** underlying implementation to return an error if one occurs during
45118   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
45119   ** data is available) and the error code returned when xColumn or
45120   ** some other method is next invoked on the save virtual table cursor.
45121   */
45122   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
45123   p->inVtabMethod = 1;
45124   rc = pModule->xNext(pCur->pVtabCursor);
45125   p->inVtabMethod = 0;
45126   if( rc==SQLITE_OK ){
45127     res = pModule->xEof(pCur->pVtabCursor);
45128   }
45129   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
45130
45131   if( !res ){
45132     /* If there is data, jump to P2 */
45133     pc = pOp->p2 - 1;
45134   }
45135   break;
45136 }
45137 #endif /* SQLITE_OMIT_VIRTUALTABLE */
45138
45139 #ifndef SQLITE_OMIT_VIRTUALTABLE
45140 /* Opcode: VRename P1 * * P4 *
45141 **
45142 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
45143 ** This opcode invokes the corresponding xRename method. The value
45144 ** in register P1 is passed as the zName argument to the xRename method.
45145 */
45146 case OP_VRename: {
45147   sqlite3_vtab *pVtab = pOp->p4.pVtab;
45148   Mem *pName = &p->aMem[pOp->p1];
45149   assert( pVtab->pModule->xRename );
45150   REGISTER_TRACE(pOp->p1, pName);
45151
45152   Stringify(pName, encoding);
45153
45154   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
45155   sqlite3VtabLock(pVtab);
45156   rc = pVtab->pModule->xRename(pVtab, pName->z);
45157   sqlite3VtabUnlock(db, pVtab);
45158   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
45159
45160   break;
45161 }
45162 #endif
45163
45164 #ifndef SQLITE_OMIT_VIRTUALTABLE
45165 /* Opcode: VUpdate P1 P2 P3 P4 *
45166 **
45167 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
45168 ** This opcode invokes the corresponding xUpdate method. P2 values
45169 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
45170 ** invocation. The value in register (P3+P2-1) corresponds to the 
45171 ** p2th element of the argv array passed to xUpdate.
45172 **
45173 ** The xUpdate method will do a DELETE or an INSERT or both.
45174 ** The argv[0] element (which corresponds to memory cell P3)
45175 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
45176 ** deletion occurs.  The argv[1] element is the rowid of the new 
45177 ** row.  This can be NULL to have the virtual table select the new 
45178 ** rowid for itself.  The subsequent elements in the array are 
45179 ** the values of columns in the new row.
45180 **
45181 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
45182 ** a row to delete.
45183 **
45184 ** P1 is a boolean flag. If it is set to true and the xUpdate call
45185 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
45186 ** is set to the value of the rowid for the row just inserted.
45187 */
45188 case OP_VUpdate: {
45189   sqlite3_vtab *pVtab = pOp->p4.pVtab;
45190   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
45191   int nArg = pOp->p2;
45192   assert( pOp->p4type==P4_VTAB );
45193   if( pModule->xUpdate==0 ){
45194     sqlite3SetString(&p->zErrMsg, "read-only table", 0);
45195     rc = SQLITE_ERROR;
45196   }else{
45197     int i;
45198     sqlite_int64 rowid;
45199     Mem **apArg = p->apArg;
45200     Mem *pX = &p->aMem[pOp->p3];
45201     for(i=0; i<nArg; i++){
45202       storeTypeInfo(pX, 0);
45203       apArg[i] = pX;
45204       pX++;
45205     }
45206     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
45207     sqlite3VtabLock(pVtab);
45208     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
45209     sqlite3VtabUnlock(db, pVtab);
45210     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
45211     if( pOp->p1 && rc==SQLITE_OK ){
45212       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
45213       db->lastRowid = rowid;
45214     }
45215   }
45216   break;
45217 }
45218 #endif /* SQLITE_OMIT_VIRTUALTABLE */
45219
45220 #ifndef SQLITE_OMIT_TRACE
45221 /* Opcode: Trace * * * P4 *
45222 **
45223 ** If tracing is enabled (by the sqlite3_trace()) interface, then
45224 ** the UTF-8 string contained in P4 is emitted on the trace callback.
45225 */
45226 case OP_Trace: {
45227   if( pOp->p4.z ){
45228     if( db->xTrace ){
45229       db->xTrace(db->pTraceArg, pOp->p4.z);
45230     }
45231 #ifdef SQLITE_DEBUG
45232     if( (db->flags & SQLITE_SqlTrace)!=0 ){
45233       sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
45234     }
45235 #endif /* SQLITE_DEBUG */
45236   }
45237   break;
45238 }
45239 #endif
45240
45241
45242 /* Opcode: Noop * * * * *
45243 **
45244 ** Do nothing.  This instruction is often useful as a jump
45245 ** destination.
45246 */
45247 /*
45248 ** The magic Explain opcode are only inserted when explain==2 (which
45249 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
45250 ** This opcode records information from the optimizer.  It is the
45251 ** the same as a no-op.  This opcodesnever appears in a real VM program.
45252 */
45253 default: {          /* This is really OP_Noop and OP_Explain */
45254   break;
45255 }
45256
45257 /*****************************************************************************
45258 ** The cases of the switch statement above this line should all be indented
45259 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
45260 ** readability.  From this point on down, the normal indentation rules are
45261 ** restored.
45262 *****************************************************************************/
45263     }
45264
45265 #ifdef VDBE_PROFILE
45266     {
45267       long long elapse = hwtime() - start;
45268       pOp->cycles += elapse;
45269       pOp->cnt++;
45270 #if 0
45271         fprintf(stdout, "%10lld ", elapse);
45272         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
45273 #endif
45274     }
45275 #endif
45276
45277     /* The following code adds nothing to the actual functionality
45278     ** of the program.  It is only here for testing and debugging.
45279     ** On the other hand, it does burn CPU cycles every time through
45280     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
45281     */
45282 #ifndef NDEBUG
45283     assert( pc>=-1 && pc<p->nOp );
45284
45285 #ifdef SQLITE_DEBUG
45286     if( p->trace ){
45287       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
45288       if( opProperty & OPFLG_OUT2_PRERELEASE ){
45289         registerTrace(p->trace, pOp->p2, pOut);
45290       }
45291       if( opProperty & OPFLG_OUT3 ){
45292         registerTrace(p->trace, pOp->p3, pOut);
45293       }
45294     }
45295 #endif  /* SQLITE_DEBUG */
45296 #endif  /* NDEBUG */
45297   }  /* The end of the for(;;) loop the loops through opcodes */
45298
45299   /* If we reach this point, it means that execution is finished with
45300   ** an error of some kind.
45301   */
45302 vdbe_error_halt:
45303   assert( rc );
45304   p->rc = rc;
45305   rc = SQLITE_ERROR;
45306   sqlite3VdbeHalt(p);
45307
45308   /* This is the only way out of this procedure.  We have to
45309   ** release the mutexes on btrees that were acquired at the
45310   ** top. */
45311 vdbe_return:
45312   sqlite3BtreeMutexArrayLeave(&p->aMutex);
45313   return rc;
45314
45315   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
45316   ** is encountered.
45317   */
45318 too_big:
45319   sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
45320   rc = SQLITE_TOOBIG;
45321   goto vdbe_error_halt;
45322
45323   /* Jump to here if a malloc() fails.
45324   */
45325 no_mem:
45326   db->mallocFailed = 1;
45327   sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
45328   rc = SQLITE_NOMEM;
45329   goto vdbe_error_halt;
45330
45331   /* Jump to here for an SQLITE_MISUSE error.
45332   */
45333 abort_due_to_misuse:
45334   rc = SQLITE_MISUSE;
45335   /* Fall thru into abort_due_to_error */
45336
45337   /* Jump to here for any other kind of fatal error.  The "rc" variable
45338   ** should hold the error number.
45339   */
45340 abort_due_to_error:
45341   assert( p->zErrMsg==0 );
45342   if( db->mallocFailed ) rc = SQLITE_NOMEM;
45343   sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
45344   goto vdbe_error_halt;
45345
45346   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
45347   ** flag.
45348   */
45349 abort_due_to_interrupt:
45350   assert( db->u1.isInterrupted );
45351   rc = SQLITE_INTERRUPT;
45352   p->rc = rc;
45353   sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
45354   goto vdbe_error_halt;
45355 }
45356
45357 /************** End of vdbe.c ************************************************/
45358 /************** Begin file vdbeblob.c ****************************************/
45359 /*
45360 ** 2007 May 1
45361 **
45362 ** The author disclaims copyright to this source code.  In place of
45363 ** a legal notice, here is a blessing:
45364 **
45365 **    May you do good and not evil.
45366 **    May you find forgiveness for yourself and forgive others.
45367 **    May you share freely, never taking more than you give.
45368 **
45369 *************************************************************************
45370 **
45371 ** This file contains code used to implement incremental BLOB I/O.
45372 **
45373 ** $Id: vdbeblob.c,v 1.20 2008/01/25 15:04:50 drh Exp $
45374 */
45375
45376
45377 #ifndef SQLITE_OMIT_INCRBLOB
45378
45379 /*
45380 ** Valid sqlite3_blob* handles point to Incrblob structures.
45381 */
45382 typedef struct Incrblob Incrblob;
45383 struct Incrblob {
45384   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
45385   int nByte;              /* Size of open blob, in bytes */
45386   int iOffset;            /* Byte offset of blob in cursor data */
45387   BtCursor *pCsr;         /* Cursor pointing at blob row */
45388   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
45389   sqlite3 *db;            /* The associated database */
45390 };
45391
45392 /*
45393 ** Open a blob handle.
45394 */
45395 SQLITE_API int sqlite3_blob_open(
45396   sqlite3* db,            /* The database connection */
45397   const char *zDb,        /* The attached database containing the blob */
45398   const char *zTable,     /* The table containing the blob */
45399   const char *zColumn,    /* The column containing the blob */
45400   sqlite_int64 iRow,      /* The row containing the glob */
45401   int flags,              /* True -> read/write access, false -> read-only */
45402   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
45403 ){
45404   int nAttempt = 0;
45405   int iCol;               /* Index of zColumn in row-record */
45406
45407   /* This VDBE program seeks a btree cursor to the identified 
45408   ** db/table/row entry. The reason for using a vdbe program instead
45409   ** of writing code to use the b-tree layer directly is that the
45410   ** vdbe program will take advantage of the various transaction,
45411   ** locking and error handling infrastructure built into the vdbe.
45412   **
45413   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
45414   ** Code external to the Vdbe then "borrows" the b-tree cursor and
45415   ** uses it to implement the blob_read(), blob_write() and 
45416   ** blob_bytes() functions.
45417   **
45418   ** The sqlite3_blob_close() function finalizes the vdbe program,
45419   ** which closes the b-tree cursor and (possibly) commits the 
45420   ** transaction.
45421   */
45422   static const VdbeOpList openBlob[] = {
45423     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
45424     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
45425
45426     /* One of the following two instructions is replaced by an
45427     ** OP_Noop before exection.
45428     */
45429     {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
45430     {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
45431     {OP_SetNumColumns, 0, 0, 0},   /* 4: Num cols for cursor */
45432
45433     {OP_Variable, 1, 1, 0},        /* 5: Push the rowid to the stack */
45434     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
45435     {OP_Column, 0, 0, 1},          /* 7  */
45436     {OP_ResultRow, 1, 0, 0},       /* 8  */
45437     {OP_Close, 0, 0, 0},           /* 9  */
45438     {OP_Halt, 0, 0, 0},            /* 10 */
45439   };
45440
45441   Vdbe *v = 0;
45442   int rc = SQLITE_OK;
45443   char zErr[128];
45444
45445   zErr[0] = 0;
45446   sqlite3_mutex_enter(db->mutex);
45447   do {
45448     Parse sParse;
45449     Table *pTab;
45450
45451     memset(&sParse, 0, sizeof(Parse));
45452     sParse.db = db;
45453
45454     rc = sqlite3SafetyOn(db);
45455     if( rc!=SQLITE_OK ){
45456       sqlite3_mutex_leave(db->mutex);
45457       return rc;
45458     }
45459
45460     sqlite3BtreeEnterAll(db);
45461     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
45462     if( !pTab ){
45463       if( sParse.zErrMsg ){
45464         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
45465       }
45466       sqlite3_free(sParse.zErrMsg);
45467       rc = SQLITE_ERROR;
45468       (void)sqlite3SafetyOff(db);
45469       sqlite3BtreeLeaveAll(db);
45470       goto blob_open_out;
45471     }
45472
45473     /* Now search pTab for the exact column. */
45474     for(iCol=0; iCol < pTab->nCol; iCol++) {
45475       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
45476         break;
45477       }
45478     }
45479     if( iCol==pTab->nCol ){
45480       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
45481       rc = SQLITE_ERROR;
45482       (void)sqlite3SafetyOff(db);
45483       sqlite3BtreeLeaveAll(db);
45484       goto blob_open_out;
45485     }
45486
45487     /* If the value is being opened for writing, check that the
45488     ** column is not indexed. It is against the rules to open an
45489     ** indexed column for writing.
45490     */
45491     if( flags ){
45492       Index *pIdx;
45493       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
45494         int j;
45495         for(j=0; j<pIdx->nColumn; j++){
45496           if( pIdx->aiColumn[j]==iCol ){
45497             sqlite3_snprintf(sizeof(zErr), zErr,
45498                              "cannot open indexed column for writing");
45499             rc = SQLITE_ERROR;
45500             (void)sqlite3SafetyOff(db);
45501             sqlite3BtreeLeaveAll(db);
45502             goto blob_open_out;
45503           }
45504         }
45505       }
45506     }
45507
45508     v = sqlite3VdbeCreate(db);
45509     if( v ){
45510       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
45511       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
45512
45513       /* Configure the OP_Transaction */
45514       sqlite3VdbeChangeP1(v, 0, iDb);
45515       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
45516
45517       /* Configure the OP_VerifyCookie */
45518       sqlite3VdbeChangeP1(v, 1, iDb);
45519       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
45520
45521       /* Make sure a mutex is held on the table to be accessed */
45522       sqlite3VdbeUsesBtree(v, iDb); 
45523
45524       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
45525       ** parameter of the other to pTab->tnum. 
45526       */
45527       sqlite3VdbeChangeToNoop(v, (flags ? 2 : 3), 1);
45528       sqlite3VdbeChangeP2(v, (flags ? 3 : 2), pTab->tnum);
45529       sqlite3VdbeChangeP3(v, (flags ? 3 : 2), iDb);
45530
45531       /* Configure the OP_SetNumColumns. Configure the cursor to
45532       ** think that the table has one more column than it really
45533       ** does. An OP_Column to retrieve this imaginary column will
45534       ** always return an SQL NULL. This is useful because it means
45535       ** we can invoke OP_Column to fill in the vdbe cursors type 
45536       ** and offset cache without causing any IO.
45537       */
45538       sqlite3VdbeChangeP2(v, 4, pTab->nCol+1);
45539       if( !db->mallocFailed ){
45540         sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
45541       }
45542     }
45543    
45544     sqlite3BtreeLeaveAll(db);
45545     rc = sqlite3SafetyOff(db);
45546     if( rc!=SQLITE_OK || db->mallocFailed ){
45547       goto blob_open_out;
45548     }
45549
45550     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
45551     rc = sqlite3_step((sqlite3_stmt *)v);
45552     if( rc!=SQLITE_ROW ){
45553       nAttempt++;
45554       rc = sqlite3_finalize((sqlite3_stmt *)v);
45555       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
45556       v = 0;
45557     }
45558   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
45559
45560   if( rc==SQLITE_ROW ){
45561     /* The row-record has been opened successfully. Check that the
45562     ** column in question contains text or a blob. If it contains
45563     ** text, it is up to the caller to get the encoding right.
45564     */
45565     Incrblob *pBlob;
45566     u32 type = v->apCsr[0]->aType[iCol];
45567
45568     if( type<12 ){
45569       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
45570           type==0?"null": type==7?"real": "integer"
45571       );
45572       rc = SQLITE_ERROR;
45573       goto blob_open_out;
45574     }
45575     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
45576     if( db->mallocFailed ){
45577       sqlite3_free(pBlob);
45578       goto blob_open_out;
45579     }
45580     pBlob->flags = flags;
45581     pBlob->pCsr =  v->apCsr[0]->pCursor;
45582     sqlite3BtreeEnterCursor(pBlob->pCsr);
45583     sqlite3BtreeCacheOverflow(pBlob->pCsr);
45584     sqlite3BtreeLeaveCursor(pBlob->pCsr);
45585     pBlob->pStmt = (sqlite3_stmt *)v;
45586     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
45587     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
45588     pBlob->db = db;
45589     *ppBlob = (sqlite3_blob *)pBlob;
45590     rc = SQLITE_OK;
45591   }else if( rc==SQLITE_OK ){
45592     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
45593     rc = SQLITE_ERROR;
45594   }
45595
45596 blob_open_out:
45597   zErr[sizeof(zErr)-1] = '\0';
45598   if( rc!=SQLITE_OK || db->mallocFailed ){
45599     sqlite3_finalize((sqlite3_stmt *)v);
45600   }
45601   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
45602   rc = sqlite3ApiExit(db, rc);
45603   sqlite3_mutex_leave(db->mutex);
45604   return rc;
45605 }
45606
45607 /*
45608 ** Close a blob handle that was previously created using
45609 ** sqlite3_blob_open().
45610 */
45611 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
45612   Incrblob *p = (Incrblob *)pBlob;
45613   int rc;
45614
45615   rc = sqlite3_finalize(p->pStmt);
45616   sqlite3_free(p);
45617   return rc;
45618 }
45619
45620 /*
45621 ** Perform a read or write operation on a blob
45622 */
45623 static int blobReadWrite(
45624   sqlite3_blob *pBlob, 
45625   void *z, 
45626   int n, 
45627   int iOffset, 
45628   int (*xCall)(BtCursor*, u32, u32, void*)
45629 ){
45630   int rc;
45631   Incrblob *p = (Incrblob *)pBlob;
45632   Vdbe *v;
45633   sqlite3 *db = p->db;  
45634
45635   /* Request is out of range. Return a transient error. */
45636   if( (iOffset+n)>p->nByte ){
45637     return SQLITE_ERROR;
45638   }
45639   sqlite3_mutex_enter(db->mutex);
45640
45641   /* If there is no statement handle, then the blob-handle has
45642   ** already been invalidated. Return SQLITE_ABORT in this case.
45643   */
45644   v = (Vdbe*)p->pStmt;
45645   if( v==0 ){
45646     rc = SQLITE_ABORT;
45647   }else{
45648     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
45649     ** returned, clean-up the statement handle.
45650     */
45651     assert( db == v->db );
45652     sqlite3BtreeEnterCursor(p->pCsr);
45653     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
45654     sqlite3BtreeLeaveCursor(p->pCsr);
45655     if( rc==SQLITE_ABORT ){
45656       sqlite3VdbeFinalize(v);
45657       p->pStmt = 0;
45658     }else{
45659       db->errCode = rc;
45660       v->rc = rc;
45661     }
45662   }
45663   rc = sqlite3ApiExit(db, rc);
45664   sqlite3_mutex_leave(db->mutex);
45665   return rc;
45666 }
45667
45668 /*
45669 ** Read data from a blob handle.
45670 */
45671 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
45672   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
45673 }
45674
45675 /*
45676 ** Write data to a blob handle.
45677 */
45678 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
45679   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
45680 }
45681
45682 /*
45683 ** Query a blob handle for the size of the data.
45684 **
45685 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
45686 ** so no mutex is required for access.
45687 */
45688 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
45689   Incrblob *p = (Incrblob *)pBlob;
45690   return p->nByte;
45691 }
45692
45693 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
45694
45695 /************** End of vdbeblob.c ********************************************/
45696 /************** Begin file journal.c *****************************************/
45697 /*
45698 ** 2007 August 22
45699 **
45700 ** The author disclaims copyright to this source code.  In place of
45701 ** a legal notice, here is a blessing:
45702 **
45703 **    May you do good and not evil.
45704 **    May you find forgiveness for yourself and forgive others.
45705 **    May you share freely, never taking more than you give.
45706 **
45707 *************************************************************************
45708 **
45709 ** @(#) $Id: journal.c,v 1.7 2007/09/06 13:49:37 drh Exp $
45710 */
45711
45712 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
45713
45714 /*
45715 ** This file implements a special kind of sqlite3_file object used
45716 ** by SQLite to create journal files if the atomic-write optimization
45717 ** is enabled.
45718 **
45719 ** The distinctive characteristic of this sqlite3_file is that the
45720 ** actual on disk file is created lazily. When the file is created,
45721 ** the caller specifies a buffer size for an in-memory buffer to
45722 ** be used to service read() and write() requests. The actual file
45723 ** on disk is not created or populated until either:
45724 **
45725 **   1) The in-memory representation grows too large for the allocated 
45726 **      buffer, or
45727 **   2) The xSync() method is called.
45728 */
45729
45730
45731
45732 /*
45733 ** A JournalFile object is a subclass of sqlite3_file used by
45734 ** as an open file handle for journal files.
45735 */
45736 struct JournalFile {
45737   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
45738   int nBuf;                       /* Size of zBuf[] in bytes */
45739   char *zBuf;                     /* Space to buffer journal writes */
45740   int iSize;                      /* Amount of zBuf[] currently used */
45741   int flags;                      /* xOpen flags */
45742   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
45743   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
45744   const char *zJournal;           /* Name of the journal file */
45745 };
45746 typedef struct JournalFile JournalFile;
45747
45748 /*
45749 ** If it does not already exists, create and populate the on-disk file 
45750 ** for JournalFile p.
45751 */
45752 static int createFile(JournalFile *p){
45753   int rc = SQLITE_OK;
45754   if( !p->pReal ){
45755     sqlite3_file *pReal = (sqlite3_file *)&p[1];
45756     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
45757     if( rc==SQLITE_OK ){
45758       p->pReal = pReal;
45759       if( p->iSize>0 ){
45760         assert(p->iSize<=p->nBuf);
45761         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
45762       }
45763     }
45764   }
45765   return rc;
45766 }
45767
45768 /*
45769 ** Close the file.
45770 */
45771 static int jrnlClose(sqlite3_file *pJfd){
45772   JournalFile *p = (JournalFile *)pJfd;
45773   if( p->pReal ){
45774     sqlite3OsClose(p->pReal);
45775   }
45776   sqlite3_free(p->zBuf);
45777   return SQLITE_OK;
45778 }
45779
45780 /*
45781 ** Read data from the file.
45782 */
45783 static int jrnlRead(
45784   sqlite3_file *pJfd,    /* The journal file from which to read */
45785   void *zBuf,            /* Put the results here */
45786   int iAmt,              /* Number of bytes to read */
45787   sqlite_int64 iOfst     /* Begin reading at this offset */
45788 ){
45789   int rc = SQLITE_OK;
45790   JournalFile *p = (JournalFile *)pJfd;
45791   if( p->pReal ){
45792     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
45793   }else{
45794     assert( iAmt+iOfst<=p->iSize );
45795     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
45796   }
45797   return rc;
45798 }
45799
45800 /*
45801 ** Write data to the file.
45802 */
45803 static int jrnlWrite(
45804   sqlite3_file *pJfd,    /* The journal file into which to write */
45805   const void *zBuf,      /* Take data to be written from here */
45806   int iAmt,              /* Number of bytes to write */
45807   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
45808 ){
45809   int rc = SQLITE_OK;
45810   JournalFile *p = (JournalFile *)pJfd;
45811   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
45812     rc = createFile(p);
45813   }
45814   if( rc==SQLITE_OK ){
45815     if( p->pReal ){
45816       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
45817     }else{
45818       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
45819       if( p->iSize<(iOfst+iAmt) ){
45820         p->iSize = (iOfst+iAmt);
45821       }
45822     }
45823   }
45824   return rc;
45825 }
45826
45827 /*
45828 ** Truncate the file.
45829 */
45830 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
45831   int rc = SQLITE_OK;
45832   JournalFile *p = (JournalFile *)pJfd;
45833   if( p->pReal ){
45834     rc = sqlite3OsTruncate(p->pReal, size);
45835   }else if( size<p->iSize ){
45836     p->iSize = size;
45837   }
45838   return rc;
45839 }
45840
45841 /*
45842 ** Sync the file.
45843 */
45844 static int jrnlSync(sqlite3_file *pJfd, int flags){
45845   int rc;
45846   JournalFile *p = (JournalFile *)pJfd;
45847   rc = createFile(p);
45848   if( rc==SQLITE_OK ){
45849     rc = sqlite3OsSync(p->pReal, flags);
45850   }
45851   return rc;
45852 }
45853
45854 /*
45855 ** Query the size of the file in bytes.
45856 */
45857 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
45858   int rc = SQLITE_OK;
45859   JournalFile *p = (JournalFile *)pJfd;
45860   if( p->pReal ){
45861     rc = sqlite3OsFileSize(p->pReal, pSize);
45862   }else{
45863     *pSize = (sqlite_int64) p->iSize;
45864   }
45865   return rc;
45866 }
45867
45868 /*
45869 ** Table of methods for JournalFile sqlite3_file object.
45870 */
45871 static struct sqlite3_io_methods JournalFileMethods = {
45872   1,             /* iVersion */
45873   jrnlClose,     /* xClose */
45874   jrnlRead,      /* xRead */
45875   jrnlWrite,     /* xWrite */
45876   jrnlTruncate,  /* xTruncate */
45877   jrnlSync,      /* xSync */
45878   jrnlFileSize,  /* xFileSize */
45879   0,             /* xLock */
45880   0,             /* xUnlock */
45881   0,             /* xCheckReservedLock */
45882   0,             /* xFileControl */
45883   0,             /* xSectorSize */
45884   0              /* xDeviceCharacteristics */
45885 };
45886
45887 /* 
45888 ** Open a journal file.
45889 */
45890 SQLITE_PRIVATE int sqlite3JournalOpen(
45891   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
45892   const char *zName,         /* Name of the journal file */
45893   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
45894   int flags,                 /* Opening flags */
45895   int nBuf                   /* Bytes buffered before opening the file */
45896 ){
45897   JournalFile *p = (JournalFile *)pJfd;
45898   memset(p, 0, sqlite3JournalSize(pVfs));
45899   if( nBuf>0 ){
45900     p->zBuf = sqlite3MallocZero(nBuf);
45901     if( !p->zBuf ){
45902       return SQLITE_NOMEM;
45903     }
45904   }else{
45905     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
45906   }
45907   p->pMethod = &JournalFileMethods;
45908   p->nBuf = nBuf;
45909   p->flags = flags;
45910   p->zJournal = zName;
45911   p->pVfs = pVfs;
45912   return SQLITE_OK;
45913 }
45914
45915 /*
45916 ** If the argument p points to a JournalFile structure, and the underlying
45917 ** file has not yet been created, create it now.
45918 */
45919 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
45920   if( p->pMethods!=&JournalFileMethods ){
45921     return SQLITE_OK;
45922   }
45923   return createFile((JournalFile *)p);
45924 }
45925
45926 /* 
45927 ** Return the number of bytes required to store a JournalFile that uses vfs
45928 ** pVfs to create the underlying on-disk files.
45929 */
45930 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
45931   return (pVfs->szOsFile+sizeof(JournalFile));
45932 }
45933 #endif
45934
45935 /************** End of journal.c *********************************************/
45936 /************** Begin file expr.c ********************************************/
45937 /*
45938 ** 2001 September 15
45939 **
45940 ** The author disclaims copyright to this source code.  In place of
45941 ** a legal notice, here is a blessing:
45942 **
45943 **    May you do good and not evil.
45944 **    May you find forgiveness for yourself and forgive others.
45945 **    May you share freely, never taking more than you give.
45946 **
45947 *************************************************************************
45948 ** This file contains routines used for analyzing expressions and
45949 ** for generating VDBE code that evaluates expressions in SQLite.
45950 **
45951 ** $Id: expr.c,v 1.354 2008/03/12 10:39:00 danielk1977 Exp $
45952 */
45953
45954 /*
45955 ** Return the 'affinity' of the expression pExpr if any.
45956 **
45957 ** If pExpr is a column, a reference to a column via an 'AS' alias,
45958 ** or a sub-select with a column as the return value, then the 
45959 ** affinity of that column is returned. Otherwise, 0x00 is returned,
45960 ** indicating no affinity for the expression.
45961 **
45962 ** i.e. the WHERE clause expresssions in the following statements all
45963 ** have an affinity:
45964 **
45965 ** CREATE TABLE t1(a);
45966 ** SELECT * FROM t1 WHERE a;
45967 ** SELECT a AS b FROM t1 WHERE b;
45968 ** SELECT * FROM t1 WHERE (select a from t1);
45969 */
45970 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
45971   int op = pExpr->op;
45972   if( op==TK_SELECT ){
45973     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
45974   }
45975 #ifndef SQLITE_OMIT_CAST
45976   if( op==TK_CAST ){
45977     return sqlite3AffinityType(&pExpr->token);
45978   }
45979 #endif
45980   return pExpr->affinity;
45981 }
45982
45983 /*
45984 ** Set the collating sequence for expression pExpr to be the collating
45985 ** sequence named by pToken.   Return a pointer to the revised expression.
45986 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
45987 ** flag.  An explicit collating sequence will override implicit
45988 ** collating sequences.
45989 */
45990 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
45991   char *zColl = 0;            /* Dequoted name of collation sequence */
45992   CollSeq *pColl;
45993   zColl = sqlite3NameFromToken(pParse->db, pName);
45994   if( pExpr && zColl ){
45995     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
45996     if( pColl ){
45997       pExpr->pColl = pColl;
45998       pExpr->flags |= EP_ExpCollate;
45999     }
46000   }
46001   sqlite3_free(zColl);
46002   return pExpr;
46003 }
46004
46005 /*
46006 ** Return the default collation sequence for the expression pExpr. If
46007 ** there is no default collation type, return 0.
46008 */
46009 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
46010   CollSeq *pColl = 0;
46011   if( pExpr ){
46012     int op;
46013     pColl = pExpr->pColl;
46014     op = pExpr->op;
46015     if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
46016       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
46017     }
46018   }
46019   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
46020     pColl = 0;
46021   }
46022   return pColl;
46023 }
46024
46025 /*
46026 ** pExpr is an operand of a comparison operator.  aff2 is the
46027 ** type affinity of the other operand.  This routine returns the
46028 ** type affinity that should be used for the comparison operator.
46029 */
46030 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
46031   char aff1 = sqlite3ExprAffinity(pExpr);
46032   if( aff1 && aff2 ){
46033     /* Both sides of the comparison are columns. If one has numeric
46034     ** affinity, use that. Otherwise use no affinity.
46035     */
46036     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
46037       return SQLITE_AFF_NUMERIC;
46038     }else{
46039       return SQLITE_AFF_NONE;
46040     }
46041   }else if( !aff1 && !aff2 ){
46042     /* Neither side of the comparison is a column.  Compare the
46043     ** results directly.
46044     */
46045     return SQLITE_AFF_NONE;
46046   }else{
46047     /* One side is a column, the other is not. Use the columns affinity. */
46048     assert( aff1==0 || aff2==0 );
46049     return (aff1 + aff2);
46050   }
46051 }
46052
46053 /*
46054 ** pExpr is a comparison operator.  Return the type affinity that should
46055 ** be applied to both operands prior to doing the comparison.
46056 */
46057 static char comparisonAffinity(Expr *pExpr){
46058   char aff;
46059   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
46060           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
46061           pExpr->op==TK_NE );
46062   assert( pExpr->pLeft );
46063   aff = sqlite3ExprAffinity(pExpr->pLeft);
46064   if( pExpr->pRight ){
46065     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
46066   }
46067   else if( pExpr->pSelect ){
46068     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
46069   }
46070   else if( !aff ){
46071     aff = SQLITE_AFF_NONE;
46072   }
46073   return aff;
46074 }
46075
46076 /*
46077 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
46078 ** idx_affinity is the affinity of an indexed column. Return true
46079 ** if the index with affinity idx_affinity may be used to implement
46080 ** the comparison in pExpr.
46081 */
46082 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
46083   char aff = comparisonAffinity(pExpr);
46084   switch( aff ){
46085     case SQLITE_AFF_NONE:
46086       return 1;
46087     case SQLITE_AFF_TEXT:
46088       return idx_affinity==SQLITE_AFF_TEXT;
46089     default:
46090       return sqlite3IsNumericAffinity(idx_affinity);
46091   }
46092 }
46093
46094 /*
46095 ** Return the P5 value that should be used for a binary comparison
46096 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
46097 */
46098 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
46099   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
46100   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
46101   return aff;
46102 }
46103
46104 /*
46105 ** Return a pointer to the collation sequence that should be used by
46106 ** a binary comparison operator comparing pLeft and pRight.
46107 **
46108 ** If the left hand expression has a collating sequence type, then it is
46109 ** used. Otherwise the collation sequence for the right hand expression
46110 ** is used, or the default (BINARY) if neither expression has a collating
46111 ** type.
46112 **
46113 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
46114 ** it is not considered.
46115 */
46116 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
46117   Parse *pParse, 
46118   Expr *pLeft, 
46119   Expr *pRight
46120 ){
46121   CollSeq *pColl;
46122   assert( pLeft );
46123   if( pLeft->flags & EP_ExpCollate ){
46124     assert( pLeft->pColl );
46125     pColl = pLeft->pColl;
46126   }else if( pRight && pRight->flags & EP_ExpCollate ){
46127     assert( pRight->pColl );
46128     pColl = pRight->pColl;
46129   }else{
46130     pColl = sqlite3ExprCollSeq(pParse, pLeft);
46131     if( !pColl ){
46132       pColl = sqlite3ExprCollSeq(pParse, pRight);
46133     }
46134   }
46135   return pColl;
46136 }
46137
46138 /*
46139 ** Generate code for a comparison operator.
46140 */
46141 static int codeCompare(
46142   Parse *pParse,    /* The parsing (and code generating) context */
46143   Expr *pLeft,      /* The left operand */
46144   Expr *pRight,     /* The right operand */
46145   int opcode,       /* The comparison opcode */
46146   int in1, int in2, /* Register holding operands */
46147   int dest,         /* Jump here if true.  */
46148   int jumpIfNull    /* If true, jump if either operand is NULL */
46149 ){
46150   int p5;
46151   int addr;
46152   CollSeq *p4;
46153
46154   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
46155   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
46156   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
46157                            (void*)p4, P4_COLLSEQ);
46158   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
46159   return addr;
46160 }
46161
46162 /*
46163 ** Construct a new expression node and return a pointer to it.  Memory
46164 ** for this node is obtained from sqlite3_malloc().  The calling function
46165 ** is responsible for making sure the node eventually gets freed.
46166 */
46167 SQLITE_PRIVATE Expr *sqlite3Expr(
46168   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
46169   int op,                 /* Expression opcode */
46170   Expr *pLeft,            /* Left operand */
46171   Expr *pRight,           /* Right operand */
46172   const Token *pToken     /* Argument token */
46173 ){
46174   Expr *pNew;
46175   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
46176   if( pNew==0 ){
46177     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
46178     ** this function must always be allocated with sqlite3Expr() for this 
46179     ** reason. 
46180     */
46181     sqlite3ExprDelete(pLeft);
46182     sqlite3ExprDelete(pRight);
46183     return 0;
46184   }
46185   pNew->op = op;
46186   pNew->pLeft = pLeft;
46187   pNew->pRight = pRight;
46188   pNew->iAgg = -1;
46189   if( pToken ){
46190     assert( pToken->dyn==0 );
46191     pNew->span = pNew->token = *pToken;
46192   }else if( pLeft ){
46193     if( pRight ){
46194       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
46195       if( pRight->flags & EP_ExpCollate ){
46196         pNew->flags |= EP_ExpCollate;
46197         pNew->pColl = pRight->pColl;
46198       }
46199     }
46200     if( pLeft->flags & EP_ExpCollate ){
46201       pNew->flags |= EP_ExpCollate;
46202       pNew->pColl = pLeft->pColl;
46203     }
46204   }
46205
46206   sqlite3ExprSetHeight(pNew);
46207   return pNew;
46208 }
46209
46210 /*
46211 ** Works like sqlite3Expr() except that it takes an extra Parse*
46212 ** argument and notifies the associated connection object if malloc fails.
46213 */
46214 SQLITE_PRIVATE Expr *sqlite3PExpr(
46215   Parse *pParse,          /* Parsing context */
46216   int op,                 /* Expression opcode */
46217   Expr *pLeft,            /* Left operand */
46218   Expr *pRight,           /* Right operand */
46219   const Token *pToken     /* Argument token */
46220 ){
46221   return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
46222 }
46223
46224 /*
46225 ** When doing a nested parse, you can include terms in an expression
46226 ** that look like this:   #1 #2 ...  These terms refer to registers
46227 ** in the virtual machine.  #N is the N-th register.
46228 **
46229 ** This routine is called by the parser to deal with on of those terms.
46230 ** It immediately generates code to store the value in a memory location.
46231 ** The returns an expression that will code to extract the value from
46232 ** that memory location as needed.
46233 */
46234 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
46235   Vdbe *v = pParse->pVdbe;
46236   Expr *p;
46237   if( pParse->nested==0 ){
46238     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
46239     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
46240   }
46241   if( v==0 ) return 0;
46242   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
46243   if( p==0 ){
46244     return 0;  /* Malloc failed */
46245   }
46246   p->iTable = atoi((char*)&pToken->z[1]);
46247   return p;
46248 }
46249
46250 /*
46251 ** Join two expressions using an AND operator.  If either expression is
46252 ** NULL, then just return the other expression.
46253 */
46254 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
46255   if( pLeft==0 ){
46256     return pRight;
46257   }else if( pRight==0 ){
46258     return pLeft;
46259   }else{
46260     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
46261   }
46262 }
46263
46264 /*
46265 ** Set the Expr.span field of the given expression to span all
46266 ** text between the two given tokens.
46267 */
46268 SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
46269   assert( pRight!=0 );
46270   assert( pLeft!=0 );
46271   if( pExpr && pRight->z && pLeft->z ){
46272     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
46273     if( pLeft->dyn==0 && pRight->dyn==0 ){
46274       pExpr->span.z = pLeft->z;
46275       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
46276     }else{
46277       pExpr->span.z = 0;
46278     }
46279   }
46280 }
46281
46282 /*
46283 ** Construct a new expression node for a function with multiple
46284 ** arguments.
46285 */
46286 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
46287   Expr *pNew;
46288   assert( pToken );
46289   pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) );
46290   if( pNew==0 ){
46291     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
46292     return 0;
46293   }
46294   pNew->op = TK_FUNCTION;
46295   pNew->pList = pList;
46296   assert( pToken->dyn==0 );
46297   pNew->token = *pToken;
46298   pNew->span = pNew->token;
46299
46300   sqlite3ExprSetHeight(pNew);
46301   return pNew;
46302 }
46303
46304 /*
46305 ** Assign a variable number to an expression that encodes a wildcard
46306 ** in the original SQL statement.  
46307 **
46308 ** Wildcards consisting of a single "?" are assigned the next sequential
46309 ** variable number.
46310 **
46311 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
46312 ** sure "nnn" is not too be to avoid a denial of service attack when
46313 ** the SQL statement comes from an external source.
46314 **
46315 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
46316 ** as the previous instance of the same wildcard.  Or if this is the first
46317 ** instance of the wildcard, the next sequenial variable number is
46318 ** assigned.
46319 */
46320 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
46321   Token *pToken;
46322   sqlite3 *db = pParse->db;
46323
46324   if( pExpr==0 ) return;
46325   pToken = &pExpr->token;
46326   assert( pToken->n>=1 );
46327   assert( pToken->z!=0 );
46328   assert( pToken->z[0]!=0 );
46329   if( pToken->n==1 ){
46330     /* Wildcard of the form "?".  Assign the next variable number */
46331     pExpr->iTable = ++pParse->nVar;
46332   }else if( pToken->z[0]=='?' ){
46333     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
46334     ** use it as the variable number */
46335     int i;
46336     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
46337     if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
46338       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
46339           SQLITE_MAX_VARIABLE_NUMBER);
46340     }
46341     if( i>pParse->nVar ){
46342       pParse->nVar = i;
46343     }
46344   }else{
46345     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
46346     ** number as the prior appearance of the same name, or if the name
46347     ** has never appeared before, reuse the same variable number
46348     */
46349     int i, n;
46350     n = pToken->n;
46351     for(i=0; i<pParse->nVarExpr; i++){
46352       Expr *pE;
46353       if( (pE = pParse->apVarExpr[i])!=0
46354           && pE->token.n==n
46355           && memcmp(pE->token.z, pToken->z, n)==0 ){
46356         pExpr->iTable = pE->iTable;
46357         break;
46358       }
46359     }
46360     if( i>=pParse->nVarExpr ){
46361       pExpr->iTable = ++pParse->nVar;
46362       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
46363         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
46364         pParse->apVarExpr =
46365             sqlite3DbReallocOrFree(
46366               db,
46367               pParse->apVarExpr,
46368               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
46369             );
46370       }
46371       if( !db->mallocFailed ){
46372         assert( pParse->apVarExpr!=0 );
46373         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
46374       }
46375     }
46376   } 
46377   if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
46378     sqlite3ErrorMsg(pParse, "too many SQL variables");
46379   }
46380 }
46381
46382 /*
46383 ** Recursively delete an expression tree.
46384 */
46385 SQLITE_PRIVATE void sqlite3ExprDelete(Expr *p){
46386   if( p==0 ) return;
46387   if( p->span.dyn ) sqlite3_free((char*)p->span.z);
46388   if( p->token.dyn ) sqlite3_free((char*)p->token.z);
46389   sqlite3ExprDelete(p->pLeft);
46390   sqlite3ExprDelete(p->pRight);
46391   sqlite3ExprListDelete(p->pList);
46392   sqlite3SelectDelete(p->pSelect);
46393   sqlite3_free(p);
46394 }
46395
46396 /*
46397 ** The Expr.token field might be a string literal that is quoted.
46398 ** If so, remove the quotation marks.
46399 */
46400 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
46401   if( ExprHasAnyProperty(p, EP_Dequoted) ){
46402     return;
46403   }
46404   ExprSetProperty(p, EP_Dequoted);
46405   if( p->token.dyn==0 ){
46406     sqlite3TokenCopy(db, &p->token, &p->token);
46407   }
46408   sqlite3Dequote((char*)p->token.z);
46409 }
46410
46411
46412 /*
46413 ** The following group of routines make deep copies of expressions,
46414 ** expression lists, ID lists, and select statements.  The copies can
46415 ** be deleted (by being passed to their respective ...Delete() routines)
46416 ** without effecting the originals.
46417 **
46418 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
46419 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
46420 ** by subsequent calls to sqlite*ListAppend() routines.
46421 **
46422 ** Any tables that the SrcList might point to are not duplicated.
46423 */
46424 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
46425   Expr *pNew;
46426   if( p==0 ) return 0;
46427   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
46428   if( pNew==0 ) return 0;
46429   memcpy(pNew, p, sizeof(*pNew));
46430   if( p->token.z!=0 ){
46431     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
46432     pNew->token.dyn = 1;
46433   }else{
46434     assert( pNew->token.z==0 );
46435   }
46436   pNew->span.z = 0;
46437   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
46438   pNew->pRight = sqlite3ExprDup(db, p->pRight);
46439   pNew->pList = sqlite3ExprListDup(db, p->pList);
46440   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
46441   return pNew;
46442 }
46443 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
46444   if( pTo->dyn ) sqlite3_free((char*)pTo->z);
46445   if( pFrom->z ){
46446     pTo->n = pFrom->n;
46447     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
46448     pTo->dyn = 1;
46449   }else{
46450     pTo->z = 0;
46451   }
46452 }
46453 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
46454   ExprList *pNew;
46455   struct ExprList_item *pItem, *pOldItem;
46456   int i;
46457   if( p==0 ) return 0;
46458   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
46459   if( pNew==0 ) return 0;
46460   pNew->iECursor = 0;
46461   pNew->nExpr = pNew->nAlloc = p->nExpr;
46462   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
46463   if( pItem==0 ){
46464     sqlite3_free(pNew);
46465     return 0;
46466   } 
46467   pOldItem = p->a;
46468   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
46469     Expr *pNewExpr, *pOldExpr;
46470     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
46471     if( pOldExpr->span.z!=0 && pNewExpr ){
46472       /* Always make a copy of the span for top-level expressions in the
46473       ** expression list.  The logic in SELECT processing that determines
46474       ** the names of columns in the result set needs this information */
46475       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
46476     }
46477     assert( pNewExpr==0 || pNewExpr->span.z!=0 
46478             || pOldExpr->span.z==0
46479             || db->mallocFailed );
46480     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
46481     pItem->sortOrder = pOldItem->sortOrder;
46482     pItem->isAgg = pOldItem->isAgg;
46483     pItem->done = 0;
46484   }
46485   return pNew;
46486 }
46487
46488 /*
46489 ** If cursors, triggers, views and subqueries are all omitted from
46490 ** the build, then none of the following routines, except for 
46491 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
46492 ** called with a NULL argument.
46493 */
46494 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
46495  || !defined(SQLITE_OMIT_SUBQUERY)
46496 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
46497   SrcList *pNew;
46498   int i;
46499   int nByte;
46500   if( p==0 ) return 0;
46501   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
46502   pNew = sqlite3DbMallocRaw(db, nByte );
46503   if( pNew==0 ) return 0;
46504   pNew->nSrc = pNew->nAlloc = p->nSrc;
46505   for(i=0; i<p->nSrc; i++){
46506     struct SrcList_item *pNewItem = &pNew->a[i];
46507     struct SrcList_item *pOldItem = &p->a[i];
46508     Table *pTab;
46509     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
46510     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
46511     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
46512     pNewItem->jointype = pOldItem->jointype;
46513     pNewItem->iCursor = pOldItem->iCursor;
46514     pNewItem->isPopulated = pOldItem->isPopulated;
46515     pTab = pNewItem->pTab = pOldItem->pTab;
46516     if( pTab ){
46517       pTab->nRef++;
46518     }
46519     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
46520     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
46521     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
46522     pNewItem->colUsed = pOldItem->colUsed;
46523   }
46524   return pNew;
46525 }
46526 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
46527   IdList *pNew;
46528   int i;
46529   if( p==0 ) return 0;
46530   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
46531   if( pNew==0 ) return 0;
46532   pNew->nId = pNew->nAlloc = p->nId;
46533   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
46534   if( pNew->a==0 ){
46535     sqlite3_free(pNew);
46536     return 0;
46537   }
46538   for(i=0; i<p->nId; i++){
46539     struct IdList_item *pNewItem = &pNew->a[i];
46540     struct IdList_item *pOldItem = &p->a[i];
46541     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
46542     pNewItem->idx = pOldItem->idx;
46543   }
46544   return pNew;
46545 }
46546 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
46547   Select *pNew;
46548   if( p==0 ) return 0;
46549   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
46550   if( pNew==0 ) return 0;
46551   pNew->isDistinct = p->isDistinct;
46552   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
46553   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
46554   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
46555   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
46556   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
46557   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
46558   pNew->op = p->op;
46559   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
46560   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
46561   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
46562   pNew->iLimit = -1;
46563   pNew->iOffset = -1;
46564   pNew->isResolved = p->isResolved;
46565   pNew->isAgg = p->isAgg;
46566   pNew->usesEphm = 0;
46567   pNew->disallowOrderBy = 0;
46568   pNew->pRightmost = 0;
46569   pNew->addrOpenEphm[0] = -1;
46570   pNew->addrOpenEphm[1] = -1;
46571   pNew->addrOpenEphm[2] = -1;
46572   return pNew;
46573 }
46574 #else
46575 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
46576   assert( p==0 );
46577   return 0;
46578 }
46579 #endif
46580
46581
46582 /*
46583 ** Add a new element to the end of an expression list.  If pList is
46584 ** initially NULL, then create a new expression list.
46585 */
46586 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
46587   Parse *pParse,          /* Parsing context */
46588   ExprList *pList,        /* List to which to append. Might be NULL */
46589   Expr *pExpr,            /* Expression to be appended */
46590   Token *pName            /* AS keyword for the expression */
46591 ){
46592   sqlite3 *db = pParse->db;
46593   if( pList==0 ){
46594     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
46595     if( pList==0 ){
46596       goto no_mem;
46597     }
46598     assert( pList->nAlloc==0 );
46599   }
46600   if( pList->nAlloc<=pList->nExpr ){
46601     struct ExprList_item *a;
46602     int n = pList->nAlloc*2 + 4;
46603     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
46604     if( a==0 ){
46605       goto no_mem;
46606     }
46607     pList->a = a;
46608     pList->nAlloc = n;
46609   }
46610   assert( pList->a!=0 );
46611   if( pExpr || pName ){
46612     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
46613     memset(pItem, 0, sizeof(*pItem));
46614     pItem->zName = sqlite3NameFromToken(db, pName);
46615     pItem->pExpr = pExpr;
46616   }
46617   return pList;
46618
46619 no_mem:     
46620   /* Avoid leaking memory if malloc has failed. */
46621   sqlite3ExprDelete(pExpr);
46622   sqlite3ExprListDelete(pList);
46623   return 0;
46624 }
46625
46626 /*
46627 ** If the expression list pEList contains more than iLimit elements,
46628 ** leave an error message in pParse.
46629 */
46630 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
46631   Parse *pParse,
46632   ExprList *pEList,
46633   int iLimit,
46634   const char *zObject
46635 ){
46636   if( pEList && pEList->nExpr>iLimit ){
46637     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
46638   }
46639 }
46640
46641
46642 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
46643 /* The following three functions, heightOfExpr(), heightOfExprList()
46644 ** and heightOfSelect(), are used to determine the maximum height
46645 ** of any expression tree referenced by the structure passed as the
46646 ** first argument.
46647 **
46648 ** If this maximum height is greater than the current value pointed
46649 ** to by pnHeight, the second parameter, then set *pnHeight to that
46650 ** value.
46651 */
46652 static void heightOfExpr(Expr *p, int *pnHeight){
46653   if( p ){
46654     if( p->nHeight>*pnHeight ){
46655       *pnHeight = p->nHeight;
46656     }
46657   }
46658 }
46659 static void heightOfExprList(ExprList *p, int *pnHeight){
46660   if( p ){
46661     int i;
46662     for(i=0; i<p->nExpr; i++){
46663       heightOfExpr(p->a[i].pExpr, pnHeight);
46664     }
46665   }
46666 }
46667 static void heightOfSelect(Select *p, int *pnHeight){
46668   if( p ){
46669     heightOfExpr(p->pWhere, pnHeight);
46670     heightOfExpr(p->pHaving, pnHeight);
46671     heightOfExpr(p->pLimit, pnHeight);
46672     heightOfExpr(p->pOffset, pnHeight);
46673     heightOfExprList(p->pEList, pnHeight);
46674     heightOfExprList(p->pGroupBy, pnHeight);
46675     heightOfExprList(p->pOrderBy, pnHeight);
46676     heightOfSelect(p->pPrior, pnHeight);
46677   }
46678 }
46679
46680 /*
46681 ** Set the Expr.nHeight variable in the structure passed as an 
46682 ** argument. An expression with no children, Expr.pList or 
46683 ** Expr.pSelect member has a height of 1. Any other expression
46684 ** has a height equal to the maximum height of any other 
46685 ** referenced Expr plus one.
46686 */
46687 SQLITE_PRIVATE void sqlite3ExprSetHeight(Expr *p){
46688   int nHeight = 0;
46689   heightOfExpr(p->pLeft, &nHeight);
46690   heightOfExpr(p->pRight, &nHeight);
46691   heightOfExprList(p->pList, &nHeight);
46692   heightOfSelect(p->pSelect, &nHeight);
46693   p->nHeight = nHeight + 1;
46694 }
46695
46696 /*
46697 ** Return the maximum height of any expression tree referenced
46698 ** by the select statement passed as an argument.
46699 */
46700 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
46701   int nHeight = 0;
46702   heightOfSelect(p, &nHeight);
46703   return nHeight;
46704 }
46705 #endif
46706
46707 /*
46708 ** Delete an entire expression list.
46709 */
46710 SQLITE_PRIVATE void sqlite3ExprListDelete(ExprList *pList){
46711   int i;
46712   struct ExprList_item *pItem;
46713   if( pList==0 ) return;
46714   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
46715   assert( pList->nExpr<=pList->nAlloc );
46716   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
46717     sqlite3ExprDelete(pItem->pExpr);
46718     sqlite3_free(pItem->zName);
46719   }
46720   sqlite3_free(pList->a);
46721   sqlite3_free(pList);
46722 }
46723
46724 /*
46725 ** Walk an expression tree.  Call xFunc for each node visited.
46726 **
46727 ** The return value from xFunc determines whether the tree walk continues.
46728 ** 0 means continue walking the tree.  1 means do not walk children
46729 ** of the current node but continue with siblings.  2 means abandon
46730 ** the tree walk completely.
46731 **
46732 ** The return value from this routine is 1 to abandon the tree walk
46733 ** and 0 to continue.
46734 **
46735 ** NOTICE:  This routine does *not* descend into subqueries.
46736 */
46737 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
46738 static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
46739   int rc;
46740   if( pExpr==0 ) return 0;
46741   rc = (*xFunc)(pArg, pExpr);
46742   if( rc==0 ){
46743     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
46744     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
46745     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
46746   }
46747   return rc>1;
46748 }
46749
46750 /*
46751 ** Call walkExprTree() for every expression in list p.
46752 */
46753 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
46754   int i;
46755   struct ExprList_item *pItem;
46756   if( !p ) return 0;
46757   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
46758     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
46759   }
46760   return 0;
46761 }
46762
46763 /*
46764 ** Call walkExprTree() for every expression in Select p, not including
46765 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
46766 ** or OFFSET expressions..
46767 */
46768 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
46769   walkExprList(p->pEList, xFunc, pArg);
46770   walkExprTree(p->pWhere, xFunc, pArg);
46771   walkExprList(p->pGroupBy, xFunc, pArg);
46772   walkExprTree(p->pHaving, xFunc, pArg);
46773   walkExprList(p->pOrderBy, xFunc, pArg);
46774   if( p->pPrior ){
46775     walkSelectExpr(p->pPrior, xFunc, pArg);
46776   }
46777   return 0;
46778 }
46779
46780
46781 /*
46782 ** This routine is designed as an xFunc for walkExprTree().
46783 **
46784 ** pArg is really a pointer to an integer.  If we can tell by looking
46785 ** at pExpr that the expression that contains pExpr is not a constant
46786 ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
46787 ** If pExpr does does not disqualify the expression from being a constant
46788 ** then do nothing.
46789 **
46790 ** After walking the whole tree, if no nodes are found that disqualify
46791 ** the expression as constant, then we assume the whole expression
46792 ** is constant.  See sqlite3ExprIsConstant() for additional information.
46793 */
46794 static int exprNodeIsConstant(void *pArg, Expr *pExpr){
46795   int *pN = (int*)pArg;
46796
46797   /* If *pArg is 3 then any term of the expression that comes from
46798   ** the ON or USING clauses of a join disqualifies the expression
46799   ** from being considered constant. */
46800   if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
46801     *pN = 0;
46802     return 2;
46803   }
46804
46805   switch( pExpr->op ){
46806     /* Consider functions to be constant if all their arguments are constant
46807     ** and *pArg==2 */
46808     case TK_FUNCTION:
46809       if( (*pN)==2 ) return 0;
46810       /* Fall through */
46811     case TK_ID:
46812     case TK_COLUMN:
46813     case TK_DOT:
46814     case TK_AGG_FUNCTION:
46815     case TK_AGG_COLUMN:
46816 #ifndef SQLITE_OMIT_SUBQUERY
46817     case TK_SELECT:
46818     case TK_EXISTS:
46819 #endif
46820       *pN = 0;
46821       return 2;
46822     case TK_IN:
46823       if( pExpr->pSelect ){
46824         *pN = 0;
46825         return 2;
46826       }
46827     default:
46828       return 0;
46829   }
46830 }
46831
46832 /*
46833 ** Walk an expression tree.  Return 1 if the expression is constant
46834 ** and 0 if it involves variables or function calls.
46835 **
46836 ** For the purposes of this function, a double-quoted string (ex: "abc")
46837 ** is considered a variable but a single-quoted string (ex: 'abc') is
46838 ** a constant.
46839 */
46840 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
46841   int isConst = 1;
46842   walkExprTree(p, exprNodeIsConstant, &isConst);
46843   return isConst;
46844 }
46845
46846 /*
46847 ** Walk an expression tree.  Return 1 if the expression is constant
46848 ** that does no originate from the ON or USING clauses of a join.
46849 ** Return 0 if it involves variables or function calls or terms from
46850 ** an ON or USING clause.
46851 */
46852 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
46853   int isConst = 3;
46854   walkExprTree(p, exprNodeIsConstant, &isConst);
46855   return isConst!=0;
46856 }
46857
46858 /*
46859 ** Walk an expression tree.  Return 1 if the expression is constant
46860 ** or a function call with constant arguments.  Return and 0 if there
46861 ** are any variables.
46862 **
46863 ** For the purposes of this function, a double-quoted string (ex: "abc")
46864 ** is considered a variable but a single-quoted string (ex: 'abc') is
46865 ** a constant.
46866 */
46867 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
46868   int isConst = 2;
46869   walkExprTree(p, exprNodeIsConstant, &isConst);
46870   return isConst!=0;
46871 }
46872
46873 /*
46874 ** If the expression p codes a constant integer that is small enough
46875 ** to fit in a 32-bit integer, return 1 and put the value of the integer
46876 ** in *pValue.  If the expression is not an integer or if it is too big
46877 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
46878 */
46879 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
46880   switch( p->op ){
46881     case TK_INTEGER: {
46882       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
46883         return 1;
46884       }
46885       break;
46886     }
46887     case TK_UPLUS: {
46888       return sqlite3ExprIsInteger(p->pLeft, pValue);
46889     }
46890     case TK_UMINUS: {
46891       int v;
46892       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
46893         *pValue = -v;
46894         return 1;
46895       }
46896       break;
46897     }
46898     default: break;
46899   }
46900   return 0;
46901 }
46902
46903 /*
46904 ** Return TRUE if the given string is a row-id column name.
46905 */
46906 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
46907   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
46908   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
46909   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
46910   return 0;
46911 }
46912
46913 /*
46914 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
46915 ** that name in the set of source tables in pSrcList and make the pExpr 
46916 ** expression node refer back to that source column.  The following changes
46917 ** are made to pExpr:
46918 **
46919 **    pExpr->iDb           Set the index in db->aDb[] of the database holding
46920 **                         the table.
46921 **    pExpr->iTable        Set to the cursor number for the table obtained
46922 **                         from pSrcList.
46923 **    pExpr->iColumn       Set to the column number within the table.
46924 **    pExpr->op            Set to TK_COLUMN.
46925 **    pExpr->pLeft         Any expression this points to is deleted
46926 **    pExpr->pRight        Any expression this points to is deleted.
46927 **
46928 ** The pDbToken is the name of the database (the "X").  This value may be
46929 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
46930 ** can be used.  The pTableToken is the name of the table (the "Y").  This
46931 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
46932 ** means that the form of the name is Z and that columns from any table
46933 ** can be used.
46934 **
46935 ** If the name cannot be resolved unambiguously, leave an error message
46936 ** in pParse and return non-zero.  Return zero on success.
46937 */
46938 static int lookupName(
46939   Parse *pParse,       /* The parsing context */
46940   Token *pDbToken,     /* Name of the database containing table, or NULL */
46941   Token *pTableToken,  /* Name of table containing column, or NULL */
46942   Token *pColumnToken, /* Name of the column. */
46943   NameContext *pNC,    /* The name context used to resolve the name */
46944   Expr *pExpr          /* Make this EXPR node point to the selected column */
46945 ){
46946   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
46947   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
46948   char *zCol = 0;      /* Name of the column.  The "Z" */
46949   int i, j;            /* Loop counters */
46950   int cnt = 0;         /* Number of matching column names */
46951   int cntTab = 0;      /* Number of matching table names */
46952   sqlite3 *db = pParse->db;  /* The database */
46953   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
46954   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
46955   NameContext *pTopNC = pNC;        /* First namecontext in the list */
46956   Schema *pSchema = 0;              /* Schema of the expression */
46957
46958   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
46959   zDb = sqlite3NameFromToken(db, pDbToken);
46960   zTab = sqlite3NameFromToken(db, pTableToken);
46961   zCol = sqlite3NameFromToken(db, pColumnToken);
46962   if( db->mallocFailed ){
46963     goto lookupname_end;
46964   }
46965
46966   pExpr->iTable = -1;
46967   while( pNC && cnt==0 ){
46968     ExprList *pEList;
46969     SrcList *pSrcList = pNC->pSrcList;
46970
46971     if( pSrcList ){
46972       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
46973         Table *pTab;
46974         int iDb;
46975         Column *pCol;
46976   
46977         pTab = pItem->pTab;
46978         assert( pTab!=0 );
46979         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
46980         assert( pTab->nCol>0 );
46981         if( zTab ){
46982           if( pItem->zAlias ){
46983             char *zTabName = pItem->zAlias;
46984             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
46985           }else{
46986             char *zTabName = pTab->zName;
46987             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
46988             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
46989               continue;
46990             }
46991           }
46992         }
46993         if( 0==(cntTab++) ){
46994           pExpr->iTable = pItem->iCursor;
46995           pSchema = pTab->pSchema;
46996           pMatch = pItem;
46997         }
46998         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
46999           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
47000             const char *zColl = pTab->aCol[j].zColl;
47001             IdList *pUsing;
47002             cnt++;
47003             pExpr->iTable = pItem->iCursor;
47004             pMatch = pItem;
47005             pSchema = pTab->pSchema;
47006             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
47007             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
47008             pExpr->affinity = pTab->aCol[j].affinity;
47009             if( (pExpr->flags & EP_ExpCollate)==0 ){
47010               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
47011             }
47012             if( i<pSrcList->nSrc-1 ){
47013               if( pItem[1].jointype & JT_NATURAL ){
47014                 /* If this match occurred in the left table of a natural join,
47015                 ** then skip the right table to avoid a duplicate match */
47016                 pItem++;
47017                 i++;
47018               }else if( (pUsing = pItem[1].pUsing)!=0 ){
47019                 /* If this match occurs on a column that is in the USING clause
47020                 ** of a join, skip the search of the right table of the join
47021                 ** to avoid a duplicate match there. */
47022                 int k;
47023                 for(k=0; k<pUsing->nId; k++){
47024                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
47025                     pItem++;
47026                     i++;
47027                     break;
47028                   }
47029                 }
47030               }
47031             }
47032             break;
47033           }
47034         }
47035       }
47036     }
47037
47038 #ifndef SQLITE_OMIT_TRIGGER
47039     /* If we have not already resolved the name, then maybe 
47040     ** it is a new.* or old.* trigger argument reference
47041     */
47042     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
47043       TriggerStack *pTriggerStack = pParse->trigStack;
47044       Table *pTab = 0;
47045       u32 *piColMask;
47046       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
47047         pExpr->iTable = pTriggerStack->newIdx;
47048         assert( pTriggerStack->pTab );
47049         pTab = pTriggerStack->pTab;
47050         piColMask = &(pTriggerStack->newColMask);
47051       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
47052         pExpr->iTable = pTriggerStack->oldIdx;
47053         assert( pTriggerStack->pTab );
47054         pTab = pTriggerStack->pTab;
47055         piColMask = &(pTriggerStack->oldColMask);
47056       }
47057
47058       if( pTab ){ 
47059         int iCol;
47060         Column *pCol = pTab->aCol;
47061
47062         pSchema = pTab->pSchema;
47063         cntTab++;
47064         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
47065           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
47066             const char *zColl = pTab->aCol[iCol].zColl;
47067             cnt++;
47068             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
47069             pExpr->affinity = pTab->aCol[iCol].affinity;
47070             if( (pExpr->flags & EP_ExpCollate)==0 ){
47071               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
47072             }
47073             pExpr->pTab = pTab;
47074             if( iCol>=0 ){
47075               *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
47076             }
47077             break;
47078           }
47079         }
47080       }
47081     }
47082 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
47083
47084     /*
47085     ** Perhaps the name is a reference to the ROWID
47086     */
47087     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
47088       cnt = 1;
47089       pExpr->iColumn = -1;
47090       pExpr->affinity = SQLITE_AFF_INTEGER;
47091     }
47092
47093     /*
47094     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
47095     ** might refer to an result-set alias.  This happens, for example, when
47096     ** we are resolving names in the WHERE clause of the following command:
47097     **
47098     **     SELECT a+b AS x FROM table WHERE x<10;
47099     **
47100     ** In cases like this, replace pExpr with a copy of the expression that
47101     ** forms the result set entry ("a+b" in the example) and return immediately.
47102     ** Note that the expression in the result set should have already been
47103     ** resolved by the time the WHERE clause is resolved.
47104     */
47105     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
47106       for(j=0; j<pEList->nExpr; j++){
47107         char *zAs = pEList->a[j].zName;
47108         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
47109           Expr *pDup, *pOrig;
47110           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
47111           assert( pExpr->pList==0 );
47112           assert( pExpr->pSelect==0 );
47113           pOrig = pEList->a[j].pExpr;
47114           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
47115             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
47116             sqlite3_free(zCol);
47117             return 2;
47118           }
47119           pDup = sqlite3ExprDup(db, pOrig);
47120           if( pExpr->flags & EP_ExpCollate ){
47121             pDup->pColl = pExpr->pColl;
47122             pDup->flags |= EP_ExpCollate;
47123           }
47124           if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z);
47125           if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z);
47126           memcpy(pExpr, pDup, sizeof(*pExpr));
47127           sqlite3_free(pDup);
47128           cnt = 1;
47129           pMatch = 0;
47130           assert( zTab==0 && zDb==0 );
47131           goto lookupname_end_2;
47132         }
47133       } 
47134     }
47135
47136     /* Advance to the next name context.  The loop will exit when either
47137     ** we have a match (cnt>0) or when we run out of name contexts.
47138     */
47139     if( cnt==0 ){
47140       pNC = pNC->pNext;
47141     }
47142   }
47143
47144   /*
47145   ** If X and Y are NULL (in other words if only the column name Z is
47146   ** supplied) and the value of Z is enclosed in double-quotes, then
47147   ** Z is a string literal if it doesn't match any column names.  In that
47148   ** case, we need to return right away and not make any changes to
47149   ** pExpr.
47150   **
47151   ** Because no reference was made to outer contexts, the pNC->nRef
47152   ** fields are not changed in any context.
47153   */
47154   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
47155     sqlite3_free(zCol);
47156     return 0;
47157   }
47158
47159   /*
47160   ** cnt==0 means there was not match.  cnt>1 means there were two or
47161   ** more matches.  Either way, we have an error.
47162   */
47163   if( cnt!=1 ){
47164     const char *zErr;
47165     zErr = cnt==0 ? "no such column" : "ambiguous column name";
47166     if( zDb ){
47167       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
47168     }else if( zTab ){
47169       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
47170     }else{
47171       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
47172     }
47173     pTopNC->nErr++;
47174   }
47175
47176   /* If a column from a table in pSrcList is referenced, then record
47177   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
47178   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
47179   ** column number is greater than the number of bits in the bitmask
47180   ** then set the high-order bit of the bitmask.
47181   */
47182   if( pExpr->iColumn>=0 && pMatch!=0 ){
47183     int n = pExpr->iColumn;
47184     if( n>=sizeof(Bitmask)*8 ){
47185       n = sizeof(Bitmask)*8-1;
47186     }
47187     assert( pMatch->iCursor==pExpr->iTable );
47188     pMatch->colUsed |= ((Bitmask)1)<<n;
47189   }
47190
47191 lookupname_end:
47192   /* Clean up and return
47193   */
47194   sqlite3_free(zDb);
47195   sqlite3_free(zTab);
47196   sqlite3ExprDelete(pExpr->pLeft);
47197   pExpr->pLeft = 0;
47198   sqlite3ExprDelete(pExpr->pRight);
47199   pExpr->pRight = 0;
47200   pExpr->op = TK_COLUMN;
47201 lookupname_end_2:
47202   sqlite3_free(zCol);
47203   if( cnt==1 ){
47204     assert( pNC!=0 );
47205     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
47206     if( pMatch && !pMatch->pSelect ){
47207       pExpr->pTab = pMatch->pTab;
47208     }
47209     /* Increment the nRef value on all name contexts from TopNC up to
47210     ** the point where the name matched. */
47211     for(;;){
47212       assert( pTopNC!=0 );
47213       pTopNC->nRef++;
47214       if( pTopNC==pNC ) break;
47215       pTopNC = pTopNC->pNext;
47216     }
47217     return 0;
47218   } else {
47219     return 1;
47220   }
47221 }
47222
47223 /*
47224 ** This routine is designed as an xFunc for walkExprTree().
47225 **
47226 ** Resolve symbolic names into TK_COLUMN operators for the current
47227 ** node in the expression tree.  Return 0 to continue the search down
47228 ** the tree or 2 to abort the tree walk.
47229 **
47230 ** This routine also does error checking and name resolution for
47231 ** function names.  The operator for aggregate functions is changed
47232 ** to TK_AGG_FUNCTION.
47233 */
47234 static int nameResolverStep(void *pArg, Expr *pExpr){
47235   NameContext *pNC = (NameContext*)pArg;
47236   Parse *pParse;
47237
47238   if( pExpr==0 ) return 1;
47239   assert( pNC!=0 );
47240   pParse = pNC->pParse;
47241
47242   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
47243   ExprSetProperty(pExpr, EP_Resolved);
47244 #ifndef NDEBUG
47245   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
47246     SrcList *pSrcList = pNC->pSrcList;
47247     int i;
47248     for(i=0; i<pNC->pSrcList->nSrc; i++){
47249       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
47250     }
47251   }
47252 #endif
47253   switch( pExpr->op ){
47254     /* Double-quoted strings (ex: "abc") are used as identifiers if
47255     ** possible.  Otherwise they remain as strings.  Single-quoted
47256     ** strings (ex: 'abc') are always string literals.
47257     */
47258     case TK_STRING: {
47259       if( pExpr->token.z[0]=='\'' ) break;
47260       /* Fall thru into the TK_ID case if this is a double-quoted string */
47261     }
47262     /* A lone identifier is the name of a column.
47263     */
47264     case TK_ID: {
47265       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
47266       return 1;
47267     }
47268   
47269     /* A table name and column name:     ID.ID
47270     ** Or a database, table and column:  ID.ID.ID
47271     */
47272     case TK_DOT: {
47273       Token *pColumn;
47274       Token *pTable;
47275       Token *pDb;
47276       Expr *pRight;
47277
47278       /* if( pSrcList==0 ) break; */
47279       pRight = pExpr->pRight;
47280       if( pRight->op==TK_ID ){
47281         pDb = 0;
47282         pTable = &pExpr->pLeft->token;
47283         pColumn = &pRight->token;
47284       }else{
47285         assert( pRight->op==TK_DOT );
47286         pDb = &pExpr->pLeft->token;
47287         pTable = &pRight->pLeft->token;
47288         pColumn = &pRight->pRight->token;
47289       }
47290       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
47291       return 1;
47292     }
47293
47294     /* Resolve function names
47295     */
47296     case TK_CONST_FUNC:
47297     case TK_FUNCTION: {
47298       ExprList *pList = pExpr->pList;    /* The argument list */
47299       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
47300       int no_such_func = 0;       /* True if no such function exists */
47301       int wrong_num_args = 0;     /* True if wrong number of arguments */
47302       int is_agg = 0;             /* True if is an aggregate function */
47303       int i;
47304       int auth;                   /* Authorization to use the function */
47305       int nId;                    /* Number of characters in function name */
47306       const char *zId;            /* The function name. */
47307       FuncDef *pDef;              /* Information about the function */
47308       int enc = ENC(pParse->db);  /* The database encoding */
47309
47310       zId = (char*)pExpr->token.z;
47311       nId = pExpr->token.n;
47312       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
47313       if( pDef==0 ){
47314         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
47315         if( pDef==0 ){
47316           no_such_func = 1;
47317         }else{
47318           wrong_num_args = 1;
47319         }
47320       }else{
47321         is_agg = pDef->xFunc==0;
47322       }
47323 #ifndef SQLITE_OMIT_AUTHORIZATION
47324       if( pDef ){
47325         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
47326         if( auth!=SQLITE_OK ){
47327           if( auth==SQLITE_DENY ){
47328             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
47329                                     pDef->zName);
47330             pNC->nErr++;
47331           }
47332           pExpr->op = TK_NULL;
47333           return 1;
47334         }
47335       }
47336 #endif
47337       if( is_agg && !pNC->allowAgg ){
47338         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
47339         pNC->nErr++;
47340         is_agg = 0;
47341       }else if( no_such_func ){
47342         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
47343         pNC->nErr++;
47344       }else if( wrong_num_args ){
47345         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
47346              nId, zId);
47347         pNC->nErr++;
47348       }
47349       if( is_agg ){
47350         pExpr->op = TK_AGG_FUNCTION;
47351         pNC->hasAgg = 1;
47352       }
47353       if( is_agg ) pNC->allowAgg = 0;
47354       for(i=0; pNC->nErr==0 && i<n; i++){
47355         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
47356       }
47357       if( is_agg ) pNC->allowAgg = 1;
47358       /* FIX ME:  Compute pExpr->affinity based on the expected return
47359       ** type of the function 
47360       */
47361       return is_agg;
47362     }
47363 #ifndef SQLITE_OMIT_SUBQUERY
47364     case TK_SELECT:
47365     case TK_EXISTS:
47366 #endif
47367     case TK_IN: {
47368       if( pExpr->pSelect ){
47369         int nRef = pNC->nRef;
47370 #ifndef SQLITE_OMIT_CHECK
47371         if( pNC->isCheck ){
47372           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
47373         }
47374 #endif
47375         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
47376         assert( pNC->nRef>=nRef );
47377         if( nRef!=pNC->nRef ){
47378           ExprSetProperty(pExpr, EP_VarSelect);
47379         }
47380       }
47381       break;
47382     }
47383 #ifndef SQLITE_OMIT_CHECK
47384     case TK_VARIABLE: {
47385       if( pNC->isCheck ){
47386         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
47387       }
47388       break;
47389     }
47390 #endif
47391   }
47392   return 0;
47393 }
47394
47395 /*
47396 ** This routine walks an expression tree and resolves references to
47397 ** table columns.  Nodes of the form ID.ID or ID resolve into an
47398 ** index to the table in the table list and a column offset.  The 
47399 ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
47400 ** value is changed to the index of the referenced table in pTabList
47401 ** plus the "base" value.  The base value will ultimately become the
47402 ** VDBE cursor number for a cursor that is pointing into the referenced
47403 ** table.  The Expr.iColumn value is changed to the index of the column 
47404 ** of the referenced table.  The Expr.iColumn value for the special
47405 ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
47406 ** alias for ROWID.
47407 **
47408 ** Also resolve function names and check the functions for proper
47409 ** usage.  Make sure all function names are recognized and all functions
47410 ** have the correct number of arguments.  Leave an error message
47411 ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
47412 **
47413 ** If the expression contains aggregate functions then set the EP_Agg
47414 ** property on the expression.
47415 */
47416 SQLITE_PRIVATE int sqlite3ExprResolveNames( 
47417   NameContext *pNC,       /* Namespace to resolve expressions in. */
47418   Expr *pExpr             /* The expression to be analyzed. */
47419 ){
47420   int savedHasAgg;
47421   if( pExpr==0 ) return 0;
47422 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
47423   if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
47424     sqlite3ErrorMsg(pNC->pParse, 
47425        "Expression tree is too large (maximum depth %d)",
47426        SQLITE_MAX_EXPR_DEPTH
47427     );
47428     return 1;
47429   }
47430   pNC->pParse->nHeight += pExpr->nHeight;
47431 #endif
47432   savedHasAgg = pNC->hasAgg;
47433   pNC->hasAgg = 0;
47434   walkExprTree(pExpr, nameResolverStep, pNC);
47435 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
47436   pNC->pParse->nHeight -= pExpr->nHeight;
47437 #endif
47438   if( pNC->nErr>0 ){
47439     ExprSetProperty(pExpr, EP_Error);
47440   }
47441   if( pNC->hasAgg ){
47442     ExprSetProperty(pExpr, EP_Agg);
47443   }else if( savedHasAgg ){
47444     pNC->hasAgg = 1;
47445   }
47446   return ExprHasProperty(pExpr, EP_Error);
47447 }
47448
47449 /*
47450 ** A pointer instance of this structure is used to pass information
47451 ** through walkExprTree into codeSubqueryStep().
47452 */
47453 typedef struct QueryCoder QueryCoder;
47454 struct QueryCoder {
47455   Parse *pParse;       /* The parsing context */
47456   NameContext *pNC;    /* Namespace of first enclosing query */
47457 };
47458
47459 #ifdef SQLITE_TEST
47460   int sqlite3_enable_in_opt = 1;
47461 #else
47462   #define sqlite3_enable_in_opt 1
47463 #endif
47464
47465 /*
47466 ** This function is used by the implementation of the IN (...) operator.
47467 ** It's job is to find or create a b-tree structure that may be used
47468 ** either to test for membership of the (...) set or to iterate through
47469 ** its members, skipping duplicates.
47470 **
47471 ** The cursor opened on the structure (database table, database index 
47472 ** or ephermal table) is stored in pX->iTable before this function returns.
47473 ** The returned value indicates the structure type, as follows:
47474 **
47475 **   IN_INDEX_ROWID - The cursor was opened on a database table.
47476 **   IN_INDEX_INDEX - The cursor was opened on a database index.
47477 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
47478 **                    populated epheremal table.
47479 **
47480 ** An existing structure may only be used if the SELECT is of the simple
47481 ** form:
47482 **
47483 **     SELECT <column> FROM <table>
47484 **
47485 ** If the mustBeUnique parameter is false, the structure will be used 
47486 ** for fast set membership tests. In this case an epheremal table must 
47487 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
47488 ** be found with <column> as its left-most column.
47489 **
47490 ** If mustBeUnique is true, then the structure will be used to iterate
47491 ** through the set members, skipping any duplicates. In this case an
47492 ** epheremal table must be used unless the selected <column> is guaranteed
47493 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
47494 ** is unique by virtue of a constraint or implicit index.
47495 */
47496 #ifndef SQLITE_OMIT_SUBQUERY
47497 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int mustBeUnique){
47498   Select *p;
47499   int eType = 0;
47500   int iTab = pParse->nTab++;
47501
47502   /* The follwing if(...) expression is true if the SELECT is of the 
47503   ** simple form:
47504   **
47505   **     SELECT <column> FROM <table>
47506   **
47507   ** If this is the case, it may be possible to use an existing table
47508   ** or index instead of generating an epheremal table.
47509   */
47510   if( sqlite3_enable_in_opt
47511    && (p=pX->pSelect)!=0 && !p->pPrior
47512    && !p->isDistinct && !p->isAgg && !p->pGroupBy
47513    && p->pSrc && p->pSrc->nSrc==1 && !p->pSrc->a[0].pSelect
47514    && p->pSrc->a[0].pTab && !p->pSrc->a[0].pTab->pSelect
47515    && p->pEList->nExpr==1 && p->pEList->a[0].pExpr->op==TK_COLUMN
47516    && !p->pLimit && !p->pOffset && !p->pWhere
47517   ){
47518     sqlite3 *db = pParse->db;
47519     Index *pIdx;
47520     Expr *pExpr = p->pEList->a[0].pExpr;
47521     int iCol = pExpr->iColumn;
47522     Vdbe *v = sqlite3GetVdbe(pParse);
47523
47524     /* This function is only called from two places. In both cases the vdbe
47525     ** has already been allocated. So assume sqlite3GetVdbe() is always
47526     ** successful here.
47527     */
47528     assert(v);
47529     if( iCol<0 ){
47530       int iMem = ++pParse->nMem;
47531       int iAddr;
47532       Table *pTab = p->pSrc->a[0].pTab;
47533       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
47534       sqlite3VdbeUsesBtree(v, iDb);
47535
47536       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
47537       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
47538
47539       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
47540       eType = IN_INDEX_ROWID;
47541
47542       sqlite3VdbeJumpHere(v, iAddr);
47543     }else{
47544       /* The collation sequence used by the comparison. If an index is to 
47545       ** be used in place of a temp-table, it must be ordered according
47546       ** to this collation sequence.
47547       */
47548       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
47549
47550       /* Check that the affinity that will be used to perform the 
47551       ** comparison is the same as the affinity of the column. If
47552       ** it is not, it is not possible to use any index.
47553       */
47554       Table *pTab = p->pSrc->a[0].pTab;
47555       char aff = comparisonAffinity(pX);
47556       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
47557
47558       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
47559         if( (pIdx->aiColumn[0]==iCol)
47560          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
47561          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
47562         ){
47563           int iDb;
47564           int iMem = ++pParse->nMem;
47565           int iAddr;
47566           char *pKey;
47567   
47568           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
47569           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
47570           sqlite3VdbeUsesBtree(v, iDb);
47571
47572           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
47573           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
47574   
47575           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
47576                                pKey,P4_KEYINFO_HANDOFF);
47577           VdbeComment((v, "%s", pIdx->zName));
47578           eType = IN_INDEX_INDEX;
47579           sqlite3VdbeAddOp2(v, OP_SetNumColumns, iTab, pIdx->nColumn);
47580
47581           sqlite3VdbeJumpHere(v, iAddr);
47582         }
47583       }
47584     }
47585   }
47586
47587   if( eType==0 ){
47588     sqlite3CodeSubselect(pParse, pX);
47589     eType = IN_INDEX_EPH;
47590   }else{
47591     pX->iTable = iTab;
47592   }
47593   return eType;
47594 }
47595 #endif
47596
47597 /*
47598 ** Generate code for scalar subqueries used as an expression
47599 ** and IN operators.  Examples:
47600 **
47601 **     (SELECT a FROM b)          -- subquery
47602 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
47603 **     x IN (4,5,11)              -- IN operator with list on right-hand side
47604 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
47605 **
47606 ** The pExpr parameter describes the expression that contains the IN
47607 ** operator or subquery.
47608 */
47609 #ifndef SQLITE_OMIT_SUBQUERY
47610 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
47611   int testAddr = 0;                       /* One-time test address */
47612   Vdbe *v = sqlite3GetVdbe(pParse);
47613   if( v==0 ) return;
47614
47615
47616   /* This code must be run in its entirety every time it is encountered
47617   ** if any of the following is true:
47618   **
47619   **    *  The right-hand side is a correlated subquery
47620   **    *  The right-hand side is an expression list containing variables
47621   **    *  We are inside a trigger
47622   **
47623   ** If all of the above are false, then we can run this code just once
47624   ** save the results, and reuse the same result on subsequent invocations.
47625   */
47626   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
47627     int mem = ++pParse->nMem;
47628     sqlite3VdbeAddOp1(v, OP_If, mem);
47629     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
47630     assert( testAddr>0 || pParse->db->mallocFailed );
47631   }
47632
47633   switch( pExpr->op ){
47634     case TK_IN: {
47635       char affinity;
47636       KeyInfo keyInfo;
47637       int addr;        /* Address of OP_OpenEphemeral instruction */
47638
47639       affinity = sqlite3ExprAffinity(pExpr->pLeft);
47640
47641       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
47642       ** expression it is handled the same way. A virtual table is 
47643       ** filled with single-field index keys representing the results
47644       ** from the SELECT or the <exprlist>.
47645       **
47646       ** If the 'x' expression is a column value, or the SELECT...
47647       ** statement returns a column value, then the affinity of that
47648       ** column is used to build the index keys. If both 'x' and the
47649       ** SELECT... statement are columns, then numeric affinity is used
47650       ** if either column has NUMERIC or INTEGER affinity. If neither
47651       ** 'x' nor the SELECT... statement are columns, then numeric affinity
47652       ** is used.
47653       */
47654       pExpr->iTable = pParse->nTab++;
47655       addr = sqlite3VdbeAddOp1(v, OP_OpenEphemeral, pExpr->iTable);
47656       memset(&keyInfo, 0, sizeof(keyInfo));
47657       keyInfo.nField = 1;
47658       sqlite3VdbeAddOp2(v, OP_SetNumColumns, pExpr->iTable, 1);
47659
47660       if( pExpr->pSelect ){
47661         /* Case 1:     expr IN (SELECT ...)
47662         **
47663         ** Generate code to write the results of the select into the temporary
47664         ** table allocated and opened above.
47665         */
47666         SelectDest dest;
47667         ExprList *pEList;
47668
47669         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
47670         dest.affinity = (int)affinity;
47671         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
47672         if( sqlite3Select(pParse, pExpr->pSelect, &dest, 0, 0, 0, 0) ){
47673           return;
47674         }
47675         pEList = pExpr->pSelect->pEList;
47676         if( pEList && pEList->nExpr>0 ){ 
47677           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
47678               pEList->a[0].pExpr);
47679         }
47680       }else if( pExpr->pList ){
47681         /* Case 2:     expr IN (exprlist)
47682         **
47683         ** For each expression, build an index key from the evaluation and
47684         ** store it in the temporary table. If <expr> is a column, then use
47685         ** that columns affinity when building index keys. If <expr> is not
47686         ** a column, use numeric affinity.
47687         */
47688         int i;
47689         ExprList *pList = pExpr->pList;
47690         struct ExprList_item *pItem;
47691         int r1, r2;
47692
47693         if( !affinity ){
47694           affinity = SQLITE_AFF_NONE;
47695         }
47696         keyInfo.aColl[0] = pExpr->pLeft->pColl;
47697
47698         /* Loop through each expression in <exprlist>. */
47699         r1 = sqlite3GetTempReg(pParse);
47700         r2 = sqlite3GetTempReg(pParse);
47701         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
47702           Expr *pE2 = pItem->pExpr;
47703
47704           /* If the expression is not constant then we will need to
47705           ** disable the test that was generated above that makes sure
47706           ** this code only executes once.  Because for a non-constant
47707           ** expression we need to rerun this code each time.
47708           */
47709           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
47710             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
47711             testAddr = 0;
47712           }
47713
47714           /* Evaluate the expression and insert it into the temp table */
47715           sqlite3ExprCode(pParse, pE2, r1);
47716           sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
47717           sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
47718         }
47719         sqlite3ReleaseTempReg(pParse, r1);
47720         sqlite3ReleaseTempReg(pParse, r2);
47721       }
47722       sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
47723       break;
47724     }
47725
47726     case TK_EXISTS:
47727     case TK_SELECT: {
47728       /* This has to be a scalar SELECT.  Generate code to put the
47729       ** value of this select in a memory cell and record the number
47730       ** of the memory cell in iColumn.
47731       */
47732       static const Token one = { (u8*)"1", 0, 1 };
47733       Select *pSel;
47734       SelectDest dest;
47735
47736       pSel = pExpr->pSelect;
47737       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
47738       if( pExpr->op==TK_SELECT ){
47739         dest.eDest = SRT_Mem;
47740         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
47741         VdbeComment((v, "Init subquery result"));
47742       }else{
47743         dest.eDest = SRT_Exists;
47744         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
47745         VdbeComment((v, "Init EXISTS result"));
47746       }
47747       sqlite3ExprDelete(pSel->pLimit);
47748       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
47749       if( sqlite3Select(pParse, pSel, &dest, 0, 0, 0, 0) ){
47750         return;
47751       }
47752       pExpr->iColumn = dest.iParm;
47753       break;
47754     }
47755   }
47756
47757   if( testAddr ){
47758     sqlite3VdbeJumpHere(v, testAddr-1);
47759   }
47760
47761   return;
47762 }
47763 #endif /* SQLITE_OMIT_SUBQUERY */
47764
47765 /*
47766 ** Duplicate an 8-byte value
47767 */
47768 static char *dup8bytes(Vdbe *v, const char *in){
47769   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
47770   if( out ){
47771     memcpy(out, in, 8);
47772   }
47773   return out;
47774 }
47775
47776 /*
47777 ** Generate an instruction that will put the floating point
47778 ** value described by z[0..n-1] into register iMem.
47779 **
47780 ** The z[] string will probably not be zero-terminated.  But the 
47781 ** z[n] character is guaranteed to be something that does not look
47782 ** like the continuation of the number.
47783 */
47784 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
47785   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
47786   if( z ){
47787     double value;
47788     char *zV;
47789     assert( !isdigit(z[n]) );
47790     sqlite3AtoF(z, &value);
47791     if( negateFlag ) value = -value;
47792     zV = dup8bytes(v, (char*)&value);
47793     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
47794   }
47795 }
47796
47797
47798 /*
47799 ** Generate an instruction that will put the integer describe by
47800 ** text z[0..n-1] into register iMem.
47801 **
47802 ** The z[] string will probably not be zero-terminated.  But the 
47803 ** z[n] character is guaranteed to be something that does not look
47804 ** like the continuation of the number.
47805 */
47806 static void codeInteger(Vdbe *v, const char *z, int n, int negFlag, int iMem){
47807   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
47808   if( z ){
47809     int i;
47810     assert( !isdigit(z[n]) );
47811     if( sqlite3GetInt32(z, &i) ){
47812       if( negFlag ) i = -i;
47813       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
47814     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
47815       i64 value;
47816       char *zV;
47817       sqlite3Atoi64(z, &value);
47818       if( negFlag ) value = -value;
47819       zV = dup8bytes(v, (char*)&value);
47820       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
47821     }else{
47822       codeReal(v, z, n, negFlag, iMem);
47823     }
47824   }
47825 }
47826
47827
47828 /*
47829 ** Generate code that will extract the iColumn-th column from
47830 ** table pTab and store the column value in register iReg.
47831 ** There is an open cursor to pTab in 
47832 ** iTable.  If iColumn<0 then code is generated that extracts the rowid.
47833 */
47834 SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(
47835   Vdbe *v,         /* The VM being created */
47836   Table *pTab,     /* Description of the table we are reading from */
47837   int iColumn,     /* Index of the table column */
47838   int iTable,      /* The cursor pointing to the table */
47839   int iReg         /* Store results here */
47840 ){
47841   if( iColumn<0 ){
47842     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
47843     sqlite3VdbeAddOp2(v, op, iTable, iReg);
47844   }else if( pTab==0 ){
47845     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
47846   }else{
47847     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
47848     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
47849     sqlite3ColumnDefault(v, pTab, iColumn);
47850 #ifndef SQLITE_OMIT_FLOATING_POINT
47851     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
47852       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
47853     }
47854 #endif
47855   }
47856 }
47857
47858 /*
47859 ** Generate code into the current Vdbe to evaluate the given
47860 ** expression.  Attempt to store the results in register "target".
47861 ** Return the register where results are stored.
47862 **
47863 ** With this routine, there is no guaranteed that results will
47864 ** be stored in target.  The result might be stored in some other
47865 ** register if it is convenient to do so.  The calling function
47866 ** must check the return code and move the results to the desired
47867 ** register.
47868 */
47869 static int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
47870   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
47871   int op;                   /* The opcode being coded */
47872   int inReg = target;       /* Results stored in register inReg */
47873   int regFree1 = 0;         /* If non-zero free this temporary register */
47874   int regFree2 = 0;         /* If non-zero free this temporary register */
47875   int r1, r2, r3;           /* Various register numbers */
47876
47877   assert( v!=0 || pParse->db->mallocFailed );
47878   assert( target>0 && target<=pParse->nMem );
47879   if( v==0 ) return 0;
47880
47881   if( pExpr==0 ){
47882     op = TK_NULL;
47883   }else{
47884     op = pExpr->op;
47885   }
47886   switch( op ){
47887     case TK_AGG_COLUMN: {
47888       AggInfo *pAggInfo = pExpr->pAggInfo;
47889       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
47890       if( !pAggInfo->directMode ){
47891         assert( pCol->iMem>0 );
47892         inReg = pCol->iMem;
47893         break;
47894       }else if( pAggInfo->useSortingIdx ){
47895         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
47896                               pCol->iSorterColumn, target);
47897         break;
47898       }
47899       /* Otherwise, fall thru into the TK_COLUMN case */
47900     }
47901     case TK_COLUMN: {
47902       if( pExpr->iTable<0 ){
47903         /* This only happens when coding check constraints */
47904         assert( pParse->ckBase>0 );
47905         inReg = pExpr->iColumn + pParse->ckBase;
47906       }else{
47907         sqlite3ExprCodeGetColumn(v, pExpr->pTab,
47908                                  pExpr->iColumn, pExpr->iTable, target);
47909       }
47910       break;
47911     }
47912     case TK_INTEGER: {
47913       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
47914       break;
47915     }
47916     case TK_FLOAT: {
47917       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
47918       break;
47919     }
47920     case TK_STRING: {
47921       sqlite3DequoteExpr(pParse->db, pExpr);
47922       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
47923                         (char*)pExpr->token.z, pExpr->token.n);
47924       break;
47925     }
47926     case TK_NULL: {
47927       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
47928       break;
47929     }
47930 #ifndef SQLITE_OMIT_BLOB_LITERAL
47931     case TK_BLOB: {
47932       int n;
47933       const char *z;
47934       char *zBlob;
47935       assert( pExpr->token.n>=3 );
47936       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
47937       assert( pExpr->token.z[1]=='\'' );
47938       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
47939       n = pExpr->token.n - 3;
47940       z = (char*)pExpr->token.z + 2;
47941       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
47942       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
47943       break;
47944     }
47945 #endif
47946     case TK_VARIABLE: {
47947       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
47948       if( pExpr->token.n>1 ){
47949         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
47950       }
47951       break;
47952     }
47953     case TK_REGISTER: {
47954       inReg = pExpr->iTable;
47955       break;
47956     }
47957 #ifndef SQLITE_OMIT_CAST
47958     case TK_CAST: {
47959       /* Expressions of the form:   CAST(pLeft AS token) */
47960       int aff, to_op;
47961       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
47962       aff = sqlite3AffinityType(&pExpr->token);
47963       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
47964       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
47965       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
47966       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
47967       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
47968       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
47969       sqlite3VdbeAddOp1(v, to_op, inReg);
47970       break;
47971     }
47972 #endif /* SQLITE_OMIT_CAST */
47973     case TK_LT:
47974     case TK_LE:
47975     case TK_GT:
47976     case TK_GE:
47977     case TK_NE:
47978     case TK_EQ: {
47979       assert( TK_LT==OP_Lt );
47980       assert( TK_LE==OP_Le );
47981       assert( TK_GT==OP_Gt );
47982       assert( TK_GE==OP_Ge );
47983       assert( TK_EQ==OP_Eq );
47984       assert( TK_NE==OP_Ne );
47985       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
47986       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
47987       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
47988                   r1, r2, inReg, SQLITE_STOREP2);
47989       break;
47990     }
47991     case TK_AND:
47992     case TK_OR:
47993     case TK_PLUS:
47994     case TK_STAR:
47995     case TK_MINUS:
47996     case TK_REM:
47997     case TK_BITAND:
47998     case TK_BITOR:
47999     case TK_SLASH:
48000     case TK_LSHIFT:
48001     case TK_RSHIFT: 
48002     case TK_CONCAT: {
48003       assert( TK_AND==OP_And );
48004       assert( TK_OR==OP_Or );
48005       assert( TK_PLUS==OP_Add );
48006       assert( TK_MINUS==OP_Subtract );
48007       assert( TK_REM==OP_Remainder );
48008       assert( TK_BITAND==OP_BitAnd );
48009       assert( TK_BITOR==OP_BitOr );
48010       assert( TK_SLASH==OP_Divide );
48011       assert( TK_LSHIFT==OP_ShiftLeft );
48012       assert( TK_RSHIFT==OP_ShiftRight );
48013       assert( TK_CONCAT==OP_Concat );
48014       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
48015       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
48016       sqlite3VdbeAddOp3(v, op, r2, r1, target);
48017       break;
48018     }
48019     case TK_UMINUS: {
48020       Expr *pLeft = pExpr->pLeft;
48021       assert( pLeft );
48022       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
48023         Token *p = &pLeft->token;
48024         if( pLeft->op==TK_FLOAT ){
48025           codeReal(v, (char*)p->z, p->n, 1, target);
48026         }else{
48027           codeInteger(v, (char*)p->z, p->n, 1, target);
48028         }
48029       }else{
48030         regFree1 = r1 = sqlite3GetTempReg(pParse);
48031         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
48032         r2 = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
48033         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
48034       }
48035       inReg = target;
48036       break;
48037     }
48038     case TK_BITNOT:
48039     case TK_NOT: {
48040       assert( TK_BITNOT==OP_BitNot );
48041       assert( TK_NOT==OP_Not );
48042       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
48043       sqlite3VdbeAddOp1(v, op, inReg);
48044       break;
48045     }
48046     case TK_ISNULL:
48047     case TK_NOTNULL: {
48048       int addr;
48049       assert( TK_ISNULL==OP_IsNull );
48050       assert( TK_NOTNULL==OP_NotNull );
48051       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
48052       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
48053       addr = sqlite3VdbeAddOp1(v, op, r1);
48054       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
48055       sqlite3VdbeJumpHere(v, addr);
48056       break;
48057     }
48058     case TK_AGG_FUNCTION: {
48059       AggInfo *pInfo = pExpr->pAggInfo;
48060       if( pInfo==0 ){
48061         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
48062             &pExpr->span);
48063       }else{
48064         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
48065       }
48066       break;
48067     }
48068     case TK_CONST_FUNC:
48069     case TK_FUNCTION: {
48070       ExprList *pList = pExpr->pList;
48071       int nExpr = pList ? pList->nExpr : 0;
48072       FuncDef *pDef;
48073       int nId;
48074       const char *zId;
48075       int constMask = 0;
48076       int i;
48077       sqlite3 *db = pParse->db;
48078       u8 enc = ENC(db);
48079       CollSeq *pColl = 0;
48080
48081       zId = (char*)pExpr->token.z;
48082       nId = pExpr->token.n;
48083       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
48084       assert( pDef!=0 );
48085       if( pList ){
48086         nExpr = pList->nExpr;
48087         r1 = sqlite3GetTempRange(pParse, nExpr);
48088         sqlite3ExprCodeExprList(pParse, pList, r1);
48089       }else{
48090         nExpr = r1 = 0;
48091       }
48092 #ifndef SQLITE_OMIT_VIRTUALTABLE
48093       /* Possibly overload the function if the first argument is
48094       ** a virtual table column.
48095       **
48096       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
48097       ** second argument, not the first, as the argument to test to
48098       ** see if it is a column in a virtual table.  This is done because
48099       ** the left operand of infix functions (the operand we want to
48100       ** control overloading) ends up as the second argument to the
48101       ** function.  The expression "A glob B" is equivalent to 
48102       ** "glob(B,A).  We want to use the A in "A glob B" to test
48103       ** for function overloading.  But we use the B term in "glob(B,A)".
48104       */
48105       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
48106         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
48107       }else if( nExpr>0 ){
48108         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
48109       }
48110 #endif
48111       for(i=0; i<nExpr && i<32; i++){
48112         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
48113           constMask |= (1<<i);
48114         }
48115         if( pDef->needCollSeq && !pColl ){
48116           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
48117         }
48118       }
48119       if( pDef->needCollSeq ){
48120         if( !pColl ) pColl = pParse->db->pDfltColl; 
48121         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
48122       }
48123       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
48124                         (char*)pDef, P4_FUNCDEF);
48125       sqlite3VdbeChangeP5(v, nExpr);
48126       if( nExpr ){
48127         sqlite3ReleaseTempRange(pParse, r1, nExpr);
48128       }
48129       break;
48130     }
48131 #ifndef SQLITE_OMIT_SUBQUERY
48132     case TK_EXISTS:
48133     case TK_SELECT: {
48134       if( pExpr->iColumn==0 ){
48135         sqlite3CodeSubselect(pParse, pExpr);
48136       }
48137       inReg = pExpr->iColumn;
48138       break;
48139     }
48140     case TK_IN: {
48141       int j1, j2, j3, j4, j5;
48142       char affinity;
48143       int eType;
48144
48145       eType = sqlite3FindInIndex(pParse, pExpr, 0);
48146
48147       /* Figure out the affinity to use to create a key from the results
48148       ** of the expression. affinityStr stores a static string suitable for
48149       ** P4 of OP_MakeRecord.
48150       */
48151       affinity = comparisonAffinity(pExpr);
48152
48153       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
48154
48155       /* Code the <expr> from "<expr> IN (...)". The temporary table
48156       ** pExpr->iTable contains the values that make up the (...) set.
48157       */
48158       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
48159       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
48160       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
48161       j2  = sqlite3VdbeAddOp0(v, OP_Goto);
48162       sqlite3VdbeJumpHere(v, j1);
48163       if( eType==IN_INDEX_ROWID ){
48164         j3 = sqlite3VdbeAddOp3(v, OP_MustBeInt, r1, 0, 1);
48165         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, r1);
48166         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
48167         sqlite3VdbeJumpHere(v, j3);
48168         sqlite3VdbeJumpHere(v, j4);
48169       }else{
48170         r2 = regFree2 = sqlite3GetTempReg(pParse);
48171         sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
48172         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
48173       }
48174       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
48175       sqlite3VdbeJumpHere(v, j2);
48176       sqlite3VdbeJumpHere(v, j5);
48177       break;
48178     }
48179 #endif
48180     /*
48181     **    x BETWEEN y AND z
48182     **
48183     ** This is equivalent to
48184     **
48185     **    x>=y AND x<=z
48186     **
48187     ** X is stored in pExpr->pLeft.
48188     ** Y is stored in pExpr->pList->a[0].pExpr.
48189     ** Z is stored in pExpr->pList->a[1].pExpr.
48190     */
48191     case TK_BETWEEN: {
48192       Expr *pLeft = pExpr->pLeft;
48193       struct ExprList_item *pLItem = pExpr->pList->a;
48194       Expr *pRight = pLItem->pExpr;
48195
48196       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
48197       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
48198       r3 = sqlite3GetTempReg(pParse);
48199       codeCompare(pParse, pLeft, pRight, OP_Ge,
48200                   r1, r2, r3, SQLITE_STOREP2);
48201       pLItem++;
48202       pRight = pLItem->pExpr;
48203       sqlite3ReleaseTempReg(pParse, regFree2);
48204       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
48205       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r2, SQLITE_STOREP2);
48206       sqlite3VdbeAddOp3(v, OP_And, r3, r2, target);
48207       sqlite3ReleaseTempReg(pParse, r3);
48208       break;
48209     }
48210     case TK_UPLUS: {
48211       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
48212       break;
48213     }
48214
48215     /*
48216     ** Form A:
48217     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
48218     **
48219     ** Form B:
48220     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
48221     **
48222     ** Form A is can be transformed into the equivalent form B as follows:
48223     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
48224     **        WHEN x=eN THEN rN ELSE y END
48225     **
48226     ** X (if it exists) is in pExpr->pLeft.
48227     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
48228     ** ELSE clause and no other term matches, then the result of the
48229     ** exprssion is NULL.
48230     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
48231     **
48232     ** The result of the expression is the Ri for the first matching Ei,
48233     ** or if there is no matching Ei, the ELSE term Y, or if there is
48234     ** no ELSE term, NULL.
48235     */
48236     case TK_CASE: {
48237       int endLabel;                     /* GOTO label for end of CASE stmt */
48238       int nextCase;                     /* GOTO label for next WHEN clause */
48239       int nExpr;                        /* 2x number of WHEN terms */
48240       int i;                            /* Loop counter */
48241       ExprList *pEList;                 /* List of WHEN terms */
48242       struct ExprList_item *aListelem;  /* Array of WHEN terms */
48243       Expr opCompare;                   /* The X==Ei expression */
48244       Expr cacheX;                      /* Cached expression X */
48245       Expr *pX;                         /* The X expression */
48246       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
48247
48248       assert(pExpr->pList);
48249       assert((pExpr->pList->nExpr % 2) == 0);
48250       assert(pExpr->pList->nExpr > 0);
48251       pEList = pExpr->pList;
48252       aListelem = pEList->a;
48253       nExpr = pEList->nExpr;
48254       endLabel = sqlite3VdbeMakeLabel(v);
48255       if( (pX = pExpr->pLeft)!=0 ){
48256         cacheX = *pX;
48257         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
48258         cacheX.op = TK_REGISTER;
48259         opCompare.op = TK_EQ;
48260         opCompare.pLeft = &cacheX;
48261         pTest = &opCompare;
48262       }
48263       for(i=0; i<nExpr; i=i+2){
48264         if( pX ){
48265           opCompare.pRight = aListelem[i].pExpr;
48266         }else{
48267           pTest = aListelem[i].pExpr;
48268         }
48269         nextCase = sqlite3VdbeMakeLabel(v);
48270         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
48271         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
48272         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
48273         sqlite3VdbeResolveLabel(v, nextCase);
48274       }
48275       if( pExpr->pRight ){
48276         sqlite3ExprCode(pParse, pExpr->pRight, target);
48277       }else{
48278         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
48279       }
48280       sqlite3VdbeResolveLabel(v, endLabel);
48281       break;
48282     }
48283 #ifndef SQLITE_OMIT_TRIGGER
48284     case TK_RAISE: {
48285       if( !pParse->trigStack ){
48286         sqlite3ErrorMsg(pParse,
48287                        "RAISE() may only be used within a trigger-program");
48288         return 0;
48289       }
48290       if( pExpr->iColumn!=OE_Ignore ){
48291          assert( pExpr->iColumn==OE_Rollback ||
48292                  pExpr->iColumn == OE_Abort ||
48293                  pExpr->iColumn == OE_Fail );
48294          sqlite3DequoteExpr(pParse->db, pExpr);
48295          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
48296                         (char*)pExpr->token.z, pExpr->token.n);
48297       } else {
48298          assert( pExpr->iColumn == OE_Ignore );
48299          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
48300          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
48301          VdbeComment((v, "raise(IGNORE)"));
48302       }
48303       break;
48304     }
48305 #endif
48306   }
48307   sqlite3ReleaseTempReg(pParse, regFree1);
48308   sqlite3ReleaseTempReg(pParse, regFree2);
48309   return inReg;
48310 }
48311
48312 /*
48313 ** Generate code to evaluate an expression and store the results
48314 ** into a register.  Return the register number where the results
48315 ** are stored.
48316 **
48317 ** If the register is a temporary register that can be deallocated,
48318 ** then write its number into *pReg.  If the result register is no
48319 ** a temporary, then set *pReg to zero.
48320 */
48321 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
48322   int r1 = sqlite3GetTempReg(pParse);
48323   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
48324   if( r2==r1 ){
48325     *pReg = r1;
48326   }else{
48327     sqlite3ReleaseTempReg(pParse, r1);
48328     *pReg = 0;
48329   }
48330   return r2;
48331 }
48332
48333 /*
48334 ** Generate code that will evaluate expression pExpr and store the
48335 ** results in register target.  The results are guaranteed to appear
48336 ** in register target.
48337 */
48338 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
48339   int inReg;
48340
48341   assert( target>0 && target<=pParse->nMem );
48342   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
48343   assert( pParse->pVdbe || pParse->db->mallocFailed );
48344   if( inReg!=target && pParse->pVdbe ){
48345     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
48346   }
48347   return target;
48348 }
48349
48350 /*
48351 ** Generate code that evalutes the given expression and puts the result
48352 ** in register target.
48353 **
48354 ** Also make a copy of the expression results into another "cache" register
48355 ** and modify the expression so that the next time it is evaluated,
48356 ** the result is a copy of the cache register.
48357 **
48358 ** This routine is used for expressions that are used multiple 
48359 ** times.  They are evaluated once and the results of the expression
48360 ** are reused.
48361 */
48362 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
48363   Vdbe *v = pParse->pVdbe;
48364   int inReg;
48365   inReg = sqlite3ExprCode(pParse, pExpr, target);
48366   assert( target>0 );
48367   if( pExpr->op!=TK_REGISTER ){  
48368     int iMem;
48369     iMem = ++pParse->nMem;
48370     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
48371     pExpr->iTable = iMem;
48372     pExpr->op = TK_REGISTER;
48373   }
48374   return inReg;
48375 }
48376
48377
48378 /*
48379 ** Generate code that pushes the value of every element of the given
48380 ** expression list into a sequence of registers beginning at target.
48381 **
48382 ** Return the number of elements evaluated.
48383 */
48384 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
48385   Parse *pParse,     /* Parsing context */
48386   ExprList *pList,   /* The expression list to be coded */
48387   int target         /* Where to write results */
48388 ){
48389   struct ExprList_item *pItem;
48390   int i, n;
48391   assert( pList!=0 || pParse->db->mallocFailed );
48392   if( pList==0 ){
48393     return 0;
48394   }
48395   assert( target>0 );
48396   n = pList->nExpr;
48397   for(pItem=pList->a, i=n; i>0; i--, pItem++){
48398     sqlite3ExprCode(pParse, pItem->pExpr, target);
48399     target++;
48400   }
48401   return n;
48402 }
48403
48404 /*
48405 ** Generate code for a boolean expression such that a jump is made
48406 ** to the label "dest" if the expression is true but execution
48407 ** continues straight thru if the expression is false.
48408 **
48409 ** If the expression evaluates to NULL (neither true nor false), then
48410 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
48411 **
48412 ** This code depends on the fact that certain token values (ex: TK_EQ)
48413 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
48414 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
48415 ** the make process cause these values to align.  Assert()s in the code
48416 ** below verify that the numbers are aligned correctly.
48417 */
48418 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
48419   Vdbe *v = pParse->pVdbe;
48420   int op = 0;
48421   int regFree1 = 0;
48422   int regFree2 = 0;
48423   int r1, r2;
48424
48425   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
48426   if( v==0 || pExpr==0 ) return;
48427   op = pExpr->op;
48428   switch( op ){
48429     case TK_AND: {
48430       int d2 = sqlite3VdbeMakeLabel(v);
48431       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
48432       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
48433       sqlite3VdbeResolveLabel(v, d2);
48434       break;
48435     }
48436     case TK_OR: {
48437       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
48438       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
48439       break;
48440     }
48441     case TK_NOT: {
48442       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
48443       break;
48444     }
48445     case TK_LT:
48446     case TK_LE:
48447     case TK_GT:
48448     case TK_GE:
48449     case TK_NE:
48450     case TK_EQ: {
48451       assert( TK_LT==OP_Lt );
48452       assert( TK_LE==OP_Le );
48453       assert( TK_GT==OP_Gt );
48454       assert( TK_GE==OP_Ge );
48455       assert( TK_EQ==OP_Eq );
48456       assert( TK_NE==OP_Ne );
48457       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
48458       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
48459       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
48460                   r1, r2, dest, jumpIfNull);
48461       break;
48462     }
48463     case TK_ISNULL:
48464     case TK_NOTNULL: {
48465       assert( TK_ISNULL==OP_IsNull );
48466       assert( TK_NOTNULL==OP_NotNull );
48467       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
48468       sqlite3VdbeAddOp2(v, op, r1, dest);
48469       break;
48470     }
48471     case TK_BETWEEN: {
48472       /*    x BETWEEN y AND z
48473       **
48474       ** Is equivalent to 
48475       **
48476       **    x>=y AND x<=z
48477       **
48478       ** Code it as such, taking care to do the common subexpression
48479       ** elementation of x.
48480       */
48481       Expr exprAnd;
48482       Expr compLeft;
48483       Expr compRight;
48484       Expr exprX;
48485
48486       exprX = *pExpr->pLeft;
48487       exprAnd.op = TK_AND;
48488       exprAnd.pLeft = &compLeft;
48489       exprAnd.pRight = &compRight;
48490       compLeft.op = TK_GE;
48491       compLeft.pLeft = &exprX;
48492       compLeft.pRight = pExpr->pList->a[0].pExpr;
48493       compRight.op = TK_LE;
48494       compRight.pLeft = &exprX;
48495       compRight.pRight = pExpr->pList->a[1].pExpr;
48496       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
48497       exprX.op = TK_REGISTER;
48498       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
48499       break;
48500     }
48501     default: {
48502       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
48503       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
48504       break;
48505     }
48506   }
48507   sqlite3ReleaseTempReg(pParse, regFree1);
48508   sqlite3ReleaseTempReg(pParse, regFree2);  
48509 }
48510
48511 /*
48512 ** Generate code for a boolean expression such that a jump is made
48513 ** to the label "dest" if the expression is false but execution
48514 ** continues straight thru if the expression is true.
48515 **
48516 ** If the expression evaluates to NULL (neither true nor false) then
48517 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
48518 ** is 0.
48519 */
48520 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
48521   Vdbe *v = pParse->pVdbe;
48522   int op = 0;
48523   int regFree1 = 0;
48524   int regFree2 = 0;
48525   int r1, r2;
48526
48527   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
48528   if( v==0 || pExpr==0 ) return;
48529
48530   /* The value of pExpr->op and op are related as follows:
48531   **
48532   **       pExpr->op            op
48533   **       ---------          ----------
48534   **       TK_ISNULL          OP_NotNull
48535   **       TK_NOTNULL         OP_IsNull
48536   **       TK_NE              OP_Eq
48537   **       TK_EQ              OP_Ne
48538   **       TK_GT              OP_Le
48539   **       TK_LE              OP_Gt
48540   **       TK_GE              OP_Lt
48541   **       TK_LT              OP_Ge
48542   **
48543   ** For other values of pExpr->op, op is undefined and unused.
48544   ** The value of TK_ and OP_ constants are arranged such that we
48545   ** can compute the mapping above using the following expression.
48546   ** Assert()s verify that the computation is correct.
48547   */
48548   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
48549
48550   /* Verify correct alignment of TK_ and OP_ constants
48551   */
48552   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
48553   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
48554   assert( pExpr->op!=TK_NE || op==OP_Eq );
48555   assert( pExpr->op!=TK_EQ || op==OP_Ne );
48556   assert( pExpr->op!=TK_LT || op==OP_Ge );
48557   assert( pExpr->op!=TK_LE || op==OP_Gt );
48558   assert( pExpr->op!=TK_GT || op==OP_Le );
48559   assert( pExpr->op!=TK_GE || op==OP_Lt );
48560
48561   switch( pExpr->op ){
48562     case TK_AND: {
48563       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
48564       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
48565       break;
48566     }
48567     case TK_OR: {
48568       int d2 = sqlite3VdbeMakeLabel(v);
48569       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
48570       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
48571       sqlite3VdbeResolveLabel(v, d2);
48572       break;
48573     }
48574     case TK_NOT: {
48575       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
48576       break;
48577     }
48578     case TK_LT:
48579     case TK_LE:
48580     case TK_GT:
48581     case TK_GE:
48582     case TK_NE:
48583     case TK_EQ: {
48584       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
48585       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
48586       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
48587                   r1, r2, dest, jumpIfNull);
48588       break;
48589     }
48590     case TK_ISNULL:
48591     case TK_NOTNULL: {
48592       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
48593       sqlite3VdbeAddOp2(v, op, r1, dest);
48594       break;
48595     }
48596     case TK_BETWEEN: {
48597       /*    x BETWEEN y AND z
48598       **
48599       ** Is equivalent to 
48600       **
48601       **    x>=y AND x<=z
48602       **
48603       ** Code it as such, taking care to do the common subexpression
48604       ** elementation of x.
48605       */
48606       Expr exprAnd;
48607       Expr compLeft;
48608       Expr compRight;
48609       Expr exprX;
48610
48611       exprX = *pExpr->pLeft;
48612       exprAnd.op = TK_AND;
48613       exprAnd.pLeft = &compLeft;
48614       exprAnd.pRight = &compRight;
48615       compLeft.op = TK_GE;
48616       compLeft.pLeft = &exprX;
48617       compLeft.pRight = pExpr->pList->a[0].pExpr;
48618       compRight.op = TK_LE;
48619       compRight.pLeft = &exprX;
48620       compRight.pRight = pExpr->pList->a[1].pExpr;
48621       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
48622       exprX.op = TK_REGISTER;
48623       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
48624       break;
48625     }
48626     default: {
48627       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
48628       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
48629       break;
48630     }
48631   }
48632   sqlite3ReleaseTempReg(pParse, regFree1);
48633   sqlite3ReleaseTempReg(pParse, regFree2);
48634 }
48635
48636 /*
48637 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
48638 ** if they are identical and return FALSE if they differ in any way.
48639 **
48640 ** Sometimes this routine will return FALSE even if the two expressions
48641 ** really are equivalent.  If we cannot prove that the expressions are
48642 ** identical, we return FALSE just to be safe.  So if this routine
48643 ** returns false, then you do not really know for certain if the two
48644 ** expressions are the same.  But if you get a TRUE return, then you
48645 ** can be sure the expressions are the same.  In the places where
48646 ** this routine is used, it does not hurt to get an extra FALSE - that
48647 ** just might result in some slightly slower code.  But returning
48648 ** an incorrect TRUE could lead to a malfunction.
48649 */
48650 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
48651   int i;
48652   if( pA==0||pB==0 ){
48653     return pB==pA;
48654   }
48655   if( pA->op!=pB->op ) return 0;
48656   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
48657   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
48658   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
48659   if( pA->pList ){
48660     if( pB->pList==0 ) return 0;
48661     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
48662     for(i=0; i<pA->pList->nExpr; i++){
48663       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
48664         return 0;
48665       }
48666     }
48667   }else if( pB->pList ){
48668     return 0;
48669   }
48670   if( pA->pSelect || pB->pSelect ) return 0;
48671   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
48672   if( pA->op!=TK_COLUMN && pA->token.z ){
48673     if( pB->token.z==0 ) return 0;
48674     if( pB->token.n!=pA->token.n ) return 0;
48675     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
48676       return 0;
48677     }
48678   }
48679   return 1;
48680 }
48681
48682
48683 /*
48684 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
48685 ** the new element.  Return a negative number if malloc fails.
48686 */
48687 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
48688   int i;
48689   pInfo->aCol = sqlite3ArrayAllocate(
48690        db,
48691        pInfo->aCol,
48692        sizeof(pInfo->aCol[0]),
48693        3,
48694        &pInfo->nColumn,
48695        &pInfo->nColumnAlloc,
48696        &i
48697   );
48698   return i;
48699 }    
48700
48701 /*
48702 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
48703 ** the new element.  Return a negative number if malloc fails.
48704 */
48705 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
48706   int i;
48707   pInfo->aFunc = sqlite3ArrayAllocate(
48708        db, 
48709        pInfo->aFunc,
48710        sizeof(pInfo->aFunc[0]),
48711        3,
48712        &pInfo->nFunc,
48713        &pInfo->nFuncAlloc,
48714        &i
48715   );
48716   return i;
48717 }    
48718
48719 /*
48720 ** This is an xFunc for walkExprTree() used to implement 
48721 ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
48722 ** for additional information.
48723 **
48724 ** This routine analyzes the aggregate function at pExpr.
48725 */
48726 static int analyzeAggregate(void *pArg, Expr *pExpr){
48727   int i;
48728   NameContext *pNC = (NameContext *)pArg;
48729   Parse *pParse = pNC->pParse;
48730   SrcList *pSrcList = pNC->pSrcList;
48731   AggInfo *pAggInfo = pNC->pAggInfo;
48732
48733   switch( pExpr->op ){
48734     case TK_AGG_COLUMN:
48735     case TK_COLUMN: {
48736       /* Check to see if the column is in one of the tables in the FROM
48737       ** clause of the aggregate query */
48738       if( pSrcList ){
48739         struct SrcList_item *pItem = pSrcList->a;
48740         for(i=0; i<pSrcList->nSrc; i++, pItem++){
48741           struct AggInfo_col *pCol;
48742           if( pExpr->iTable==pItem->iCursor ){
48743             /* If we reach this point, it means that pExpr refers to a table
48744             ** that is in the FROM clause of the aggregate query.  
48745             **
48746             ** Make an entry for the column in pAggInfo->aCol[] if there
48747             ** is not an entry there already.
48748             */
48749             int k;
48750             pCol = pAggInfo->aCol;
48751             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
48752               if( pCol->iTable==pExpr->iTable &&
48753                   pCol->iColumn==pExpr->iColumn ){
48754                 break;
48755               }
48756             }
48757             if( (k>=pAggInfo->nColumn)
48758              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
48759             ){
48760               pCol = &pAggInfo->aCol[k];
48761               pCol->pTab = pExpr->pTab;
48762               pCol->iTable = pExpr->iTable;
48763               pCol->iColumn = pExpr->iColumn;
48764               pCol->iMem = ++pParse->nMem;
48765               pCol->iSorterColumn = -1;
48766               pCol->pExpr = pExpr;
48767               if( pAggInfo->pGroupBy ){
48768                 int j, n;
48769                 ExprList *pGB = pAggInfo->pGroupBy;
48770                 struct ExprList_item *pTerm = pGB->a;
48771                 n = pGB->nExpr;
48772                 for(j=0; j<n; j++, pTerm++){
48773                   Expr *pE = pTerm->pExpr;
48774                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
48775                       pE->iColumn==pExpr->iColumn ){
48776                     pCol->iSorterColumn = j;
48777                     break;
48778                   }
48779                 }
48780               }
48781               if( pCol->iSorterColumn<0 ){
48782                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
48783               }
48784             }
48785             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
48786             ** because it was there before or because we just created it).
48787             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
48788             ** pAggInfo->aCol[] entry.
48789             */
48790             pExpr->pAggInfo = pAggInfo;
48791             pExpr->op = TK_AGG_COLUMN;
48792             pExpr->iAgg = k;
48793             break;
48794           } /* endif pExpr->iTable==pItem->iCursor */
48795         } /* end loop over pSrcList */
48796       }
48797       return 1;
48798     }
48799     case TK_AGG_FUNCTION: {
48800       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
48801       ** to be ignored */
48802       if( pNC->nDepth==0 ){
48803         /* Check to see if pExpr is a duplicate of another aggregate 
48804         ** function that is already in the pAggInfo structure
48805         */
48806         struct AggInfo_func *pItem = pAggInfo->aFunc;
48807         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
48808           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
48809             break;
48810           }
48811         }
48812         if( i>=pAggInfo->nFunc ){
48813           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
48814           */
48815           u8 enc = ENC(pParse->db);
48816           i = addAggInfoFunc(pParse->db, pAggInfo);
48817           if( i>=0 ){
48818             pItem = &pAggInfo->aFunc[i];
48819             pItem->pExpr = pExpr;
48820             pItem->iMem = ++pParse->nMem;
48821             pItem->pFunc = sqlite3FindFunction(pParse->db,
48822                    (char*)pExpr->token.z, pExpr->token.n,
48823                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
48824             if( pExpr->flags & EP_Distinct ){
48825               pItem->iDistinct = pParse->nTab++;
48826             }else{
48827               pItem->iDistinct = -1;
48828             }
48829           }
48830         }
48831         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
48832         */
48833         pExpr->iAgg = i;
48834         pExpr->pAggInfo = pAggInfo;
48835         return 1;
48836       }
48837     }
48838   }
48839
48840   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
48841   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
48842   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
48843   */
48844   if( pExpr->pSelect ){
48845     pNC->nDepth++;
48846     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
48847     pNC->nDepth--;
48848   }
48849   return 0;
48850 }
48851
48852 /*
48853 ** Analyze the given expression looking for aggregate functions and
48854 ** for variables that need to be added to the pParse->aAgg[] array.
48855 ** Make additional entries to the pParse->aAgg[] array as necessary.
48856 **
48857 ** This routine should only be called after the expression has been
48858 ** analyzed by sqlite3ExprResolveNames().
48859 */
48860 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
48861   walkExprTree(pExpr, analyzeAggregate, pNC);
48862 }
48863
48864 /*
48865 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
48866 ** expression list.  Return the number of errors.
48867 **
48868 ** If an error is found, the analysis is cut short.
48869 */
48870 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
48871   struct ExprList_item *pItem;
48872   int i;
48873   if( pList ){
48874     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
48875       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
48876     }
48877   }
48878 }
48879
48880 /*
48881 ** Allocate or deallocate temporary use registers during code generation.
48882 */
48883 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
48884   if( pParse->nTempReg ){
48885     return pParse->aTempReg[--pParse->nTempReg];
48886   }else{
48887     return ++pParse->nMem;
48888   }
48889 }
48890 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
48891   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
48892     assert( iReg>0 );
48893     pParse->aTempReg[pParse->nTempReg++] = iReg;
48894   }
48895 }
48896
48897 /*
48898 ** Allocate or deallocate a block of nReg consecutive registers
48899 */
48900 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
48901   int i;
48902   if( nReg<=pParse->nRangeReg ){
48903     i  = pParse->iRangeReg;
48904     pParse->iRangeReg += nReg;
48905     pParse->nRangeReg -= nReg;
48906   }else{
48907     i = pParse->nMem+1;
48908     pParse->nMem += nReg;
48909   }
48910   return i;
48911 }
48912 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
48913   if( nReg>pParse->nRangeReg ){
48914     pParse->nRangeReg = nReg;
48915     pParse->iRangeReg = iReg;
48916   }
48917 }
48918
48919 /************** End of expr.c ************************************************/
48920 /************** Begin file alter.c *******************************************/
48921 /*
48922 ** 2005 February 15
48923 **
48924 ** The author disclaims copyright to this source code.  In place of
48925 ** a legal notice, here is a blessing:
48926 **
48927 **    May you do good and not evil.
48928 **    May you find forgiveness for yourself and forgive others.
48929 **    May you share freely, never taking more than you give.
48930 **
48931 *************************************************************************
48932 ** This file contains C code routines that used to generate VDBE code
48933 ** that implements the ALTER TABLE command.
48934 **
48935 ** $Id: alter.c,v 1.42 2008/02/09 14:30:30 drh Exp $
48936 */
48937
48938 /*
48939 ** The code in this file only exists if we are not omitting the
48940 ** ALTER TABLE logic from the build.
48941 */
48942 #ifndef SQLITE_OMIT_ALTERTABLE
48943
48944
48945 /*
48946 ** This function is used by SQL generated to implement the 
48947 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
48948 ** CREATE INDEX command. The second is a table name. The table name in 
48949 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
48950 ** argument and the result returned. Examples:
48951 **
48952 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
48953 **     -> 'CREATE TABLE def(a, b, c)'
48954 **
48955 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
48956 **     -> 'CREATE INDEX i ON def(a, b, c)'
48957 */
48958 static void renameTableFunc(
48959   sqlite3_context *context,
48960   int argc,
48961   sqlite3_value **argv
48962 ){
48963   unsigned char const *zSql = sqlite3_value_text(argv[0]);
48964   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
48965
48966   int token;
48967   Token tname;
48968   unsigned char const *zCsr = zSql;
48969   int len = 0;
48970   char *zRet;
48971
48972   sqlite3 *db = sqlite3_user_data(context);
48973
48974   /* The principle used to locate the table name in the CREATE TABLE 
48975   ** statement is that the table name is the first token that is immediatedly
48976   ** followed by a left parenthesis - TK_LP - or "USING" TK_USING.
48977   */
48978   if( zSql ){
48979     do {
48980       if( !*zCsr ){
48981         /* Ran out of input before finding an opening bracket. Return NULL. */
48982         return;
48983       }
48984
48985       /* Store the token that zCsr points to in tname. */
48986       tname.z = zCsr;
48987       tname.n = len;
48988
48989       /* Advance zCsr to the next token. Store that token type in 'token',
48990       ** and its length in 'len' (to be used next iteration of this loop).
48991       */
48992       do {
48993         zCsr += len;
48994         len = sqlite3GetToken(zCsr, &token);
48995       } while( token==TK_SPACE );
48996       assert( len>0 );
48997     } while( token!=TK_LP && token!=TK_USING );
48998
48999     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
49000        zTableName, tname.z+tname.n);
49001     sqlite3_result_text(context, zRet, -1, sqlite3_free);
49002   }
49003 }
49004
49005 #ifndef SQLITE_OMIT_TRIGGER
49006 /* This function is used by SQL generated to implement the
49007 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
49008 ** statement. The second is a table name. The table name in the CREATE 
49009 ** TRIGGER statement is replaced with the third argument and the result 
49010 ** returned. This is analagous to renameTableFunc() above, except for CREATE
49011 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
49012 */
49013 static void renameTriggerFunc(
49014   sqlite3_context *context,
49015   int argc,
49016   sqlite3_value **argv
49017 ){
49018   unsigned char const *zSql = sqlite3_value_text(argv[0]);
49019   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
49020
49021   int token;
49022   Token tname;
49023   int dist = 3;
49024   unsigned char const *zCsr = zSql;
49025   int len = 0;
49026   char *zRet;
49027
49028   sqlite3 *db = sqlite3_user_data(context);
49029
49030   /* The principle used to locate the table name in the CREATE TRIGGER 
49031   ** statement is that the table name is the first token that is immediatedly
49032   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
49033   ** of TK_WHEN, TK_BEGIN or TK_FOR.
49034   */
49035   if( zSql ){
49036     do {
49037
49038       if( !*zCsr ){
49039         /* Ran out of input before finding the table name. Return NULL. */
49040         return;
49041       }
49042
49043       /* Store the token that zCsr points to in tname. */
49044       tname.z = zCsr;
49045       tname.n = len;
49046
49047       /* Advance zCsr to the next token. Store that token type in 'token',
49048       ** and its length in 'len' (to be used next iteration of this loop).
49049       */
49050       do {
49051         zCsr += len;
49052         len = sqlite3GetToken(zCsr, &token);
49053       }while( token==TK_SPACE );
49054       assert( len>0 );
49055
49056       /* Variable 'dist' stores the number of tokens read since the most
49057       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
49058       ** token is read and 'dist' equals 2, the condition stated above
49059       ** to be met.
49060       **
49061       ** Note that ON cannot be a database, table or column name, so
49062       ** there is no need to worry about syntax like 
49063       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
49064       */
49065       dist++;
49066       if( token==TK_DOT || token==TK_ON ){
49067         dist = 0;
49068       }
49069     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
49070
49071     /* Variable tname now contains the token that is the old table-name
49072     ** in the CREATE TRIGGER statement.
49073     */
49074     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
49075        zTableName, tname.z+tname.n);
49076     sqlite3_result_text(context, zRet, -1, sqlite3_free);
49077   }
49078 }
49079 #endif   /* !SQLITE_OMIT_TRIGGER */
49080
49081 /*
49082 ** Register built-in functions used to help implement ALTER TABLE
49083 */
49084 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
49085   static const struct {
49086      char *zName;
49087      signed char nArg;
49088      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
49089   } aFuncs[] = {
49090     { "sqlite_rename_table",    2, renameTableFunc},
49091 #ifndef SQLITE_OMIT_TRIGGER
49092     { "sqlite_rename_trigger",  2, renameTriggerFunc},
49093 #endif
49094   };
49095   int i;
49096
49097   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
49098     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
49099         SQLITE_UTF8, (void *)db, aFuncs[i].xFunc, 0, 0);
49100   }
49101 }
49102
49103 /*
49104 ** Generate the text of a WHERE expression which can be used to select all
49105 ** temporary triggers on table pTab from the sqlite_temp_master table. If
49106 ** table pTab has no temporary triggers, or is itself stored in the 
49107 ** temporary database, NULL is returned.
49108 */
49109 static char *whereTempTriggers(Parse *pParse, Table *pTab){
49110   Trigger *pTrig;
49111   char *zWhere = 0;
49112   char *tmp = 0;
49113   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
49114
49115   /* If the table is not located in the temp-db (in which case NULL is 
49116   ** returned, loop through the tables list of triggers. For each trigger
49117   ** that is not part of the temp-db schema, add a clause to the WHERE 
49118   ** expression being built up in zWhere.
49119   */
49120   if( pTab->pSchema!=pTempSchema ){
49121     sqlite3 *db = pParse->db;
49122     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
49123       if( pTrig->pSchema==pTempSchema ){
49124         if( !zWhere ){
49125           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
49126         }else{
49127           tmp = zWhere;
49128           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
49129           sqlite3_free(tmp);
49130         }
49131       }
49132     }
49133   }
49134   return zWhere;
49135 }
49136
49137 /*
49138 ** Generate code to drop and reload the internal representation of table
49139 ** pTab from the database, including triggers and temporary triggers.
49140 ** Argument zName is the name of the table in the database schema at
49141 ** the time the generated code is executed. This can be different from
49142 ** pTab->zName if this function is being called to code part of an 
49143 ** "ALTER TABLE RENAME TO" statement.
49144 */
49145 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
49146   Vdbe *v;
49147   char *zWhere;
49148   int iDb;                   /* Index of database containing pTab */
49149 #ifndef SQLITE_OMIT_TRIGGER
49150   Trigger *pTrig;
49151 #endif
49152
49153   v = sqlite3GetVdbe(pParse);
49154   if( !v ) return;
49155   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
49156   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
49157   assert( iDb>=0 );
49158
49159 #ifndef SQLITE_OMIT_TRIGGER
49160   /* Drop any table triggers from the internal schema. */
49161   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
49162     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
49163     assert( iTrigDb==iDb || iTrigDb==1 );
49164     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
49165   }
49166 #endif
49167
49168   /* Drop the table and index from the internal schema */
49169   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
49170
49171   /* Reload the table, index and permanent trigger schemas. */
49172   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
49173   if( !zWhere ) return;
49174   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
49175
49176 #ifndef SQLITE_OMIT_TRIGGER
49177   /* Now, if the table is not stored in the temp database, reload any temp 
49178   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
49179   */
49180   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
49181     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
49182   }
49183 #endif
49184 }
49185
49186 /*
49187 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
49188 ** command. 
49189 */
49190 SQLITE_PRIVATE void sqlite3AlterRenameTable(
49191   Parse *pParse,            /* Parser context. */
49192   SrcList *pSrc,            /* The table to rename. */
49193   Token *pName              /* The new table name. */
49194 ){
49195   int iDb;                  /* Database that contains the table */
49196   char *zDb;                /* Name of database iDb */
49197   Table *pTab;              /* Table being renamed */
49198   char *zName = 0;          /* NULL-terminated version of pName */ 
49199   sqlite3 *db = pParse->db; /* Database connection */
49200   int nTabName;             /* Number of UTF-8 characters in zTabName */
49201   const char *zTabName;     /* Original name of the table */
49202   Vdbe *v;
49203 #ifndef SQLITE_OMIT_TRIGGER
49204   char *zWhere = 0;         /* Where clause to locate temp triggers */
49205 #endif
49206   int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
49207   
49208   if( db->mallocFailed ) goto exit_rename_table;
49209   assert( pSrc->nSrc==1 );
49210   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
49211
49212   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
49213   if( !pTab ) goto exit_rename_table;
49214   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
49215   zDb = db->aDb[iDb].zName;
49216
49217   /* Get a NULL terminated version of the new table name. */
49218   zName = sqlite3NameFromToken(db, pName);
49219   if( !zName ) goto exit_rename_table;
49220
49221   /* Check that a table or index named 'zName' does not already exist
49222   ** in database iDb. If so, this is an error.
49223   */
49224   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
49225     sqlite3ErrorMsg(pParse, 
49226         "there is already another table or index with this name: %s", zName);
49227     goto exit_rename_table;
49228   }
49229
49230   /* Make sure it is not a system table being altered, or a reserved name
49231   ** that the table is being renamed to.
49232   */
49233   if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
49234     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
49235     goto exit_rename_table;
49236   }
49237   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
49238     goto exit_rename_table;
49239   }
49240
49241 #ifndef SQLITE_OMIT_VIEW
49242   if( pTab->pSelect ){
49243     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
49244     goto exit_rename_table;
49245   }
49246 #endif
49247
49248 #ifndef SQLITE_OMIT_AUTHORIZATION
49249   /* Invoke the authorization callback. */
49250   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
49251     goto exit_rename_table;
49252   }
49253 #endif
49254
49255 #ifndef SQLITE_OMIT_VIRTUALTABLE
49256   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
49257     goto exit_rename_table;
49258   }
49259   if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
49260     isVirtualRename = 1;
49261   }
49262 #endif
49263
49264   /* Begin a transaction and code the VerifyCookie for database iDb. 
49265   ** Then modify the schema cookie (since the ALTER TABLE modifies the
49266   ** schema). Open a statement transaction if the table is a virtual
49267   ** table.
49268   */
49269   v = sqlite3GetVdbe(pParse);
49270   if( v==0 ){
49271     goto exit_rename_table;
49272   }
49273   sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
49274   sqlite3ChangeCookie(pParse, iDb);
49275
49276   /* If this is a virtual table, invoke the xRename() function if
49277   ** one is defined. The xRename() callback will modify the names
49278   ** of any resources used by the v-table implementation (including other
49279   ** SQLite tables) that are identified by the name of the virtual table.
49280   */
49281 #ifndef SQLITE_OMIT_VIRTUALTABLE
49282   if( isVirtualRename ){
49283     int i = ++pParse->nMem;
49284     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
49285     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
49286   }
49287 #endif
49288
49289   /* figure out how many UTF-8 characters are in zName */
49290   zTabName = pTab->zName;
49291   nTabName = sqlite3Utf8CharLen(zTabName, -1);
49292
49293   /* Modify the sqlite_master table to use the new table name. */
49294   sqlite3NestedParse(pParse,
49295       "UPDATE %Q.%s SET "
49296 #ifdef SQLITE_OMIT_TRIGGER
49297           "sql = sqlite_rename_table(sql, %Q), "
49298 #else
49299           "sql = CASE "
49300             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
49301             "ELSE sqlite_rename_table(sql, %Q) END, "
49302 #endif
49303           "tbl_name = %Q, "
49304           "name = CASE "
49305             "WHEN type='table' THEN %Q "
49306             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
49307              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
49308             "ELSE name END "
49309       "WHERE tbl_name=%Q AND "
49310           "(type='table' OR type='index' OR type='trigger');", 
49311       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
49312 #ifndef SQLITE_OMIT_TRIGGER
49313       zName,
49314 #endif
49315       zName, nTabName, zTabName
49316   );
49317
49318 #ifndef SQLITE_OMIT_AUTOINCREMENT
49319   /* If the sqlite_sequence table exists in this database, then update 
49320   ** it with the new table name.
49321   */
49322   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
49323     sqlite3NestedParse(pParse,
49324         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
49325         zDb, zName, pTab->zName);
49326   }
49327 #endif
49328
49329 #ifndef SQLITE_OMIT_TRIGGER
49330   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
49331   ** table. Don't do this if the table being ALTERed is itself located in
49332   ** the temp database.
49333   */
49334   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
49335     sqlite3NestedParse(pParse, 
49336         "UPDATE sqlite_temp_master SET "
49337             "sql = sqlite_rename_trigger(sql, %Q), "
49338             "tbl_name = %Q "
49339             "WHERE %s;", zName, zName, zWhere);
49340     sqlite3_free(zWhere);
49341   }
49342 #endif
49343
49344   /* Drop and reload the internal table schema. */
49345   reloadTableSchema(pParse, pTab, zName);
49346
49347 exit_rename_table:
49348   sqlite3SrcListDelete(pSrc);
49349   sqlite3_free(zName);
49350 }
49351
49352
49353 /*
49354 ** This function is called after an "ALTER TABLE ... ADD" statement
49355 ** has been parsed. Argument pColDef contains the text of the new
49356 ** column definition.
49357 **
49358 ** The Table structure pParse->pNewTable was extended to include
49359 ** the new column during parsing.
49360 */
49361 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
49362   Table *pNew;              /* Copy of pParse->pNewTable */
49363   Table *pTab;              /* Table being altered */
49364   int iDb;                  /* Database number */
49365   const char *zDb;          /* Database name */
49366   const char *zTab;         /* Table name */
49367   char *zCol;               /* Null-terminated column definition */
49368   Column *pCol;             /* The new column */
49369   Expr *pDflt;              /* Default value for the new column */
49370   sqlite3 *db;              /* The database connection; */
49371
49372   if( pParse->nErr ) return;
49373   pNew = pParse->pNewTable;
49374   assert( pNew );
49375
49376   db = pParse->db;
49377   assert( sqlite3BtreeHoldsAllMutexes(db) );
49378   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
49379   zDb = db->aDb[iDb].zName;
49380   zTab = pNew->zName;
49381   pCol = &pNew->aCol[pNew->nCol-1];
49382   pDflt = pCol->pDflt;
49383   pTab = sqlite3FindTable(db, zTab, zDb);
49384   assert( pTab );
49385
49386 #ifndef SQLITE_OMIT_AUTHORIZATION
49387   /* Invoke the authorization callback. */
49388   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
49389     return;
49390   }
49391 #endif
49392
49393   /* If the default value for the new column was specified with a 
49394   ** literal NULL, then set pDflt to 0. This simplifies checking
49395   ** for an SQL NULL default below.
49396   */
49397   if( pDflt && pDflt->op==TK_NULL ){
49398     pDflt = 0;
49399   }
49400
49401   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
49402   ** If there is a NOT NULL constraint, then the default value for the
49403   ** column must not be NULL.
49404   */
49405   if( pCol->isPrimKey ){
49406     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
49407     return;
49408   }
49409   if( pNew->pIndex ){
49410     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
49411     return;
49412   }
49413   if( pCol->notNull && !pDflt ){
49414     sqlite3ErrorMsg(pParse, 
49415         "Cannot add a NOT NULL column with default value NULL");
49416     return;
49417   }
49418
49419   /* Ensure the default expression is something that sqlite3ValueFromExpr()
49420   ** can handle (i.e. not CURRENT_TIME etc.)
49421   */
49422   if( pDflt ){
49423     sqlite3_value *pVal;
49424     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
49425       db->mallocFailed = 1;
49426       return;
49427     }
49428     if( !pVal ){
49429       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
49430       return;
49431     }
49432     sqlite3ValueFree(pVal);
49433   }
49434
49435   /* Modify the CREATE TABLE statement. */
49436   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
49437   if( zCol ){
49438     char *zEnd = &zCol[pColDef->n-1];
49439     while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
49440       *zEnd-- = '\0';
49441     }
49442     sqlite3NestedParse(pParse, 
49443         "UPDATE \"%w\".%s SET "
49444           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
49445         "WHERE type = 'table' AND name = %Q", 
49446       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
49447       zTab
49448     );
49449     sqlite3_free(zCol);
49450   }
49451
49452   /* If the default value of the new column is NULL, then set the file
49453   ** format to 2. If the default value of the new column is not NULL,
49454   ** the file format becomes 3.
49455   */
49456   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
49457
49458   /* Reload the schema of the modified table. */
49459   reloadTableSchema(pParse, pTab, pTab->zName);
49460 }
49461
49462 /*
49463 ** This function is called by the parser after the table-name in
49464 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
49465 ** pSrc is the full-name of the table being altered.
49466 **
49467 ** This routine makes a (partial) copy of the Table structure
49468 ** for the table being altered and sets Parse.pNewTable to point
49469 ** to it. Routines called by the parser as the column definition
49470 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
49471 ** the copy. The copy of the Table structure is deleted by tokenize.c 
49472 ** after parsing is finished.
49473 **
49474 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
49475 ** coding the "ALTER TABLE ... ADD" statement.
49476 */
49477 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
49478   Table *pNew;
49479   Table *pTab;
49480   Vdbe *v;
49481   int iDb;
49482   int i;
49483   int nAlloc;
49484   sqlite3 *db = pParse->db;
49485
49486   /* Look up the table being altered. */
49487   assert( pParse->pNewTable==0 );
49488   assert( sqlite3BtreeHoldsAllMutexes(db) );
49489   if( db->mallocFailed ) goto exit_begin_add_column;
49490   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
49491   if( !pTab ) goto exit_begin_add_column;
49492
49493 #ifndef SQLITE_OMIT_VIRTUALTABLE
49494   if( IsVirtual(pTab) ){
49495     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
49496     goto exit_begin_add_column;
49497   }
49498 #endif
49499
49500   /* Make sure this is not an attempt to ALTER a view. */
49501   if( pTab->pSelect ){
49502     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
49503     goto exit_begin_add_column;
49504   }
49505
49506   assert( pTab->addColOffset>0 );
49507   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
49508
49509   /* Put a copy of the Table struct in Parse.pNewTable for the
49510   ** sqlite3AddColumn() function and friends to modify.
49511   */
49512   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
49513   if( !pNew ) goto exit_begin_add_column;
49514   pParse->pNewTable = pNew;
49515   pNew->nRef = 1;
49516   pNew->nCol = pTab->nCol;
49517   assert( pNew->nCol>0 );
49518   nAlloc = (((pNew->nCol-1)/8)*8)+8;
49519   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
49520   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
49521   pNew->zName = sqlite3DbStrDup(db, pTab->zName);
49522   if( !pNew->aCol || !pNew->zName ){
49523     db->mallocFailed = 1;
49524     goto exit_begin_add_column;
49525   }
49526   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
49527   for(i=0; i<pNew->nCol; i++){
49528     Column *pCol = &pNew->aCol[i];
49529     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
49530     pCol->zColl = 0;
49531     pCol->zType = 0;
49532     pCol->pDflt = 0;
49533   }
49534   pNew->pSchema = db->aDb[iDb].pSchema;
49535   pNew->addColOffset = pTab->addColOffset;
49536   pNew->nRef = 1;
49537
49538   /* Begin a transaction and increment the schema cookie.  */
49539   sqlite3BeginWriteOperation(pParse, 0, iDb);
49540   v = sqlite3GetVdbe(pParse);
49541   if( !v ) goto exit_begin_add_column;
49542   sqlite3ChangeCookie(pParse, iDb);
49543
49544 exit_begin_add_column:
49545   sqlite3SrcListDelete(pSrc);
49546   return;
49547 }
49548 #endif  /* SQLITE_ALTER_TABLE */
49549
49550 /************** End of alter.c ***********************************************/
49551 /************** Begin file analyze.c *****************************************/
49552 /*
49553 ** 2005 July 8
49554 **
49555 ** The author disclaims copyright to this source code.  In place of
49556 ** a legal notice, here is a blessing:
49557 **
49558 **    May you do good and not evil.
49559 **    May you find forgiveness for yourself and forgive others.
49560 **    May you share freely, never taking more than you give.
49561 **
49562 *************************************************************************
49563 ** This file contains code associated with the ANALYZE command.
49564 **
49565 ** @(#) $Id: analyze.c,v 1.41 2008/01/25 15:04:49 drh Exp $
49566 */
49567 #ifndef SQLITE_OMIT_ANALYZE
49568
49569 /*
49570 ** This routine generates code that opens the sqlite_stat1 table on cursor
49571 ** iStatCur.
49572 **
49573 ** If the sqlite_stat1 tables does not previously exist, it is created.
49574 ** If it does previously exist, all entires associated with table zWhere
49575 ** are removed.  If zWhere==0 then all entries are removed.
49576 */
49577 static void openStatTable(
49578   Parse *pParse,          /* Parsing context */
49579   int iDb,                /* The database we are looking in */
49580   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
49581   const char *zWhere      /* Delete entries associated with this table */
49582 ){
49583   sqlite3 *db = pParse->db;
49584   Db *pDb;
49585   int iRootPage;
49586   int createStat1 = 0;
49587   Table *pStat;
49588   Vdbe *v = sqlite3GetVdbe(pParse);
49589
49590   if( v==0 ) return;
49591   assert( sqlite3BtreeHoldsAllMutexes(db) );
49592   assert( sqlite3VdbeDb(v)==db );
49593   pDb = &db->aDb[iDb];
49594   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
49595     /* The sqlite_stat1 tables does not exist.  Create it.  
49596     ** Note that a side-effect of the CREATE TABLE statement is to leave
49597     ** the rootpage of the new table in register pParse->regRoot.  This is
49598     ** important because the OpenWrite opcode below will be needing it. */
49599     sqlite3NestedParse(pParse,
49600       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
49601       pDb->zName
49602     );
49603     iRootPage = pParse->regRoot;
49604     createStat1 = 1;  /* Cause rootpage to be taken from top of stack */
49605   }else if( zWhere ){
49606     /* The sqlite_stat1 table exists.  Delete all entries associated with
49607     ** the table zWhere. */
49608     sqlite3NestedParse(pParse,
49609        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
49610        pDb->zName, zWhere
49611     );
49612     iRootPage = pStat->tnum;
49613   }else{
49614     /* The sqlite_stat1 table already exists.  Delete all rows. */
49615     iRootPage = pStat->tnum;
49616     sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
49617   }
49618
49619   /* Open the sqlite_stat1 table for writing. Unless it was created
49620   ** by this vdbe program, lock it for writing at the shared-cache level. 
49621   ** If this vdbe did create the sqlite_stat1 table, then it must have 
49622   ** already obtained a schema-lock, making the write-lock redundant.
49623   */
49624   if( !createStat1 ){
49625     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
49626   }
49627   sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
49628   sqlite3VdbeChangeP5(v, createStat1);
49629   sqlite3VdbeAddOp2(v, OP_SetNumColumns, iStatCur, 3);
49630 }
49631
49632 /*
49633 ** Generate code to do an analysis of all indices associated with
49634 ** a single table.
49635 */
49636 static void analyzeOneTable(
49637   Parse *pParse,   /* Parser context */
49638   Table *pTab,     /* Table whose indices are to be analyzed */
49639   int iStatCur,    /* Cursor that writes to the sqlite_stat1 table */
49640   int iMem         /* Available memory locations begin here */
49641 ){
49642   Index *pIdx;     /* An index to being analyzed */
49643   int iIdxCur;     /* Cursor number for index being analyzed */
49644   int nCol;        /* Number of columns in the index */
49645   Vdbe *v;         /* The virtual machine being built up */
49646   int i;           /* Loop counter */
49647   int topOfLoop;   /* The top of the loop */
49648   int endOfLoop;   /* The end of the loop */
49649   int addr;        /* The address of an instruction */
49650   int iDb;         /* Index of database containing pTab */
49651
49652   v = sqlite3GetVdbe(pParse);
49653   if( v==0 || pTab==0 || pTab->pIndex==0 ){
49654     /* Do no analysis for tables that have no indices */
49655     return;
49656   }
49657   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
49658   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
49659   assert( iDb>=0 );
49660 #ifndef SQLITE_OMIT_AUTHORIZATION
49661   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
49662       pParse->db->aDb[iDb].zName ) ){
49663     return;
49664   }
49665 #endif
49666
49667   /* Establish a read-lock on the table at the shared-cache level. */
49668   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
49669
49670   iIdxCur = pParse->nTab;
49671   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
49672     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
49673     int regFields;    /* Register block for building records */
49674     int regRec;       /* Register holding completed record */
49675     int regTemp;      /* Temporary use register */
49676     int regCol;       /* Content of a column from the table being analyzed */
49677     int regRowid;     /* Rowid for the inserted record */
49678     int regF2;
49679
49680     /* Open a cursor to the index to be analyzed
49681     */
49682     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
49683     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
49684         (char *)pKey, P4_KEYINFO_HANDOFF);
49685     VdbeComment((v, "%s", pIdx->zName));
49686     nCol = pIdx->nColumn;
49687     regFields = iMem+nCol*2;
49688     regTemp = regRowid = regCol = regFields+3;
49689     regRec = regCol+1;
49690     if( regRec>pParse->nMem ){
49691       pParse->nMem = regRec;
49692     }
49693     sqlite3VdbeAddOp2(v, OP_SetNumColumns, iIdxCur, nCol+1);
49694
49695     /* Memory cells are used as follows:
49696     **
49697     **    mem[iMem]:             The total number of rows in the table.
49698     **    mem[iMem+1]:           Number of distinct values in column 1
49699     **    ...
49700     **    mem[iMem+nCol]:        Number of distinct values in column N
49701     **    mem[iMem+nCol+1]       Last observed value of column 1
49702     **    ...
49703     **    mem[iMem+nCol+nCol]:   Last observed value of column N
49704     **
49705     ** Cells iMem through iMem+nCol are initialized to 0.  The others
49706     ** are initialized to NULL.
49707     */
49708     for(i=0; i<=nCol; i++){
49709       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
49710     }
49711     for(i=0; i<nCol; i++){
49712       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
49713     }
49714
49715     /* Do the analysis.
49716     */
49717     endOfLoop = sqlite3VdbeMakeLabel(v);
49718     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
49719     topOfLoop = sqlite3VdbeCurrentAddr(v);
49720     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
49721     for(i=0; i<nCol; i++){
49722       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
49723       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
49724       /**** TODO:  add collating sequence *****/
49725       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
49726     }
49727     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
49728     for(i=0; i<nCol; i++){
49729       sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
49730       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
49731       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
49732     }
49733     sqlite3VdbeResolveLabel(v, endOfLoop);
49734     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
49735     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
49736
49737     /* Store the results.  
49738     **
49739     ** The result is a single row of the sqlite_stat1 table.  The first
49740     ** two columns are the names of the table and index.  The third column
49741     ** is a string composed of a list of integer statistics about the
49742     ** index.  The first integer in the list is the total number of entires
49743     ** in the index.  There is one additional integer in the list for each
49744     ** column of the table.  This additional integer is a guess of how many
49745     ** rows of the table the index will select.  If D is the count of distinct
49746     ** values and K is the total number of rows, then the integer is computed
49747     ** as:
49748     **
49749     **        I = (K+D-1)/D
49750     **
49751     ** If K==0 then no entry is made into the sqlite_stat1 table.  
49752     ** If K>0 then it is always the case the D>0 so division by zero
49753     ** is never possible.
49754     */
49755     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
49756     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
49757     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
49758     regF2 = regFields+2;
49759     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
49760     for(i=0; i<nCol; i++){
49761       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
49762       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
49763       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
49764       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
49765       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
49766       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
49767       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
49768     }
49769     sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
49770     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
49771     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
49772     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
49773     sqlite3VdbeJumpHere(v, addr);
49774   }
49775 }
49776
49777 /*
49778 ** Generate code that will cause the most recent index analysis to
49779 ** be laoded into internal hash tables where is can be used.
49780 */
49781 static void loadAnalysis(Parse *pParse, int iDb){
49782   Vdbe *v = sqlite3GetVdbe(pParse);
49783   if( v ){
49784     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
49785   }
49786 }
49787
49788 /*
49789 ** Generate code that will do an analysis of an entire database
49790 */
49791 static void analyzeDatabase(Parse *pParse, int iDb){
49792   sqlite3 *db = pParse->db;
49793   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
49794   HashElem *k;
49795   int iStatCur;
49796   int iMem;
49797
49798   sqlite3BeginWriteOperation(pParse, 0, iDb);
49799   iStatCur = pParse->nTab++;
49800   openStatTable(pParse, iDb, iStatCur, 0);
49801   iMem = pParse->nMem+1;
49802   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
49803     Table *pTab = (Table*)sqliteHashData(k);
49804     analyzeOneTable(pParse, pTab, iStatCur, iMem);
49805   }
49806   loadAnalysis(pParse, iDb);
49807 }
49808
49809 /*
49810 ** Generate code that will do an analysis of a single table in
49811 ** a database.
49812 */
49813 static void analyzeTable(Parse *pParse, Table *pTab){
49814   int iDb;
49815   int iStatCur;
49816
49817   assert( pTab!=0 );
49818   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
49819   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
49820   sqlite3BeginWriteOperation(pParse, 0, iDb);
49821   iStatCur = pParse->nTab++;
49822   openStatTable(pParse, iDb, iStatCur, pTab->zName);
49823   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
49824   loadAnalysis(pParse, iDb);
49825 }
49826
49827 /*
49828 ** Generate code for the ANALYZE command.  The parser calls this routine
49829 ** when it recognizes an ANALYZE command.
49830 **
49831 **        ANALYZE                            -- 1
49832 **        ANALYZE  <database>                -- 2
49833 **        ANALYZE  ?<database>.?<tablename>  -- 3
49834 **
49835 ** Form 1 causes all indices in all attached databases to be analyzed.
49836 ** Form 2 analyzes all indices the single database named.
49837 ** Form 3 analyzes all indices associated with the named table.
49838 */
49839 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
49840   sqlite3 *db = pParse->db;
49841   int iDb;
49842   int i;
49843   char *z, *zDb;
49844   Table *pTab;
49845   Token *pTableName;
49846
49847   /* Read the database schema. If an error occurs, leave an error message
49848   ** and code in pParse and return NULL. */
49849   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
49850   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
49851     return;
49852   }
49853
49854   if( pName1==0 ){
49855     /* Form 1:  Analyze everything */
49856     for(i=0; i<db->nDb; i++){
49857       if( i==1 ) continue;  /* Do not analyze the TEMP database */
49858       analyzeDatabase(pParse, i);
49859     }
49860   }else if( pName2==0 || pName2->n==0 ){
49861     /* Form 2:  Analyze the database or table named */
49862     iDb = sqlite3FindDb(db, pName1);
49863     if( iDb>=0 ){
49864       analyzeDatabase(pParse, iDb);
49865     }else{
49866       z = sqlite3NameFromToken(db, pName1);
49867       if( z ){
49868         pTab = sqlite3LocateTable(pParse, 0, z, 0);
49869         sqlite3_free(z);
49870         if( pTab ){
49871           analyzeTable(pParse, pTab);
49872         }
49873       }
49874     }
49875   }else{
49876     /* Form 3: Analyze the fully qualified table name */
49877     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
49878     if( iDb>=0 ){
49879       zDb = db->aDb[iDb].zName;
49880       z = sqlite3NameFromToken(db, pTableName);
49881       if( z ){
49882         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
49883         sqlite3_free(z);
49884         if( pTab ){
49885           analyzeTable(pParse, pTab);
49886         }
49887       }
49888     }   
49889   }
49890 }
49891
49892 /*
49893 ** Used to pass information from the analyzer reader through to the
49894 ** callback routine.
49895 */
49896 typedef struct analysisInfo analysisInfo;
49897 struct analysisInfo {
49898   sqlite3 *db;
49899   const char *zDatabase;
49900 };
49901
49902 /*
49903 ** This callback is invoked once for each index when reading the
49904 ** sqlite_stat1 table.  
49905 **
49906 **     argv[0] = name of the index
49907 **     argv[1] = results of analysis - on integer for each column
49908 */
49909 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
49910   analysisInfo *pInfo = (analysisInfo*)pData;
49911   Index *pIndex;
49912   int i, c;
49913   unsigned int v;
49914   const char *z;
49915
49916   assert( argc==2 );
49917   if( argv==0 || argv[0]==0 || argv[1]==0 ){
49918     return 0;
49919   }
49920   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
49921   if( pIndex==0 ){
49922     return 0;
49923   }
49924   z = argv[1];
49925   for(i=0; *z && i<=pIndex->nColumn; i++){
49926     v = 0;
49927     while( (c=z[0])>='0' && c<='9' ){
49928       v = v*10 + c - '0';
49929       z++;
49930     }
49931     pIndex->aiRowEst[i] = v;
49932     if( *z==' ' ) z++;
49933   }
49934   return 0;
49935 }
49936
49937 /*
49938 ** Load the content of the sqlite_stat1 table into the index hash tables.
49939 */
49940 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
49941   analysisInfo sInfo;
49942   HashElem *i;
49943   char *zSql;
49944   int rc;
49945
49946   assert( iDb>=0 && iDb<db->nDb );
49947   assert( db->aDb[iDb].pBt!=0 );
49948   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
49949
49950   /* Clear any prior statistics */
49951   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
49952     Index *pIdx = sqliteHashData(i);
49953     sqlite3DefaultRowEst(pIdx);
49954   }
49955
49956   /* Check to make sure the sqlite_stat1 table existss */
49957   sInfo.db = db;
49958   sInfo.zDatabase = db->aDb[iDb].zName;
49959   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
49960      return SQLITE_ERROR;
49961   }
49962
49963
49964   /* Load new statistics out of the sqlite_stat1 table */
49965   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
49966                         sInfo.zDatabase);
49967   (void)sqlite3SafetyOff(db);
49968   rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
49969   (void)sqlite3SafetyOn(db);
49970   sqlite3_free(zSql);
49971   return rc;
49972 }
49973
49974
49975 #endif /* SQLITE_OMIT_ANALYZE */
49976
49977 /************** End of analyze.c *********************************************/
49978 /************** Begin file attach.c ******************************************/
49979 /*
49980 ** 2003 April 6
49981 **
49982 ** The author disclaims copyright to this source code.  In place of
49983 ** a legal notice, here is a blessing:
49984 **
49985 **    May you do good and not evil.
49986 **    May you find forgiveness for yourself and forgive others.
49987 **    May you share freely, never taking more than you give.
49988 **
49989 *************************************************************************
49990 ** This file contains code used to implement the ATTACH and DETACH commands.
49991 **
49992 ** $Id: attach.c,v 1.72 2008/02/13 18:25:27 danielk1977 Exp $
49993 */
49994
49995 #ifndef SQLITE_OMIT_ATTACH
49996 /*
49997 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
49998 ** is slightly different from resolving a normal SQL expression, because simple
49999 ** identifiers are treated as strings, not possible column names or aliases.
50000 **
50001 ** i.e. if the parser sees:
50002 **
50003 **     ATTACH DATABASE abc AS def
50004 **
50005 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
50006 ** looking for columns of the same name.
50007 **
50008 ** This only applies to the root node of pExpr, so the statement:
50009 **
50010 **     ATTACH DATABASE abc||def AS 'db2'
50011 **
50012 ** will fail because neither abc or def can be resolved.
50013 */
50014 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
50015 {
50016   int rc = SQLITE_OK;
50017   if( pExpr ){
50018     if( pExpr->op!=TK_ID ){
50019       rc = sqlite3ExprResolveNames(pName, pExpr);
50020       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
50021         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
50022         return SQLITE_ERROR;
50023       }
50024     }else{
50025       pExpr->op = TK_STRING;
50026     }
50027   }
50028   return rc;
50029 }
50030
50031 /*
50032 ** An SQL user-function registered to do the work of an ATTACH statement. The
50033 ** three arguments to the function come directly from an attach statement:
50034 **
50035 **     ATTACH DATABASE x AS y KEY z
50036 **
50037 **     SELECT sqlite_attach(x, y, z)
50038 **
50039 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
50040 ** third argument.
50041 */
50042 static void attachFunc(
50043   sqlite3_context *context,
50044   int argc,
50045   sqlite3_value **argv
50046 ){
50047   int i;
50048   int rc = 0;
50049   sqlite3 *db = sqlite3_user_data(context);
50050   const char *zName;
50051   const char *zFile;
50052   Db *aNew;
50053   char *zErrDyn = 0;
50054   char zErr[128];
50055
50056   zFile = (const char *)sqlite3_value_text(argv[0]);
50057   zName = (const char *)sqlite3_value_text(argv[1]);
50058   if( zFile==0 ) zFile = "";
50059   if( zName==0 ) zName = "";
50060
50061   /* Check for the following errors:
50062   **
50063   **     * Too many attached databases,
50064   **     * Transaction currently open
50065   **     * Specified database name already being used.
50066   */
50067   if( db->nDb>=SQLITE_MAX_ATTACHED+2 ){
50068     sqlite3_snprintf(
50069       sizeof(zErr), zErr, "too many attached databases - max %d", 
50070       SQLITE_MAX_ATTACHED
50071     );
50072     goto attach_error;
50073   }
50074   if( !db->autoCommit ){
50075     sqlite3_snprintf(sizeof(zErr), zErr,
50076                      "cannot ATTACH database within transaction");
50077     goto attach_error;
50078   }
50079   for(i=0; i<db->nDb; i++){
50080     char *z = db->aDb[i].zName;
50081     if( z && zName && sqlite3StrICmp(z, zName)==0 ){
50082       sqlite3_snprintf(sizeof(zErr), zErr, 
50083                        "database %s is already in use", zName);
50084       goto attach_error;
50085     }
50086   }
50087
50088   /* Allocate the new entry in the db->aDb[] array and initialise the schema
50089   ** hash tables.
50090   */
50091   if( db->aDb==db->aDbStatic ){
50092     aNew = sqlite3_malloc( sizeof(db->aDb[0])*3 );
50093     if( aNew==0 ){
50094       db->mallocFailed = 1;
50095       return;
50096     }
50097     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
50098   }else{
50099     aNew = sqlite3_realloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
50100     if( aNew==0 ){
50101       db->mallocFailed = 1;
50102       return;
50103     } 
50104   }
50105   db->aDb = aNew;
50106   aNew = &db->aDb[db->nDb++];
50107   memset(aNew, 0, sizeof(*aNew));
50108
50109   /* Open the database file. If the btree is successfully opened, use
50110   ** it to obtain the database schema. At this point the schema may
50111   ** or may not be initialised.
50112   */
50113   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
50114                            db->openFlags | SQLITE_OPEN_MAIN_DB,
50115                            &aNew->pBt);
50116   if( rc==SQLITE_OK ){
50117     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
50118     if( !aNew->pSchema ){
50119       rc = SQLITE_NOMEM;
50120     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
50121       sqlite3_snprintf(sizeof(zErr), zErr, 
50122         "attached databases must use the same text encoding as main database");
50123       goto attach_error;
50124     }
50125     sqlite3PagerLockingMode(sqlite3BtreePager(aNew->pBt), db->dfltLockMode);
50126   }
50127   aNew->zName = sqlite3DbStrDup(db, zName);
50128   aNew->safety_level = 3;
50129
50130 #if SQLITE_HAS_CODEC
50131   {
50132     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
50133     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
50134     int nKey;
50135     char *zKey;
50136     int t = sqlite3_value_type(argv[2]);
50137     switch( t ){
50138       case SQLITE_INTEGER:
50139       case SQLITE_FLOAT:
50140         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
50141         rc = SQLITE_ERROR;
50142         break;
50143         
50144       case SQLITE_TEXT:
50145       case SQLITE_BLOB:
50146         nKey = sqlite3_value_bytes(argv[2]);
50147         zKey = (char *)sqlite3_value_blob(argv[2]);
50148         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
50149         break;
50150
50151       case SQLITE_NULL:
50152         /* No key specified.  Use the key from the main database */
50153         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
50154         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
50155         break;
50156     }
50157   }
50158 #endif
50159
50160   /* If the file was opened successfully, read the schema for the new database.
50161   ** If this fails, or if opening the file failed, then close the file and 
50162   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
50163   ** we found it.
50164   */
50165   if( rc==SQLITE_OK ){
50166     (void)sqlite3SafetyOn(db);
50167     sqlite3BtreeEnterAll(db);
50168     rc = sqlite3Init(db, &zErrDyn);
50169     sqlite3BtreeLeaveAll(db);
50170     (void)sqlite3SafetyOff(db);
50171   }
50172   if( rc ){
50173     int iDb = db->nDb - 1;
50174     assert( iDb>=2 );
50175     if( db->aDb[iDb].pBt ){
50176       sqlite3BtreeClose(db->aDb[iDb].pBt);
50177       db->aDb[iDb].pBt = 0;
50178       db->aDb[iDb].pSchema = 0;
50179     }
50180     sqlite3ResetInternalSchema(db, 0);
50181     db->nDb = iDb;
50182     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
50183       db->mallocFailed = 1;
50184       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
50185     }else{
50186       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
50187     }
50188     goto attach_error;
50189   }
50190   
50191   return;
50192
50193 attach_error:
50194   /* Return an error if we get here */
50195   if( zErrDyn ){
50196     sqlite3_result_error(context, zErrDyn, -1);
50197     sqlite3_free(zErrDyn);
50198   }else{
50199     zErr[sizeof(zErr)-1] = 0;
50200     sqlite3_result_error(context, zErr, -1);
50201   }
50202   if( rc ) sqlite3_result_error_code(context, rc);
50203 }
50204
50205 /*
50206 ** An SQL user-function registered to do the work of an DETACH statement. The
50207 ** three arguments to the function come directly from a detach statement:
50208 **
50209 **     DETACH DATABASE x
50210 **
50211 **     SELECT sqlite_detach(x)
50212 */
50213 static void detachFunc(
50214   sqlite3_context *context,
50215   int argc,
50216   sqlite3_value **argv
50217 ){
50218   const char *zName = (const char *)sqlite3_value_text(argv[0]);
50219   sqlite3 *db = sqlite3_user_data(context);
50220   int i;
50221   Db *pDb = 0;
50222   char zErr[128];
50223
50224   if( zName==0 ) zName = "";
50225   for(i=0; i<db->nDb; i++){
50226     pDb = &db->aDb[i];
50227     if( pDb->pBt==0 ) continue;
50228     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
50229   }
50230
50231   if( i>=db->nDb ){
50232     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
50233     goto detach_error;
50234   }
50235   if( i<2 ){
50236     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
50237     goto detach_error;
50238   }
50239   if( !db->autoCommit ){
50240     sqlite3_snprintf(sizeof(zErr), zErr,
50241                      "cannot DETACH database within transaction");
50242     goto detach_error;
50243   }
50244   if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
50245     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
50246     goto detach_error;
50247   }
50248
50249   sqlite3BtreeClose(pDb->pBt);
50250   pDb->pBt = 0;
50251   pDb->pSchema = 0;
50252   sqlite3ResetInternalSchema(db, 0);
50253   return;
50254
50255 detach_error:
50256   sqlite3_result_error(context, zErr, -1);
50257 }
50258
50259 /*
50260 ** This procedure generates VDBE code for a single invocation of either the
50261 ** sqlite_detach() or sqlite_attach() SQL user functions.
50262 */
50263 static void codeAttach(
50264   Parse *pParse,       /* The parser context */
50265   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
50266   const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
50267   int nFunc,           /* Number of args to pass to zFunc */
50268   Expr *pAuthArg,      /* Expression to pass to authorization callback */
50269   Expr *pFilename,     /* Name of database file */
50270   Expr *pDbname,       /* Name of the database to use internally */
50271   Expr *pKey           /* Database key for encryption extension */
50272 ){
50273   int rc;
50274   NameContext sName;
50275   Vdbe *v;
50276   FuncDef *pFunc;
50277   sqlite3* db = pParse->db;
50278   int regArgs;
50279
50280 #ifndef SQLITE_OMIT_AUTHORIZATION
50281   assert( db->mallocFailed || pAuthArg );
50282   if( pAuthArg ){
50283     char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
50284     if( !zAuthArg ){
50285       goto attach_end;
50286     }
50287     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
50288     sqlite3_free(zAuthArg);
50289     if(rc!=SQLITE_OK ){
50290       goto attach_end;
50291     }
50292   }
50293 #endif /* SQLITE_OMIT_AUTHORIZATION */
50294
50295   memset(&sName, 0, sizeof(NameContext));
50296   sName.pParse = pParse;
50297
50298   if( 
50299       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
50300       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
50301       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
50302   ){
50303     pParse->nErr++;
50304     goto attach_end;
50305   }
50306
50307   v = sqlite3GetVdbe(pParse);
50308   regArgs = sqlite3GetTempRange(pParse, 4);
50309   sqlite3ExprCode(pParse, pFilename, regArgs);
50310   sqlite3ExprCode(pParse, pDbname, regArgs+1);
50311   sqlite3ExprCode(pParse, pKey, regArgs+2);
50312
50313   assert( v || db->mallocFailed );
50314   if( v ){
50315     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-nFunc, regArgs+3);
50316     sqlite3VdbeChangeP5(v, nFunc);
50317     pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
50318     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
50319
50320     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
50321     ** statement only). For DETACH, set it to false (expire all existing
50322     ** statements).
50323     */
50324     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
50325   }
50326   
50327 attach_end:
50328   sqlite3ExprDelete(pFilename);
50329   sqlite3ExprDelete(pDbname);
50330   sqlite3ExprDelete(pKey);
50331 }
50332
50333 /*
50334 ** Called by the parser to compile a DETACH statement.
50335 **
50336 **     DETACH pDbname
50337 */
50338 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
50339   codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
50340 }
50341
50342 /*
50343 ** Called by the parser to compile an ATTACH statement.
50344 **
50345 **     ATTACH p AS pDbname KEY pKey
50346 */
50347 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
50348   codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
50349 }
50350 #endif /* SQLITE_OMIT_ATTACH */
50351
50352 /*
50353 ** Register the functions sqlite_attach and sqlite_detach.
50354 */
50355 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *db){
50356 #ifndef SQLITE_OMIT_ATTACH
50357   static const int enc = SQLITE_UTF8;
50358   sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
50359   sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
50360 #endif
50361 }
50362
50363 /*
50364 ** Initialize a DbFixer structure.  This routine must be called prior
50365 ** to passing the structure to one of the sqliteFixAAAA() routines below.
50366 **
50367 ** The return value indicates whether or not fixation is required.  TRUE
50368 ** means we do need to fix the database references, FALSE means we do not.
50369 */
50370 SQLITE_PRIVATE int sqlite3FixInit(
50371   DbFixer *pFix,      /* The fixer to be initialized */
50372   Parse *pParse,      /* Error messages will be written here */
50373   int iDb,            /* This is the database that must be used */
50374   const char *zType,  /* "view", "trigger", or "index" */
50375   const Token *pName  /* Name of the view, trigger, or index */
50376 ){
50377   sqlite3 *db;
50378
50379   if( iDb<0 || iDb==1 ) return 0;
50380   db = pParse->db;
50381   assert( db->nDb>iDb );
50382   pFix->pParse = pParse;
50383   pFix->zDb = db->aDb[iDb].zName;
50384   pFix->zType = zType;
50385   pFix->pName = pName;
50386   return 1;
50387 }
50388
50389 /*
50390 ** The following set of routines walk through the parse tree and assign
50391 ** a specific database to all table references where the database name
50392 ** was left unspecified in the original SQL statement.  The pFix structure
50393 ** must have been initialized by a prior call to sqlite3FixInit().
50394 **
50395 ** These routines are used to make sure that an index, trigger, or
50396 ** view in one database does not refer to objects in a different database.
50397 ** (Exception: indices, triggers, and views in the TEMP database are
50398 ** allowed to refer to anything.)  If a reference is explicitly made
50399 ** to an object in a different database, an error message is added to
50400 ** pParse->zErrMsg and these routines return non-zero.  If everything
50401 ** checks out, these routines return 0.
50402 */
50403 SQLITE_PRIVATE int sqlite3FixSrcList(
50404   DbFixer *pFix,       /* Context of the fixation */
50405   SrcList *pList       /* The Source list to check and modify */
50406 ){
50407   int i;
50408   const char *zDb;
50409   struct SrcList_item *pItem;
50410
50411   if( pList==0 ) return 0;
50412   zDb = pFix->zDb;
50413   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
50414     if( pItem->zDatabase==0 ){
50415       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
50416     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
50417       sqlite3ErrorMsg(pFix->pParse,
50418          "%s %T cannot reference objects in database %s",
50419          pFix->zType, pFix->pName, pItem->zDatabase);
50420       return 1;
50421     }
50422 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
50423     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
50424     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
50425 #endif
50426   }
50427   return 0;
50428 }
50429 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
50430 SQLITE_PRIVATE int sqlite3FixSelect(
50431   DbFixer *pFix,       /* Context of the fixation */
50432   Select *pSelect      /* The SELECT statement to be fixed to one database */
50433 ){
50434   while( pSelect ){
50435     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
50436       return 1;
50437     }
50438     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
50439       return 1;
50440     }
50441     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
50442       return 1;
50443     }
50444     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
50445       return 1;
50446     }
50447     pSelect = pSelect->pPrior;
50448   }
50449   return 0;
50450 }
50451 SQLITE_PRIVATE int sqlite3FixExpr(
50452   DbFixer *pFix,     /* Context of the fixation */
50453   Expr *pExpr        /* The expression to be fixed to one database */
50454 ){
50455   while( pExpr ){
50456     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
50457       return 1;
50458     }
50459     if( sqlite3FixExprList(pFix, pExpr->pList) ){
50460       return 1;
50461     }
50462     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
50463       return 1;
50464     }
50465     pExpr = pExpr->pLeft;
50466   }
50467   return 0;
50468 }
50469 SQLITE_PRIVATE int sqlite3FixExprList(
50470   DbFixer *pFix,     /* Context of the fixation */
50471   ExprList *pList    /* The expression to be fixed to one database */
50472 ){
50473   int i;
50474   struct ExprList_item *pItem;
50475   if( pList==0 ) return 0;
50476   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
50477     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
50478       return 1;
50479     }
50480   }
50481   return 0;
50482 }
50483 #endif
50484
50485 #ifndef SQLITE_OMIT_TRIGGER
50486 SQLITE_PRIVATE int sqlite3FixTriggerStep(
50487   DbFixer *pFix,     /* Context of the fixation */
50488   TriggerStep *pStep /* The trigger step be fixed to one database */
50489 ){
50490   while( pStep ){
50491     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
50492       return 1;
50493     }
50494     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
50495       return 1;
50496     }
50497     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
50498       return 1;
50499     }
50500     pStep = pStep->pNext;
50501   }
50502   return 0;
50503 }
50504 #endif
50505
50506 /************** End of attach.c **********************************************/
50507 /************** Begin file auth.c ********************************************/
50508 /*
50509 ** 2003 January 11
50510 **
50511 ** The author disclaims copyright to this source code.  In place of
50512 ** a legal notice, here is a blessing:
50513 **
50514 **    May you do good and not evil.
50515 **    May you find forgiveness for yourself and forgive others.
50516 **    May you share freely, never taking more than you give.
50517 **
50518 *************************************************************************
50519 ** This file contains code used to implement the sqlite3_set_authorizer()
50520 ** API.  This facility is an optional feature of the library.  Embedded
50521 ** systems that do not need this facility may omit it by recompiling
50522 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
50523 **
50524 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
50525 */
50526
50527 /*
50528 ** All of the code in this file may be omitted by defining a single
50529 ** macro.
50530 */
50531 #ifndef SQLITE_OMIT_AUTHORIZATION
50532
50533 /*
50534 ** Set or clear the access authorization function.
50535 **
50536 ** The access authorization function is be called during the compilation
50537 ** phase to verify that the user has read and/or write access permission on
50538 ** various fields of the database.  The first argument to the auth function
50539 ** is a copy of the 3rd argument to this routine.  The second argument
50540 ** to the auth function is one of these constants:
50541 **
50542 **       SQLITE_CREATE_INDEX
50543 **       SQLITE_CREATE_TABLE
50544 **       SQLITE_CREATE_TEMP_INDEX
50545 **       SQLITE_CREATE_TEMP_TABLE
50546 **       SQLITE_CREATE_TEMP_TRIGGER
50547 **       SQLITE_CREATE_TEMP_VIEW
50548 **       SQLITE_CREATE_TRIGGER
50549 **       SQLITE_CREATE_VIEW
50550 **       SQLITE_DELETE
50551 **       SQLITE_DROP_INDEX
50552 **       SQLITE_DROP_TABLE
50553 **       SQLITE_DROP_TEMP_INDEX
50554 **       SQLITE_DROP_TEMP_TABLE
50555 **       SQLITE_DROP_TEMP_TRIGGER
50556 **       SQLITE_DROP_TEMP_VIEW
50557 **       SQLITE_DROP_TRIGGER
50558 **       SQLITE_DROP_VIEW
50559 **       SQLITE_INSERT
50560 **       SQLITE_PRAGMA
50561 **       SQLITE_READ
50562 **       SQLITE_SELECT
50563 **       SQLITE_TRANSACTION
50564 **       SQLITE_UPDATE
50565 **
50566 ** The third and fourth arguments to the auth function are the name of
50567 ** the table and the column that are being accessed.  The auth function
50568 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
50569 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
50570 ** means that the SQL statement will never-run - the sqlite3_exec() call
50571 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
50572 ** should run but attempts to read the specified column will return NULL
50573 ** and attempts to write the column will be ignored.
50574 **
50575 ** Setting the auth function to NULL disables this hook.  The default
50576 ** setting of the auth function is NULL.
50577 */
50578 SQLITE_API int sqlite3_set_authorizer(
50579   sqlite3 *db,
50580   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
50581   void *pArg
50582 ){
50583   sqlite3_mutex_enter(db->mutex);
50584   db->xAuth = xAuth;
50585   db->pAuthArg = pArg;
50586   sqlite3ExpirePreparedStatements(db);
50587   sqlite3_mutex_leave(db->mutex);
50588   return SQLITE_OK;
50589 }
50590
50591 /*
50592 ** Write an error message into pParse->zErrMsg that explains that the
50593 ** user-supplied authorization function returned an illegal value.
50594 */
50595 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
50596   sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
50597     "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
50598     "or SQLITE_DENY", rc);
50599   pParse->rc = SQLITE_ERROR;
50600 }
50601
50602 /*
50603 ** The pExpr should be a TK_COLUMN expression.  The table referred to
50604 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
50605 ** Check to see if it is OK to read this particular column.
50606 **
50607 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
50608 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
50609 ** then generate an error.
50610 */
50611 SQLITE_PRIVATE void sqlite3AuthRead(
50612   Parse *pParse,        /* The parser context */
50613   Expr *pExpr,          /* The expression to check authorization on */
50614   Schema *pSchema,      /* The schema of the expression */
50615   SrcList *pTabList     /* All table that pExpr might refer to */
50616 ){
50617   sqlite3 *db = pParse->db;
50618   int rc;
50619   Table *pTab = 0;      /* The table being read */
50620   const char *zCol;     /* Name of the column of the table */
50621   int iSrc;             /* Index in pTabList->a[] of table being read */
50622   const char *zDBase;   /* Name of database being accessed */
50623   TriggerStack *pStack; /* The stack of current triggers */
50624   int iDb;              /* The index of the database the expression refers to */
50625
50626   if( db->xAuth==0 ) return;
50627   if( pExpr->op!=TK_COLUMN ) return;
50628   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
50629   if( iDb<0 ){
50630     /* An attempt to read a column out of a subquery or other
50631     ** temporary table. */
50632     return;
50633   }
50634   for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
50635     if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
50636   }
50637   if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
50638     pTab = pTabList->a[iSrc].pTab;
50639   }else if( (pStack = pParse->trigStack)!=0 ){
50640     /* This must be an attempt to read the NEW or OLD pseudo-tables
50641     ** of a trigger.
50642     */
50643     assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
50644     pTab = pStack->pTab;
50645   }
50646   if( pTab==0 ) return;
50647   if( pExpr->iColumn>=0 ){
50648     assert( pExpr->iColumn<pTab->nCol );
50649     zCol = pTab->aCol[pExpr->iColumn].zName;
50650   }else if( pTab->iPKey>=0 ){
50651     assert( pTab->iPKey<pTab->nCol );
50652     zCol = pTab->aCol[pTab->iPKey].zName;
50653   }else{
50654     zCol = "ROWID";
50655   }
50656   assert( iDb>=0 && iDb<db->nDb );
50657   zDBase = db->aDb[iDb].zName;
50658   rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
50659                  pParse->zAuthContext);
50660   if( rc==SQLITE_IGNORE ){
50661     pExpr->op = TK_NULL;
50662   }else if( rc==SQLITE_DENY ){
50663     if( db->nDb>2 || iDb!=0 ){
50664       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
50665          zDBase, pTab->zName, zCol);
50666     }else{
50667       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
50668     }
50669     pParse->rc = SQLITE_AUTH;
50670   }else if( rc!=SQLITE_OK ){
50671     sqliteAuthBadReturnCode(pParse, rc);
50672   }
50673 }
50674
50675 /*
50676 ** Do an authorization check using the code and arguments given.  Return
50677 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
50678 ** is returned, then the error count and error message in pParse are
50679 ** modified appropriately.
50680 */
50681 SQLITE_PRIVATE int sqlite3AuthCheck(
50682   Parse *pParse,
50683   int code,
50684   const char *zArg1,
50685   const char *zArg2,
50686   const char *zArg3
50687 ){
50688   sqlite3 *db = pParse->db;
50689   int rc;
50690
50691   /* Don't do any authorization checks if the database is initialising
50692   ** or if the parser is being invoked from within sqlite3_declare_vtab.
50693   */
50694   if( db->init.busy || IN_DECLARE_VTAB ){
50695     return SQLITE_OK;
50696   }
50697
50698   if( db->xAuth==0 ){
50699     return SQLITE_OK;
50700   }
50701   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
50702   if( rc==SQLITE_DENY ){
50703     sqlite3ErrorMsg(pParse, "not authorized");
50704     pParse->rc = SQLITE_AUTH;
50705   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
50706     rc = SQLITE_DENY;
50707     sqliteAuthBadReturnCode(pParse, rc);
50708   }
50709   return rc;
50710 }
50711
50712 /*
50713 ** Push an authorization context.  After this routine is called, the
50714 ** zArg3 argument to authorization callbacks will be zContext until
50715 ** popped.  Or if pParse==0, this routine is a no-op.
50716 */
50717 SQLITE_PRIVATE void sqlite3AuthContextPush(
50718   Parse *pParse,
50719   AuthContext *pContext, 
50720   const char *zContext
50721 ){
50722   pContext->pParse = pParse;
50723   if( pParse ){
50724     pContext->zAuthContext = pParse->zAuthContext;
50725     pParse->zAuthContext = zContext;
50726   }
50727 }
50728
50729 /*
50730 ** Pop an authorization context that was previously pushed
50731 ** by sqlite3AuthContextPush
50732 */
50733 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
50734   if( pContext->pParse ){
50735     pContext->pParse->zAuthContext = pContext->zAuthContext;
50736     pContext->pParse = 0;
50737   }
50738 }
50739
50740 #endif /* SQLITE_OMIT_AUTHORIZATION */
50741
50742 /************** End of auth.c ************************************************/
50743 /************** Begin file build.c *******************************************/
50744 /*
50745 ** 2001 September 15
50746 **
50747 ** The author disclaims copyright to this source code.  In place of
50748 ** a legal notice, here is a blessing:
50749 **
50750 **    May you do good and not evil.
50751 **    May you find forgiveness for yourself and forgive others.
50752 **    May you share freely, never taking more than you give.
50753 **
50754 *************************************************************************
50755 ** This file contains C code routines that are called by the SQLite parser
50756 ** when syntax rules are reduced.  The routines in this file handle the
50757 ** following kinds of SQL syntax:
50758 **
50759 **     CREATE TABLE
50760 **     DROP TABLE
50761 **     CREATE INDEX
50762 **     DROP INDEX
50763 **     creating ID lists
50764 **     BEGIN TRANSACTION
50765 **     COMMIT
50766 **     ROLLBACK
50767 **
50768 ** $Id: build.c,v 1.474 2008/03/06 09:58:50 mlcreech Exp $
50769 */
50770
50771 /*
50772 ** This routine is called when a new SQL statement is beginning to
50773 ** be parsed.  Initialize the pParse structure as needed.
50774 */
50775 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
50776   pParse->explain = explainFlag;
50777   pParse->nVar = 0;
50778 }
50779
50780 #ifndef SQLITE_OMIT_SHARED_CACHE
50781 /*
50782 ** The TableLock structure is only used by the sqlite3TableLock() and
50783 ** codeTableLocks() functions.
50784 */
50785 struct TableLock {
50786   int iDb;             /* The database containing the table to be locked */
50787   int iTab;            /* The root page of the table to be locked */
50788   u8 isWriteLock;      /* True for write lock.  False for a read lock */
50789   const char *zName;   /* Name of the table */
50790 };
50791
50792 /*
50793 ** Record the fact that we want to lock a table at run-time.  
50794 **
50795 ** The table to be locked has root page iTab and is found in database iDb.
50796 ** A read or a write lock can be taken depending on isWritelock.
50797 **
50798 ** This routine just records the fact that the lock is desired.  The
50799 ** code to make the lock occur is generated by a later call to
50800 ** codeTableLocks() which occurs during sqlite3FinishCoding().
50801 */
50802 SQLITE_PRIVATE void sqlite3TableLock(
50803   Parse *pParse,     /* Parsing context */
50804   int iDb,           /* Index of the database containing the table to lock */
50805   int iTab,          /* Root page number of the table to be locked */
50806   u8 isWriteLock,    /* True for a write lock */
50807   const char *zName  /* Name of the table to be locked */
50808 ){
50809   int i;
50810   int nBytes;
50811   TableLock *p;
50812
50813   if( iDb<0 ){
50814     return;
50815   }
50816
50817   for(i=0; i<pParse->nTableLock; i++){
50818     p = &pParse->aTableLock[i];
50819     if( p->iDb==iDb && p->iTab==iTab ){
50820       p->isWriteLock = (p->isWriteLock || isWriteLock);
50821       return;
50822     }
50823   }
50824
50825   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
50826   pParse->aTableLock = 
50827       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
50828   if( pParse->aTableLock ){
50829     p = &pParse->aTableLock[pParse->nTableLock++];
50830     p->iDb = iDb;
50831     p->iTab = iTab;
50832     p->isWriteLock = isWriteLock;
50833     p->zName = zName;
50834   }else{
50835     pParse->nTableLock = 0;
50836     pParse->db->mallocFailed = 1;
50837   }
50838 }
50839
50840 /*
50841 ** Code an OP_TableLock instruction for each table locked by the
50842 ** statement (configured by calls to sqlite3TableLock()).
50843 */
50844 static void codeTableLocks(Parse *pParse){
50845   int i;
50846   Vdbe *pVdbe; 
50847
50848   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
50849     return;
50850   }
50851
50852   for(i=0; i<pParse->nTableLock; i++){
50853     TableLock *p = &pParse->aTableLock[i];
50854     int p1 = p->iDb;
50855     if( p->isWriteLock ){
50856       p1 = -1*(p1+1);
50857     }
50858     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, 0, p->zName, P4_STATIC);
50859   }
50860 }
50861 #else
50862   #define codeTableLocks(x)
50863 #endif
50864
50865 /*
50866 ** This routine is called after a single SQL statement has been
50867 ** parsed and a VDBE program to execute that statement has been
50868 ** prepared.  This routine puts the finishing touches on the
50869 ** VDBE program and resets the pParse structure for the next
50870 ** parse.
50871 **
50872 ** Note that if an error occurred, it might be the case that
50873 ** no VDBE code was generated.
50874 */
50875 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
50876   sqlite3 *db;
50877   Vdbe *v;
50878
50879   db = pParse->db;
50880   if( db->mallocFailed ) return;
50881   if( pParse->nested ) return;
50882   if( pParse->nErr ) return;
50883   if( !pParse->pVdbe ){
50884     if( pParse->rc==SQLITE_OK && pParse->nErr ){
50885       pParse->rc = SQLITE_ERROR;
50886       return;
50887     }
50888   }
50889
50890   /* Begin by generating some termination code at the end of the
50891   ** vdbe program
50892   */
50893   v = sqlite3GetVdbe(pParse);
50894   if( v ){
50895     sqlite3VdbeAddOp0(v, OP_Halt);
50896
50897     /* The cookie mask contains one bit for each database file open.
50898     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
50899     ** set for each database that is used.  Generate code to start a
50900     ** transaction on each used database and to verify the schema cookie
50901     ** on each used database.
50902     */
50903     if( pParse->cookieGoto>0 ){
50904       u32 mask;
50905       int iDb;
50906       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
50907       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
50908         if( (mask & pParse->cookieMask)==0 ) continue;
50909         sqlite3VdbeUsesBtree(v, iDb);
50910         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
50911         sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
50912       }
50913 #ifndef SQLITE_OMIT_VIRTUALTABLE
50914       if( pParse->pVirtualLock ){
50915         char *vtab = (char *)pParse->pVirtualLock->pVtab;
50916         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
50917       }
50918 #endif
50919
50920       /* Once all the cookies have been verified and transactions opened, 
50921       ** obtain the required table-locks. This is a no-op unless the 
50922       ** shared-cache feature is enabled.
50923       */
50924       codeTableLocks(pParse);
50925       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
50926     }
50927
50928 #ifndef SQLITE_OMIT_TRACE
50929     if( !db->init.busy ){
50930       /* Change the P4 argument of the first opcode (which will always be
50931       ** an OP_Trace) to be the complete text of the current SQL statement.
50932       */
50933       VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
50934       if( pOp && pOp->opcode==OP_Trace ){
50935         sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
50936       }
50937     }
50938 #endif /* SQLITE_OMIT_TRACE */
50939   }
50940
50941
50942   /* Get the VDBE program ready for execution
50943   */
50944   if( v && pParse->nErr==0 && !db->mallocFailed ){
50945 #ifdef SQLITE_DEBUG
50946     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
50947     sqlite3VdbeTrace(v, trace);
50948 #endif
50949     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
50950                          pParse->nTab+3, pParse->explain);
50951     pParse->rc = SQLITE_DONE;
50952     pParse->colNamesSet = 0;
50953   }else if( pParse->rc==SQLITE_OK ){
50954     pParse->rc = SQLITE_ERROR;
50955   }
50956   pParse->nTab = 0;
50957   pParse->nMem = 0;
50958   pParse->nSet = 0;
50959   pParse->nVar = 0;
50960   pParse->cookieMask = 0;
50961   pParse->cookieGoto = 0;
50962 }
50963
50964 /*
50965 ** Run the parser and code generator recursively in order to generate
50966 ** code for the SQL statement given onto the end of the pParse context
50967 ** currently under construction.  When the parser is run recursively
50968 ** this way, the final OP_Halt is not appended and other initialization
50969 ** and finalization steps are omitted because those are handling by the
50970 ** outermost parser.
50971 **
50972 ** Not everything is nestable.  This facility is designed to permit
50973 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
50974 ** care if you decide to try to use this routine for some other purposes.
50975 */
50976 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
50977   va_list ap;
50978   char *zSql;
50979 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
50980   char saveBuf[SAVE_SZ];
50981
50982   if( pParse->nErr ) return;
50983   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
50984   va_start(ap, zFormat);
50985   zSql = sqlite3VMPrintf(pParse->db, zFormat, ap);
50986   va_end(ap);
50987   if( zSql==0 ){
50988     pParse->db->mallocFailed = 1;
50989     return;   /* A malloc must have failed */
50990   }
50991   pParse->nested++;
50992   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
50993   memset(&pParse->nVar, 0, SAVE_SZ);
50994   sqlite3RunParser(pParse, zSql, 0);
50995   sqlite3_free(zSql);
50996   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
50997   pParse->nested--;
50998 }
50999
51000 /*
51001 ** Locate the in-memory structure that describes a particular database
51002 ** table given the name of that table and (optionally) the name of the
51003 ** database containing the table.  Return NULL if not found.
51004 **
51005 ** If zDatabase is 0, all databases are searched for the table and the
51006 ** first matching table is returned.  (No checking for duplicate table
51007 ** names is done.)  The search order is TEMP first, then MAIN, then any
51008 ** auxiliary databases added using the ATTACH command.
51009 **
51010 ** See also sqlite3LocateTable().
51011 */
51012 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
51013   Table *p = 0;
51014   int i;
51015   assert( zName!=0 );
51016   for(i=OMIT_TEMPDB; i<db->nDb; i++){
51017     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
51018     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
51019     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
51020     if( p ) break;
51021   }
51022   return p;
51023 }
51024
51025 /*
51026 ** Locate the in-memory structure that describes a particular database
51027 ** table given the name of that table and (optionally) the name of the
51028 ** database containing the table.  Return NULL if not found.  Also leave an
51029 ** error message in pParse->zErrMsg.
51030 **
51031 ** The difference between this routine and sqlite3FindTable() is that this
51032 ** routine leaves an error message in pParse->zErrMsg where
51033 ** sqlite3FindTable() does not.
51034 */
51035 SQLITE_PRIVATE Table *sqlite3LocateTable(
51036   Parse *pParse,         /* context in which to report errors */
51037   int isView,            /* True if looking for a VIEW rather than a TABLE */
51038   const char *zName,     /* Name of the table we are looking for */
51039   const char *zDbase     /* Name of the database.  Might be NULL */
51040 ){
51041   Table *p;
51042
51043   /* Read the database schema. If an error occurs, leave an error message
51044   ** and code in pParse and return NULL. */
51045   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
51046     return 0;
51047   }
51048
51049   p = sqlite3FindTable(pParse->db, zName, zDbase);
51050   if( p==0 ){
51051     const char *zMsg = isView ? "no such view" : "no such table";
51052     if( zDbase ){
51053       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
51054     }else{
51055       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
51056     }
51057     pParse->checkSchema = 1;
51058   }
51059   return p;
51060 }
51061
51062 /*
51063 ** Locate the in-memory structure that describes 
51064 ** a particular index given the name of that index
51065 ** and the name of the database that contains the index.
51066 ** Return NULL if not found.
51067 **
51068 ** If zDatabase is 0, all databases are searched for the
51069 ** table and the first matching index is returned.  (No checking
51070 ** for duplicate index names is done.)  The search order is
51071 ** TEMP first, then MAIN, then any auxiliary databases added
51072 ** using the ATTACH command.
51073 */
51074 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
51075   Index *p = 0;
51076   int i;
51077   for(i=OMIT_TEMPDB; i<db->nDb; i++){
51078     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
51079     Schema *pSchema = db->aDb[j].pSchema;
51080     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
51081     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
51082     if( pSchema ){
51083       p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
51084     }
51085     if( p ) break;
51086   }
51087   return p;
51088 }
51089
51090 /*
51091 ** Reclaim the memory used by an index
51092 */
51093 static void freeIndex(Index *p){
51094   sqlite3_free(p->zColAff);
51095   sqlite3_free(p);
51096 }
51097
51098 /*
51099 ** Remove the given index from the index hash table, and free
51100 ** its memory structures.
51101 **
51102 ** The index is removed from the database hash tables but
51103 ** it is not unlinked from the Table that it indexes.
51104 ** Unlinking from the Table must be done by the calling function.
51105 */
51106 static void sqliteDeleteIndex(Index *p){
51107   Index *pOld;
51108   const char *zName = p->zName;
51109
51110   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
51111   assert( pOld==0 || pOld==p );
51112   freeIndex(p);
51113 }
51114
51115 /*
51116 ** For the index called zIdxName which is found in the database iDb,
51117 ** unlike that index from its Table then remove the index from
51118 ** the index hash table and free all memory structures associated
51119 ** with the index.
51120 */
51121 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
51122   Index *pIndex;
51123   int len;
51124   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
51125
51126   len = strlen(zIdxName);
51127   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
51128   if( pIndex ){
51129     if( pIndex->pTable->pIndex==pIndex ){
51130       pIndex->pTable->pIndex = pIndex->pNext;
51131     }else{
51132       Index *p;
51133       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
51134       if( p && p->pNext==pIndex ){
51135         p->pNext = pIndex->pNext;
51136       }
51137     }
51138     freeIndex(pIndex);
51139   }
51140   db->flags |= SQLITE_InternChanges;
51141 }
51142
51143 /*
51144 ** Erase all schema information from the in-memory hash tables of
51145 ** a single database.  This routine is called to reclaim memory
51146 ** before the database closes.  It is also called during a rollback
51147 ** if there were schema changes during the transaction or if a
51148 ** schema-cookie mismatch occurs.
51149 **
51150 ** If iDb<=0 then reset the internal schema tables for all database
51151 ** files.  If iDb>=2 then reset the internal schema for only the
51152 ** single file indicated.
51153 */
51154 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
51155   int i, j;
51156   assert( iDb>=0 && iDb<db->nDb );
51157
51158   if( iDb==0 ){
51159     sqlite3BtreeEnterAll(db);
51160   }
51161   for(i=iDb; i<db->nDb; i++){
51162     Db *pDb = &db->aDb[i];
51163     if( pDb->pSchema ){
51164       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
51165       sqlite3SchemaFree(pDb->pSchema);
51166     }
51167     if( iDb>0 ) return;
51168   }
51169   assert( iDb==0 );
51170   db->flags &= ~SQLITE_InternChanges;
51171   sqlite3BtreeLeaveAll(db);
51172
51173   /* If one or more of the auxiliary database files has been closed,
51174   ** then remove them from the auxiliary database list.  We take the
51175   ** opportunity to do this here since we have just deleted all of the
51176   ** schema hash tables and therefore do not have to make any changes
51177   ** to any of those tables.
51178   */
51179   for(i=0; i<db->nDb; i++){
51180     struct Db *pDb = &db->aDb[i];
51181     if( pDb->pBt==0 ){
51182       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
51183       pDb->pAux = 0;
51184     }
51185   }
51186   for(i=j=2; i<db->nDb; i++){
51187     struct Db *pDb = &db->aDb[i];
51188     if( pDb->pBt==0 ){
51189       sqlite3_free(pDb->zName);
51190       pDb->zName = 0;
51191       continue;
51192     }
51193     if( j<i ){
51194       db->aDb[j] = db->aDb[i];
51195     }
51196     j++;
51197   }
51198   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
51199   db->nDb = j;
51200   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
51201     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
51202     sqlite3_free(db->aDb);
51203     db->aDb = db->aDbStatic;
51204   }
51205 }
51206
51207 /*
51208 ** This routine is called when a commit occurs.
51209 */
51210 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
51211   db->flags &= ~SQLITE_InternChanges;
51212 }
51213
51214 /*
51215 ** Clear the column names from a table or view.
51216 */
51217 static void sqliteResetColumnNames(Table *pTable){
51218   int i;
51219   Column *pCol;
51220   assert( pTable!=0 );
51221   if( (pCol = pTable->aCol)!=0 ){
51222     for(i=0; i<pTable->nCol; i++, pCol++){
51223       sqlite3_free(pCol->zName);
51224       sqlite3ExprDelete(pCol->pDflt);
51225       sqlite3_free(pCol->zType);
51226       sqlite3_free(pCol->zColl);
51227     }
51228     sqlite3_free(pTable->aCol);
51229   }
51230   pTable->aCol = 0;
51231   pTable->nCol = 0;
51232 }
51233
51234 /*
51235 ** Remove the memory data structures associated with the given
51236 ** Table.  No changes are made to disk by this routine.
51237 **
51238 ** This routine just deletes the data structure.  It does not unlink
51239 ** the table data structure from the hash table.  Nor does it remove
51240 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
51241 ** memory structures of the indices and foreign keys associated with 
51242 ** the table.
51243 */
51244 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
51245   Index *pIndex, *pNext;
51246   FKey *pFKey, *pNextFKey;
51247
51248   if( pTable==0 ) return;
51249
51250   /* Do not delete the table until the reference count reaches zero. */
51251   pTable->nRef--;
51252   if( pTable->nRef>0 ){
51253     return;
51254   }
51255   assert( pTable->nRef==0 );
51256
51257   /* Delete all indices associated with this table
51258   */
51259   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
51260     pNext = pIndex->pNext;
51261     assert( pIndex->pSchema==pTable->pSchema );
51262     sqliteDeleteIndex(pIndex);
51263   }
51264
51265 #ifndef SQLITE_OMIT_FOREIGN_KEY
51266   /* Delete all foreign keys associated with this table.  The keys
51267   ** should have already been unlinked from the pSchema->aFKey hash table 
51268   */
51269   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
51270     pNextFKey = pFKey->pNextFrom;
51271     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
51272                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
51273     sqlite3_free(pFKey);
51274   }
51275 #endif
51276
51277   /* Delete the Table structure itself.
51278   */
51279   sqliteResetColumnNames(pTable);
51280   sqlite3_free(pTable->zName);
51281   sqlite3_free(pTable->zColAff);
51282   sqlite3SelectDelete(pTable->pSelect);
51283 #ifndef SQLITE_OMIT_CHECK
51284   sqlite3ExprDelete(pTable->pCheck);
51285 #endif
51286   sqlite3VtabClear(pTable);
51287   sqlite3_free(pTable);
51288 }
51289
51290 /*
51291 ** Unlink the given table from the hash tables and the delete the
51292 ** table structure with all its indices and foreign keys.
51293 */
51294 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
51295   Table *p;
51296   FKey *pF1, *pF2;
51297   Db *pDb;
51298
51299   assert( db!=0 );
51300   assert( iDb>=0 && iDb<db->nDb );
51301   assert( zTabName && zTabName[0] );
51302   pDb = &db->aDb[iDb];
51303   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
51304   if( p ){
51305 #ifndef SQLITE_OMIT_FOREIGN_KEY
51306     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
51307       int nTo = strlen(pF1->zTo) + 1;
51308       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
51309       if( pF2==pF1 ){
51310         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
51311       }else{
51312         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
51313         if( pF2 ){
51314           pF2->pNextTo = pF1->pNextTo;
51315         }
51316       }
51317     }
51318 #endif
51319     sqlite3DeleteTable(p);
51320   }
51321   db->flags |= SQLITE_InternChanges;
51322 }
51323
51324 /*
51325 ** Given a token, return a string that consists of the text of that
51326 ** token with any quotations removed.  Space to hold the returned string
51327 ** is obtained from sqliteMalloc() and must be freed by the calling
51328 ** function.
51329 **
51330 ** Tokens are often just pointers into the original SQL text and so
51331 ** are not \000 terminated and are not persistent.  The returned string
51332 ** is \000 terminated and is persistent.
51333 */
51334 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
51335   char *zName;
51336   if( pName ){
51337     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
51338     sqlite3Dequote(zName);
51339   }else{
51340     zName = 0;
51341   }
51342   return zName;
51343 }
51344
51345 /*
51346 ** Open the sqlite_master table stored in database number iDb for
51347 ** writing. The table is opened using cursor 0.
51348 */
51349 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
51350   Vdbe *v = sqlite3GetVdbe(p);
51351   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
51352   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
51353   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
51354 }
51355
51356 /*
51357 ** The token *pName contains the name of a database (either "main" or
51358 ** "temp" or the name of an attached db). This routine returns the
51359 ** index of the named database in db->aDb[], or -1 if the named db 
51360 ** does not exist.
51361 */
51362 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
51363   int i = -1;    /* Database number */
51364   int n;         /* Number of characters in the name */
51365   Db *pDb;       /* A database whose name space is being searched */
51366   char *zName;   /* Name we are searching for */
51367
51368   zName = sqlite3NameFromToken(db, pName);
51369   if( zName ){
51370     n = strlen(zName);
51371     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
51372       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
51373           0==sqlite3StrICmp(pDb->zName, zName) ){
51374         break;
51375       }
51376     }
51377     sqlite3_free(zName);
51378   }
51379   return i;
51380 }
51381
51382 /* The table or view or trigger name is passed to this routine via tokens
51383 ** pName1 and pName2. If the table name was fully qualified, for example:
51384 **
51385 ** CREATE TABLE xxx.yyy (...);
51386 ** 
51387 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
51388 ** the table name is not fully qualified, i.e.:
51389 **
51390 ** CREATE TABLE yyy(...);
51391 **
51392 ** Then pName1 is set to "yyy" and pName2 is "".
51393 **
51394 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
51395 ** pName2) that stores the unqualified table name.  The index of the
51396 ** database "xxx" is returned.
51397 */
51398 SQLITE_PRIVATE int sqlite3TwoPartName(
51399   Parse *pParse,      /* Parsing and code generating context */
51400   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
51401   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
51402   Token **pUnqual     /* Write the unqualified object name here */
51403 ){
51404   int iDb;                    /* Database holding the object */
51405   sqlite3 *db = pParse->db;
51406
51407   if( pName2 && pName2->n>0 ){
51408     assert( !db->init.busy );
51409     *pUnqual = pName2;
51410     iDb = sqlite3FindDb(db, pName1);
51411     if( iDb<0 ){
51412       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
51413       pParse->nErr++;
51414       return -1;
51415     }
51416   }else{
51417     assert( db->init.iDb==0 || db->init.busy );
51418     iDb = db->init.iDb;
51419     *pUnqual = pName1;
51420   }
51421   return iDb;
51422 }
51423
51424 /*
51425 ** This routine is used to check if the UTF-8 string zName is a legal
51426 ** unqualified name for a new schema object (table, index, view or
51427 ** trigger). All names are legal except those that begin with the string
51428 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
51429 ** is reserved for internal use.
51430 */
51431 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
51432   if( !pParse->db->init.busy && pParse->nested==0 
51433           && (pParse->db->flags & SQLITE_WriteSchema)==0
51434           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
51435     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
51436     return SQLITE_ERROR;
51437   }
51438   return SQLITE_OK;
51439 }
51440
51441 /*
51442 ** Begin constructing a new table representation in memory.  This is
51443 ** the first of several action routines that get called in response
51444 ** to a CREATE TABLE statement.  In particular, this routine is called
51445 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
51446 ** flag is true if the table should be stored in the auxiliary database
51447 ** file instead of in the main database file.  This is normally the case
51448 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
51449 ** CREATE and TABLE.
51450 **
51451 ** The new table record is initialized and put in pParse->pNewTable.
51452 ** As more of the CREATE TABLE statement is parsed, additional action
51453 ** routines will be called to add more information to this record.
51454 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
51455 ** is called to complete the construction of the new table record.
51456 */
51457 SQLITE_PRIVATE void sqlite3StartTable(
51458   Parse *pParse,   /* Parser context */
51459   Token *pName1,   /* First part of the name of the table or view */
51460   Token *pName2,   /* Second part of the name of the table or view */
51461   int isTemp,      /* True if this is a TEMP table */
51462   int isView,      /* True if this is a VIEW */
51463   int isVirtual,   /* True if this is a VIRTUAL table */
51464   int noErr        /* Do nothing if table already exists */
51465 ){
51466   Table *pTable;
51467   char *zName = 0; /* The name of the new table */
51468   sqlite3 *db = pParse->db;
51469   Vdbe *v;
51470   int iDb;         /* Database number to create the table in */
51471   Token *pName;    /* Unqualified name of the table to create */
51472
51473   /* The table or view name to create is passed to this routine via tokens
51474   ** pName1 and pName2. If the table name was fully qualified, for example:
51475   **
51476   ** CREATE TABLE xxx.yyy (...);
51477   ** 
51478   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
51479   ** the table name is not fully qualified, i.e.:
51480   **
51481   ** CREATE TABLE yyy(...);
51482   **
51483   ** Then pName1 is set to "yyy" and pName2 is "".
51484   **
51485   ** The call below sets the pName pointer to point at the token (pName1 or
51486   ** pName2) that stores the unqualified table name. The variable iDb is
51487   ** set to the index of the database that the table or view is to be
51488   ** created in.
51489   */
51490   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
51491   if( iDb<0 ) return;
51492   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
51493     /* If creating a temp table, the name may not be qualified */
51494     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
51495     return;
51496   }
51497   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
51498
51499   pParse->sNameToken = *pName;
51500   zName = sqlite3NameFromToken(db, pName);
51501   if( zName==0 ) return;
51502   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
51503     goto begin_table_error;
51504   }
51505   if( db->init.iDb==1 ) isTemp = 1;
51506 #ifndef SQLITE_OMIT_AUTHORIZATION
51507   assert( (isTemp & 1)==isTemp );
51508   {
51509     int code;
51510     char *zDb = db->aDb[iDb].zName;
51511     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
51512       goto begin_table_error;
51513     }
51514     if( isView ){
51515       if( !OMIT_TEMPDB && isTemp ){
51516         code = SQLITE_CREATE_TEMP_VIEW;
51517       }else{
51518         code = SQLITE_CREATE_VIEW;
51519       }
51520     }else{
51521       if( !OMIT_TEMPDB && isTemp ){
51522         code = SQLITE_CREATE_TEMP_TABLE;
51523       }else{
51524         code = SQLITE_CREATE_TABLE;
51525       }
51526     }
51527     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
51528       goto begin_table_error;
51529     }
51530   }
51531 #endif
51532
51533   /* Make sure the new table name does not collide with an existing
51534   ** index or table name in the same database.  Issue an error message if
51535   ** it does. The exception is if the statement being parsed was passed
51536   ** to an sqlite3_declare_vtab() call. In that case only the column names
51537   ** and types will be used, so there is no need to test for namespace
51538   ** collisions.
51539   */
51540   if( !IN_DECLARE_VTAB ){
51541     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
51542       goto begin_table_error;
51543     }
51544     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
51545     if( pTable ){
51546       if( !noErr ){
51547         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
51548       }
51549       goto begin_table_error;
51550     }
51551     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
51552       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
51553       goto begin_table_error;
51554     }
51555   }
51556
51557   pTable = sqlite3DbMallocZero(db, sizeof(Table));
51558   if( pTable==0 ){
51559     db->mallocFailed = 1;
51560     pParse->rc = SQLITE_NOMEM;
51561     pParse->nErr++;
51562     goto begin_table_error;
51563   }
51564   pTable->zName = zName;
51565   pTable->iPKey = -1;
51566   pTable->pSchema = db->aDb[iDb].pSchema;
51567   pTable->nRef = 1;
51568   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
51569   pParse->pNewTable = pTable;
51570
51571   /* If this is the magic sqlite_sequence table used by autoincrement,
51572   ** then record a pointer to this table in the main database structure
51573   ** so that INSERT can find the table easily.
51574   */
51575 #ifndef SQLITE_OMIT_AUTOINCREMENT
51576   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
51577     pTable->pSchema->pSeqTab = pTable;
51578   }
51579 #endif
51580
51581   /* Begin generating the code that will insert the table record into
51582   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
51583   ** and allocate the record number for the table entry now.  Before any
51584   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
51585   ** indices to be created and the table record must come before the 
51586   ** indices.  Hence, the record number for the table must be allocated
51587   ** now.
51588   */
51589   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
51590     int j1;
51591     int fileFormat;
51592     int reg1, reg2, reg3;
51593     sqlite3BeginWriteOperation(pParse, 0, iDb);
51594
51595 #ifndef SQLITE_OMIT_VIRTUALTABLE
51596     if( isVirtual ){
51597       sqlite3VdbeAddOp0(v, OP_VBegin);
51598     }
51599 #endif
51600
51601     /* If the file format and encoding in the database have not been set, 
51602     ** set them now.
51603     */
51604     reg1 = pParse->regRowid = ++pParse->nMem;
51605     reg2 = pParse->regRoot = ++pParse->nMem;
51606     reg3 = ++pParse->nMem;
51607     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
51608     sqlite3VdbeUsesBtree(v, iDb);
51609     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
51610     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
51611                   1 : SQLITE_MAX_FILE_FORMAT;
51612     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
51613     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
51614     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
51615     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
51616     sqlite3VdbeJumpHere(v, j1);
51617
51618     /* This just creates a place-holder record in the sqlite_master table.
51619     ** The record created does not contain anything yet.  It will be replaced
51620     ** by the real entry in code generated at sqlite3EndTable().
51621     **
51622     ** The rowid for the new entry is left on the top of the stack.
51623     ** The rowid value is needed by the code that sqlite3EndTable will
51624     ** generate.
51625     */
51626 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
51627     if( isView || isVirtual ){
51628       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
51629     }else
51630 #endif
51631     {
51632       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
51633     }
51634     sqlite3OpenMasterTable(pParse, iDb);
51635     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
51636     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
51637     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
51638     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
51639     sqlite3VdbeAddOp0(v, OP_Close);
51640   }
51641
51642   /* Normal (non-error) return. */
51643   return;
51644
51645   /* If an error occurs, we jump here */
51646 begin_table_error:
51647   sqlite3_free(zName);
51648   return;
51649 }
51650
51651 /*
51652 ** This macro is used to compare two strings in a case-insensitive manner.
51653 ** It is slightly faster than calling sqlite3StrICmp() directly, but
51654 ** produces larger code.
51655 **
51656 ** WARNING: This macro is not compatible with the strcmp() family. It
51657 ** returns true if the two strings are equal, otherwise false.
51658 */
51659 #define STRICMP(x, y) (\
51660 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
51661 sqlite3UpperToLower[*(unsigned char *)(y)]     \
51662 && sqlite3StrICmp((x)+1,(y)+1)==0 )
51663
51664 /*
51665 ** Add a new column to the table currently being constructed.
51666 **
51667 ** The parser calls this routine once for each column declaration
51668 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
51669 ** first to get things going.  Then this routine is called for each
51670 ** column.
51671 */
51672 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
51673   Table *p;
51674   int i;
51675   char *z;
51676   Column *pCol;
51677   if( (p = pParse->pNewTable)==0 ) return;
51678   if( p->nCol+1>SQLITE_MAX_COLUMN ){
51679     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
51680     return;
51681   }
51682   z = sqlite3NameFromToken(pParse->db, pName);
51683   if( z==0 ) return;
51684   for(i=0; i<p->nCol; i++){
51685     if( STRICMP(z, p->aCol[i].zName) ){
51686       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
51687       sqlite3_free(z);
51688       return;
51689     }
51690   }
51691   if( (p->nCol & 0x7)==0 ){
51692     Column *aNew;
51693     aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
51694     if( aNew==0 ){
51695       sqlite3_free(z);
51696       return;
51697     }
51698     p->aCol = aNew;
51699   }
51700   pCol = &p->aCol[p->nCol];
51701   memset(pCol, 0, sizeof(p->aCol[0]));
51702   pCol->zName = z;
51703  
51704   /* If there is no type specified, columns have the default affinity
51705   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
51706   ** be called next to set pCol->affinity correctly.
51707   */
51708   pCol->affinity = SQLITE_AFF_NONE;
51709   p->nCol++;
51710 }
51711
51712 /*
51713 ** This routine is called by the parser while in the middle of
51714 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
51715 ** been seen on a column.  This routine sets the notNull flag on
51716 ** the column currently under construction.
51717 */
51718 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
51719   Table *p;
51720   int i;
51721   if( (p = pParse->pNewTable)==0 ) return;
51722   i = p->nCol-1;
51723   if( i>=0 ) p->aCol[i].notNull = onError;
51724 }
51725
51726 /*
51727 ** Scan the column type name zType (length nType) and return the
51728 ** associated affinity type.
51729 **
51730 ** This routine does a case-independent search of zType for the 
51731 ** substrings in the following table. If one of the substrings is
51732 ** found, the corresponding affinity is returned. If zType contains
51733 ** more than one of the substrings, entries toward the top of 
51734 ** the table take priority. For example, if zType is 'BLOBINT', 
51735 ** SQLITE_AFF_INTEGER is returned.
51736 **
51737 ** Substring     | Affinity
51738 ** --------------------------------
51739 ** 'INT'         | SQLITE_AFF_INTEGER
51740 ** 'CHAR'        | SQLITE_AFF_TEXT
51741 ** 'CLOB'        | SQLITE_AFF_TEXT
51742 ** 'TEXT'        | SQLITE_AFF_TEXT
51743 ** 'BLOB'        | SQLITE_AFF_NONE
51744 ** 'REAL'        | SQLITE_AFF_REAL
51745 ** 'FLOA'        | SQLITE_AFF_REAL
51746 ** 'DOUB'        | SQLITE_AFF_REAL
51747 **
51748 ** If none of the substrings in the above table are found,
51749 ** SQLITE_AFF_NUMERIC is returned.
51750 */
51751 SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
51752   u32 h = 0;
51753   char aff = SQLITE_AFF_NUMERIC;
51754   const unsigned char *zIn = pType->z;
51755   const unsigned char *zEnd = &pType->z[pType->n];
51756
51757   while( zIn!=zEnd ){
51758     h = (h<<8) + sqlite3UpperToLower[*zIn];
51759     zIn++;
51760     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
51761       aff = SQLITE_AFF_TEXT; 
51762     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
51763       aff = SQLITE_AFF_TEXT;
51764     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
51765       aff = SQLITE_AFF_TEXT;
51766     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
51767         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
51768       aff = SQLITE_AFF_NONE;
51769 #ifndef SQLITE_OMIT_FLOATING_POINT
51770     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
51771         && aff==SQLITE_AFF_NUMERIC ){
51772       aff = SQLITE_AFF_REAL;
51773     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
51774         && aff==SQLITE_AFF_NUMERIC ){
51775       aff = SQLITE_AFF_REAL;
51776     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
51777         && aff==SQLITE_AFF_NUMERIC ){
51778       aff = SQLITE_AFF_REAL;
51779 #endif
51780     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
51781       aff = SQLITE_AFF_INTEGER;
51782       break;
51783     }
51784   }
51785
51786   return aff;
51787 }
51788
51789 /*
51790 ** This routine is called by the parser while in the middle of
51791 ** parsing a CREATE TABLE statement.  The pFirst token is the first
51792 ** token in the sequence of tokens that describe the type of the
51793 ** column currently under construction.   pLast is the last token
51794 ** in the sequence.  Use this information to construct a string
51795 ** that contains the typename of the column and store that string
51796 ** in zType.
51797 */ 
51798 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
51799   Table *p;
51800   int i;
51801   Column *pCol;
51802
51803   if( (p = pParse->pNewTable)==0 ) return;
51804   i = p->nCol-1;
51805   if( i<0 ) return;
51806   pCol = &p->aCol[i];
51807   sqlite3_free(pCol->zType);
51808   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
51809   pCol->affinity = sqlite3AffinityType(pType);
51810 }
51811
51812 /*
51813 ** The expression is the default value for the most recently added column
51814 ** of the table currently under construction.
51815 **
51816 ** Default value expressions must be constant.  Raise an exception if this
51817 ** is not the case.
51818 **
51819 ** This routine is called by the parser while in the middle of
51820 ** parsing a CREATE TABLE statement.
51821 */
51822 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
51823   Table *p;
51824   Column *pCol;
51825   if( (p = pParse->pNewTable)!=0 ){
51826     pCol = &(p->aCol[p->nCol-1]);
51827     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
51828       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
51829           pCol->zName);
51830     }else{
51831       Expr *pCopy;
51832       sqlite3 *db = pParse->db;
51833       sqlite3ExprDelete(pCol->pDflt);
51834       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
51835       if( pCopy ){
51836         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
51837       }
51838     }
51839   }
51840   sqlite3ExprDelete(pExpr);
51841 }
51842
51843 /*
51844 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
51845 ** of columns that form the primary key.  If pList is NULL, then the
51846 ** most recently added column of the table is the primary key.
51847 **
51848 ** A table can have at most one primary key.  If the table already has
51849 ** a primary key (and this is the second primary key) then create an
51850 ** error.
51851 **
51852 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
51853 ** then we will try to use that column as the rowid.  Set the Table.iPKey
51854 ** field of the table under construction to be the index of the
51855 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
51856 ** no INTEGER PRIMARY KEY.
51857 **
51858 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
51859 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
51860 */
51861 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
51862   Parse *pParse,    /* Parsing context */
51863   ExprList *pList,  /* List of field names to be indexed */
51864   int onError,      /* What to do with a uniqueness conflict */
51865   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
51866   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
51867 ){
51868   Table *pTab = pParse->pNewTable;
51869   char *zType = 0;
51870   int iCol = -1, i;
51871   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
51872   if( pTab->hasPrimKey ){
51873     sqlite3ErrorMsg(pParse, 
51874       "table \"%s\" has more than one primary key", pTab->zName);
51875     goto primary_key_exit;
51876   }
51877   pTab->hasPrimKey = 1;
51878   if( pList==0 ){
51879     iCol = pTab->nCol - 1;
51880     pTab->aCol[iCol].isPrimKey = 1;
51881   }else{
51882     for(i=0; i<pList->nExpr; i++){
51883       for(iCol=0; iCol<pTab->nCol; iCol++){
51884         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
51885           break;
51886         }
51887       }
51888       if( iCol<pTab->nCol ){
51889         pTab->aCol[iCol].isPrimKey = 1;
51890       }
51891     }
51892     if( pList->nExpr>1 ) iCol = -1;
51893   }
51894   if( iCol>=0 && iCol<pTab->nCol ){
51895     zType = pTab->aCol[iCol].zType;
51896   }
51897   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
51898         && sortOrder==SQLITE_SO_ASC ){
51899     pTab->iPKey = iCol;
51900     pTab->keyConf = onError;
51901     pTab->autoInc = autoInc;
51902   }else if( autoInc ){
51903 #ifndef SQLITE_OMIT_AUTOINCREMENT
51904     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
51905        "INTEGER PRIMARY KEY");
51906 #endif
51907   }else{
51908     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
51909     pList = 0;
51910   }
51911
51912 primary_key_exit:
51913   sqlite3ExprListDelete(pList);
51914   return;
51915 }
51916
51917 /*
51918 ** Add a new CHECK constraint to the table currently under construction.
51919 */
51920 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
51921   Parse *pParse,    /* Parsing context */
51922   Expr *pCheckExpr  /* The check expression */
51923 ){
51924 #ifndef SQLITE_OMIT_CHECK
51925   Table *pTab = pParse->pNewTable;
51926   sqlite3 *db = pParse->db;
51927   if( pTab && !IN_DECLARE_VTAB ){
51928     /* The CHECK expression must be duplicated so that tokens refer
51929     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
51930     ** statement */
51931     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
51932                                   sqlite3ExprDup(db, pCheckExpr));
51933   }
51934 #endif
51935   sqlite3ExprDelete(pCheckExpr);
51936 }
51937
51938 /*
51939 ** Set the collation function of the most recently parsed table column
51940 ** to the CollSeq given.
51941 */
51942 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
51943   Table *p;
51944   int i;
51945   char *zColl;              /* Dequoted name of collation sequence */
51946
51947   if( (p = pParse->pNewTable)==0 ) return;
51948   i = p->nCol-1;
51949
51950   zColl = sqlite3NameFromToken(pParse->db, pToken);
51951   if( !zColl ) return;
51952
51953   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
51954     Index *pIdx;
51955     p->aCol[i].zColl = zColl;
51956   
51957     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
51958     ** then an index may have been created on this column before the
51959     ** collation type was added. Correct this if it is the case.
51960     */
51961     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
51962       assert( pIdx->nColumn==1 );
51963       if( pIdx->aiColumn[0]==i ){
51964         pIdx->azColl[0] = p->aCol[i].zColl;
51965       }
51966     }
51967   }else{
51968     sqlite3_free(zColl);
51969   }
51970 }
51971
51972 /*
51973 ** This function returns the collation sequence for database native text
51974 ** encoding identified by the string zName, length nName.
51975 **
51976 ** If the requested collation sequence is not available, or not available
51977 ** in the database native encoding, the collation factory is invoked to
51978 ** request it. If the collation factory does not supply such a sequence,
51979 ** and the sequence is available in another text encoding, then that is
51980 ** returned instead.
51981 **
51982 ** If no versions of the requested collations sequence are available, or
51983 ** another error occurs, NULL is returned and an error message written into
51984 ** pParse.
51985 **
51986 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
51987 ** invokes the collation factory if the named collation cannot be found
51988 ** and generates an error message.
51989 */
51990 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
51991   sqlite3 *db = pParse->db;
51992   u8 enc = ENC(db);
51993   u8 initbusy = db->init.busy;
51994   CollSeq *pColl;
51995
51996   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
51997   if( !initbusy && (!pColl || !pColl->xCmp) ){
51998     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
51999     if( !pColl ){
52000       if( nName<0 ){
52001         nName = strlen(zName);
52002       }
52003       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
52004       pColl = 0;
52005     }
52006   }
52007
52008   return pColl;
52009 }
52010
52011
52012 /*
52013 ** Generate code that will increment the schema cookie.
52014 **
52015 ** The schema cookie is used to determine when the schema for the
52016 ** database changes.  After each schema change, the cookie value
52017 ** changes.  When a process first reads the schema it records the
52018 ** cookie.  Thereafter, whenever it goes to access the database,
52019 ** it checks the cookie to make sure the schema has not changed
52020 ** since it was last read.
52021 **
52022 ** This plan is not completely bullet-proof.  It is possible for
52023 ** the schema to change multiple times and for the cookie to be
52024 ** set back to prior value.  But schema changes are infrequent
52025 ** and the probability of hitting the same cookie value is only
52026 ** 1 chance in 2^32.  So we're safe enough.
52027 */
52028 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
52029   int r1 = sqlite3GetTempReg(pParse);
52030   sqlite3 *db = pParse->db;
52031   Vdbe *v = pParse->pVdbe;
52032   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
52033   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
52034   sqlite3ReleaseTempReg(pParse, r1);
52035 }
52036
52037 /*
52038 ** Measure the number of characters needed to output the given
52039 ** identifier.  The number returned includes any quotes used
52040 ** but does not include the null terminator.
52041 **
52042 ** The estimate is conservative.  It might be larger that what is
52043 ** really needed.
52044 */
52045 static int identLength(const char *z){
52046   int n;
52047   for(n=0; *z; n++, z++){
52048     if( *z=='"' ){ n++; }
52049   }
52050   return n + 2;
52051 }
52052
52053 /*
52054 ** Write an identifier onto the end of the given string.  Add
52055 ** quote characters as needed.
52056 */
52057 static void identPut(char *z, int *pIdx, char *zSignedIdent){
52058   unsigned char *zIdent = (unsigned char*)zSignedIdent;
52059   int i, j, needQuote;
52060   i = *pIdx;
52061   for(j=0; zIdent[j]; j++){
52062     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
52063   }
52064   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
52065                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
52066   if( needQuote ) z[i++] = '"';
52067   for(j=0; zIdent[j]; j++){
52068     z[i++] = zIdent[j];
52069     if( zIdent[j]=='"' ) z[i++] = '"';
52070   }
52071   if( needQuote ) z[i++] = '"';
52072   z[i] = 0;
52073   *pIdx = i;
52074 }
52075
52076 /*
52077 ** Generate a CREATE TABLE statement appropriate for the given
52078 ** table.  Memory to hold the text of the statement is obtained
52079 ** from sqliteMalloc() and must be freed by the calling function.
52080 */
52081 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
52082   int i, k, n;
52083   char *zStmt;
52084   char *zSep, *zSep2, *zEnd, *z;
52085   Column *pCol;
52086   n = 0;
52087   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
52088     n += identLength(pCol->zName);
52089     z = pCol->zType;
52090     if( z ){
52091       n += (strlen(z) + 1);
52092     }
52093   }
52094   n += identLength(p->zName);
52095   if( n<50 ){
52096     zSep = "";
52097     zSep2 = ",";
52098     zEnd = ")";
52099   }else{
52100     zSep = "\n  ";
52101     zSep2 = ",\n  ";
52102     zEnd = "\n)";
52103   }
52104   n += 35 + 6*p->nCol;
52105   zStmt = sqlite3_malloc( n );
52106   if( zStmt==0 ){
52107     db->mallocFailed = 1;
52108     return 0;
52109   }
52110   sqlite3_snprintf(n, zStmt,
52111                   !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
52112   k = strlen(zStmt);
52113   identPut(zStmt, &k, p->zName);
52114   zStmt[k++] = '(';
52115   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
52116     sqlite3_snprintf(n-k, &zStmt[k], zSep);
52117     k += strlen(&zStmt[k]);
52118     zSep = zSep2;
52119     identPut(zStmt, &k, pCol->zName);
52120     if( (z = pCol->zType)!=0 ){
52121       zStmt[k++] = ' ';
52122       assert( strlen(z)+k+1<=n );
52123       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
52124       k += strlen(z);
52125     }
52126   }
52127   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
52128   return zStmt;
52129 }
52130
52131 /*
52132 ** This routine is called to report the final ")" that terminates
52133 ** a CREATE TABLE statement.
52134 **
52135 ** The table structure that other action routines have been building
52136 ** is added to the internal hash tables, assuming no errors have
52137 ** occurred.
52138 **
52139 ** An entry for the table is made in the master table on disk, unless
52140 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
52141 ** it means we are reading the sqlite_master table because we just
52142 ** connected to the database or because the sqlite_master table has
52143 ** recently changed, so the entry for this table already exists in
52144 ** the sqlite_master table.  We do not want to create it again.
52145 **
52146 ** If the pSelect argument is not NULL, it means that this routine
52147 ** was called to create a table generated from a 
52148 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
52149 ** the new table will match the result set of the SELECT.
52150 */
52151 SQLITE_PRIVATE void sqlite3EndTable(
52152   Parse *pParse,          /* Parse context */
52153   Token *pCons,           /* The ',' token after the last column defn. */
52154   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
52155   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
52156 ){
52157   Table *p;
52158   sqlite3 *db = pParse->db;
52159   int iDb;
52160
52161   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
52162     return;
52163   }
52164   p = pParse->pNewTable;
52165   if( p==0 ) return;
52166
52167   assert( !db->init.busy || !pSelect );
52168
52169   iDb = sqlite3SchemaToIndex(db, p->pSchema);
52170
52171 #ifndef SQLITE_OMIT_CHECK
52172   /* Resolve names in all CHECK constraint expressions.
52173   */
52174   if( p->pCheck ){
52175     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
52176     NameContext sNC;                /* Name context for pParse->pNewTable */
52177
52178     memset(&sNC, 0, sizeof(sNC));
52179     memset(&sSrc, 0, sizeof(sSrc));
52180     sSrc.nSrc = 1;
52181     sSrc.a[0].zName = p->zName;
52182     sSrc.a[0].pTab = p;
52183     sSrc.a[0].iCursor = -1;
52184     sNC.pParse = pParse;
52185     sNC.pSrcList = &sSrc;
52186     sNC.isCheck = 1;
52187     if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
52188       return;
52189     }
52190   }
52191 #endif /* !defined(SQLITE_OMIT_CHECK) */
52192
52193   /* If the db->init.busy is 1 it means we are reading the SQL off the
52194   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
52195   ** So do not write to the disk again.  Extract the root page number
52196   ** for the table from the db->init.newTnum field.  (The page number
52197   ** should have been put there by the sqliteOpenCb routine.)
52198   */
52199   if( db->init.busy ){
52200     p->tnum = db->init.newTnum;
52201   }
52202
52203   /* If not initializing, then create a record for the new table
52204   ** in the SQLITE_MASTER table of the database.  The record number
52205   ** for the new table entry should already be on the stack.
52206   **
52207   ** If this is a TEMPORARY table, write the entry into the auxiliary
52208   ** file instead of into the main database file.
52209   */
52210   if( !db->init.busy ){
52211     int n;
52212     Vdbe *v;
52213     char *zType;    /* "view" or "table" */
52214     char *zType2;   /* "VIEW" or "TABLE" */
52215     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
52216
52217     v = sqlite3GetVdbe(pParse);
52218     if( v==0 ) return;
52219
52220     sqlite3VdbeAddOp1(v, OP_Close, 0);
52221
52222     /* Create the rootpage for the new table and push it onto the stack.
52223     ** A view has no rootpage, so just push a zero onto the stack for
52224     ** views.  Initialize zType at the same time.
52225     */
52226     if( p->pSelect==0 ){
52227       /* A regular table */
52228       zType = "table";
52229       zType2 = "TABLE";
52230 #ifndef SQLITE_OMIT_VIEW
52231     }else{
52232       /* A view */
52233       zType = "view";
52234       zType2 = "VIEW";
52235 #endif
52236     }
52237
52238     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
52239     ** statement to populate the new table. The root-page number for the
52240     ** new table is on the top of the vdbe stack.
52241     **
52242     ** Once the SELECT has been coded by sqlite3Select(), it is in a
52243     ** suitable state to query for the column names and types to be used
52244     ** by the new table.
52245     **
52246     ** A shared-cache write-lock is not required to write to the new table,
52247     ** as a schema-lock must have already been obtained to create it. Since
52248     ** a schema-lock excludes all other database users, the write-lock would
52249     ** be redundant.
52250     */
52251     if( pSelect ){
52252       SelectDest dest;
52253       Table *pSelTab;
52254
52255       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
52256       sqlite3VdbeChangeP5(v, 1);
52257       pParse->nTab = 2;
52258       sqlite3SelectDestInit(&dest, SRT_Table, 1);
52259       sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
52260       sqlite3VdbeAddOp1(v, OP_Close, 1);
52261       if( pParse->nErr==0 ){
52262         pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
52263         if( pSelTab==0 ) return;
52264         assert( p->aCol==0 );
52265         p->nCol = pSelTab->nCol;
52266         p->aCol = pSelTab->aCol;
52267         pSelTab->nCol = 0;
52268         pSelTab->aCol = 0;
52269         sqlite3DeleteTable(pSelTab);
52270       }
52271     }
52272
52273     /* Compute the complete text of the CREATE statement */
52274     if( pSelect ){
52275       zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
52276     }else{
52277       n = pEnd->z - pParse->sNameToken.z + 1;
52278       zStmt = sqlite3MPrintf(db, 
52279           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
52280       );
52281     }
52282
52283     /* A slot for the record has already been allocated in the 
52284     ** SQLITE_MASTER table.  We just need to update that slot with all
52285     ** the information we've collected.  The rowid for the preallocated
52286     ** slot is the 2nd item on the stack.  The top of the stack is the
52287     ** root page for the new table (or a 0 if this is a view).
52288     */
52289     sqlite3NestedParse(pParse,
52290       "UPDATE %Q.%s "
52291          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
52292        "WHERE rowid=#%d",
52293       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
52294       zType,
52295       p->zName,
52296       p->zName,
52297       pParse->regRoot,
52298       zStmt,
52299       pParse->regRowid
52300     );
52301     sqlite3_free(zStmt);
52302     sqlite3ChangeCookie(pParse, iDb);
52303
52304 #ifndef SQLITE_OMIT_AUTOINCREMENT
52305     /* Check to see if we need to create an sqlite_sequence table for
52306     ** keeping track of autoincrement keys.
52307     */
52308     if( p->autoInc ){
52309       Db *pDb = &db->aDb[iDb];
52310       if( pDb->pSchema->pSeqTab==0 ){
52311         sqlite3NestedParse(pParse,
52312           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
52313           pDb->zName
52314         );
52315       }
52316     }
52317 #endif
52318
52319     /* Reparse everything to update our internal data structures */
52320     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
52321         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
52322   }
52323
52324
52325   /* Add the table to the in-memory representation of the database.
52326   */
52327   if( db->init.busy && pParse->nErr==0 ){
52328     Table *pOld;
52329     FKey *pFKey; 
52330     Schema *pSchema = p->pSchema;
52331     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
52332     if( pOld ){
52333       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
52334       db->mallocFailed = 1;
52335       return;
52336     }
52337 #ifndef SQLITE_OMIT_FOREIGN_KEY
52338     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
52339       void *data;
52340       int nTo = strlen(pFKey->zTo) + 1;
52341       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
52342       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
52343       if( data==(void *)pFKey ){
52344         db->mallocFailed = 1;
52345       }
52346     }
52347 #endif
52348     pParse->pNewTable = 0;
52349     db->nTable++;
52350     db->flags |= SQLITE_InternChanges;
52351
52352 #ifndef SQLITE_OMIT_ALTERTABLE
52353     if( !p->pSelect ){
52354       const char *zName = (const char *)pParse->sNameToken.z;
52355       int nName;
52356       assert( !pSelect && pCons && pEnd );
52357       if( pCons->z==0 ){
52358         pCons = pEnd;
52359       }
52360       nName = (const char *)pCons->z - zName;
52361       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
52362     }
52363 #endif
52364   }
52365 }
52366
52367 #ifndef SQLITE_OMIT_VIEW
52368 /*
52369 ** The parser calls this routine in order to create a new VIEW
52370 */
52371 SQLITE_PRIVATE void sqlite3CreateView(
52372   Parse *pParse,     /* The parsing context */
52373   Token *pBegin,     /* The CREATE token that begins the statement */
52374   Token *pName1,     /* The token that holds the name of the view */
52375   Token *pName2,     /* The token that holds the name of the view */
52376   Select *pSelect,   /* A SELECT statement that will become the new view */
52377   int isTemp,        /* TRUE for a TEMPORARY view */
52378   int noErr          /* Suppress error messages if VIEW already exists */
52379 ){
52380   Table *p;
52381   int n;
52382   const unsigned char *z;
52383   Token sEnd;
52384   DbFixer sFix;
52385   Token *pName;
52386   int iDb;
52387   sqlite3 *db = pParse->db;
52388
52389   if( pParse->nVar>0 ){
52390     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
52391     sqlite3SelectDelete(pSelect);
52392     return;
52393   }
52394   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
52395   p = pParse->pNewTable;
52396   if( p==0 || pParse->nErr ){
52397     sqlite3SelectDelete(pSelect);
52398     return;
52399   }
52400   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
52401   iDb = sqlite3SchemaToIndex(db, p->pSchema);
52402   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
52403     && sqlite3FixSelect(&sFix, pSelect)
52404   ){
52405     sqlite3SelectDelete(pSelect);
52406     return;
52407   }
52408
52409   /* Make a copy of the entire SELECT statement that defines the view.
52410   ** This will force all the Expr.token.z values to be dynamically
52411   ** allocated rather than point to the input string - which means that
52412   ** they will persist after the current sqlite3_exec() call returns.
52413   */
52414   p->pSelect = sqlite3SelectDup(db, pSelect);
52415   sqlite3SelectDelete(pSelect);
52416   if( db->mallocFailed ){
52417     return;
52418   }
52419   if( !db->init.busy ){
52420     sqlite3ViewGetColumnNames(pParse, p);
52421   }
52422
52423   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
52424   ** the end.
52425   */
52426   sEnd = pParse->sLastToken;
52427   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
52428     sEnd.z += sEnd.n;
52429   }
52430   sEnd.n = 0;
52431   n = sEnd.z - pBegin->z;
52432   z = (const unsigned char*)pBegin->z;
52433   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
52434   sEnd.z = &z[n-1];
52435   sEnd.n = 1;
52436
52437   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
52438   sqlite3EndTable(pParse, 0, &sEnd, 0);
52439   return;
52440 }
52441 #endif /* SQLITE_OMIT_VIEW */
52442
52443 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
52444 /*
52445 ** The Table structure pTable is really a VIEW.  Fill in the names of
52446 ** the columns of the view in the pTable structure.  Return the number
52447 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
52448 */
52449 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
52450   Table *pSelTab;   /* A fake table from which we get the result set */
52451   Select *pSel;     /* Copy of the SELECT that implements the view */
52452   int nErr = 0;     /* Number of errors encountered */
52453   int n;            /* Temporarily holds the number of cursors assigned */
52454   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
52455   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
52456
52457   assert( pTable );
52458
52459 #ifndef SQLITE_OMIT_VIRTUALTABLE
52460   if( sqlite3VtabCallConnect(pParse, pTable) ){
52461     return SQLITE_ERROR;
52462   }
52463   if( IsVirtual(pTable) ) return 0;
52464 #endif
52465
52466 #ifndef SQLITE_OMIT_VIEW
52467   /* A positive nCol means the columns names for this view are
52468   ** already known.
52469   */
52470   if( pTable->nCol>0 ) return 0;
52471
52472   /* A negative nCol is a special marker meaning that we are currently
52473   ** trying to compute the column names.  If we enter this routine with
52474   ** a negative nCol, it means two or more views form a loop, like this:
52475   **
52476   **     CREATE VIEW one AS SELECT * FROM two;
52477   **     CREATE VIEW two AS SELECT * FROM one;
52478   **
52479   ** Actually, this error is caught previously and so the following test
52480   ** should always fail.  But we will leave it in place just to be safe.
52481   */
52482   if( pTable->nCol<0 ){
52483     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
52484     return 1;
52485   }
52486   assert( pTable->nCol>=0 );
52487
52488   /* If we get this far, it means we need to compute the table names.
52489   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
52490   ** "*" elements in the results set of the view and will assign cursors
52491   ** to the elements of the FROM clause.  But we do not want these changes
52492   ** to be permanent.  So the computation is done on a copy of the SELECT
52493   ** statement that defines the view.
52494   */
52495   assert( pTable->pSelect );
52496   pSel = sqlite3SelectDup(db, pTable->pSelect);
52497   if( pSel ){
52498     n = pParse->nTab;
52499     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
52500     pTable->nCol = -1;
52501 #ifndef SQLITE_OMIT_AUTHORIZATION
52502     xAuth = db->xAuth;
52503     db->xAuth = 0;
52504     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
52505     db->xAuth = xAuth;
52506 #else
52507     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
52508 #endif
52509     pParse->nTab = n;
52510     if( pSelTab ){
52511       assert( pTable->aCol==0 );
52512       pTable->nCol = pSelTab->nCol;
52513       pTable->aCol = pSelTab->aCol;
52514       pSelTab->nCol = 0;
52515       pSelTab->aCol = 0;
52516       sqlite3DeleteTable(pSelTab);
52517       pTable->pSchema->flags |= DB_UnresetViews;
52518     }else{
52519       pTable->nCol = 0;
52520       nErr++;
52521     }
52522     sqlite3SelectDelete(pSel);
52523   } else {
52524     nErr++;
52525   }
52526 #endif /* SQLITE_OMIT_VIEW */
52527   return nErr;  
52528 }
52529 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
52530
52531 #ifndef SQLITE_OMIT_VIEW
52532 /*
52533 ** Clear the column names from every VIEW in database idx.
52534 */
52535 static void sqliteViewResetAll(sqlite3 *db, int idx){
52536   HashElem *i;
52537   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
52538   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
52539     Table *pTab = sqliteHashData(i);
52540     if( pTab->pSelect ){
52541       sqliteResetColumnNames(pTab);
52542     }
52543   }
52544   DbClearProperty(db, idx, DB_UnresetViews);
52545 }
52546 #else
52547 # define sqliteViewResetAll(A,B)
52548 #endif /* SQLITE_OMIT_VIEW */
52549
52550 /*
52551 ** This function is called by the VDBE to adjust the internal schema
52552 ** used by SQLite when the btree layer moves a table root page. The
52553 ** root-page of a table or index in database iDb has changed from iFrom
52554 ** to iTo.
52555 **
52556 ** Ticket #1728:  The symbol table might still contain information
52557 ** on tables and/or indices that are the process of being deleted.
52558 ** If you are unlucky, one of those deleted indices or tables might
52559 ** have the same rootpage number as the real table or index that is
52560 ** being moved.  So we cannot stop searching after the first match 
52561 ** because the first match might be for one of the deleted indices
52562 ** or tables and not the table/index that is actually being moved.
52563 ** We must continue looping until all tables and indices with
52564 ** rootpage==iFrom have been converted to have a rootpage of iTo
52565 ** in order to be certain that we got the right one.
52566 */
52567 #ifndef SQLITE_OMIT_AUTOVACUUM
52568 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
52569   HashElem *pElem;
52570   Hash *pHash;
52571
52572   pHash = &pDb->pSchema->tblHash;
52573   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
52574     Table *pTab = sqliteHashData(pElem);
52575     if( pTab->tnum==iFrom ){
52576       pTab->tnum = iTo;
52577     }
52578   }
52579   pHash = &pDb->pSchema->idxHash;
52580   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
52581     Index *pIdx = sqliteHashData(pElem);
52582     if( pIdx->tnum==iFrom ){
52583       pIdx->tnum = iTo;
52584     }
52585   }
52586 }
52587 #endif
52588
52589 /*
52590 ** Write code to erase the table with root-page iTable from database iDb.
52591 ** Also write code to modify the sqlite_master table and internal schema
52592 ** if a root-page of another table is moved by the btree-layer whilst
52593 ** erasing iTable (this can happen with an auto-vacuum database).
52594 */ 
52595 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
52596   Vdbe *v = sqlite3GetVdbe(pParse);
52597   int r1 = sqlite3GetTempReg(pParse);
52598   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
52599 #ifndef SQLITE_OMIT_AUTOVACUUM
52600   /* OP_Destroy stores an in integer r1. If this integer
52601   ** is non-zero, then it is the root page number of a table moved to
52602   ** location iTable. The following code modifies the sqlite_master table to
52603   ** reflect this.
52604   **
52605   ** The "#%d" in the SQL is a special constant that means whatever value
52606   ** is on the top of the stack.  See sqlite3RegisterExpr().
52607   */
52608   sqlite3NestedParse(pParse, 
52609      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
52610      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
52611 #endif
52612   sqlite3ReleaseTempReg(pParse, r1);
52613 }
52614
52615 /*
52616 ** Write VDBE code to erase table pTab and all associated indices on disk.
52617 ** Code to update the sqlite_master tables and internal schema definitions
52618 ** in case a root-page belonging to another table is moved by the btree layer
52619 ** is also added (this can happen with an auto-vacuum database).
52620 */
52621 static void destroyTable(Parse *pParse, Table *pTab){
52622 #ifdef SQLITE_OMIT_AUTOVACUUM
52623   Index *pIdx;
52624   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
52625   destroyRootPage(pParse, pTab->tnum, iDb);
52626   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
52627     destroyRootPage(pParse, pIdx->tnum, iDb);
52628   }
52629 #else
52630   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
52631   ** is not defined), then it is important to call OP_Destroy on the
52632   ** table and index root-pages in order, starting with the numerically 
52633   ** largest root-page number. This guarantees that none of the root-pages
52634   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
52635   ** following were coded:
52636   **
52637   ** OP_Destroy 4 0
52638   ** ...
52639   ** OP_Destroy 5 0
52640   **
52641   ** and root page 5 happened to be the largest root-page number in the
52642   ** database, then root page 5 would be moved to page 4 by the 
52643   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
52644   ** a free-list page.
52645   */
52646   int iTab = pTab->tnum;
52647   int iDestroyed = 0;
52648
52649   while( 1 ){
52650     Index *pIdx;
52651     int iLargest = 0;
52652
52653     if( iDestroyed==0 || iTab<iDestroyed ){
52654       iLargest = iTab;
52655     }
52656     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
52657       int iIdx = pIdx->tnum;
52658       assert( pIdx->pSchema==pTab->pSchema );
52659       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
52660         iLargest = iIdx;
52661       }
52662     }
52663     if( iLargest==0 ){
52664       return;
52665     }else{
52666       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
52667       destroyRootPage(pParse, iLargest, iDb);
52668       iDestroyed = iLargest;
52669     }
52670   }
52671 #endif
52672 }
52673
52674 /*
52675 ** This routine is called to do the work of a DROP TABLE statement.
52676 ** pName is the name of the table to be dropped.
52677 */
52678 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
52679   Table *pTab;
52680   Vdbe *v;
52681   sqlite3 *db = pParse->db;
52682   int iDb;
52683
52684   if( pParse->nErr || db->mallocFailed ){
52685     goto exit_drop_table;
52686   }
52687   assert( pName->nSrc==1 );
52688   pTab = sqlite3LocateTable(pParse, isView, 
52689                             pName->a[0].zName, pName->a[0].zDatabase);
52690
52691   if( pTab==0 ){
52692     if( noErr ){
52693       sqlite3ErrorClear(pParse);
52694     }
52695     goto exit_drop_table;
52696   }
52697   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
52698   assert( iDb>=0 && iDb<db->nDb );
52699
52700   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
52701   ** it is initialized.
52702   */
52703   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
52704     goto exit_drop_table;
52705   }
52706 #ifndef SQLITE_OMIT_AUTHORIZATION
52707   {
52708     int code;
52709     const char *zTab = SCHEMA_TABLE(iDb);
52710     const char *zDb = db->aDb[iDb].zName;
52711     const char *zArg2 = 0;
52712     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
52713       goto exit_drop_table;
52714     }
52715     if( isView ){
52716       if( !OMIT_TEMPDB && iDb==1 ){
52717         code = SQLITE_DROP_TEMP_VIEW;
52718       }else{
52719         code = SQLITE_DROP_VIEW;
52720       }
52721 #ifndef SQLITE_OMIT_VIRTUALTABLE
52722     }else if( IsVirtual(pTab) ){
52723       code = SQLITE_DROP_VTABLE;
52724       zArg2 = pTab->pMod->zName;
52725 #endif
52726     }else{
52727       if( !OMIT_TEMPDB && iDb==1 ){
52728         code = SQLITE_DROP_TEMP_TABLE;
52729       }else{
52730         code = SQLITE_DROP_TABLE;
52731       }
52732     }
52733     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
52734       goto exit_drop_table;
52735     }
52736     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
52737       goto exit_drop_table;
52738     }
52739   }
52740 #endif
52741   if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
52742     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
52743     goto exit_drop_table;
52744   }
52745
52746 #ifndef SQLITE_OMIT_VIEW
52747   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
52748   ** on a table.
52749   */
52750   if( isView && pTab->pSelect==0 ){
52751     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
52752     goto exit_drop_table;
52753   }
52754   if( !isView && pTab->pSelect ){
52755     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
52756     goto exit_drop_table;
52757   }
52758 #endif
52759
52760   /* Generate code to remove the table from the master table
52761   ** on disk.
52762   */
52763   v = sqlite3GetVdbe(pParse);
52764   if( v ){
52765     Trigger *pTrigger;
52766     Db *pDb = &db->aDb[iDb];
52767     sqlite3BeginWriteOperation(pParse, 1, iDb);
52768
52769 #ifndef SQLITE_OMIT_VIRTUALTABLE
52770     if( IsVirtual(pTab) ){
52771       Vdbe *v = sqlite3GetVdbe(pParse);
52772       if( v ){
52773         sqlite3VdbeAddOp0(v, OP_VBegin);
52774       }
52775     }
52776 #endif
52777
52778     /* Drop all triggers associated with the table being dropped. Code
52779     ** is generated to remove entries from sqlite_master and/or
52780     ** sqlite_temp_master if required.
52781     */
52782     pTrigger = pTab->pTrigger;
52783     while( pTrigger ){
52784       assert( pTrigger->pSchema==pTab->pSchema || 
52785           pTrigger->pSchema==db->aDb[1].pSchema );
52786       sqlite3DropTriggerPtr(pParse, pTrigger);
52787       pTrigger = pTrigger->pNext;
52788     }
52789
52790 #ifndef SQLITE_OMIT_AUTOINCREMENT
52791     /* Remove any entries of the sqlite_sequence table associated with
52792     ** the table being dropped. This is done before the table is dropped
52793     ** at the btree level, in case the sqlite_sequence table needs to
52794     ** move as a result of the drop (can happen in auto-vacuum mode).
52795     */
52796     if( pTab->autoInc ){
52797       sqlite3NestedParse(pParse,
52798         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
52799         pDb->zName, pTab->zName
52800       );
52801     }
52802 #endif
52803
52804     /* Drop all SQLITE_MASTER table and index entries that refer to the
52805     ** table. The program name loops through the master table and deletes
52806     ** every row that refers to a table of the same name as the one being
52807     ** dropped. Triggers are handled seperately because a trigger can be
52808     ** created in the temp database that refers to a table in another
52809     ** database.
52810     */
52811     sqlite3NestedParse(pParse, 
52812         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
52813         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
52814     if( !isView && !IsVirtual(pTab) ){
52815       destroyTable(pParse, pTab);
52816     }
52817
52818     /* Remove the table entry from SQLite's internal schema and modify
52819     ** the schema cookie.
52820     */
52821     if( IsVirtual(pTab) ){
52822       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
52823     }
52824     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
52825     sqlite3ChangeCookie(pParse, iDb);
52826   }
52827   sqliteViewResetAll(db, iDb);
52828
52829 exit_drop_table:
52830   sqlite3SrcListDelete(pName);
52831 }
52832
52833 /*
52834 ** This routine is called to create a new foreign key on the table
52835 ** currently under construction.  pFromCol determines which columns
52836 ** in the current table point to the foreign key.  If pFromCol==0 then
52837 ** connect the key to the last column inserted.  pTo is the name of
52838 ** the table referred to.  pToCol is a list of tables in the other
52839 ** pTo table that the foreign key points to.  flags contains all
52840 ** information about the conflict resolution algorithms specified
52841 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
52842 **
52843 ** An FKey structure is created and added to the table currently
52844 ** under construction in the pParse->pNewTable field.  The new FKey
52845 ** is not linked into db->aFKey at this point - that does not happen
52846 ** until sqlite3EndTable().
52847 **
52848 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
52849 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
52850 */
52851 SQLITE_PRIVATE void sqlite3CreateForeignKey(
52852   Parse *pParse,       /* Parsing context */
52853   ExprList *pFromCol,  /* Columns in this table that point to other table */
52854   Token *pTo,          /* Name of the other table */
52855   ExprList *pToCol,    /* Columns in the other table */
52856   int flags            /* Conflict resolution algorithms. */
52857 ){
52858 #ifndef SQLITE_OMIT_FOREIGN_KEY
52859   FKey *pFKey = 0;
52860   Table *p = pParse->pNewTable;
52861   int nByte;
52862   int i;
52863   int nCol;
52864   char *z;
52865
52866   assert( pTo!=0 );
52867   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
52868   if( pFromCol==0 ){
52869     int iCol = p->nCol-1;
52870     if( iCol<0 ) goto fk_end;
52871     if( pToCol && pToCol->nExpr!=1 ){
52872       sqlite3ErrorMsg(pParse, "foreign key on %s"
52873          " should reference only one column of table %T",
52874          p->aCol[iCol].zName, pTo);
52875       goto fk_end;
52876     }
52877     nCol = 1;
52878   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
52879     sqlite3ErrorMsg(pParse,
52880         "number of columns in foreign key does not match the number of "
52881         "columns in the referenced table");
52882     goto fk_end;
52883   }else{
52884     nCol = pFromCol->nExpr;
52885   }
52886   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
52887   if( pToCol ){
52888     for(i=0; i<pToCol->nExpr; i++){
52889       nByte += strlen(pToCol->a[i].zName) + 1;
52890     }
52891   }
52892   pFKey = sqlite3DbMallocZero(pParse->db, nByte );
52893   if( pFKey==0 ){
52894     goto fk_end;
52895   }
52896   pFKey->pFrom = p;
52897   pFKey->pNextFrom = p->pFKey;
52898   z = (char*)&pFKey[1];
52899   pFKey->aCol = (struct sColMap*)z;
52900   z += sizeof(struct sColMap)*nCol;
52901   pFKey->zTo = z;
52902   memcpy(z, pTo->z, pTo->n);
52903   z[pTo->n] = 0;
52904   z += pTo->n+1;
52905   pFKey->pNextTo = 0;
52906   pFKey->nCol = nCol;
52907   if( pFromCol==0 ){
52908     pFKey->aCol[0].iFrom = p->nCol-1;
52909   }else{
52910     for(i=0; i<nCol; i++){
52911       int j;
52912       for(j=0; j<p->nCol; j++){
52913         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
52914           pFKey->aCol[i].iFrom = j;
52915           break;
52916         }
52917       }
52918       if( j>=p->nCol ){
52919         sqlite3ErrorMsg(pParse, 
52920           "unknown column \"%s\" in foreign key definition", 
52921           pFromCol->a[i].zName);
52922         goto fk_end;
52923       }
52924     }
52925   }
52926   if( pToCol ){
52927     for(i=0; i<nCol; i++){
52928       int n = strlen(pToCol->a[i].zName);
52929       pFKey->aCol[i].zCol = z;
52930       memcpy(z, pToCol->a[i].zName, n);
52931       z[n] = 0;
52932       z += n+1;
52933     }
52934   }
52935   pFKey->isDeferred = 0;
52936   pFKey->deleteConf = flags & 0xff;
52937   pFKey->updateConf = (flags >> 8 ) & 0xff;
52938   pFKey->insertConf = (flags >> 16 ) & 0xff;
52939
52940   /* Link the foreign key to the table as the last step.
52941   */
52942   p->pFKey = pFKey;
52943   pFKey = 0;
52944
52945 fk_end:
52946   sqlite3_free(pFKey);
52947 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
52948   sqlite3ExprListDelete(pFromCol);
52949   sqlite3ExprListDelete(pToCol);
52950 }
52951
52952 /*
52953 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
52954 ** clause is seen as part of a foreign key definition.  The isDeferred
52955 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
52956 ** The behavior of the most recently created foreign key is adjusted
52957 ** accordingly.
52958 */
52959 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
52960 #ifndef SQLITE_OMIT_FOREIGN_KEY
52961   Table *pTab;
52962   FKey *pFKey;
52963   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
52964   pFKey->isDeferred = isDeferred;
52965 #endif
52966 }
52967
52968 /*
52969 ** Generate code that will erase and refill index *pIdx.  This is
52970 ** used to initialize a newly created index or to recompute the
52971 ** content of an index in response to a REINDEX command.
52972 **
52973 ** if memRootPage is not negative, it means that the index is newly
52974 ** created.  The register specified by memRootPage contains the
52975 ** root page number of the index.  If memRootPage is negative, then
52976 ** the index already exists and must be cleared before being refilled and
52977 ** the root page number of the index is taken from pIndex->tnum.
52978 */
52979 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
52980   Table *pTab = pIndex->pTable;  /* The table that is indexed */
52981   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
52982   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
52983   int addr1;                     /* Address of top of loop */
52984   int tnum;                      /* Root page of index */
52985   Vdbe *v;                       /* Generate code into this virtual machine */
52986   KeyInfo *pKey;                 /* KeyInfo for index */
52987   int regIdxKey;                 /* Registers containing the index key */
52988   int regRecord;                 /* Register holding assemblied index record */
52989   sqlite3 *db = pParse->db;      /* The database connection */
52990   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
52991
52992 #ifndef SQLITE_OMIT_AUTHORIZATION
52993   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
52994       db->aDb[iDb].zName ) ){
52995     return;
52996   }
52997 #endif
52998
52999   /* Require a write-lock on the table to perform this operation */
53000   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
53001
53002   v = sqlite3GetVdbe(pParse);
53003   if( v==0 ) return;
53004   if( memRootPage>=0 ){
53005     tnum = memRootPage;
53006   }else{
53007     tnum = pIndex->tnum;
53008     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
53009   }
53010   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
53011   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
53012                     (char *)pKey, P4_KEYINFO_HANDOFF);
53013   if( memRootPage>=0 ){
53014     sqlite3VdbeChangeP5(v, 1);
53015   }
53016   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
53017   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
53018   regRecord = sqlite3GetTempReg(pParse);
53019   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord);
53020   if( pIndex->onError!=OE_None ){
53021     int j1, j2;
53022     int regRowid;
53023
53024     regRowid = regIdxKey + pIndex->nColumn;
53025     j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
53026     j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
53027                            0, regRowid, (char*)(sqlite3_intptr_t)regRecord, P4_INT32);
53028     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
53029                     "indexed columns are not unique", P4_STATIC);
53030     sqlite3VdbeJumpHere(v, j1);
53031     sqlite3VdbeJumpHere(v, j2);
53032   }
53033   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
53034   sqlite3ReleaseTempReg(pParse, regRecord);
53035   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
53036   sqlite3VdbeJumpHere(v, addr1);
53037   sqlite3VdbeAddOp1(v, OP_Close, iTab);
53038   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
53039 }
53040
53041 /*
53042 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
53043 ** and pTblList is the name of the table that is to be indexed.  Both will 
53044 ** be NULL for a primary key or an index that is created to satisfy a
53045 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
53046 ** as the table to be indexed.  pParse->pNewTable is a table that is
53047 ** currently being constructed by a CREATE TABLE statement.
53048 **
53049 ** pList is a list of columns to be indexed.  pList will be NULL if this
53050 ** is a primary key or unique-constraint on the most recent column added
53051 ** to the table currently under construction.  
53052 */
53053 SQLITE_PRIVATE void sqlite3CreateIndex(
53054   Parse *pParse,     /* All information about this parse */
53055   Token *pName1,     /* First part of index name. May be NULL */
53056   Token *pName2,     /* Second part of index name. May be NULL */
53057   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
53058   ExprList *pList,   /* A list of columns to be indexed */
53059   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
53060   Token *pStart,     /* The CREATE token that begins this statement */
53061   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
53062   int sortOrder,     /* Sort order of primary key when pList==NULL */
53063   int ifNotExist     /* Omit error if index already exists */
53064 ){
53065   Table *pTab = 0;     /* Table to be indexed */
53066   Index *pIndex = 0;   /* The index to be created */
53067   char *zName = 0;     /* Name of the index */
53068   int nName;           /* Number of characters in zName */
53069   int i, j;
53070   Token nullId;        /* Fake token for an empty ID list */
53071   DbFixer sFix;        /* For assigning database names to pTable */
53072   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
53073   sqlite3 *db = pParse->db;
53074   Db *pDb;             /* The specific table containing the indexed database */
53075   int iDb;             /* Index of the database that is being written */
53076   Token *pName = 0;    /* Unqualified name of the index to create */
53077   struct ExprList_item *pListItem; /* For looping over pList */
53078   int nCol;
53079   int nExtra = 0;
53080   char *zExtra;
53081
53082   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
53083     goto exit_create_index;
53084   }
53085
53086   /*
53087   ** Find the table that is to be indexed.  Return early if not found.
53088   */
53089   if( pTblName!=0 ){
53090
53091     /* Use the two-part index name to determine the database 
53092     ** to search for the table. 'Fix' the table name to this db
53093     ** before looking up the table.
53094     */
53095     assert( pName1 && pName2 );
53096     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
53097     if( iDb<0 ) goto exit_create_index;
53098
53099 #ifndef SQLITE_OMIT_TEMPDB
53100     /* If the index name was unqualified, check if the the table
53101     ** is a temp table. If so, set the database to 1. Do not do this
53102     ** if initialising a database schema.
53103     */
53104     if( !db->init.busy ){
53105       pTab = sqlite3SrcListLookup(pParse, pTblName);
53106       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
53107         iDb = 1;
53108       }
53109     }
53110 #endif
53111
53112     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
53113         sqlite3FixSrcList(&sFix, pTblName)
53114     ){
53115       /* Because the parser constructs pTblName from a single identifier,
53116       ** sqlite3FixSrcList can never fail. */
53117       assert(0);
53118     }
53119     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
53120         pTblName->a[0].zDatabase);
53121     if( !pTab ) goto exit_create_index;
53122     assert( db->aDb[iDb].pSchema==pTab->pSchema );
53123   }else{
53124     assert( pName==0 );
53125     pTab = pParse->pNewTable;
53126     if( !pTab ) goto exit_create_index;
53127     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
53128   }
53129   pDb = &db->aDb[iDb];
53130
53131   if( pTab==0 || pParse->nErr ) goto exit_create_index;
53132   if( pTab->readOnly ){
53133     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
53134     goto exit_create_index;
53135   }
53136 #ifndef SQLITE_OMIT_VIEW
53137   if( pTab->pSelect ){
53138     sqlite3ErrorMsg(pParse, "views may not be indexed");
53139     goto exit_create_index;
53140   }
53141 #endif
53142 #ifndef SQLITE_OMIT_VIRTUALTABLE
53143   if( IsVirtual(pTab) ){
53144     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
53145     goto exit_create_index;
53146   }
53147 #endif
53148
53149   /*
53150   ** Find the name of the index.  Make sure there is not already another
53151   ** index or table with the same name.  
53152   **
53153   ** Exception:  If we are reading the names of permanent indices from the
53154   ** sqlite_master table (because some other process changed the schema) and
53155   ** one of the index names collides with the name of a temporary table or
53156   ** index, then we will continue to process this index.
53157   **
53158   ** If pName==0 it means that we are
53159   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
53160   ** own name.
53161   */
53162   if( pName ){
53163     zName = sqlite3NameFromToken(db, pName);
53164     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
53165     if( zName==0 ) goto exit_create_index;
53166     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
53167       goto exit_create_index;
53168     }
53169     if( !db->init.busy ){
53170       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
53171       if( sqlite3FindTable(db, zName, 0)!=0 ){
53172         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
53173         goto exit_create_index;
53174       }
53175     }
53176     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
53177       if( !ifNotExist ){
53178         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
53179       }
53180       goto exit_create_index;
53181     }
53182   }else{
53183     char zBuf[30];
53184     int n;
53185     Index *pLoop;
53186     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
53187     sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n);
53188     zName = 0;
53189     sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
53190     if( zName==0 ){
53191       db->mallocFailed = 1;
53192       goto exit_create_index;
53193     }
53194   }
53195
53196   /* Check for authorization to create an index.
53197   */
53198 #ifndef SQLITE_OMIT_AUTHORIZATION
53199   {
53200     const char *zDb = pDb->zName;
53201     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
53202       goto exit_create_index;
53203     }
53204     i = SQLITE_CREATE_INDEX;
53205     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
53206     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
53207       goto exit_create_index;
53208     }
53209   }
53210 #endif
53211
53212   /* If pList==0, it means this routine was called to make a primary
53213   ** key out of the last column added to the table under construction.
53214   ** So create a fake list to simulate this.
53215   */
53216   if( pList==0 ){
53217     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
53218     nullId.n = strlen((char*)nullId.z);
53219     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
53220     if( pList==0 ) goto exit_create_index;
53221     pList->a[0].sortOrder = sortOrder;
53222   }
53223
53224   /* Figure out how many bytes of space are required to store explicitly
53225   ** specified collation sequence names.
53226   */
53227   for(i=0; i<pList->nExpr; i++){
53228     Expr *pExpr = pList->a[i].pExpr;
53229     if( pExpr ){
53230       nExtra += (1 + strlen(pExpr->pColl->zName));
53231     }
53232   }
53233
53234   /* 
53235   ** Allocate the index structure. 
53236   */
53237   nName = strlen(zName);
53238   nCol = pList->nExpr;
53239   pIndex = sqlite3DbMallocZero(db, 
53240       sizeof(Index) +              /* Index structure  */
53241       sizeof(int)*nCol +           /* Index.aiColumn   */
53242       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
53243       sizeof(char *)*nCol +        /* Index.azColl     */
53244       sizeof(u8)*nCol +            /* Index.aSortOrder */
53245       nName + 1 +                  /* Index.zName      */
53246       nExtra                       /* Collation sequence names */
53247   );
53248   if( db->mallocFailed ){
53249     goto exit_create_index;
53250   }
53251   pIndex->azColl = (char**)(&pIndex[1]);
53252   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
53253   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
53254   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
53255   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
53256   zExtra = (char *)(&pIndex->zName[nName+1]);
53257   memcpy(pIndex->zName, zName, nName+1);
53258   pIndex->pTable = pTab;
53259   pIndex->nColumn = pList->nExpr;
53260   pIndex->onError = onError;
53261   pIndex->autoIndex = pName==0;
53262   pIndex->pSchema = db->aDb[iDb].pSchema;
53263
53264   /* Check to see if we should honor DESC requests on index columns
53265   */
53266   if( pDb->pSchema->file_format>=4 ){
53267     sortOrderMask = -1;   /* Honor DESC */
53268   }else{
53269     sortOrderMask = 0;    /* Ignore DESC */
53270   }
53271
53272   /* Scan the names of the columns of the table to be indexed and
53273   ** load the column indices into the Index structure.  Report an error
53274   ** if any column is not found.
53275   */
53276   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
53277     const char *zColName = pListItem->zName;
53278     Column *pTabCol;
53279     int requestedSortOrder;
53280     char *zColl;                   /* Collation sequence name */
53281
53282     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
53283       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
53284     }
53285     if( j>=pTab->nCol ){
53286       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
53287         pTab->zName, zColName);
53288       goto exit_create_index;
53289     }
53290     /* TODO:  Add a test to make sure that the same column is not named
53291     ** more than once within the same index.  Only the first instance of
53292     ** the column will ever be used by the optimizer.  Note that using the
53293     ** same column more than once cannot be an error because that would 
53294     ** break backwards compatibility - it needs to be a warning.
53295     */
53296     pIndex->aiColumn[i] = j;
53297     if( pListItem->pExpr ){
53298       assert( pListItem->pExpr->pColl );
53299       zColl = zExtra;
53300       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
53301       zExtra += (strlen(zColl) + 1);
53302     }else{
53303       zColl = pTab->aCol[j].zColl;
53304       if( !zColl ){
53305         zColl = db->pDfltColl->zName;
53306       }
53307     }
53308     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
53309       goto exit_create_index;
53310     }
53311     pIndex->azColl[i] = zColl;
53312     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
53313     pIndex->aSortOrder[i] = requestedSortOrder;
53314   }
53315   sqlite3DefaultRowEst(pIndex);
53316
53317   if( pTab==pParse->pNewTable ){
53318     /* This routine has been called to create an automatic index as a
53319     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
53320     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
53321     ** i.e. one of:
53322     **
53323     ** CREATE TABLE t(x PRIMARY KEY, y);
53324     ** CREATE TABLE t(x, y, UNIQUE(x, y));
53325     **
53326     ** Either way, check to see if the table already has such an index. If
53327     ** so, don't bother creating this one. This only applies to
53328     ** automatically created indices. Users can do as they wish with
53329     ** explicit indices.
53330     */
53331     Index *pIdx;
53332     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
53333       int k;
53334       assert( pIdx->onError!=OE_None );
53335       assert( pIdx->autoIndex );
53336       assert( pIndex->onError!=OE_None );
53337
53338       if( pIdx->nColumn!=pIndex->nColumn ) continue;
53339       for(k=0; k<pIdx->nColumn; k++){
53340         const char *z1 = pIdx->azColl[k];
53341         const char *z2 = pIndex->azColl[k];
53342         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
53343         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
53344         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
53345       }
53346       if( k==pIdx->nColumn ){
53347         if( pIdx->onError!=pIndex->onError ){
53348           /* This constraint creates the same index as a previous
53349           ** constraint specified somewhere in the CREATE TABLE statement.
53350           ** However the ON CONFLICT clauses are different. If both this 
53351           ** constraint and the previous equivalent constraint have explicit
53352           ** ON CONFLICT clauses this is an error. Otherwise, use the
53353           ** explicitly specified behaviour for the index.
53354           */
53355           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
53356             sqlite3ErrorMsg(pParse, 
53357                 "conflicting ON CONFLICT clauses specified", 0);
53358           }
53359           if( pIdx->onError==OE_Default ){
53360             pIdx->onError = pIndex->onError;
53361           }
53362         }
53363         goto exit_create_index;
53364       }
53365     }
53366   }
53367
53368   /* Link the new Index structure to its table and to the other
53369   ** in-memory database structures. 
53370   */
53371   if( db->init.busy ){
53372     Index *p;
53373     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
53374                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
53375     if( p ){
53376       assert( p==pIndex );  /* Malloc must have failed */
53377       db->mallocFailed = 1;
53378       goto exit_create_index;
53379     }
53380     db->flags |= SQLITE_InternChanges;
53381     if( pTblName!=0 ){
53382       pIndex->tnum = db->init.newTnum;
53383     }
53384   }
53385
53386   /* If the db->init.busy is 0 then create the index on disk.  This
53387   ** involves writing the index into the master table and filling in the
53388   ** index with the current table contents.
53389   **
53390   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
53391   ** command.  db->init.busy is 1 when a database is opened and 
53392   ** CREATE INDEX statements are read out of the master table.  In
53393   ** the latter case the index already exists on disk, which is why
53394   ** we don't want to recreate it.
53395   **
53396   ** If pTblName==0 it means this index is generated as a primary key
53397   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
53398   ** has just been created, it contains no data and the index initialization
53399   ** step can be skipped.
53400   */
53401   else if( db->init.busy==0 ){
53402     Vdbe *v;
53403     char *zStmt;
53404     int iMem = ++pParse->nMem;
53405
53406     v = sqlite3GetVdbe(pParse);
53407     if( v==0 ) goto exit_create_index;
53408
53409
53410     /* Create the rootpage for the index
53411     */
53412     sqlite3BeginWriteOperation(pParse, 1, iDb);
53413     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
53414
53415     /* Gather the complete text of the CREATE INDEX statement into
53416     ** the zStmt variable
53417     */
53418     if( pStart && pEnd ){
53419       /* A named index with an explicit CREATE INDEX statement */
53420       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
53421         onError==OE_None ? "" : " UNIQUE",
53422         pEnd->z - pName->z + 1,
53423         pName->z);
53424     }else{
53425       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
53426       /* zStmt = sqlite3MPrintf(""); */
53427       zStmt = 0;
53428     }
53429
53430     /* Add an entry in sqlite_master for this index
53431     */
53432     sqlite3NestedParse(pParse, 
53433         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
53434         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
53435         pIndex->zName,
53436         pTab->zName,
53437         iMem,
53438         zStmt
53439     );
53440     sqlite3_free(zStmt);
53441
53442     /* Fill the index with data and reparse the schema. Code an OP_Expire
53443     ** to invalidate all pre-compiled statements.
53444     */
53445     if( pTblName ){
53446       sqlite3RefillIndex(pParse, pIndex, iMem);
53447       sqlite3ChangeCookie(pParse, iDb);
53448       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
53449          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
53450       sqlite3VdbeAddOp1(v, OP_Expire, 0);
53451     }
53452   }
53453
53454   /* When adding an index to the list of indices for a table, make
53455   ** sure all indices labeled OE_Replace come after all those labeled
53456   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
53457   ** and INSERT.
53458   */
53459   if( db->init.busy || pTblName==0 ){
53460     if( onError!=OE_Replace || pTab->pIndex==0
53461          || pTab->pIndex->onError==OE_Replace){
53462       pIndex->pNext = pTab->pIndex;
53463       pTab->pIndex = pIndex;
53464     }else{
53465       Index *pOther = pTab->pIndex;
53466       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
53467         pOther = pOther->pNext;
53468       }
53469       pIndex->pNext = pOther->pNext;
53470       pOther->pNext = pIndex;
53471     }
53472     pIndex = 0;
53473   }
53474
53475   /* Clean up before exiting */
53476 exit_create_index:
53477   if( pIndex ){
53478     freeIndex(pIndex);
53479   }
53480   sqlite3ExprListDelete(pList);
53481   sqlite3SrcListDelete(pTblName);
53482   sqlite3_free(zName);
53483   return;
53484 }
53485
53486 /*
53487 ** Generate code to make sure the file format number is at least minFormat.
53488 ** The generated code will increase the file format number if necessary.
53489 */
53490 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
53491   Vdbe *v;
53492   v = sqlite3GetVdbe(pParse);
53493   if( v ){
53494     int r1 = sqlite3GetTempReg(pParse);
53495     int r2 = sqlite3GetTempReg(pParse);
53496     int j1;
53497     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
53498     sqlite3VdbeUsesBtree(v, iDb);
53499     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
53500     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
53501     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
53502     sqlite3VdbeJumpHere(v, j1);
53503     sqlite3ReleaseTempReg(pParse, r1);
53504     sqlite3ReleaseTempReg(pParse, r2);
53505   }
53506 }
53507
53508 /*
53509 ** Fill the Index.aiRowEst[] array with default information - information
53510 ** to be used when we have not run the ANALYZE command.
53511 **
53512 ** aiRowEst[0] is suppose to contain the number of elements in the index.
53513 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
53514 ** number of rows in the table that match any particular value of the
53515 ** first column of the index.  aiRowEst[2] is an estimate of the number
53516 ** of rows that match any particular combiniation of the first 2 columns
53517 ** of the index.  And so forth.  It must always be the case that
53518 *
53519 **           aiRowEst[N]<=aiRowEst[N-1]
53520 **           aiRowEst[N]>=1
53521 **
53522 ** Apart from that, we have little to go on besides intuition as to
53523 ** how aiRowEst[] should be initialized.  The numbers generated here
53524 ** are based on typical values found in actual indices.
53525 */
53526 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
53527   unsigned *a = pIdx->aiRowEst;
53528   int i;
53529   assert( a!=0 );
53530   a[0] = 1000000;
53531   for(i=pIdx->nColumn; i>=5; i--){
53532     a[i] = 5;
53533   }
53534   while( i>=1 ){
53535     a[i] = 11 - i;
53536     i--;
53537   }
53538   if( pIdx->onError!=OE_None ){
53539     a[pIdx->nColumn] = 1;
53540   }
53541 }
53542
53543 /*
53544 ** This routine will drop an existing named index.  This routine
53545 ** implements the DROP INDEX statement.
53546 */
53547 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
53548   Index *pIndex;
53549   Vdbe *v;
53550   sqlite3 *db = pParse->db;
53551   int iDb;
53552
53553   if( pParse->nErr || db->mallocFailed ){
53554     goto exit_drop_index;
53555   }
53556   assert( pName->nSrc==1 );
53557   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
53558     goto exit_drop_index;
53559   }
53560   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
53561   if( pIndex==0 ){
53562     if( !ifExists ){
53563       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
53564     }
53565     pParse->checkSchema = 1;
53566     goto exit_drop_index;
53567   }
53568   if( pIndex->autoIndex ){
53569     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
53570       "or PRIMARY KEY constraint cannot be dropped", 0);
53571     goto exit_drop_index;
53572   }
53573   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
53574 #ifndef SQLITE_OMIT_AUTHORIZATION
53575   {
53576     int code = SQLITE_DROP_INDEX;
53577     Table *pTab = pIndex->pTable;
53578     const char *zDb = db->aDb[iDb].zName;
53579     const char *zTab = SCHEMA_TABLE(iDb);
53580     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
53581       goto exit_drop_index;
53582     }
53583     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
53584     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
53585       goto exit_drop_index;
53586     }
53587   }
53588 #endif
53589
53590   /* Generate code to remove the index and from the master table */
53591   v = sqlite3GetVdbe(pParse);
53592   if( v ){
53593     sqlite3BeginWriteOperation(pParse, 1, iDb);
53594     sqlite3NestedParse(pParse,
53595        "DELETE FROM %Q.%s WHERE name=%Q",
53596        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
53597        pIndex->zName
53598     );
53599     sqlite3ChangeCookie(pParse, iDb);
53600     destroyRootPage(pParse, pIndex->tnum, iDb);
53601     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
53602   }
53603
53604 exit_drop_index:
53605   sqlite3SrcListDelete(pName);
53606 }
53607
53608 /*
53609 ** pArray is a pointer to an array of objects.  Each object in the
53610 ** array is szEntry bytes in size.  This routine allocates a new
53611 ** object on the end of the array.
53612 **
53613 ** *pnEntry is the number of entries already in use.  *pnAlloc is
53614 ** the previously allocated size of the array.  initSize is the
53615 ** suggested initial array size allocation.
53616 **
53617 ** The index of the new entry is returned in *pIdx.
53618 **
53619 ** This routine returns a pointer to the array of objects.  This
53620 ** might be the same as the pArray parameter or it might be a different
53621 ** pointer if the array was resized.
53622 */
53623 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
53624   sqlite3 *db,      /* Connection to notify of malloc failures */
53625   void *pArray,     /* Array of objects.  Might be reallocated */
53626   int szEntry,      /* Size of each object in the array */
53627   int initSize,     /* Suggested initial allocation, in elements */
53628   int *pnEntry,     /* Number of objects currently in use */
53629   int *pnAlloc,     /* Current size of the allocation, in elements */
53630   int *pIdx         /* Write the index of a new slot here */
53631 ){
53632   char *z;
53633   if( *pnEntry >= *pnAlloc ){
53634     void *pNew;
53635     int newSize;
53636     newSize = (*pnAlloc)*2 + initSize;
53637     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
53638     if( pNew==0 ){
53639       *pIdx = -1;
53640       return pArray;
53641     }
53642     *pnAlloc = newSize;
53643     pArray = pNew;
53644   }
53645   z = (char*)pArray;
53646   memset(&z[*pnEntry * szEntry], 0, szEntry);
53647   *pIdx = *pnEntry;
53648   ++*pnEntry;
53649   return pArray;
53650 }
53651
53652 /*
53653 ** Append a new element to the given IdList.  Create a new IdList if
53654 ** need be.
53655 **
53656 ** A new IdList is returned, or NULL if malloc() fails.
53657 */
53658 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
53659   int i;
53660   if( pList==0 ){
53661     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
53662     if( pList==0 ) return 0;
53663     pList->nAlloc = 0;
53664   }
53665   pList->a = sqlite3ArrayAllocate(
53666       db,
53667       pList->a,
53668       sizeof(pList->a[0]),
53669       5,
53670       &pList->nId,
53671       &pList->nAlloc,
53672       &i
53673   );
53674   if( i<0 ){
53675     sqlite3IdListDelete(pList);
53676     return 0;
53677   }
53678   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
53679   return pList;
53680 }
53681
53682 /*
53683 ** Delete an IdList.
53684 */
53685 SQLITE_PRIVATE void sqlite3IdListDelete(IdList *pList){
53686   int i;
53687   if( pList==0 ) return;
53688   for(i=0; i<pList->nId; i++){
53689     sqlite3_free(pList->a[i].zName);
53690   }
53691   sqlite3_free(pList->a);
53692   sqlite3_free(pList);
53693 }
53694
53695 /*
53696 ** Return the index in pList of the identifier named zId.  Return -1
53697 ** if not found.
53698 */
53699 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
53700   int i;
53701   if( pList==0 ) return -1;
53702   for(i=0; i<pList->nId; i++){
53703     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
53704   }
53705   return -1;
53706 }
53707
53708 /*
53709 ** Append a new table name to the given SrcList.  Create a new SrcList if
53710 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
53711 **
53712 ** A new SrcList is returned, or NULL if malloc() fails.
53713 **
53714 ** If pDatabase is not null, it means that the table has an optional
53715 ** database name prefix.  Like this:  "database.table".  The pDatabase
53716 ** points to the table name and the pTable points to the database name.
53717 ** The SrcList.a[].zName field is filled with the table name which might
53718 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
53719 ** SrcList.a[].zDatabase is filled with the database name from pTable,
53720 ** or with NULL if no database is specified.
53721 **
53722 ** In other words, if call like this:
53723 **
53724 **         sqlite3SrcListAppend(D,A,B,0);
53725 **
53726 ** Then B is a table name and the database name is unspecified.  If called
53727 ** like this:
53728 **
53729 **         sqlite3SrcListAppend(D,A,B,C);
53730 **
53731 ** Then C is the table name and B is the database name.
53732 */
53733 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
53734   sqlite3 *db,        /* Connection to notify of malloc failures */
53735   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
53736   Token *pTable,      /* Table to append */
53737   Token *pDatabase    /* Database of the table */
53738 ){
53739   struct SrcList_item *pItem;
53740   if( pList==0 ){
53741     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
53742     if( pList==0 ) return 0;
53743     pList->nAlloc = 1;
53744   }
53745   if( pList->nSrc>=pList->nAlloc ){
53746     SrcList *pNew;
53747     pList->nAlloc *= 2;
53748     pNew = sqlite3DbRealloc(db, pList,
53749                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
53750     if( pNew==0 ){
53751       sqlite3SrcListDelete(pList);
53752       return 0;
53753     }
53754     pList = pNew;
53755   }
53756   pItem = &pList->a[pList->nSrc];
53757   memset(pItem, 0, sizeof(pList->a[0]));
53758   if( pDatabase && pDatabase->z==0 ){
53759     pDatabase = 0;
53760   }
53761   if( pDatabase && pTable ){
53762     Token *pTemp = pDatabase;
53763     pDatabase = pTable;
53764     pTable = pTemp;
53765   }
53766   pItem->zName = sqlite3NameFromToken(db, pTable);
53767   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
53768   pItem->iCursor = -1;
53769   pItem->isPopulated = 0;
53770   pList->nSrc++;
53771   return pList;
53772 }
53773
53774 /*
53775 ** Assign cursors to all tables in a SrcList
53776 */
53777 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
53778   int i;
53779   struct SrcList_item *pItem;
53780   assert(pList || pParse->db->mallocFailed );
53781   if( pList ){
53782     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
53783       if( pItem->iCursor>=0 ) break;
53784       pItem->iCursor = pParse->nTab++;
53785       if( pItem->pSelect ){
53786         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
53787       }
53788     }
53789   }
53790 }
53791
53792 /*
53793 ** Delete an entire SrcList including all its substructure.
53794 */
53795 SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList *pList){
53796   int i;
53797   struct SrcList_item *pItem;
53798   if( pList==0 ) return;
53799   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
53800     sqlite3_free(pItem->zDatabase);
53801     sqlite3_free(pItem->zName);
53802     sqlite3_free(pItem->zAlias);
53803     sqlite3DeleteTable(pItem->pTab);
53804     sqlite3SelectDelete(pItem->pSelect);
53805     sqlite3ExprDelete(pItem->pOn);
53806     sqlite3IdListDelete(pItem->pUsing);
53807   }
53808   sqlite3_free(pList);
53809 }
53810
53811 /*
53812 ** This routine is called by the parser to add a new term to the
53813 ** end of a growing FROM clause.  The "p" parameter is the part of
53814 ** the FROM clause that has already been constructed.  "p" is NULL
53815 ** if this is the first term of the FROM clause.  pTable and pDatabase
53816 ** are the name of the table and database named in the FROM clause term.
53817 ** pDatabase is NULL if the database name qualifier is missing - the
53818 ** usual case.  If the term has a alias, then pAlias points to the
53819 ** alias token.  If the term is a subquery, then pSubquery is the
53820 ** SELECT statement that the subquery encodes.  The pTable and
53821 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
53822 ** parameters are the content of the ON and USING clauses.
53823 **
53824 ** Return a new SrcList which encodes is the FROM with the new
53825 ** term added.
53826 */
53827 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
53828   Parse *pParse,          /* Parsing context */
53829   SrcList *p,             /* The left part of the FROM clause already seen */
53830   Token *pTable,          /* Name of the table to add to the FROM clause */
53831   Token *pDatabase,       /* Name of the database containing pTable */
53832   Token *pAlias,          /* The right-hand side of the AS subexpression */
53833   Select *pSubquery,      /* A subquery used in place of a table name */
53834   Expr *pOn,              /* The ON clause of a join */
53835   IdList *pUsing          /* The USING clause of a join */
53836 ){
53837   struct SrcList_item *pItem;
53838   sqlite3 *db = pParse->db;
53839   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
53840   if( p==0 || p->nSrc==0 ){
53841     sqlite3ExprDelete(pOn);
53842     sqlite3IdListDelete(pUsing);
53843     sqlite3SelectDelete(pSubquery);
53844     return p;
53845   }
53846   pItem = &p->a[p->nSrc-1];
53847   if( pAlias && pAlias->n ){
53848     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
53849   }
53850   pItem->pSelect = pSubquery;
53851   pItem->pOn = pOn;
53852   pItem->pUsing = pUsing;
53853   return p;
53854 }
53855
53856 /*
53857 ** When building up a FROM clause in the parser, the join operator
53858 ** is initially attached to the left operand.  But the code generator
53859 ** expects the join operator to be on the right operand.  This routine
53860 ** Shifts all join operators from left to right for an entire FROM
53861 ** clause.
53862 **
53863 ** Example: Suppose the join is like this:
53864 **
53865 **           A natural cross join B
53866 **
53867 ** The operator is "natural cross join".  The A and B operands are stored
53868 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
53869 ** operator with A.  This routine shifts that operator over to B.
53870 */
53871 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
53872   if( p && p->a ){
53873     int i;
53874     for(i=p->nSrc-1; i>0; i--){
53875       p->a[i].jointype = p->a[i-1].jointype;
53876     }
53877     p->a[0].jointype = 0;
53878   }
53879 }
53880
53881 /*
53882 ** Begin a transaction
53883 */
53884 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
53885   sqlite3 *db;
53886   Vdbe *v;
53887   int i;
53888
53889   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
53890   if( pParse->nErr || db->mallocFailed ) return;
53891   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
53892
53893   v = sqlite3GetVdbe(pParse);
53894   if( !v ) return;
53895   if( type!=TK_DEFERRED ){
53896     for(i=0; i<db->nDb; i++){
53897       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
53898       sqlite3VdbeUsesBtree(v, i);
53899     }
53900   }
53901   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
53902 }
53903
53904 /*
53905 ** Commit a transaction
53906 */
53907 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
53908   sqlite3 *db;
53909   Vdbe *v;
53910
53911   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
53912   if( pParse->nErr || db->mallocFailed ) return;
53913   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
53914
53915   v = sqlite3GetVdbe(pParse);
53916   if( v ){
53917     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
53918   }
53919 }
53920
53921 /*
53922 ** Rollback a transaction
53923 */
53924 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
53925   sqlite3 *db;
53926   Vdbe *v;
53927
53928   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
53929   if( pParse->nErr || db->mallocFailed ) return;
53930   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
53931
53932   v = sqlite3GetVdbe(pParse);
53933   if( v ){
53934     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
53935   }
53936 }
53937
53938 /*
53939 ** Make sure the TEMP database is open and available for use.  Return
53940 ** the number of errors.  Leave any error messages in the pParse structure.
53941 */
53942 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
53943   sqlite3 *db = pParse->db;
53944   if( db->aDb[1].pBt==0 && !pParse->explain ){
53945     int rc;
53946     static const int flags = 
53947           SQLITE_OPEN_READWRITE |
53948           SQLITE_OPEN_CREATE |
53949           SQLITE_OPEN_EXCLUSIVE |
53950           SQLITE_OPEN_DELETEONCLOSE |
53951           SQLITE_OPEN_TEMP_DB;
53952
53953     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
53954                                  &db->aDb[1].pBt);
53955     if( rc!=SQLITE_OK ){
53956       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
53957         "file for storing temporary tables");
53958       pParse->rc = rc;
53959       return 1;
53960     }
53961     assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
53962     assert( db->aDb[1].pSchema );
53963   }
53964   return 0;
53965 }
53966
53967 /*
53968 ** Generate VDBE code that will verify the schema cookie and start
53969 ** a read-transaction for all named database files.
53970 **
53971 ** It is important that all schema cookies be verified and all
53972 ** read transactions be started before anything else happens in
53973 ** the VDBE program.  But this routine can be called after much other
53974 ** code has been generated.  So here is what we do:
53975 **
53976 ** The first time this routine is called, we code an OP_Goto that
53977 ** will jump to a subroutine at the end of the program.  Then we
53978 ** record every database that needs its schema verified in the
53979 ** pParse->cookieMask field.  Later, after all other code has been
53980 ** generated, the subroutine that does the cookie verifications and
53981 ** starts the transactions will be coded and the OP_Goto P2 value
53982 ** will be made to point to that subroutine.  The generation of the
53983 ** cookie verification subroutine code happens in sqlite3FinishCoding().
53984 **
53985 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
53986 ** schema on any databases.  This can be used to position the OP_Goto
53987 ** early in the code, before we know if any database tables will be used.
53988 */
53989 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
53990   sqlite3 *db;
53991   Vdbe *v;
53992   int mask;
53993
53994   v = sqlite3GetVdbe(pParse);
53995   if( v==0 ) return;  /* This only happens if there was a prior error */
53996   db = pParse->db;
53997   if( pParse->cookieGoto==0 ){
53998     pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
53999   }
54000   if( iDb>=0 ){
54001     assert( iDb<db->nDb );
54002     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
54003     assert( iDb<SQLITE_MAX_ATTACHED+2 );
54004     mask = 1<<iDb;
54005     if( (pParse->cookieMask & mask)==0 ){
54006       pParse->cookieMask |= mask;
54007       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
54008       if( !OMIT_TEMPDB && iDb==1 ){
54009         sqlite3OpenTempDatabase(pParse);
54010       }
54011     }
54012   }
54013 }
54014
54015 /*
54016 ** Generate VDBE code that prepares for doing an operation that
54017 ** might change the database.
54018 **
54019 ** This routine starts a new transaction if we are not already within
54020 ** a transaction.  If we are already within a transaction, then a checkpoint
54021 ** is set if the setStatement parameter is true.  A checkpoint should
54022 ** be set for operations that might fail (due to a constraint) part of
54023 ** the way through and which will need to undo some writes without having to
54024 ** rollback the whole transaction.  For operations where all constraints
54025 ** can be checked before any changes are made to the database, it is never
54026 ** necessary to undo a write and the checkpoint should not be set.
54027 **
54028 ** Only database iDb and the temp database are made writable by this call.
54029 ** If iDb==0, then the main and temp databases are made writable.   If
54030 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
54031 ** specified auxiliary database and the temp database are made writable.
54032 */
54033 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
54034   Vdbe *v = sqlite3GetVdbe(pParse);
54035   if( v==0 ) return;
54036   sqlite3CodeVerifySchema(pParse, iDb);
54037   pParse->writeMask |= 1<<iDb;
54038   if( setStatement && pParse->nested==0 ){
54039     sqlite3VdbeAddOp1(v, OP_Statement, iDb);
54040   }
54041   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
54042     sqlite3BeginWriteOperation(pParse, setStatement, 1);
54043   }
54044 }
54045
54046 /*
54047 ** Check to see if pIndex uses the collating sequence pColl.  Return
54048 ** true if it does and false if it does not.
54049 */
54050 #ifndef SQLITE_OMIT_REINDEX
54051 static int collationMatch(const char *zColl, Index *pIndex){
54052   int i;
54053   for(i=0; i<pIndex->nColumn; i++){
54054     const char *z = pIndex->azColl[i];
54055     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
54056       return 1;
54057     }
54058   }
54059   return 0;
54060 }
54061 #endif
54062
54063 /*
54064 ** Recompute all indices of pTab that use the collating sequence pColl.
54065 ** If pColl==0 then recompute all indices of pTab.
54066 */
54067 #ifndef SQLITE_OMIT_REINDEX
54068 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
54069   Index *pIndex;              /* An index associated with pTab */
54070
54071   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
54072     if( zColl==0 || collationMatch(zColl, pIndex) ){
54073       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
54074       sqlite3BeginWriteOperation(pParse, 0, iDb);
54075       sqlite3RefillIndex(pParse, pIndex, -1);
54076     }
54077   }
54078 }
54079 #endif
54080
54081 /*
54082 ** Recompute all indices of all tables in all databases where the
54083 ** indices use the collating sequence pColl.  If pColl==0 then recompute
54084 ** all indices everywhere.
54085 */
54086 #ifndef SQLITE_OMIT_REINDEX
54087 static void reindexDatabases(Parse *pParse, char const *zColl){
54088   Db *pDb;                    /* A single database */
54089   int iDb;                    /* The database index number */
54090   sqlite3 *db = pParse->db;   /* The database connection */
54091   HashElem *k;                /* For looping over tables in pDb */
54092   Table *pTab;                /* A table in the database */
54093
54094   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
54095     assert( pDb!=0 );
54096     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
54097       pTab = (Table*)sqliteHashData(k);
54098       reindexTable(pParse, pTab, zColl);
54099     }
54100   }
54101 }
54102 #endif
54103
54104 /*
54105 ** Generate code for the REINDEX command.
54106 **
54107 **        REINDEX                            -- 1
54108 **        REINDEX  <collation>               -- 2
54109 **        REINDEX  ?<database>.?<tablename>  -- 3
54110 **        REINDEX  ?<database>.?<indexname>  -- 4
54111 **
54112 ** Form 1 causes all indices in all attached databases to be rebuilt.
54113 ** Form 2 rebuilds all indices in all databases that use the named
54114 ** collating function.  Forms 3 and 4 rebuild the named index or all
54115 ** indices associated with the named table.
54116 */
54117 #ifndef SQLITE_OMIT_REINDEX
54118 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
54119   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
54120   char *z;                    /* Name of a table or index */
54121   const char *zDb;            /* Name of the database */
54122   Table *pTab;                /* A table in the database */
54123   Index *pIndex;              /* An index associated with pTab */
54124   int iDb;                    /* The database index number */
54125   sqlite3 *db = pParse->db;   /* The database connection */
54126   Token *pObjName;            /* Name of the table or index to be reindexed */
54127
54128   /* Read the database schema. If an error occurs, leave an error message
54129   ** and code in pParse and return NULL. */
54130   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
54131     return;
54132   }
54133
54134   if( pName1==0 || pName1->z==0 ){
54135     reindexDatabases(pParse, 0);
54136     return;
54137   }else if( pName2==0 || pName2->z==0 ){
54138     char *zColl;
54139     assert( pName1->z );
54140     zColl = sqlite3NameFromToken(pParse->db, pName1);
54141     if( !zColl ) return;
54142     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
54143     if( pColl ){
54144       if( zColl ){
54145         reindexDatabases(pParse, zColl);
54146         sqlite3_free(zColl);
54147       }
54148       return;
54149     }
54150     sqlite3_free(zColl);
54151   }
54152   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
54153   if( iDb<0 ) return;
54154   z = sqlite3NameFromToken(db, pObjName);
54155   if( z==0 ) return;
54156   zDb = db->aDb[iDb].zName;
54157   pTab = sqlite3FindTable(db, z, zDb);
54158   if( pTab ){
54159     reindexTable(pParse, pTab, 0);
54160     sqlite3_free(z);
54161     return;
54162   }
54163   pIndex = sqlite3FindIndex(db, z, zDb);
54164   sqlite3_free(z);
54165   if( pIndex ){
54166     sqlite3BeginWriteOperation(pParse, 0, iDb);
54167     sqlite3RefillIndex(pParse, pIndex, -1);
54168     return;
54169   }
54170   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
54171 }
54172 #endif
54173
54174 /*
54175 ** Return a dynamicly allocated KeyInfo structure that can be used
54176 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
54177 **
54178 ** If successful, a pointer to the new structure is returned. In this case
54179 ** the caller is responsible for calling sqlite3_free() on the returned 
54180 ** pointer. If an error occurs (out of memory or missing collation 
54181 ** sequence), NULL is returned and the state of pParse updated to reflect
54182 ** the error.
54183 */
54184 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
54185   int i;
54186   int nCol = pIdx->nColumn;
54187   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
54188   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(pParse->db, nBytes);
54189
54190   if( pKey ){
54191     pKey->db = pParse->db;
54192     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
54193     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
54194     for(i=0; i<nCol; i++){
54195       char *zColl = pIdx->azColl[i];
54196       assert( zColl );
54197       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
54198       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
54199     }
54200     pKey->nField = nCol;
54201   }
54202
54203   if( pParse->nErr ){
54204     sqlite3_free(pKey);
54205     pKey = 0;
54206   }
54207   return pKey;
54208 }
54209
54210 /************** End of build.c ***********************************************/
54211 /************** Begin file callback.c ****************************************/
54212 /*
54213 ** 2005 May 23 
54214 **
54215 ** The author disclaims copyright to this source code.  In place of
54216 ** a legal notice, here is a blessing:
54217 **
54218 **    May you do good and not evil.
54219 **    May you find forgiveness for yourself and forgive others.
54220 **    May you share freely, never taking more than you give.
54221 **
54222 *************************************************************************
54223 **
54224 ** This file contains functions used to access the internal hash tables
54225 ** of user defined functions and collation sequences.
54226 **
54227 ** $Id: callback.c,v 1.23 2007/08/29 12:31:26 danielk1977 Exp $
54228 */
54229
54230
54231 /*
54232 ** Invoke the 'collation needed' callback to request a collation sequence
54233 ** in the database text encoding of name zName, length nName.
54234 ** If the collation sequence
54235 */
54236 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
54237   assert( !db->xCollNeeded || !db->xCollNeeded16 );
54238   if( nName<0 ) nName = strlen(zName);
54239   if( db->xCollNeeded ){
54240     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
54241     if( !zExternal ) return;
54242     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
54243     sqlite3_free(zExternal);
54244   }
54245 #ifndef SQLITE_OMIT_UTF16
54246   if( db->xCollNeeded16 ){
54247     char const *zExternal;
54248     sqlite3_value *pTmp = sqlite3ValueNew(db);
54249     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
54250     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
54251     if( zExternal ){
54252       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
54253     }
54254     sqlite3ValueFree(pTmp);
54255   }
54256 #endif
54257 }
54258
54259 /*
54260 ** This routine is called if the collation factory fails to deliver a
54261 ** collation function in the best encoding but there may be other versions
54262 ** of this collation function (for other text encodings) available. Use one
54263 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
54264 ** possible.
54265 */
54266 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
54267   CollSeq *pColl2;
54268   char *z = pColl->zName;
54269   int n = strlen(z);
54270   int i;
54271   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
54272   for(i=0; i<3; i++){
54273     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
54274     if( pColl2->xCmp!=0 ){
54275       memcpy(pColl, pColl2, sizeof(CollSeq));
54276       pColl->xDel = 0;         /* Do not copy the destructor */
54277       return SQLITE_OK;
54278     }
54279   }
54280   return SQLITE_ERROR;
54281 }
54282
54283 /*
54284 ** This function is responsible for invoking the collation factory callback
54285 ** or substituting a collation sequence of a different encoding when the
54286 ** requested collation sequence is not available in the database native
54287 ** encoding.
54288 ** 
54289 ** If it is not NULL, then pColl must point to the database native encoding 
54290 ** collation sequence with name zName, length nName.
54291 **
54292 ** The return value is either the collation sequence to be used in database
54293 ** db for collation type name zName, length nName, or NULL, if no collation
54294 ** sequence can be found.
54295 */
54296 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
54297   sqlite3* db, 
54298   CollSeq *pColl, 
54299   const char *zName, 
54300   int nName
54301 ){
54302   CollSeq *p;
54303
54304   p = pColl;
54305   if( !p ){
54306     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
54307   }
54308   if( !p || !p->xCmp ){
54309     /* No collation sequence of this type for this encoding is registered.
54310     ** Call the collation factory to see if it can supply us with one.
54311     */
54312     callCollNeeded(db, zName, nName);
54313     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
54314   }
54315   if( p && !p->xCmp && synthCollSeq(db, p) ){
54316     p = 0;
54317   }
54318   assert( !p || p->xCmp );
54319   return p;
54320 }
54321
54322 /*
54323 ** This routine is called on a collation sequence before it is used to
54324 ** check that it is defined. An undefined collation sequence exists when
54325 ** a database is loaded that contains references to collation sequences
54326 ** that have not been defined by sqlite3_create_collation() etc.
54327 **
54328 ** If required, this routine calls the 'collation needed' callback to
54329 ** request a definition of the collating sequence. If this doesn't work, 
54330 ** an equivalent collating sequence that uses a text encoding different
54331 ** from the main database is substituted, if one is available.
54332 */
54333 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
54334   if( pColl ){
54335     const char *zName = pColl->zName;
54336     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
54337     if( !p ){
54338       if( pParse->nErr==0 ){
54339         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
54340       }
54341       pParse->nErr++;
54342       return SQLITE_ERROR;
54343     }
54344     assert( p==pColl );
54345   }
54346   return SQLITE_OK;
54347 }
54348
54349
54350
54351 /*
54352 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
54353 ** specified by zName and nName is not found and parameter 'create' is
54354 ** true, then create a new entry. Otherwise return NULL.
54355 **
54356 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
54357 ** array of three CollSeq structures. The first is the collation sequence
54358 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
54359 **
54360 ** Stored immediately after the three collation sequences is a copy of
54361 ** the collation sequence name. A pointer to this string is stored in
54362 ** each collation sequence structure.
54363 */
54364 static CollSeq *findCollSeqEntry(
54365   sqlite3 *db,
54366   const char *zName,
54367   int nName,
54368   int create
54369 ){
54370   CollSeq *pColl;
54371   if( nName<0 ) nName = strlen(zName);
54372   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
54373
54374   if( 0==pColl && create ){
54375     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
54376     if( pColl ){
54377       CollSeq *pDel = 0;
54378       pColl[0].zName = (char*)&pColl[3];
54379       pColl[0].enc = SQLITE_UTF8;
54380       pColl[1].zName = (char*)&pColl[3];
54381       pColl[1].enc = SQLITE_UTF16LE;
54382       pColl[2].zName = (char*)&pColl[3];
54383       pColl[2].enc = SQLITE_UTF16BE;
54384       memcpy(pColl[0].zName, zName, nName);
54385       pColl[0].zName[nName] = 0;
54386       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
54387
54388       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
54389       ** return the pColl pointer to be deleted (because it wasn't added
54390       ** to the hash table).
54391       */
54392       assert( pDel==0 || pDel==pColl );
54393       if( pDel!=0 ){
54394         db->mallocFailed = 1;
54395         sqlite3_free(pDel);
54396         pColl = 0;
54397       }
54398     }
54399   }
54400   return pColl;
54401 }
54402
54403 /*
54404 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
54405 ** Return the CollSeq* pointer for the collation sequence named zName
54406 ** for the encoding 'enc' from the database 'db'.
54407 **
54408 ** If the entry specified is not found and 'create' is true, then create a
54409 ** new entry.  Otherwise return NULL.
54410 **
54411 ** A separate function sqlite3LocateCollSeq() is a wrapper around
54412 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
54413 ** if necessary and generates an error message if the collating sequence
54414 ** cannot be found.
54415 */
54416 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
54417   sqlite3 *db,
54418   u8 enc,
54419   const char *zName,
54420   int nName,
54421   int create
54422 ){
54423   CollSeq *pColl;
54424   if( zName ){
54425     pColl = findCollSeqEntry(db, zName, nName, create);
54426   }else{
54427     pColl = db->pDfltColl;
54428   }
54429   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
54430   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
54431   if( pColl ) pColl += enc-1;
54432   return pColl;
54433 }
54434
54435 /*
54436 ** Locate a user function given a name, a number of arguments and a flag
54437 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
54438 ** pointer to the FuncDef structure that defines that function, or return
54439 ** NULL if the function does not exist.
54440 **
54441 ** If the createFlag argument is true, then a new (blank) FuncDef
54442 ** structure is created and liked into the "db" structure if a
54443 ** no matching function previously existed.  When createFlag is true
54444 ** and the nArg parameter is -1, then only a function that accepts
54445 ** any number of arguments will be returned.
54446 **
54447 ** If createFlag is false and nArg is -1, then the first valid
54448 ** function found is returned.  A function is valid if either xFunc
54449 ** or xStep is non-zero.
54450 **
54451 ** If createFlag is false, then a function with the required name and
54452 ** number of arguments may be returned even if the eTextRep flag does not
54453 ** match that requested.
54454 */
54455 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
54456   sqlite3 *db,       /* An open database */
54457   const char *zName, /* Name of the function.  Not null-terminated */
54458   int nName,         /* Number of characters in the name */
54459   int nArg,          /* Number of arguments.  -1 means any number */
54460   u8 enc,            /* Preferred text encoding */
54461   int createFlag     /* Create new entry if true and does not otherwise exist */
54462 ){
54463   FuncDef *p;         /* Iterator variable */
54464   FuncDef *pFirst;    /* First function with this name */
54465   FuncDef *pBest = 0; /* Best match found so far */
54466   int bestmatch = 0;  
54467
54468
54469   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
54470   if( nArg<-1 ) nArg = -1;
54471
54472   pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
54473   for(p=pFirst; p; p=p->pNext){
54474     /* During the search for the best function definition, bestmatch is set
54475     ** as follows to indicate the quality of the match with the definition
54476     ** pointed to by pBest:
54477     **
54478     ** 0: pBest is NULL. No match has been found.
54479     ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
54480     **    encoding is requested, or vice versa.
54481     ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
54482     **    requested, or vice versa.
54483     ** 3: A variable arguments function using the same text encoding.
54484     ** 4: A function with the exact number of arguments requested that
54485     **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
54486     ** 5: A function with the exact number of arguments requested that
54487     **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
54488     ** 6: An exact match.
54489     **
54490     ** A larger value of 'matchqual' indicates a more desirable match.
54491     */
54492     if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
54493       int match = 1;          /* Quality of this match */
54494       if( p->nArg==nArg || nArg==-1 ){
54495         match = 4;
54496       }
54497       if( enc==p->iPrefEnc ){
54498         match += 2;
54499       }
54500       else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
54501                (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
54502         match += 1;
54503       }
54504
54505       if( match>bestmatch ){
54506         pBest = p;
54507         bestmatch = match;
54508       }
54509     }
54510   }
54511
54512   /* If the createFlag parameter is true, and the seach did not reveal an
54513   ** exact match for the name, number of arguments and encoding, then add a
54514   ** new entry to the hash table and return it.
54515   */
54516   if( createFlag && bestmatch<6 && 
54517       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName))!=0 ){
54518     pBest->nArg = nArg;
54519     pBest->pNext = pFirst;
54520     pBest->iPrefEnc = enc;
54521     memcpy(pBest->zName, zName, nName);
54522     pBest->zName[nName] = 0;
54523     if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
54524       db->mallocFailed = 1;
54525       sqlite3_free(pBest);
54526       return 0;
54527     }
54528   }
54529
54530   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
54531     return pBest;
54532   }
54533   return 0;
54534 }
54535
54536 /*
54537 ** Free all resources held by the schema structure. The void* argument points
54538 ** at a Schema struct. This function does not call sqlite3_free() on the 
54539 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
54540 ** of the schema hash tables).
54541 */
54542 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
54543   Hash temp1;
54544   Hash temp2;
54545   HashElem *pElem;
54546   Schema *pSchema = (Schema *)p;
54547
54548   temp1 = pSchema->tblHash;
54549   temp2 = pSchema->trigHash;
54550   sqlite3HashInit(&pSchema->trigHash, SQLITE_HASH_STRING, 0);
54551   sqlite3HashClear(&pSchema->aFKey);
54552   sqlite3HashClear(&pSchema->idxHash);
54553   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
54554     sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
54555   }
54556   sqlite3HashClear(&temp2);
54557   sqlite3HashInit(&pSchema->tblHash, SQLITE_HASH_STRING, 0);
54558   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
54559     Table *pTab = sqliteHashData(pElem);
54560     sqlite3DeleteTable(pTab);
54561   }
54562   sqlite3HashClear(&temp1);
54563   pSchema->pSeqTab = 0;
54564   pSchema->flags &= ~DB_SchemaLoaded;
54565 }
54566
54567 /*
54568 ** Find and return the schema associated with a BTree.  Create
54569 ** a new one if necessary.
54570 */
54571 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
54572   Schema * p;
54573   if( pBt ){
54574     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
54575   }else{
54576     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
54577   }
54578   if( !p ){
54579     db->mallocFailed = 1;
54580   }else if ( 0==p->file_format ){
54581     sqlite3HashInit(&p->tblHash, SQLITE_HASH_STRING, 0);
54582     sqlite3HashInit(&p->idxHash, SQLITE_HASH_STRING, 0);
54583     sqlite3HashInit(&p->trigHash, SQLITE_HASH_STRING, 0);
54584     sqlite3HashInit(&p->aFKey, SQLITE_HASH_STRING, 1);
54585     p->enc = SQLITE_UTF8;
54586   }
54587   return p;
54588 }
54589
54590 /************** End of callback.c ********************************************/
54591 /************** Begin file delete.c ******************************************/
54592 /*
54593 ** 2001 September 15
54594 **
54595 ** The author disclaims copyright to this source code.  In place of
54596 ** a legal notice, here is a blessing:
54597 **
54598 **    May you do good and not evil.
54599 **    May you find forgiveness for yourself and forgive others.
54600 **    May you share freely, never taking more than you give.
54601 **
54602 *************************************************************************
54603 ** This file contains C code routines that are called by the parser
54604 ** in order to generate code for DELETE FROM statements.
54605 **
54606 ** $Id: delete.c,v 1.161 2008/02/12 16:52:14 drh Exp $
54607 */
54608
54609 /*
54610 ** Look up every table that is named in pSrc.  If any table is not found,
54611 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
54612 ** are found, return a pointer to the last table.
54613 */
54614 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
54615   Table *pTab = 0;
54616   int i;
54617   struct SrcList_item *pItem;
54618   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
54619     pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
54620     sqlite3DeleteTable(pItem->pTab);
54621     pItem->pTab = pTab;
54622     if( pTab ){
54623       pTab->nRef++;
54624     }
54625   }
54626   return pTab;
54627 }
54628
54629 /*
54630 ** Check to make sure the given table is writable.  If it is not
54631 ** writable, generate an error message and return 1.  If it is
54632 ** writable return 0;
54633 */
54634 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
54635   if( (pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
54636         && pParse->nested==0) 
54637 #ifndef SQLITE_OMIT_VIRTUALTABLE
54638       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
54639 #endif
54640   ){
54641     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
54642     return 1;
54643   }
54644 #ifndef SQLITE_OMIT_VIEW
54645   if( !viewOk && pTab->pSelect ){
54646     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
54647     return 1;
54648   }
54649 #endif
54650   return 0;
54651 }
54652
54653 /*
54654 ** Generate code that will open a table for reading.
54655 */
54656 SQLITE_PRIVATE void sqlite3OpenTable(
54657   Parse *p,       /* Generate code into this VDBE */
54658   int iCur,       /* The cursor number of the table */
54659   int iDb,        /* The database index in sqlite3.aDb[] */
54660   Table *pTab,    /* The table to be opened */
54661   int opcode      /* OP_OpenRead or OP_OpenWrite */
54662 ){
54663   Vdbe *v;
54664   if( IsVirtual(pTab) ) return;
54665   v = sqlite3GetVdbe(p);
54666   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
54667   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
54668   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
54669   VdbeComment((v, "%s", pTab->zName));
54670   sqlite3VdbeAddOp2(v, OP_SetNumColumns, iCur, pTab->nCol);
54671 }
54672
54673
54674 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
54675 /*
54676 ** Evaluate a view and store its result in an ephemeral table.  The
54677 ** pWhere argument is an optional WHERE clause that restricts the
54678 ** set of rows in the view that are to be added to the ephemeral table.
54679 */
54680 SQLITE_PRIVATE void sqlite3MaterializeView(
54681   Parse *pParse,       /* Parsing context */
54682   Select *pView,       /* View definition */
54683   Expr *pWhere,        /* Optional WHERE clause to be added */
54684   u32 col_mask,        /* Render only the columns in this mask. */
54685   int iCur             /* Cursor number for ephemerial table */
54686 ){
54687   SelectDest dest;
54688   Select *pDup;
54689   sqlite3 *db = pParse->db;
54690
54691   pDup = sqlite3SelectDup(db, pView);
54692   if( pWhere ){
54693     SrcList *pFrom;
54694     
54695     pWhere = sqlite3ExprDup(db, pWhere);
54696     pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, 0, pDup, 0, 0);
54697     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
54698   }
54699   sqlite3SelectMask(pParse, pDup, col_mask);
54700   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
54701   sqlite3Select(pParse, pDup, &dest, 0, 0, 0, 0);
54702   sqlite3SelectDelete(pDup);
54703 }
54704 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
54705
54706
54707 /*
54708 ** Generate code for a DELETE FROM statement.
54709 **
54710 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
54711 **                 \________/       \________________/
54712 **                  pTabList              pWhere
54713 */
54714 SQLITE_PRIVATE void sqlite3DeleteFrom(
54715   Parse *pParse,         /* The parser context */
54716   SrcList *pTabList,     /* The table from which we should delete things */
54717   Expr *pWhere           /* The WHERE clause.  May be null */
54718 ){
54719   Vdbe *v;               /* The virtual database engine */
54720   Table *pTab;           /* The table from which records will be deleted */
54721   const char *zDb;       /* Name of database holding pTab */
54722   int end, addr = 0;     /* A couple addresses of generated code */
54723   int i;                 /* Loop counter */
54724   WhereInfo *pWInfo;     /* Information about the WHERE clause */
54725   Index *pIdx;           /* For looping over indices of the table */
54726   int iCur;              /* VDBE Cursor number for pTab */
54727   sqlite3 *db;           /* Main database structure */
54728   AuthContext sContext;  /* Authorization context */
54729   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
54730   NameContext sNC;       /* Name context to resolve expressions in */
54731   int iDb;               /* Database number */
54732   int memCnt = 0;        /* Memory cell used for change counting */
54733
54734 #ifndef SQLITE_OMIT_TRIGGER
54735   int isView;                  /* True if attempting to delete from a view */
54736   int triggers_exist = 0;      /* True if any triggers exist */
54737 #endif
54738   int iBeginAfterTrigger;      /* Address of after trigger program */
54739   int iEndAfterTrigger;        /* Exit of after trigger program */
54740   int iBeginBeforeTrigger;     /* Address of before trigger program */
54741   int iEndBeforeTrigger;       /* Exit of before trigger program */
54742   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
54743
54744   sContext.pParse = 0;
54745   db = pParse->db;
54746   if( pParse->nErr || db->mallocFailed ){
54747     goto delete_from_cleanup;
54748   }
54749   assert( pTabList->nSrc==1 );
54750
54751   /* Locate the table which we want to delete.  This table has to be
54752   ** put in an SrcList structure because some of the subroutines we
54753   ** will be calling are designed to work with multiple tables and expect
54754   ** an SrcList* parameter instead of just a Table* parameter.
54755   */
54756   pTab = sqlite3SrcListLookup(pParse, pTabList);
54757   if( pTab==0 )  goto delete_from_cleanup;
54758
54759   /* Figure out if we have any triggers and if the table being
54760   ** deleted from is a view
54761   */
54762 #ifndef SQLITE_OMIT_TRIGGER
54763   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
54764   isView = pTab->pSelect!=0;
54765 #else
54766 # define triggers_exist 0
54767 # define isView 0
54768 #endif
54769 #ifdef SQLITE_OMIT_VIEW
54770 # undef isView
54771 # define isView 0
54772 #endif
54773
54774   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
54775     goto delete_from_cleanup;
54776   }
54777   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
54778   assert( iDb<db->nDb );
54779   zDb = db->aDb[iDb].zName;
54780   if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
54781     goto delete_from_cleanup;
54782   }
54783
54784   /* If pTab is really a view, make sure it has been initialized.
54785   */
54786   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
54787     goto delete_from_cleanup;
54788   }
54789
54790   /* Allocate a cursor used to store the old.* data for a trigger.
54791   */
54792   if( triggers_exist ){ 
54793     oldIdx = pParse->nTab++;
54794   }
54795
54796   /* Assign  cursor number to the table and all its indices.
54797   */
54798   assert( pTabList->nSrc==1 );
54799   iCur = pTabList->a[0].iCursor = pParse->nTab++;
54800   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
54801     pParse->nTab++;
54802   }
54803
54804   /* Start the view context
54805   */
54806   if( isView ){
54807     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
54808   }
54809
54810   /* Begin generating code.
54811   */
54812   v = sqlite3GetVdbe(pParse);
54813   if( v==0 ){
54814     goto delete_from_cleanup;
54815   }
54816   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
54817   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
54818
54819   if( triggers_exist ){
54820     int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
54821     int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
54822     addr = sqlite3VdbeMakeLabel(v);
54823
54824     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
54825     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
54826         -1, oldIdx, orconf, addr, &old_col_mask, 0);
54827     iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
54828
54829     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
54830     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
54831         oldIdx, orconf, addr, &old_col_mask, 0);
54832     iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
54833
54834     sqlite3VdbeJumpHere(v, iGoto);
54835   }
54836
54837   /* If we are trying to delete from a view, realize that view into
54838   ** a ephemeral table.
54839   */
54840   if( isView ){
54841     sqlite3MaterializeView(pParse, pTab->pSelect, pWhere, old_col_mask, iCur);
54842   }
54843
54844   /* Resolve the column names in the WHERE clause.
54845   */
54846   memset(&sNC, 0, sizeof(sNC));
54847   sNC.pParse = pParse;
54848   sNC.pSrcList = pTabList;
54849   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
54850     goto delete_from_cleanup;
54851   }
54852
54853   /* Initialize the counter of the number of rows deleted, if
54854   ** we are counting rows.
54855   */
54856   if( db->flags & SQLITE_CountRows ){
54857     memCnt = ++pParse->nMem;
54858     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
54859   }
54860
54861   /* Special case: A DELETE without a WHERE clause deletes everything.
54862   ** It is easier just to erase the whole table.  Note, however, that
54863   ** this means that the row change count will be incorrect.
54864   */
54865   if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
54866     if( db->flags & SQLITE_CountRows ){
54867       /* If counting rows deleted, just count the total number of
54868       ** entries in the table. */
54869       int addr2;
54870       if( !isView ){
54871         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
54872       }
54873       sqlite3VdbeAddOp2(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
54874       addr2 = sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
54875       sqlite3VdbeAddOp2(v, OP_Next, iCur, addr2);
54876       sqlite3VdbeAddOp1(v, OP_Close, iCur);
54877     }
54878     if( !isView ){
54879       sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb);
54880       if( !pParse->nested ){
54881         sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
54882       }
54883       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
54884         assert( pIdx->pSchema==pTab->pSchema );
54885         sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
54886       }
54887     }
54888   } 
54889   /* The usual case: There is a WHERE clause so we have to scan through
54890   ** the table and pick which records to delete.
54891   */
54892   else{
54893     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
54894
54895     /* Begin the database scan
54896     */
54897     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
54898     if( pWInfo==0 ) goto delete_from_cleanup;
54899
54900     /* Remember the rowid of every item to be deleted.
54901     */
54902     sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid);
54903     sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid);
54904     if( db->flags & SQLITE_CountRows ){
54905       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
54906     }
54907
54908     /* End the database scan loop.
54909     */
54910     sqlite3WhereEnd(pWInfo);
54911
54912     /* Open the pseudo-table used to store OLD if there are triggers.
54913     */
54914     if( triggers_exist ){
54915       sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
54916       sqlite3VdbeAddOp2(v, OP_SetNumColumns, oldIdx, pTab->nCol);
54917     }
54918
54919     /* Delete every item whose key was written to the list during the
54920     ** database scan.  We have to delete items after the scan is complete
54921     ** because deleting an item can change the scan order.
54922     */
54923     end = sqlite3VdbeMakeLabel(v);
54924
54925     if( !isView ){
54926       /* Open cursors for the table we are deleting from and 
54927       ** all its indices.
54928       */
54929       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
54930     }
54931
54932     /* This is the beginning of the delete loop. If a trigger encounters
54933     ** an IGNORE constraint, it jumps back to here.
54934     */
54935     if( triggers_exist ){
54936       sqlite3VdbeResolveLabel(v, addr);
54937     }
54938     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end);
54939
54940     if( triggers_exist ){
54941       int iData = ++pParse->nMem;   /* For storing row data of OLD table */
54942
54943       /* If the record is no longer present in the table, jump to the
54944       ** next iteration of the loop through the contents of the fifo.
54945       */
54946       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
54947
54948       /* Populate the OLD.* pseudo-table */
54949       if( old_col_mask ){
54950         sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
54951       }else{
54952         sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
54953       }
54954       sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
54955
54956       /* Jump back and run the BEFORE triggers */
54957       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
54958       sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
54959     }
54960
54961     if( !isView ){
54962       /* Delete the row */
54963 #ifndef SQLITE_OMIT_VIRTUALTABLE
54964       if( IsVirtual(pTab) ){
54965         const char *pVtab = (const char *)pTab->pVtab;
54966         pParse->pVirtualLock = pTab;
54967         sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
54968       }else
54969 #endif
54970       {
54971         sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
54972       }
54973     }
54974
54975     /* If there are row triggers, close all cursors then invoke
54976     ** the AFTER triggers
54977     */
54978     if( triggers_exist ){
54979       /* Jump back and run the AFTER triggers */
54980       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
54981       sqlite3VdbeJumpHere(v, iEndAfterTrigger);
54982     }
54983
54984     /* End of the delete loop */
54985     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
54986     sqlite3VdbeResolveLabel(v, end);
54987
54988     /* Close the cursors after the loop if there are no row triggers */
54989     if( !isView  && !IsVirtual(pTab) ){
54990       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
54991         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
54992       }
54993       sqlite3VdbeAddOp1(v, OP_Close, iCur);
54994     }
54995   }
54996
54997   /*
54998   ** Return the number of rows that were deleted. If this routine is 
54999   ** generating code because of a call to sqlite3NestedParse(), do not
55000   ** invoke the callback function.
55001   */
55002   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
55003     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
55004     sqlite3VdbeSetNumCols(v, 1);
55005     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC);
55006   }
55007
55008 delete_from_cleanup:
55009   sqlite3AuthContextPop(&sContext);
55010   sqlite3SrcListDelete(pTabList);
55011   sqlite3ExprDelete(pWhere);
55012   return;
55013 }
55014
55015 /*
55016 ** This routine generates VDBE code that causes a single row of a
55017 ** single table to be deleted.
55018 **
55019 ** The VDBE must be in a particular state when this routine is called.
55020 ** These are the requirements:
55021 **
55022 **   1.  A read/write cursor pointing to pTab, the table containing the row
55023 **       to be deleted, must be opened as cursor number "base".
55024 **
55025 **   2.  Read/write cursors for all indices of pTab must be open as
55026 **       cursor number base+i for the i-th index.
55027 **
55028 **   3.  The record number of the row to be deleted must be stored in
55029 **       memory cell iRowid.
55030 **
55031 ** This routine pops the top of the stack to remove the record number
55032 ** and then generates code to remove both the table record and all index
55033 ** entries that point to that record.
55034 */
55035 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
55036   Parse *pParse,     /* Parsing context */
55037   Table *pTab,       /* Table containing the row to be deleted */
55038   int iCur,          /* Cursor number for the table */
55039   int iRowid,        /* Memory cell that contains the rowid to delete */
55040   int count          /* Increment the row change counter */
55041 ){
55042   int addr;
55043   Vdbe *v;
55044
55045   v = pParse->pVdbe;
55046   addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
55047   sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
55048   sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
55049   if( count ){
55050     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
55051   }
55052   sqlite3VdbeJumpHere(v, addr);
55053 }
55054
55055 /*
55056 ** This routine generates VDBE code that causes the deletion of all
55057 ** index entries associated with a single row of a single table.
55058 **
55059 ** The VDBE must be in a particular state when this routine is called.
55060 ** These are the requirements:
55061 **
55062 **   1.  A read/write cursor pointing to pTab, the table containing the row
55063 **       to be deleted, must be opened as cursor number "iCur".
55064 **
55065 **   2.  Read/write cursors for all indices of pTab must be open as
55066 **       cursor number iCur+i for the i-th index.
55067 **
55068 **   3.  The "iCur" cursor must be pointing to the row that is to be
55069 **       deleted.
55070 */
55071 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
55072   Parse *pParse,     /* Parsing and code generating context */
55073   Table *pTab,       /* Table containing the row to be deleted */
55074   int iCur,          /* Cursor number for the table */
55075   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
55076 ){
55077   int i;
55078   Index *pIdx;
55079   int r1;
55080
55081   r1 = sqlite3GetTempReg(pParse);
55082   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
55083     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
55084     sqlite3GenerateIndexKey(pParse, pIdx, iCur, r1);
55085     sqlite3VdbeAddOp2(pParse->pVdbe, OP_IdxDelete, iCur+i, r1);
55086   }
55087   sqlite3ReleaseTempReg(pParse, r1);
55088 }
55089
55090 /*
55091 ** Generate code that will assemble an index key and put it on the top
55092 ** of the tack.  The key with be for index pIdx which is an index on pTab.
55093 ** iCur is the index of a cursor open on the pTab table and pointing to
55094 ** the entry that needs indexing.
55095 **
55096 ** Return a register number which is the first in a block of
55097 ** registers that holds the elements of the index key.  The
55098 ** block of registers has already been deallocated by the time
55099 ** this routine returns.
55100 */
55101 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
55102   Parse *pParse,     /* Parsing context */
55103   Index *pIdx,       /* The index for which to generate a key */
55104   int iCur,          /* Cursor number for the pIdx->pTable table */
55105   int regOut         /* Write the new index key to this register */
55106 ){
55107   Vdbe *v = pParse->pVdbe;
55108   int j;
55109   Table *pTab = pIdx->pTable;
55110   int regBase;
55111   int nCol;
55112
55113   nCol = pIdx->nColumn;
55114   regBase = sqlite3GetTempRange(pParse, nCol+1);
55115   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
55116   for(j=0; j<nCol; j++){
55117     int idx = pIdx->aiColumn[j];
55118     if( idx==pTab->iPKey ){
55119       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
55120     }else{
55121       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
55122       sqlite3ColumnDefault(v, pTab, idx);
55123     }
55124   }
55125   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
55126   sqlite3IndexAffinityStr(v, pIdx);
55127   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
55128   return regBase;
55129 }
55130
55131 /************** End of delete.c **********************************************/
55132 /************** Begin file func.c ********************************************/
55133 /*
55134 ** 2002 February 23
55135 **
55136 ** The author disclaims copyright to this source code.  In place of
55137 ** a legal notice, here is a blessing:
55138 **
55139 **    May you do good and not evil.
55140 **    May you find forgiveness for yourself and forgive others.
55141 **    May you share freely, never taking more than you give.
55142 **
55143 *************************************************************************
55144 ** This file contains the C functions that implement various SQL
55145 ** functions of SQLite.  
55146 **
55147 ** There is only one exported symbol in this file - the function
55148 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
55149 ** All other code has file scope.
55150 **
55151 ** $Id: func.c,v 1.186 2008/03/06 09:58:50 mlcreech Exp $
55152 */
55153
55154
55155 /*
55156 ** Return the collating function associated with a function.
55157 */
55158 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
55159   return context->pColl;
55160 }
55161
55162 /*
55163 ** Implementation of the non-aggregate min() and max() functions
55164 */
55165 static void minmaxFunc(
55166   sqlite3_context *context,
55167   int argc,
55168   sqlite3_value **argv
55169 ){
55170   int i;
55171   int mask;    /* 0 for min() or 0xffffffff for max() */
55172   int iBest;
55173   CollSeq *pColl;
55174
55175   if( argc==0 ) return;
55176   mask = sqlite3_user_data(context)==0 ? 0 : -1;
55177   pColl = sqlite3GetFuncCollSeq(context);
55178   assert( pColl );
55179   assert( mask==-1 || mask==0 );
55180   iBest = 0;
55181   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
55182   for(i=1; i<argc; i++){
55183     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
55184     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
55185       iBest = i;
55186     }
55187   }
55188   sqlite3_result_value(context, argv[iBest]);
55189 }
55190
55191 /*
55192 ** Return the type of the argument.
55193 */
55194 static void typeofFunc(
55195   sqlite3_context *context,
55196   int argc,
55197   sqlite3_value **argv
55198 ){
55199   const char *z = 0;
55200   switch( sqlite3_value_type(argv[0]) ){
55201     case SQLITE_NULL:    z = "null";    break;
55202     case SQLITE_INTEGER: z = "integer"; break;
55203     case SQLITE_TEXT:    z = "text";    break;
55204     case SQLITE_FLOAT:   z = "real";    break;
55205     case SQLITE_BLOB:    z = "blob";    break;
55206   }
55207   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
55208 }
55209
55210
55211 /*
55212 ** Implementation of the length() function
55213 */
55214 static void lengthFunc(
55215   sqlite3_context *context,
55216   int argc,
55217   sqlite3_value **argv
55218 ){
55219   int len;
55220
55221   assert( argc==1 );
55222   switch( sqlite3_value_type(argv[0]) ){
55223     case SQLITE_BLOB:
55224     case SQLITE_INTEGER:
55225     case SQLITE_FLOAT: {
55226       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
55227       break;
55228     }
55229     case SQLITE_TEXT: {
55230       const unsigned char *z = sqlite3_value_text(argv[0]);
55231       if( z==0 ) return;
55232       len = 0;
55233       while( *z ){
55234         len++;
55235         SQLITE_SKIP_UTF8(z);
55236       }
55237       sqlite3_result_int(context, len);
55238       break;
55239     }
55240     default: {
55241       sqlite3_result_null(context);
55242       break;
55243     }
55244   }
55245 }
55246
55247 /*
55248 ** Implementation of the abs() function
55249 */
55250 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
55251   assert( argc==1 );
55252   switch( sqlite3_value_type(argv[0]) ){
55253     case SQLITE_INTEGER: {
55254       i64 iVal = sqlite3_value_int64(argv[0]);
55255       if( iVal<0 ){
55256         if( (iVal<<1)==0 ){
55257           sqlite3_result_error(context, "integer overflow", -1);
55258           return;
55259         }
55260         iVal = -iVal;
55261       } 
55262       sqlite3_result_int64(context, iVal);
55263       break;
55264     }
55265     case SQLITE_NULL: {
55266       sqlite3_result_null(context);
55267       break;
55268     }
55269     default: {
55270       double rVal = sqlite3_value_double(argv[0]);
55271       if( rVal<0 ) rVal = -rVal;
55272       sqlite3_result_double(context, rVal);
55273       break;
55274     }
55275   }
55276 }
55277
55278 /*
55279 ** Implementation of the substr() function.
55280 **
55281 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
55282 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
55283 ** of x.  If x is text, then we actually count UTF-8 characters.
55284 ** If x is a blob, then we count bytes.
55285 **
55286 ** If p1 is negative, then we begin abs(p1) from the end of x[].
55287 */
55288 static void substrFunc(
55289   sqlite3_context *context,
55290   int argc,
55291   sqlite3_value **argv
55292 ){
55293   const unsigned char *z;
55294   const unsigned char *z2;
55295   int len;
55296   int p0type;
55297   i64 p1, p2;
55298
55299   assert( argc==3 || argc==2 );
55300   p0type = sqlite3_value_type(argv[0]);
55301   if( p0type==SQLITE_BLOB ){
55302     len = sqlite3_value_bytes(argv[0]);
55303     z = sqlite3_value_blob(argv[0]);
55304     if( z==0 ) return;
55305     assert( len==sqlite3_value_bytes(argv[0]) );
55306   }else{
55307     z = sqlite3_value_text(argv[0]);
55308     if( z==0 ) return;
55309     len = 0;
55310     for(z2=z; *z2; len++){
55311       SQLITE_SKIP_UTF8(z2);
55312     }
55313   }
55314   p1 = sqlite3_value_int(argv[1]);
55315   if( argc==3 ){
55316     p2 = sqlite3_value_int(argv[2]);
55317   }else{
55318     p2 = SQLITE_MAX_LENGTH;
55319   }
55320   if( p1<0 ){
55321     p1 += len;
55322     if( p1<0 ){
55323       p2 += p1;
55324       p1 = 0;
55325     }
55326   }else if( p1>0 ){
55327     p1--;
55328   }
55329   if( p1+p2>len ){
55330     p2 = len-p1;
55331   }
55332   if( p0type!=SQLITE_BLOB ){
55333     while( *z && p1 ){
55334       SQLITE_SKIP_UTF8(z);
55335       p1--;
55336     }
55337     for(z2=z; *z2 && p2; p2--){
55338       SQLITE_SKIP_UTF8(z2);
55339     }
55340     sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
55341   }else{
55342     if( p2<0 ) p2 = 0;
55343     sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
55344   }
55345 }
55346
55347 /*
55348 ** Implementation of the round() function
55349 */
55350 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
55351   int n = 0;
55352   double r;
55353   char zBuf[500];  /* larger than the %f representation of the largest double */
55354   assert( argc==1 || argc==2 );
55355   if( argc==2 ){
55356     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
55357     n = sqlite3_value_int(argv[1]);
55358     if( n>30 ) n = 30;
55359     if( n<0 ) n = 0;
55360   }
55361   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
55362   r = sqlite3_value_double(argv[0]);
55363   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
55364   sqlite3AtoF(zBuf, &r);
55365   sqlite3_result_double(context, r);
55366 }
55367
55368 /*
55369 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
55370 ** allocation fails, call sqlite3_result_error_nomem() to notify
55371 ** the database handle that malloc() has failed.
55372 */
55373 static void *contextMalloc(sqlite3_context *context, int nByte){
55374   char *z = sqlite3_malloc(nByte);
55375   if( !z && nByte>0 ){
55376     sqlite3_result_error_nomem(context);
55377   }
55378   return z;
55379 }
55380
55381 /*
55382 ** Implementation of the upper() and lower() SQL functions.
55383 */
55384 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
55385   char *z1;
55386   const char *z2;
55387   int i, n;
55388   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
55389   z2 = (char*)sqlite3_value_text(argv[0]);
55390   n = sqlite3_value_bytes(argv[0]);
55391   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
55392   assert( z2==(char*)sqlite3_value_text(argv[0]) );
55393   if( z2 ){
55394     z1 = contextMalloc(context, n+1);
55395     if( z1 ){
55396       memcpy(z1, z2, n+1);
55397       for(i=0; z1[i]; i++){
55398         z1[i] = toupper(z1[i]);
55399       }
55400       sqlite3_result_text(context, z1, -1, sqlite3_free);
55401     }
55402   }
55403 }
55404 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
55405   char *z1;
55406   const char *z2;
55407   int i, n;
55408   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
55409   z2 = (char*)sqlite3_value_text(argv[0]);
55410   n = sqlite3_value_bytes(argv[0]);
55411   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
55412   assert( z2==(char*)sqlite3_value_text(argv[0]) );
55413   if( z2 ){
55414     z1 = contextMalloc(context, n+1);
55415     if( z1 ){
55416       memcpy(z1, z2, n+1);
55417       for(i=0; z1[i]; i++){
55418         z1[i] = tolower(z1[i]);
55419       }
55420       sqlite3_result_text(context, z1, -1, sqlite3_free);
55421     }
55422   }
55423 }
55424
55425 /*
55426 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
55427 ** All three do the same thing.  They return the first non-NULL
55428 ** argument.
55429 */
55430 static void ifnullFunc(
55431   sqlite3_context *context,
55432   int argc,
55433   sqlite3_value **argv
55434 ){
55435   int i;
55436   for(i=0; i<argc; i++){
55437     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
55438       sqlite3_result_value(context, argv[i]);
55439       break;
55440     }
55441   }
55442 }
55443
55444 /*
55445 ** Implementation of random().  Return a random integer.  
55446 */
55447 static void randomFunc(
55448   sqlite3_context *context,
55449   int argc,
55450   sqlite3_value **argv
55451 ){
55452   sqlite_int64 r;
55453   sqlite3Randomness(sizeof(r), &r);
55454   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
55455                           /* can always do abs() of the result */
55456   sqlite3_result_int64(context, r);
55457 }
55458
55459 /*
55460 ** Implementation of randomblob(N).  Return a random blob
55461 ** that is N bytes long.
55462 */
55463 static void randomBlob(
55464   sqlite3_context *context,
55465   int argc,
55466   sqlite3_value **argv
55467 ){
55468   int n;
55469   unsigned char *p;
55470   assert( argc==1 );
55471   n = sqlite3_value_int(argv[0]);
55472   if( n<1 ){
55473     n = 1;
55474   }
55475   if( n>SQLITE_MAX_LENGTH ){
55476     sqlite3_result_error_toobig(context);
55477     return;
55478   }
55479   p = contextMalloc(context, n);
55480   if( p ){
55481     sqlite3Randomness(n, p);
55482     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
55483   }
55484 }
55485
55486 /*
55487 ** Implementation of the last_insert_rowid() SQL function.  The return
55488 ** value is the same as the sqlite3_last_insert_rowid() API function.
55489 */
55490 static void last_insert_rowid(
55491   sqlite3_context *context, 
55492   int arg, 
55493   sqlite3_value **argv
55494 ){
55495   sqlite3 *db = sqlite3_user_data(context);
55496   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
55497 }
55498
55499 /*
55500 ** Implementation of the changes() SQL function.  The return value is the
55501 ** same as the sqlite3_changes() API function.
55502 */
55503 static void changes(
55504   sqlite3_context *context,
55505   int arg,
55506   sqlite3_value **argv
55507 ){
55508   sqlite3 *db = sqlite3_user_data(context);
55509   sqlite3_result_int(context, sqlite3_changes(db));
55510 }
55511
55512 /*
55513 ** Implementation of the total_changes() SQL function.  The return value is
55514 ** the same as the sqlite3_total_changes() API function.
55515 */
55516 static void total_changes(
55517   sqlite3_context *context,
55518   int arg,
55519   sqlite3_value **argv
55520 ){
55521   sqlite3 *db = sqlite3_user_data(context);
55522   sqlite3_result_int(context, sqlite3_total_changes(db));
55523 }
55524
55525 /*
55526 ** A structure defining how to do GLOB-style comparisons.
55527 */
55528 struct compareInfo {
55529   u8 matchAll;
55530   u8 matchOne;
55531   u8 matchSet;
55532   u8 noCase;
55533 };
55534
55535 /*
55536 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
55537 ** character is exactly one byte in size.  Also, all characters are
55538 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
55539 ** whereas only characters less than 0x80 do in ASCII.
55540 */
55541 #if defined(SQLITE_EBCDIC)
55542 # define sqlite3Utf8Read(A,B,C)  (*(A++))
55543 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
55544 #else
55545 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
55546 #endif
55547
55548 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
55549 /* The correct SQL-92 behavior is for the LIKE operator to ignore
55550 ** case.  Thus  'a' LIKE 'A' would be true. */
55551 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
55552 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
55553 ** is case sensitive causing 'a' LIKE 'A' to be false */
55554 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
55555
55556 /*
55557 ** Compare two UTF-8 strings for equality where the first string can
55558 ** potentially be a "glob" expression.  Return true (1) if they
55559 ** are the same and false (0) if they are different.
55560 **
55561 ** Globbing rules:
55562 **
55563 **      '*'       Matches any sequence of zero or more characters.
55564 **
55565 **      '?'       Matches exactly one character.
55566 **
55567 **     [...]      Matches one character from the enclosed list of
55568 **                characters.
55569 **
55570 **     [^...]     Matches one character not in the enclosed list.
55571 **
55572 ** With the [...] and [^...] matching, a ']' character can be included
55573 ** in the list by making it the first character after '[' or '^'.  A
55574 ** range of characters can be specified using '-'.  Example:
55575 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
55576 ** it the last character in the list.
55577 **
55578 ** This routine is usually quick, but can be N**2 in the worst case.
55579 **
55580 ** Hints: to match '*' or '?', put them in "[]".  Like this:
55581 **
55582 **         abc[*]xyz        Matches "abc*xyz" only
55583 */
55584 static int patternCompare(
55585   const u8 *zPattern,              /* The glob pattern */
55586   const u8 *zString,               /* The string to compare against the glob */
55587   const struct compareInfo *pInfo, /* Information about how to do the compare */
55588   const int esc                    /* The escape character */
55589 ){
55590   int c, c2;
55591   int invert;
55592   int seen;
55593   u8 matchOne = pInfo->matchOne;
55594   u8 matchAll = pInfo->matchAll;
55595   u8 matchSet = pInfo->matchSet;
55596   u8 noCase = pInfo->noCase; 
55597   int prevEscape = 0;     /* True if the previous character was 'escape' */
55598
55599   while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
55600     if( !prevEscape && c==matchAll ){
55601       while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
55602                || c == matchOne ){
55603         if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
55604           return 0;
55605         }
55606       }
55607       if( c==0 ){
55608         return 1;
55609       }else if( c==esc ){
55610         c = sqlite3Utf8Read(zPattern, 0, &zPattern);
55611         if( c==0 ){
55612           return 0;
55613         }
55614       }else if( c==matchSet ){
55615         assert( esc==0 );         /* This is GLOB, not LIKE */
55616         assert( matchSet<0x80 );  /* '[' is a single-byte character */
55617         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
55618           SQLITE_SKIP_UTF8(zString);
55619         }
55620         return *zString!=0;
55621       }
55622       while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
55623         if( noCase ){
55624           GlogUpperToLower(c2);
55625           GlogUpperToLower(c);
55626           while( c2 != 0 && c2 != c ){
55627             c2 = sqlite3Utf8Read(zString, 0, &zString);
55628             GlogUpperToLower(c2);
55629           }
55630         }else{
55631           while( c2 != 0 && c2 != c ){
55632             c2 = sqlite3Utf8Read(zString, 0, &zString);
55633           }
55634         }
55635         if( c2==0 ) return 0;
55636         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
55637       }
55638       return 0;
55639     }else if( !prevEscape && c==matchOne ){
55640       if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
55641         return 0;
55642       }
55643     }else if( c==matchSet ){
55644       int prior_c = 0;
55645       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
55646       seen = 0;
55647       invert = 0;
55648       c = sqlite3Utf8Read(zString, 0, &zString);
55649       if( c==0 ) return 0;
55650       c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
55651       if( c2=='^' ){
55652         invert = 1;
55653         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
55654       }
55655       if( c2==']' ){
55656         if( c==']' ) seen = 1;
55657         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
55658       }
55659       while( c2 && c2!=']' ){
55660         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
55661           c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
55662           if( c>=prior_c && c<=c2 ) seen = 1;
55663           prior_c = 0;
55664         }else{
55665           if( c==c2 ){
55666             seen = 1;
55667           }
55668           prior_c = c2;
55669         }
55670         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
55671       }
55672       if( c2==0 || (seen ^ invert)==0 ){
55673         return 0;
55674       }
55675     }else if( esc==c && !prevEscape ){
55676       prevEscape = 1;
55677     }else{
55678       c2 = sqlite3Utf8Read(zString, 0, &zString);
55679       if( noCase ){
55680         GlogUpperToLower(c);
55681         GlogUpperToLower(c2);
55682       }
55683       if( c!=c2 ){
55684         return 0;
55685       }
55686       prevEscape = 0;
55687     }
55688   }
55689   return *zString==0;
55690 }
55691
55692 /*
55693 ** Count the number of times that the LIKE operator (or GLOB which is
55694 ** just a variation of LIKE) gets called.  This is used for testing
55695 ** only.
55696 */
55697 #ifdef SQLITE_TEST
55698 SQLITE_API int sqlite3_like_count = 0;
55699 #endif
55700
55701
55702 /*
55703 ** Implementation of the like() SQL function.  This function implements
55704 ** the build-in LIKE operator.  The first argument to the function is the
55705 ** pattern and the second argument is the string.  So, the SQL statements:
55706 **
55707 **       A LIKE B
55708 **
55709 ** is implemented as like(B,A).
55710 **
55711 ** This same function (with a different compareInfo structure) computes
55712 ** the GLOB operator.
55713 */
55714 static void likeFunc(
55715   sqlite3_context *context, 
55716   int argc, 
55717   sqlite3_value **argv
55718 ){
55719   const unsigned char *zA, *zB;
55720   int escape = 0;
55721
55722   zB = sqlite3_value_text(argv[0]);
55723   zA = sqlite3_value_text(argv[1]);
55724
55725   /* Limit the length of the LIKE or GLOB pattern to avoid problems
55726   ** of deep recursion and N*N behavior in patternCompare().
55727   */
55728   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
55729     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
55730     return;
55731   }
55732   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
55733
55734   if( argc==3 ){
55735     /* The escape character string must consist of a single UTF-8 character.
55736     ** Otherwise, return an error.
55737     */
55738     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
55739     if( zEsc==0 ) return;
55740     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
55741       sqlite3_result_error(context, 
55742           "ESCAPE expression must be a single character", -1);
55743       return;
55744     }
55745     escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
55746   }
55747   if( zA && zB ){
55748     struct compareInfo *pInfo = sqlite3_user_data(context);
55749 #ifdef SQLITE_TEST
55750     sqlite3_like_count++;
55751 #endif
55752     
55753     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
55754   }
55755 }
55756
55757 /*
55758 ** Implementation of the NULLIF(x,y) function.  The result is the first
55759 ** argument if the arguments are different.  The result is NULL if the
55760 ** arguments are equal to each other.
55761 */
55762 static void nullifFunc(
55763   sqlite3_context *context,
55764   int argc,
55765   sqlite3_value **argv
55766 ){
55767   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
55768   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
55769     sqlite3_result_value(context, argv[0]);
55770   }
55771 }
55772
55773 /*
55774 ** Implementation of the VERSION(*) function.  The result is the version
55775 ** of the SQLite library that is running.
55776 */
55777 static void versionFunc(
55778   sqlite3_context *context,
55779   int argc,
55780   sqlite3_value **argv
55781 ){
55782   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
55783 }
55784
55785 /* Array for converting from half-bytes (nybbles) into ASCII hex
55786 ** digits. */
55787 static const char hexdigits[] = {
55788   '0', '1', '2', '3', '4', '5', '6', '7',
55789   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
55790 };
55791
55792 /*
55793 ** EXPERIMENTAL - This is not an official function.  The interface may
55794 ** change.  This function may disappear.  Do not write code that depends
55795 ** on this function.
55796 **
55797 ** Implementation of the QUOTE() function.  This function takes a single
55798 ** argument.  If the argument is numeric, the return value is the same as
55799 ** the argument.  If the argument is NULL, the return value is the string
55800 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
55801 ** single-quote escapes.
55802 */
55803 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
55804   if( argc<1 ) return;
55805   switch( sqlite3_value_type(argv[0]) ){
55806     case SQLITE_NULL: {
55807       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
55808       break;
55809     }
55810     case SQLITE_INTEGER:
55811     case SQLITE_FLOAT: {
55812       sqlite3_result_value(context, argv[0]);
55813       break;
55814     }
55815     case SQLITE_BLOB: {
55816       char *zText = 0;
55817       char const *zBlob = sqlite3_value_blob(argv[0]);
55818       int nBlob = sqlite3_value_bytes(argv[0]);
55819       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
55820
55821       if( 2*nBlob+4>SQLITE_MAX_LENGTH ){
55822         sqlite3_result_error_toobig(context);
55823         return;
55824       }
55825       zText = (char *)contextMalloc(context, (2*nBlob)+4); 
55826       if( zText ){
55827         int i;
55828         for(i=0; i<nBlob; i++){
55829           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
55830           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
55831         }
55832         zText[(nBlob*2)+2] = '\'';
55833         zText[(nBlob*2)+3] = '\0';
55834         zText[0] = 'X';
55835         zText[1] = '\'';
55836         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
55837         sqlite3_free(zText);
55838       }
55839       break;
55840     }
55841     case SQLITE_TEXT: {
55842       int i,j;
55843       u64 n;
55844       const unsigned char *zArg = sqlite3_value_text(argv[0]);
55845       char *z;
55846
55847       if( zArg==0 ) return;
55848       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
55849       if( i+n+3>SQLITE_MAX_LENGTH ){
55850         sqlite3_result_error_toobig(context);
55851         return;
55852       }
55853       z = contextMalloc(context, i+n+3);
55854       if( z ){
55855         z[0] = '\'';
55856         for(i=0, j=1; zArg[i]; i++){
55857           z[j++] = zArg[i];
55858           if( zArg[i]=='\'' ){
55859             z[j++] = '\'';
55860           }
55861         }
55862         z[j++] = '\'';
55863         z[j] = 0;
55864         sqlite3_result_text(context, z, j, sqlite3_free);
55865       }
55866     }
55867   }
55868 }
55869
55870 /*
55871 ** The hex() function.  Interpret the argument as a blob.  Return
55872 ** a hexadecimal rendering as text.
55873 */
55874 static void hexFunc(
55875   sqlite3_context *context,
55876   int argc,
55877   sqlite3_value **argv
55878 ){
55879   int i, n;
55880   const unsigned char *pBlob;
55881   char *zHex, *z;
55882   assert( argc==1 );
55883   pBlob = sqlite3_value_blob(argv[0]);
55884   n = sqlite3_value_bytes(argv[0]);
55885   if( n*2+1>SQLITE_MAX_LENGTH ){
55886     sqlite3_result_error_toobig(context);
55887     return;
55888   }
55889   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
55890   z = zHex = contextMalloc(context, n*2 + 1);
55891   if( zHex ){
55892     for(i=0; i<n; i++, pBlob++){
55893       unsigned char c = *pBlob;
55894       *(z++) = hexdigits[(c>>4)&0xf];
55895       *(z++) = hexdigits[c&0xf];
55896     }
55897     *z = 0;
55898     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
55899   }
55900 }
55901
55902 /*
55903 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
55904 */
55905 static void zeroblobFunc(
55906   sqlite3_context *context,
55907   int argc,
55908   sqlite3_value **argv
55909 ){
55910   i64 n;
55911   assert( argc==1 );
55912   n = sqlite3_value_int64(argv[0]);
55913   if( n>SQLITE_MAX_LENGTH ){
55914     sqlite3_result_error_toobig(context);
55915   }else{
55916     sqlite3_result_zeroblob(context, n);
55917   }
55918 }
55919
55920 /*
55921 ** The replace() function.  Three arguments are all strings: call
55922 ** them A, B, and C. The result is also a string which is derived
55923 ** from A by replacing every occurance of B with C.  The match
55924 ** must be exact.  Collating sequences are not used.
55925 */
55926 static void replaceFunc(
55927   sqlite3_context *context,
55928   int argc,
55929   sqlite3_value **argv
55930 ){
55931   const unsigned char *zStr;        /* The input string A */
55932   const unsigned char *zPattern;    /* The pattern string B */
55933   const unsigned char *zRep;        /* The replacement string C */
55934   unsigned char *zOut;              /* The output */
55935   int nStr;                /* Size of zStr */
55936   int nPattern;            /* Size of zPattern */
55937   int nRep;                /* Size of zRep */
55938   i64 nOut;                /* Maximum size of zOut */
55939   int loopLimit;           /* Last zStr[] that might match zPattern[] */
55940   int i, j;                /* Loop counters */
55941
55942   assert( argc==3 );
55943   zStr = sqlite3_value_text(argv[0]);
55944   if( zStr==0 ) return;
55945   nStr = sqlite3_value_bytes(argv[0]);
55946   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
55947   zPattern = sqlite3_value_text(argv[1]);
55948   if( zPattern==0 || zPattern[0]==0 ) return;
55949   nPattern = sqlite3_value_bytes(argv[1]);
55950   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
55951   zRep = sqlite3_value_text(argv[2]);
55952   if( zRep==0 ) return;
55953   nRep = sqlite3_value_bytes(argv[2]);
55954   assert( zRep==sqlite3_value_text(argv[2]) );
55955   nOut = nStr + 1;
55956   assert( nOut<SQLITE_MAX_LENGTH );
55957   zOut = contextMalloc(context, (int)nOut);
55958   if( zOut==0 ){
55959     return;
55960   }
55961   loopLimit = nStr - nPattern;  
55962   for(i=j=0; i<=loopLimit; i++){
55963     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
55964       zOut[j++] = zStr[i];
55965     }else{
55966       u8 *zOld;
55967       nOut += nRep - nPattern;
55968       if( nOut>=SQLITE_MAX_LENGTH ){
55969         sqlite3_result_error_toobig(context);
55970         sqlite3_free(zOut);
55971         return;
55972       }
55973       zOld = zOut;
55974       zOut = sqlite3_realloc(zOut, (int)nOut);
55975       if( zOut==0 ){
55976         sqlite3_result_error_nomem(context);
55977         sqlite3_free(zOld);
55978         return;
55979       }
55980       memcpy(&zOut[j], zRep, nRep);
55981       j += nRep;
55982       i += nPattern-1;
55983     }
55984   }
55985   assert( j+nStr-i+1==nOut );
55986   memcpy(&zOut[j], &zStr[i], nStr-i);
55987   j += nStr - i;
55988   assert( j<=nOut );
55989   zOut[j] = 0;
55990   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
55991 }
55992
55993 /*
55994 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
55995 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
55996 */
55997 static void trimFunc(
55998   sqlite3_context *context,
55999   int argc,
56000   sqlite3_value **argv
56001 ){
56002   const unsigned char *zIn;         /* Input string */
56003   const unsigned char *zCharSet;    /* Set of characters to trim */
56004   int nIn;                          /* Number of bytes in input */
56005   sqlite3_intptr_t flags;           /* 1: trimleft  2: trimright  3: trim */
56006   int i;                            /* Loop counter */
56007   unsigned char *aLen;              /* Length of each character in zCharSet */
56008   unsigned char **azChar;           /* Individual characters in zCharSet */
56009   int nChar;                        /* Number of characters in zCharSet */
56010
56011   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
56012     return;
56013   }
56014   zIn = sqlite3_value_text(argv[0]);
56015   if( zIn==0 ) return;
56016   nIn = sqlite3_value_bytes(argv[0]);
56017   assert( zIn==sqlite3_value_text(argv[0]) );
56018   if( argc==1 ){
56019     static const unsigned char lenOne[] = { 1 };
56020     static const unsigned char *azOne[] = { (u8*)" " };
56021     nChar = 1;
56022     aLen = (u8*)lenOne;
56023     azChar = (unsigned char **)azOne;
56024     zCharSet = 0;
56025   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
56026     return;
56027   }else{
56028     const unsigned char *z;
56029     for(z=zCharSet, nChar=0; *z; nChar++){
56030       SQLITE_SKIP_UTF8(z);
56031     }
56032     if( nChar>0 ){
56033       azChar = contextMalloc(context, nChar*(sizeof(char*)+1));
56034       if( azChar==0 ){
56035         return;
56036       }
56037       aLen = (unsigned char*)&azChar[nChar];
56038       for(z=zCharSet, nChar=0; *z; nChar++){
56039         azChar[nChar] = (unsigned char *)z;
56040         SQLITE_SKIP_UTF8(z);
56041         aLen[nChar] = z - azChar[nChar];
56042       }
56043     }
56044   }
56045   if( nChar>0 ){
56046     flags = (sqlite3_intptr_t)sqlite3_user_data(context);
56047     if( flags & 1 ){
56048       while( nIn>0 ){
56049         int len;
56050         for(i=0; i<nChar; i++){
56051           len = aLen[i];
56052           if( memcmp(zIn, azChar[i], len)==0 ) break;
56053         }
56054         if( i>=nChar ) break;
56055         zIn += len;
56056         nIn -= len;
56057       }
56058     }
56059     if( flags & 2 ){
56060       while( nIn>0 ){
56061         int len;
56062         for(i=0; i<nChar; i++){
56063           len = aLen[i];
56064           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
56065         }
56066         if( i>=nChar ) break;
56067         nIn -= len;
56068       }
56069     }
56070     if( zCharSet ){
56071       sqlite3_free(azChar);
56072     }
56073   }
56074   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
56075 }
56076
56077 #ifdef SQLITE_SOUNDEX
56078 /*
56079 ** Compute the soundex encoding of a word.
56080 */
56081 static void soundexFunc(
56082   sqlite3_context *context,
56083   int argc,
56084   sqlite3_value **argv
56085 ){
56086   char zResult[8];
56087   const u8 *zIn;
56088   int i, j;
56089   static const unsigned char iCode[] = {
56090     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
56091     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
56092     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
56093     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
56094     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
56095     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
56096     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
56097     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
56098   };
56099   assert( argc==1 );
56100   zIn = (u8*)sqlite3_value_text(argv[0]);
56101   if( zIn==0 ) zIn = (u8*)"";
56102   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
56103   if( zIn[i] ){
56104     u8 prevcode = iCode[zIn[i]&0x7f];
56105     zResult[0] = toupper(zIn[i]);
56106     for(j=1; j<4 && zIn[i]; i++){
56107       int code = iCode[zIn[i]&0x7f];
56108       if( code>0 ){
56109         if( code!=prevcode ){
56110           prevcode = code;
56111           zResult[j++] = code + '0';
56112         }
56113       }else{
56114         prevcode = 0;
56115       }
56116     }
56117     while( j<4 ){
56118       zResult[j++] = '0';
56119     }
56120     zResult[j] = 0;
56121     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
56122   }else{
56123     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
56124   }
56125 }
56126 #endif
56127
56128 #ifndef SQLITE_OMIT_LOAD_EXTENSION
56129 /*
56130 ** A function that loads a shared-library extension then returns NULL.
56131 */
56132 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
56133   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
56134   const char *zProc;
56135   sqlite3 *db = sqlite3_user_data(context);
56136   char *zErrMsg = 0;
56137
56138   if( argc==2 ){
56139     zProc = (const char *)sqlite3_value_text(argv[1]);
56140   }else{
56141     zProc = 0;
56142   }
56143   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
56144     sqlite3_result_error(context, zErrMsg, -1);
56145     sqlite3_free(zErrMsg);
56146   }
56147 }
56148 #endif
56149
56150 #ifdef SQLITE_TEST
56151 /*
56152 ** This function generates a string of random characters.  Used for
56153 ** generating test data.
56154 */
56155 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
56156   static const unsigned char zSrc[] = 
56157      "abcdefghijklmnopqrstuvwxyz"
56158      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
56159      "0123456789"
56160      ".-!,:*^+=_|?/<> ";
56161   int iMin, iMax, n, r, i;
56162   unsigned char zBuf[1000];
56163
56164   /* It used to be possible to call randstr() with any number of arguments,
56165   ** but now it is registered with SQLite as requiring exactly 2.
56166   */
56167   assert(argc==2);
56168
56169   iMin = sqlite3_value_int(argv[0]);
56170   if( iMin<0 ) iMin = 0;
56171   if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
56172   iMax = sqlite3_value_int(argv[1]);
56173   if( iMax<iMin ) iMax = iMin;
56174   if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
56175   n = iMin;
56176   if( iMax>iMin ){
56177     sqlite3Randomness(sizeof(r), &r);
56178     r &= 0x7fffffff;
56179     n += r%(iMax + 1 - iMin);
56180   }
56181   assert( n<sizeof(zBuf) );
56182   sqlite3Randomness(n, zBuf);
56183   for(i=0; i<n; i++){
56184     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
56185   }
56186   zBuf[n] = 0;
56187   sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
56188 }
56189 #endif /* SQLITE_TEST */
56190
56191 #ifdef SQLITE_TEST
56192 /*
56193 ** The following two SQL functions are used to test returning a text
56194 ** result with a destructor. Function 'test_destructor' takes one argument
56195 ** and returns the same argument interpreted as TEXT. A destructor is
56196 ** passed with the sqlite3_result_text() call.
56197 **
56198 ** SQL function 'test_destructor_count' returns the number of outstanding 
56199 ** allocations made by 'test_destructor';
56200 **
56201 ** WARNING: Not threadsafe.
56202 */
56203 static int test_destructor_count_var = 0;
56204 static void destructor(void *p){
56205   char *zVal = (char *)p;
56206   assert(zVal);
56207   zVal--;
56208   sqlite3_free(zVal);
56209   test_destructor_count_var--;
56210 }
56211 static void test_destructor(
56212   sqlite3_context *pCtx, 
56213   int nArg,
56214   sqlite3_value **argv
56215 ){
56216   char *zVal;
56217   int len;
56218   sqlite3 *db = sqlite3_user_data(pCtx);
56219  
56220   test_destructor_count_var++;
56221   assert( nArg==1 );
56222   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
56223   len = sqlite3ValueBytes(argv[0], ENC(db)); 
56224   zVal = contextMalloc(pCtx, len+3);
56225   if( !zVal ){
56226     return;
56227   }
56228   zVal[len+1] = 0;
56229   zVal[len+2] = 0;
56230   zVal++;
56231   memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
56232   if( ENC(db)==SQLITE_UTF8 ){
56233     sqlite3_result_text(pCtx, zVal, -1, destructor);
56234 #ifndef SQLITE_OMIT_UTF16
56235   }else if( ENC(db)==SQLITE_UTF16LE ){
56236     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
56237   }else{
56238     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
56239 #endif /* SQLITE_OMIT_UTF16 */
56240   }
56241 }
56242 static void test_destructor_count(
56243   sqlite3_context *pCtx, 
56244   int nArg,
56245   sqlite3_value **argv
56246 ){
56247   sqlite3_result_int(pCtx, test_destructor_count_var);
56248 }
56249 #endif /* SQLITE_TEST */
56250
56251 #ifdef SQLITE_TEST
56252 /*
56253 ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
56254 ** interface.
56255 **
56256 ** The test_auxdata() SQL function attempts to register each of its arguments
56257 ** as auxiliary data.  If there are no prior registrations of aux data for
56258 ** that argument (meaning the argument is not a constant or this is its first
56259 ** call) then the result for that argument is 0.  If there is a prior
56260 ** registration, the result for that argument is 1.  The overall result
56261 ** is the individual argument results separated by spaces.
56262 */
56263 static void free_test_auxdata(void *p) {sqlite3_free(p);}
56264 static void test_auxdata(
56265   sqlite3_context *pCtx, 
56266   int nArg,
56267   sqlite3_value **argv
56268 ){
56269   int i;
56270   char *zRet = contextMalloc(pCtx, nArg*2);
56271   if( !zRet ) return;
56272   memset(zRet, 0, nArg*2);
56273   for(i=0; i<nArg; i++){
56274     char const *z = (char*)sqlite3_value_text(argv[i]);
56275     if( z ){
56276       int n;
56277       char *zAux = sqlite3_get_auxdata(pCtx, i);
56278       if( zAux ){
56279         zRet[i*2] = '1';
56280         assert( strcmp(zAux,z)==0 );
56281       }else {
56282         zRet[i*2] = '0';
56283       }
56284       n = strlen(z) + 1;
56285       zAux = contextMalloc(pCtx, n);
56286       if( zAux ){
56287         memcpy(zAux, z, n);
56288         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
56289       }
56290       zRet[i*2+1] = ' ';
56291     }
56292   }
56293   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
56294 }
56295 #endif /* SQLITE_TEST */
56296
56297 #ifdef SQLITE_TEST
56298 /*
56299 ** A function to test error reporting from user functions. This function
56300 ** returns a copy of its first argument as an error.
56301 */
56302 static void test_error(
56303   sqlite3_context *pCtx, 
56304   int nArg,
56305   sqlite3_value **argv
56306 ){
56307   sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
56308 }
56309 #endif /* SQLITE_TEST */
56310
56311 /*
56312 ** An instance of the following structure holds the context of a
56313 ** sum() or avg() aggregate computation.
56314 */
56315 typedef struct SumCtx SumCtx;
56316 struct SumCtx {
56317   double rSum;      /* Floating point sum */
56318   i64 iSum;         /* Integer sum */   
56319   i64 cnt;          /* Number of elements summed */
56320   u8 overflow;      /* True if integer overflow seen */
56321   u8 approx;        /* True if non-integer value was input to the sum */
56322 };
56323
56324 /*
56325 ** Routines used to compute the sum, average, and total.
56326 **
56327 ** The SUM() function follows the (broken) SQL standard which means
56328 ** that it returns NULL if it sums over no inputs.  TOTAL returns
56329 ** 0.0 in that case.  In addition, TOTAL always returns a float where
56330 ** SUM might return an integer if it never encounters a floating point
56331 ** value.  TOTAL never fails, but SUM might through an exception if
56332 ** it overflows an integer.
56333 */
56334 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
56335   SumCtx *p;
56336   int type;
56337   assert( argc==1 );
56338   p = sqlite3_aggregate_context(context, sizeof(*p));
56339   type = sqlite3_value_numeric_type(argv[0]);
56340   if( p && type!=SQLITE_NULL ){
56341     p->cnt++;
56342     if( type==SQLITE_INTEGER ){
56343       i64 v = sqlite3_value_int64(argv[0]);
56344       p->rSum += v;
56345       if( (p->approx|p->overflow)==0 ){
56346         i64 iNewSum = p->iSum + v;
56347         int s1 = p->iSum >> (sizeof(i64)*8-1);
56348         int s2 = v       >> (sizeof(i64)*8-1);
56349         int s3 = iNewSum >> (sizeof(i64)*8-1);
56350         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
56351         p->iSum = iNewSum;
56352       }
56353     }else{
56354       p->rSum += sqlite3_value_double(argv[0]);
56355       p->approx = 1;
56356     }
56357   }
56358 }
56359 static void sumFinalize(sqlite3_context *context){
56360   SumCtx *p;
56361   p = sqlite3_aggregate_context(context, 0);
56362   if( p && p->cnt>0 ){
56363     if( p->overflow ){
56364       sqlite3_result_error(context,"integer overflow",-1);
56365     }else if( p->approx ){
56366       sqlite3_result_double(context, p->rSum);
56367     }else{
56368       sqlite3_result_int64(context, p->iSum);
56369     }
56370   }
56371 }
56372 static void avgFinalize(sqlite3_context *context){
56373   SumCtx *p;
56374   p = sqlite3_aggregate_context(context, 0);
56375   if( p && p->cnt>0 ){
56376     sqlite3_result_double(context, p->rSum/(double)p->cnt);
56377   }
56378 }
56379 static void totalFinalize(sqlite3_context *context){
56380   SumCtx *p;
56381   p = sqlite3_aggregate_context(context, 0);
56382   sqlite3_result_double(context, p ? p->rSum : 0.0);
56383 }
56384
56385 /*
56386 ** The following structure keeps track of state information for the
56387 ** count() aggregate function.
56388 */
56389 typedef struct CountCtx CountCtx;
56390 struct CountCtx {
56391   i64 n;
56392 };
56393
56394 /*
56395 ** Routines to implement the count() aggregate function.
56396 */
56397 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
56398   CountCtx *p;
56399   p = sqlite3_aggregate_context(context, sizeof(*p));
56400   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
56401     p->n++;
56402   }
56403 }   
56404 static void countFinalize(sqlite3_context *context){
56405   CountCtx *p;
56406   p = sqlite3_aggregate_context(context, 0);
56407   sqlite3_result_int64(context, p ? p->n : 0);
56408 }
56409
56410 /*
56411 ** Routines to implement min() and max() aggregate functions.
56412 */
56413 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
56414   Mem *pArg  = (Mem *)argv[0];
56415   Mem *pBest;
56416
56417   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
56418   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
56419   if( !pBest ) return;
56420
56421   if( pBest->flags ){
56422     int max;
56423     int cmp;
56424     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
56425     /* This step function is used for both the min() and max() aggregates,
56426     ** the only difference between the two being that the sense of the
56427     ** comparison is inverted. For the max() aggregate, the
56428     ** sqlite3_user_data() function returns (void *)-1. For min() it
56429     ** returns (void *)db, where db is the sqlite3* database pointer.
56430     ** Therefore the next statement sets variable 'max' to 1 for the max()
56431     ** aggregate, or 0 for min().
56432     */
56433     max = sqlite3_user_data(context)!=0;
56434     cmp = sqlite3MemCompare(pBest, pArg, pColl);
56435     if( (max && cmp<0) || (!max && cmp>0) ){
56436       sqlite3VdbeMemCopy(pBest, pArg);
56437     }
56438   }else{
56439     sqlite3VdbeMemCopy(pBest, pArg);
56440   }
56441 }
56442 static void minMaxFinalize(sqlite3_context *context){
56443   sqlite3_value *pRes;
56444   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
56445   if( pRes ){
56446     if( pRes->flags ){
56447       sqlite3_result_value(context, pRes);
56448     }
56449     sqlite3VdbeMemRelease(pRes);
56450   }
56451 }
56452
56453 /*
56454 ** group_concat(EXPR, ?SEPARATOR?)
56455 */
56456 static void groupConcatStep(
56457   sqlite3_context *context,
56458   int argc,
56459   sqlite3_value **argv
56460 ){
56461   const char *zVal;
56462   StrAccum *pAccum;
56463   const char *zSep;
56464   int nVal, nSep;
56465   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
56466   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
56467
56468   if( pAccum ){
56469     pAccum->useMalloc = 1;
56470     if( pAccum->nChar ){
56471       if( argc==2 ){
56472         zSep = (char*)sqlite3_value_text(argv[1]);
56473         nSep = sqlite3_value_bytes(argv[1]);
56474       }else{
56475         zSep = ",";
56476         nSep = 1;
56477       }
56478       sqlite3StrAccumAppend(pAccum, zSep, nSep);
56479     }
56480     zVal = (char*)sqlite3_value_text(argv[0]);
56481     nVal = sqlite3_value_bytes(argv[0]);
56482     sqlite3StrAccumAppend(pAccum, zVal, nVal);
56483   }
56484 }
56485 static void groupConcatFinalize(sqlite3_context *context){
56486   StrAccum *pAccum;
56487   pAccum = sqlite3_aggregate_context(context, 0);
56488   if( pAccum ){
56489     if( pAccum->tooBig ){
56490       sqlite3_result_error_toobig(context);
56491     }else if( pAccum->mallocFailed ){
56492       sqlite3_result_error_nomem(context);
56493     }else{    
56494       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
56495                           sqlite3_free);
56496     }
56497   }
56498 }
56499
56500 /*
56501 ** This function registered all of the above C functions as SQL
56502 ** functions.  This should be the only routine in this file with
56503 ** external linkage.
56504 */
56505 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
56506   static const struct {
56507      char *zName;
56508      signed char nArg;
56509      u8 argType;           /* ff: db   1: 0, 2: 1, 3: 2,...  N:  N-1. */
56510      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
56511      u8 needCollSeq;
56512      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
56513   } aFuncs[] = {
56514     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
56515     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
56516     { "max",               -1, 1, SQLITE_UTF8,    1, minmaxFunc },
56517     { "max",                0, 1, SQLITE_UTF8,    1, 0          },
56518     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
56519     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
56520     { "substr",             2, 0, SQLITE_UTF8,    0, substrFunc },
56521     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
56522     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
56523     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
56524     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
56525     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
56526     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
56527     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
56528     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
56529     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
56530     { "hex",                1, 0, SQLITE_UTF8,    0, hexFunc    },
56531     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
56532     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
56533     { "randomblob",         1, 0, SQLITE_UTF8,    0, randomBlob },
56534     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
56535     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
56536     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
56537     { "last_insert_rowid",  0, 0xff, SQLITE_UTF8, 0, last_insert_rowid },
56538     { "changes",            0, 0xff, SQLITE_UTF8, 0, changes           },
56539     { "total_changes",      0, 0xff, SQLITE_UTF8, 0, total_changes     },
56540     { "replace",            3, 0, SQLITE_UTF8,    0, replaceFunc       },
56541     { "ltrim",              1, 1, SQLITE_UTF8,    0, trimFunc          },
56542     { "ltrim",              2, 1, SQLITE_UTF8,    0, trimFunc          },
56543     { "rtrim",              1, 2, SQLITE_UTF8,    0, trimFunc          },
56544     { "rtrim",              2, 2, SQLITE_UTF8,    0, trimFunc          },
56545     { "trim",               1, 3, SQLITE_UTF8,    0, trimFunc          },
56546     { "trim",               2, 3, SQLITE_UTF8,    0, trimFunc          },
56547     { "zeroblob",           1, 0, SQLITE_UTF8,    0, zeroblobFunc      },
56548 #ifdef SQLITE_SOUNDEX
56549     { "soundex",            1, 0, SQLITE_UTF8,    0, soundexFunc},
56550 #endif
56551 #ifndef SQLITE_OMIT_LOAD_EXTENSION
56552     { "load_extension",     1, 0xff, SQLITE_UTF8, 0, loadExt },
56553     { "load_extension",     2, 0xff, SQLITE_UTF8, 0, loadExt },
56554 #endif
56555 #ifdef SQLITE_TEST
56556     { "randstr",               2, 0,    SQLITE_UTF8, 0, randStr    },
56557     { "test_destructor",       1, 0xff, SQLITE_UTF8, 0, test_destructor},
56558     { "test_destructor_count", 0, 0,    SQLITE_UTF8, 0, test_destructor_count},
56559     { "test_auxdata",         -1, 0,    SQLITE_UTF8, 0, test_auxdata},
56560     { "test_error",            1, 0,    SQLITE_UTF8, 0, test_error},
56561 #endif
56562   };
56563   static const struct {
56564     char *zName;
56565     signed char nArg;
56566     u8 argType;
56567     u8 needCollSeq;
56568     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
56569     void (*xFinalize)(sqlite3_context*);
56570   } aAggs[] = {
56571     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
56572     { "max",    1, 1, 1, minmaxStep,   minMaxFinalize },
56573     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
56574     { "total",  1, 0, 0, sumStep,      totalFinalize    },
56575     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
56576     { "count",  0, 0, 0, countStep,    countFinalize  },
56577     { "count",  1, 0, 0, countStep,    countFinalize  },
56578     { "group_concat", 1, 0, 0, groupConcatStep, groupConcatFinalize },
56579     { "group_concat", 2, 0, 0, groupConcatStep, groupConcatFinalize },
56580   };
56581   int i;
56582
56583   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
56584     void *pArg;
56585     u8 argType = aFuncs[i].argType;
56586     if( argType==0xff ){
56587       pArg = db;
56588     }else{
56589       pArg = (void*)(sqlite3_intptr_t)argType;
56590     }
56591     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
56592         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
56593     if( aFuncs[i].needCollSeq ){
56594       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName, 
56595           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
56596       if( pFunc && aFuncs[i].needCollSeq ){
56597         pFunc->needCollSeq = 1;
56598       }
56599     }
56600   }
56601 #ifndef SQLITE_OMIT_ALTERTABLE
56602   sqlite3AlterFunctions(db);
56603 #endif
56604 #ifndef SQLITE_OMIT_PARSER
56605   sqlite3AttachFunctions(db);
56606 #endif
56607   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
56608     void *pArg = (void*)(sqlite3_intptr_t)aAggs[i].argType;
56609     sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8, 
56610         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
56611     if( aAggs[i].needCollSeq ){
56612       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
56613           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
56614       if( pFunc && aAggs[i].needCollSeq ){
56615         pFunc->needCollSeq = 1;
56616       }
56617     }
56618   }
56619   sqlite3RegisterDateTimeFunctions(db);
56620   if( !db->mallocFailed ){
56621     int rc = sqlite3_overload_function(db, "MATCH", 2);
56622     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
56623     if( rc==SQLITE_NOMEM ){
56624       db->mallocFailed = 1;
56625     }
56626   }
56627 #ifdef SQLITE_SSE
56628   (void)sqlite3SseFunctions(db);
56629 #endif
56630 #ifdef SQLITE_CASE_SENSITIVE_LIKE
56631   sqlite3RegisterLikeFunctions(db, 1);
56632 #else
56633   sqlite3RegisterLikeFunctions(db, 0);
56634 #endif
56635 }
56636
56637 /*
56638 ** Set the LIKEOPT flag on the 2-argument function with the given name.
56639 */
56640 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
56641   FuncDef *pDef;
56642   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
56643   if( pDef ){
56644     pDef->flags = flagVal;
56645   }
56646 }
56647
56648 /*
56649 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
56650 ** parameter determines whether or not the LIKE operator is case
56651 ** sensitive.  GLOB is always case sensitive.
56652 */
56653 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
56654   struct compareInfo *pInfo;
56655   if( caseSensitive ){
56656     pInfo = (struct compareInfo*)&likeInfoAlt;
56657   }else{
56658     pInfo = (struct compareInfo*)&likeInfoNorm;
56659   }
56660   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
56661   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
56662   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
56663       (struct compareInfo*)&globInfo, likeFunc, 0,0);
56664   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
56665   setLikeOptFlag(db, "like", 
56666       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
56667 }
56668
56669 /*
56670 ** pExpr points to an expression which implements a function.  If
56671 ** it is appropriate to apply the LIKE optimization to that function
56672 ** then set aWc[0] through aWc[2] to the wildcard characters and
56673 ** return TRUE.  If the function is not a LIKE-style function then
56674 ** return FALSE.
56675 */
56676 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
56677   FuncDef *pDef;
56678   if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
56679     return 0;
56680   }
56681   if( pExpr->pList->nExpr!=2 ){
56682     return 0;
56683   }
56684   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
56685                              SQLITE_UTF8, 0);
56686   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
56687     return 0;
56688   }
56689
56690   /* The memcpy() statement assumes that the wildcard characters are
56691   ** the first three statements in the compareInfo structure.  The
56692   ** asserts() that follow verify that assumption
56693   */
56694   memcpy(aWc, pDef->pUserData, 3);
56695   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
56696   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
56697   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
56698   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
56699   return 1;
56700 }
56701
56702 /************** End of func.c ************************************************/
56703 /************** Begin file insert.c ******************************************/
56704 /*
56705 ** 2001 September 15
56706 **
56707 ** The author disclaims copyright to this source code.  In place of
56708 ** a legal notice, here is a blessing:
56709 **
56710 **    May you do good and not evil.
56711 **    May you find forgiveness for yourself and forgive others.
56712 **    May you share freely, never taking more than you give.
56713 **
56714 *************************************************************************
56715 ** This file contains C code routines that are called by the parser
56716 ** to handle INSERT statements in SQLite.
56717 **
56718 ** $Id: insert.c,v 1.231 2008/03/06 09:58:50 mlcreech Exp $
56719 */
56720
56721 /*
56722 ** Set P4 of the most recently inserted opcode to a column affinity
56723 ** string for index pIdx. A column affinity string has one character
56724 ** for each column in the table, according to the affinity of the column:
56725 **
56726 **  Character      Column affinity
56727 **  ------------------------------
56728 **  'a'            TEXT
56729 **  'b'            NONE
56730 **  'c'            NUMERIC
56731 **  'd'            INTEGER
56732 **  'e'            REAL
56733 **
56734 ** An extra 'b' is appended to the end of the string to cover the
56735 ** rowid that appears as the last column in every index.
56736 */
56737 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
56738   if( !pIdx->zColAff ){
56739     /* The first time a column affinity string for a particular index is
56740     ** required, it is allocated and populated here. It is then stored as
56741     ** a member of the Index structure for subsequent use.
56742     **
56743     ** The column affinity string will eventually be deleted by
56744     ** sqliteDeleteIndex() when the Index structure itself is cleaned
56745     ** up.
56746     */
56747     int n;
56748     Table *pTab = pIdx->pTable;
56749     sqlite3 *db = sqlite3VdbeDb(v);
56750     pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+2);
56751     if( !pIdx->zColAff ){
56752       return;
56753     }
56754     for(n=0; n<pIdx->nColumn; n++){
56755       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
56756     }
56757     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
56758     pIdx->zColAff[n] = 0;
56759   }
56760  
56761   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
56762 }
56763
56764 /*
56765 ** Set P4 of the most recently inserted opcode to a column affinity
56766 ** string for table pTab. A column affinity string has one character
56767 ** for each column indexed by the index, according to the affinity of the
56768 ** column:
56769 **
56770 **  Character      Column affinity
56771 **  ------------------------------
56772 **  'a'            TEXT
56773 **  'b'            NONE
56774 **  'c'            NUMERIC
56775 **  'd'            INTEGER
56776 **  'e'            REAL
56777 */
56778 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
56779   /* The first time a column affinity string for a particular table
56780   ** is required, it is allocated and populated here. It is then 
56781   ** stored as a member of the Table structure for subsequent use.
56782   **
56783   ** The column affinity string will eventually be deleted by
56784   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
56785   */
56786   if( !pTab->zColAff ){
56787     char *zColAff;
56788     int i;
56789     sqlite3 *db = sqlite3VdbeDb(v);
56790
56791     zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1);
56792     if( !zColAff ){
56793       return;
56794     }
56795
56796     for(i=0; i<pTab->nCol; i++){
56797       zColAff[i] = pTab->aCol[i].affinity;
56798     }
56799     zColAff[pTab->nCol] = '\0';
56800
56801     pTab->zColAff = zColAff;
56802   }
56803
56804   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
56805 }
56806
56807 /*
56808 ** Return non-zero if the table pTab in database iDb or any of its indices
56809 ** have been opened at any point in the VDBE program beginning at location
56810 ** iStartAddr throught the end of the program.  This is used to see if 
56811 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
56812 ** run without using temporary table for the results of the SELECT. 
56813 */
56814 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
56815   int i;
56816   int iEnd = sqlite3VdbeCurrentAddr(v);
56817   for(i=iStartAddr; i<iEnd; i++){
56818     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
56819     assert( pOp!=0 );
56820     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
56821       Index *pIndex;
56822       int tnum = pOp->p2;
56823       if( tnum==pTab->tnum ){
56824         return 1;
56825       }
56826       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
56827         if( tnum==pIndex->tnum ){
56828           return 1;
56829         }
56830       }
56831     }
56832 #ifndef SQLITE_OMIT_VIRTUALTABLE
56833     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
56834       assert( pOp->p4.pVtab!=0 );
56835       assert( pOp->p4type==P4_VTAB );
56836       return 1;
56837     }
56838 #endif
56839   }
56840   return 0;
56841 }
56842
56843 #ifndef SQLITE_OMIT_AUTOINCREMENT
56844 /*
56845 ** Write out code to initialize the autoincrement logic.  This code
56846 ** looks up the current autoincrement value in the sqlite_sequence
56847 ** table and stores that value in a register.  Code generated by
56848 ** autoIncStep() will keep that register holding the largest
56849 ** rowid value.  Code generated by autoIncEnd() will write the new
56850 ** largest value of the counter back into the sqlite_sequence table.
56851 **
56852 ** This routine returns the index of the mem[] cell that contains
56853 ** the maximum rowid counter.
56854 **
56855 ** Three consecutive registers are allocated by this routine.  The
56856 ** first two hold the name of the target table and the maximum rowid 
56857 ** inserted into the target table, respectively.
56858 ** The third holds the rowid in sqlite_sequence where we will
56859 ** write back the revised maximum rowid.  This routine returns the
56860 ** index of the second of these three registers.
56861 */
56862 static int autoIncBegin(
56863   Parse *pParse,      /* Parsing context */
56864   int iDb,            /* Index of the database holding pTab */
56865   Table *pTab         /* The table we are writing to */
56866 ){
56867   int memId = 0;      /* Register holding maximum rowid */
56868   if( pTab->autoInc ){
56869     Vdbe *v = pParse->pVdbe;
56870     Db *pDb = &pParse->db->aDb[iDb];
56871     int iCur = pParse->nTab;
56872     int addr;               /* Address of the top of the loop */
56873     assert( v );
56874     pParse->nMem++;         /* Holds name of table */
56875     memId = ++pParse->nMem;
56876     pParse->nMem++;
56877     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
56878     addr = sqlite3VdbeCurrentAddr(v);
56879     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
56880     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+8);
56881     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
56882     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
56883     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
56884     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
56885     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
56886     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+8);
56887     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
56888     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
56889   }
56890   return memId;
56891 }
56892
56893 /*
56894 ** Update the maximum rowid for an autoincrement calculation.
56895 **
56896 ** This routine should be called when the top of the stack holds a
56897 ** new rowid that is about to be inserted.  If that new rowid is
56898 ** larger than the maximum rowid in the memId memory cell, then the
56899 ** memory cell is updated.  The stack is unchanged.
56900 */
56901 static void autoIncStep(Parse *pParse, int memId, int regRowid){
56902   if( memId>0 ){
56903     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
56904   }
56905 }
56906
56907 /*
56908 ** After doing one or more inserts, the maximum rowid is stored
56909 ** in reg[memId].  Generate code to write this value back into the
56910 ** the sqlite_sequence table.
56911 */
56912 static void autoIncEnd(
56913   Parse *pParse,     /* The parsing context */
56914   int iDb,           /* Index of the database holding pTab */
56915   Table *pTab,       /* Table we are inserting into */
56916   int memId          /* Memory cell holding the maximum rowid */
56917 ){
56918   if( pTab->autoInc ){
56919     int iCur = pParse->nTab;
56920     Vdbe *v = pParse->pVdbe;
56921     Db *pDb = &pParse->db->aDb[iDb];
56922     int j1;
56923     int iRec = ++pParse->nMem;    /* Memory cell used for record */
56924
56925     assert( v );
56926     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
56927     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
56928     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
56929     sqlite3VdbeJumpHere(v, j1);
56930     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
56931     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
56932     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
56933     sqlite3VdbeAddOp1(v, OP_Close, iCur);
56934   }
56935 }
56936 #else
56937 /*
56938 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
56939 ** above are all no-ops
56940 */
56941 # define autoIncBegin(A,B,C) (0)
56942 # define autoIncStep(A,B,C)
56943 # define autoIncEnd(A,B,C,D)
56944 #endif /* SQLITE_OMIT_AUTOINCREMENT */
56945
56946
56947 /* Forward declaration */
56948 static int xferOptimization(
56949   Parse *pParse,        /* Parser context */
56950   Table *pDest,         /* The table we are inserting into */
56951   Select *pSelect,      /* A SELECT statement to use as the data source */
56952   int onError,          /* How to handle constraint errors */
56953   int iDbDest           /* The database of pDest */
56954 );
56955
56956 /*
56957 ** This routine is call to handle SQL of the following forms:
56958 **
56959 **    insert into TABLE (IDLIST) values(EXPRLIST)
56960 **    insert into TABLE (IDLIST) select
56961 **
56962 ** The IDLIST following the table name is always optional.  If omitted,
56963 ** then a list of all columns for the table is substituted.  The IDLIST
56964 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
56965 **
56966 ** The pList parameter holds EXPRLIST in the first form of the INSERT
56967 ** statement above, and pSelect is NULL.  For the second form, pList is
56968 ** NULL and pSelect is a pointer to the select statement used to generate
56969 ** data for the insert.
56970 **
56971 ** The code generated follows one of four templates.  For a simple
56972 ** select with data coming from a VALUES clause, the code executes
56973 ** once straight down through.  The template looks like this:
56974 **
56975 **         open write cursor to <table> and its indices
56976 **         puts VALUES clause expressions onto the stack
56977 **         write the resulting record into <table>
56978 **         cleanup
56979 **
56980 ** The three remaining templates assume the statement is of the form
56981 **
56982 **   INSERT INTO <table> SELECT ...
56983 **
56984 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
56985 ** in other words if the SELECT pulls all columns from a single table
56986 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
56987 ** if <table2> and <table1> are distinct tables but have identical
56988 ** schemas, including all the same indices, then a special optimization
56989 ** is invoked that copies raw records from <table2> over to <table1>.
56990 ** See the xferOptimization() function for the implementation of this
56991 ** template.  This is the second template.
56992 **
56993 **         open a write cursor to <table>
56994 **         open read cursor on <table2>
56995 **         transfer all records in <table2> over to <table>
56996 **         close cursors
56997 **         foreach index on <table>
56998 **           open a write cursor on the <table> index
56999 **           open a read cursor on the corresponding <table2> index
57000 **           transfer all records from the read to the write cursors
57001 **           close cursors
57002 **         end foreach
57003 **
57004 ** The third template is for when the second template does not apply
57005 ** and the SELECT clause does not read from <table> at any time.
57006 ** The generated code follows this template:
57007 **
57008 **         goto B
57009 **      A: setup for the SELECT
57010 **         loop over the rows in the SELECT
57011 **           gosub C
57012 **         end loop
57013 **         cleanup after the SELECT
57014 **         goto D
57015 **      B: open write cursor to <table> and its indices
57016 **         goto A
57017 **      C: insert the select result into <table>
57018 **         return
57019 **      D: cleanup
57020 **
57021 ** The fourth template is used if the insert statement takes its
57022 ** values from a SELECT but the data is being inserted into a table
57023 ** that is also read as part of the SELECT.  In the third form,
57024 ** we have to use a intermediate table to store the results of
57025 ** the select.  The template is like this:
57026 **
57027 **         goto B
57028 **      A: setup for the SELECT
57029 **         loop over the tables in the SELECT
57030 **           gosub C
57031 **         end loop
57032 **         cleanup after the SELECT
57033 **         goto D
57034 **      C: insert the select result into the intermediate table
57035 **         return
57036 **      B: open a cursor to an intermediate table
57037 **         goto A
57038 **      D: open write cursor to <table> and its indices
57039 **         loop over the intermediate table
57040 **           transfer values form intermediate table into <table>
57041 **         end the loop
57042 **         cleanup
57043 */
57044 SQLITE_PRIVATE void sqlite3Insert(
57045   Parse *pParse,        /* Parser context */
57046   SrcList *pTabList,    /* Name of table into which we are inserting */
57047   ExprList *pList,      /* List of values to be inserted */
57048   Select *pSelect,      /* A SELECT statement to use as the data source */
57049   IdList *pColumn,      /* Column names corresponding to IDLIST. */
57050   int onError           /* How to handle constraint errors */
57051 ){
57052   sqlite3 *db;          /* The main database structure */
57053   Table *pTab;          /* The table to insert into.  aka TABLE */
57054   char *zTab;           /* Name of the table into which we are inserting */
57055   const char *zDb;      /* Name of the database holding this table */
57056   int i, j, idx;        /* Loop counters */
57057   Vdbe *v;              /* Generate code into this virtual machine */
57058   Index *pIdx;          /* For looping over indices of the table */
57059   int nColumn;          /* Number of columns in the data */
57060   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
57061   int baseCur = 0;      /* VDBE Cursor number for pTab */
57062   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
57063   int endOfLoop;        /* Label for the end of the insertion loop */
57064   int useTempTable = 0; /* Store SELECT results in intermediate table */
57065   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
57066   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
57067   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
57068   int iCleanup = 0;     /* Address of the cleanup code */
57069   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
57070   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
57071   int iDb;              /* Index of database holding TABLE */
57072   Db *pDb;              /* The database containing table being inserted into */
57073   int appendFlag = 0;   /* True if the insert is likely to be an append */
57074
57075   /* Register allocations */
57076   int regFromSelect;    /* Base register for data coming from SELECT */
57077   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
57078   int regRowCount = 0;  /* Memory cell used for the row counter */
57079   int regIns;           /* Block of regs holding rowid+data being inserted */
57080   int regRowid;         /* registers holding insert rowid */
57081   int regData;          /* register holding first column to insert */
57082   int regRecord;        /* Holds the assemblied row record */
57083   int *aRegIdx = 0;     /* One register allocated to each index */
57084
57085
57086 #ifndef SQLITE_OMIT_TRIGGER
57087   int isView;                 /* True if attempting to insert into a view */
57088   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
57089 #endif
57090
57091   db = pParse->db;
57092   if( pParse->nErr || db->mallocFailed ){
57093     goto insert_cleanup;
57094   }
57095
57096   /* Locate the table into which we will be inserting new information.
57097   */
57098   assert( pTabList->nSrc==1 );
57099   zTab = pTabList->a[0].zName;
57100   if( zTab==0 ) goto insert_cleanup;
57101   pTab = sqlite3SrcListLookup(pParse, pTabList);
57102   if( pTab==0 ){
57103     goto insert_cleanup;
57104   }
57105   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
57106   assert( iDb<db->nDb );
57107   pDb = &db->aDb[iDb];
57108   zDb = pDb->zName;
57109   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
57110     goto insert_cleanup;
57111   }
57112
57113   /* Figure out if we have any triggers and if the table being
57114   ** inserted into is a view
57115   */
57116 #ifndef SQLITE_OMIT_TRIGGER
57117   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
57118   isView = pTab->pSelect!=0;
57119 #else
57120 # define triggers_exist 0
57121 # define isView 0
57122 #endif
57123 #ifdef SQLITE_OMIT_VIEW
57124 # undef isView
57125 # define isView 0
57126 #endif
57127
57128   /* Ensure that:
57129   *  (a) the table is not read-only, 
57130   *  (b) that if it is a view then ON INSERT triggers exist
57131   */
57132   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
57133     goto insert_cleanup;
57134   }
57135   assert( pTab!=0 );
57136
57137   /* If pTab is really a view, make sure it has been initialized.
57138   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
57139   ** module table).
57140   */
57141   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
57142     goto insert_cleanup;
57143   }
57144
57145   /* Allocate a VDBE
57146   */
57147   v = sqlite3GetVdbe(pParse);
57148   if( v==0 ) goto insert_cleanup;
57149   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
57150   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
57151
57152   /* if there are row triggers, allocate a temp table for new.* references. */
57153   if( triggers_exist ){
57154     newIdx = pParse->nTab++;
57155   }
57156
57157 #ifndef SQLITE_OMIT_XFER_OPT
57158   /* If the statement is of the form
57159   **
57160   **       INSERT INTO <table1> SELECT * FROM <table2>;
57161   **
57162   ** Then special optimizations can be applied that make the transfer
57163   ** very fast and which reduce fragmentation of indices.
57164   */
57165   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
57166     assert( !triggers_exist );
57167     assert( pList==0 );
57168     goto insert_cleanup;
57169   }
57170 #endif /* SQLITE_OMIT_XFER_OPT */
57171
57172   /* If this is an AUTOINCREMENT table, look up the sequence number in the
57173   ** sqlite_sequence table and store it in memory cell regAutoinc.
57174   */
57175   regAutoinc = autoIncBegin(pParse, iDb, pTab);
57176
57177   /* Figure out how many columns of data are supplied.  If the data
57178   ** is coming from a SELECT statement, then this step also generates
57179   ** all the code to implement the SELECT statement and invoke a subroutine
57180   ** to process each row of the result. (Template 2.) If the SELECT
57181   ** statement uses the the table that is being inserted into, then the
57182   ** subroutine is also coded here.  That subroutine stores the SELECT
57183   ** results in a temporary table. (Template 3.)
57184   */
57185   if( pSelect ){
57186     /* Data is coming from a SELECT.  Generate code to implement that SELECT
57187     */
57188     SelectDest dest;
57189     int rc, iInitCode;
57190
57191     iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
57192     iSelectLoop = sqlite3VdbeCurrentAddr(v);
57193     iInsertBlock = sqlite3VdbeMakeLabel(v);
57194     sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock);
57195
57196     /* Resolve the expressions in the SELECT statement and execute it. */
57197     rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
57198     if( rc || pParse->nErr || db->mallocFailed ){
57199       goto insert_cleanup;
57200     }
57201
57202     regFromSelect = dest.iMem;
57203     iCleanup = sqlite3VdbeMakeLabel(v);
57204     sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
57205     assert( pSelect->pEList );
57206     nColumn = pSelect->pEList->nExpr;
57207
57208     /* Set useTempTable to TRUE if the result of the SELECT statement
57209     ** should be written into a temporary table.  Set to FALSE if each
57210     ** row of the SELECT can be written directly into the result table.
57211     **
57212     ** A temp table must be used if the table being updated is also one
57213     ** of the tables being read by the SELECT statement.  Also use a 
57214     ** temp table in the case of row triggers.
57215     */
57216     if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
57217       useTempTable = 1;
57218     }
57219
57220     if( useTempTable ){
57221       /* Generate the subroutine that SELECT calls to process each row of
57222       ** the result.  Store the result in a temporary table
57223       */
57224       int regRec, regRowid;
57225
57226       srcTab = pParse->nTab++;
57227       regRec = sqlite3GetTempReg(pParse);
57228       regRowid = sqlite3GetTempReg(pParse);
57229       sqlite3VdbeResolveLabel(v, iInsertBlock);
57230       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
57231       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
57232       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
57233       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
57234       sqlite3ReleaseTempReg(pParse, regRec);
57235       sqlite3ReleaseTempReg(pParse, regRowid);
57236
57237       /* The following code runs first because the GOTO at the very top
57238       ** of the program jumps to it.  Create the temporary table, then jump
57239       ** back up and execute the SELECT code above.
57240       */
57241       sqlite3VdbeJumpHere(v, iInitCode);
57242       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0);
57243       sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn);
57244       sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
57245       sqlite3VdbeResolveLabel(v, iCleanup);
57246     }else{
57247       sqlite3VdbeJumpHere(v, iInitCode);
57248     }
57249   }else{
57250     /* This is the case if the data for the INSERT is coming from a VALUES
57251     ** clause
57252     */
57253     NameContext sNC;
57254     memset(&sNC, 0, sizeof(sNC));
57255     sNC.pParse = pParse;
57256     srcTab = -1;
57257     assert( useTempTable==0 );
57258     nColumn = pList ? pList->nExpr : 0;
57259     for(i=0; i<nColumn; i++){
57260       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
57261         goto insert_cleanup;
57262       }
57263     }
57264   }
57265
57266   /* Make sure the number of columns in the source data matches the number
57267   ** of columns to be inserted into the table.
57268   */
57269   if( IsVirtual(pTab) ){
57270     for(i=0; i<pTab->nCol; i++){
57271       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
57272     }
57273   }
57274   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
57275     sqlite3ErrorMsg(pParse, 
57276        "table %S has %d columns but %d values were supplied",
57277        pTabList, 0, pTab->nCol, nColumn);
57278     goto insert_cleanup;
57279   }
57280   if( pColumn!=0 && nColumn!=pColumn->nId ){
57281     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
57282     goto insert_cleanup;
57283   }
57284
57285   /* If the INSERT statement included an IDLIST term, then make sure
57286   ** all elements of the IDLIST really are columns of the table and 
57287   ** remember the column indices.
57288   **
57289   ** If the table has an INTEGER PRIMARY KEY column and that column
57290   ** is named in the IDLIST, then record in the keyColumn variable
57291   ** the index into IDLIST of the primary key column.  keyColumn is
57292   ** the index of the primary key as it appears in IDLIST, not as
57293   ** is appears in the original table.  (The index of the primary
57294   ** key in the original table is pTab->iPKey.)
57295   */
57296   if( pColumn ){
57297     for(i=0; i<pColumn->nId; i++){
57298       pColumn->a[i].idx = -1;
57299     }
57300     for(i=0; i<pColumn->nId; i++){
57301       for(j=0; j<pTab->nCol; j++){
57302         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
57303           pColumn->a[i].idx = j;
57304           if( j==pTab->iPKey ){
57305             keyColumn = i;
57306           }
57307           break;
57308         }
57309       }
57310       if( j>=pTab->nCol ){
57311         if( sqlite3IsRowid(pColumn->a[i].zName) ){
57312           keyColumn = i;
57313         }else{
57314           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
57315               pTabList, 0, pColumn->a[i].zName);
57316           pParse->nErr++;
57317           goto insert_cleanup;
57318         }
57319       }
57320     }
57321   }
57322
57323   /* If there is no IDLIST term but the table has an integer primary
57324   ** key, the set the keyColumn variable to the primary key column index
57325   ** in the original table definition.
57326   */
57327   if( pColumn==0 && nColumn>0 ){
57328     keyColumn = pTab->iPKey;
57329   }
57330
57331   /* Open the temp table for FOR EACH ROW triggers
57332   */
57333   if( triggers_exist ){
57334     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
57335     sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol);
57336   }
57337     
57338   /* Initialize the count of rows to be inserted
57339   */
57340   if( db->flags & SQLITE_CountRows ){
57341     regRowCount = ++pParse->nMem;
57342     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
57343   }
57344
57345   /* If this is not a view, open the table and and all indices */
57346   if( !isView ){
57347     int nIdx;
57348     int i;
57349
57350     baseCur = pParse->nTab;
57351     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
57352     aRegIdx = sqlite3DbMallocZero(db, sizeof(int)*(nIdx+1));
57353     if( aRegIdx==0 ){
57354       goto insert_cleanup;
57355     }
57356     for(i=0; i<nIdx; i++){
57357       aRegIdx[i] = ++pParse->nMem;
57358     }
57359   }
57360
57361   /* If the data source is a temporary table, then we have to create
57362   ** a loop because there might be multiple rows of data.  If the data
57363   ** source is a subroutine call from the SELECT statement, then we need
57364   ** to launch the SELECT statement processing.
57365   */
57366   if( useTempTable ){
57367     iBreak = sqlite3VdbeMakeLabel(v);
57368     sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
57369     iCont = sqlite3VdbeCurrentAddr(v);
57370   }else if( pSelect ){
57371     sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
57372     sqlite3VdbeResolveLabel(v, iInsertBlock);
57373   }
57374
57375   /* Allocate registers for holding the rowid of the new row,
57376   ** the content of the new row, and the assemblied row record.
57377   */
57378   regRecord = ++pParse->nMem;
57379   regRowid = regIns = pParse->nMem+1;
57380   pParse->nMem += pTab->nCol + 1;
57381   if( IsVirtual(pTab) ){
57382     regRowid++;
57383     pParse->nMem++;
57384   }
57385   regData = regRowid+1;
57386
57387   /* Run the BEFORE and INSTEAD OF triggers, if there are any
57388   */
57389   endOfLoop = sqlite3VdbeMakeLabel(v);
57390   if( triggers_exist & TRIGGER_BEFORE ){
57391     int regRowid;
57392     int regCols;
57393     int regRec;
57394
57395     /* build the NEW.* reference row.  Note that if there is an INTEGER
57396     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
57397     ** translated into a unique ID for the row.  But on a BEFORE trigger,
57398     ** we do not know what the unique ID will be (because the insert has
57399     ** not happened yet) so we substitute a rowid of -1
57400     */
57401     regRowid = sqlite3GetTempReg(pParse);
57402     if( keyColumn<0 ){
57403       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
57404     }else if( useTempTable ){
57405       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
57406     }else{
57407       int j1;
57408       assert( pSelect==0 );  /* Otherwise useTempTable is true */
57409       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
57410       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
57411       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
57412       sqlite3VdbeJumpHere(v, j1);
57413       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
57414     }
57415
57416     /* Cannot have triggers on a virtual table. If it were possible,
57417     ** this block would have to account for hidden column.
57418     */
57419     assert(!IsVirtual(pTab));
57420
57421     /* Create the new column data
57422     */
57423     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
57424     for(i=0; i<pTab->nCol; i++){
57425       if( pColumn==0 ){
57426         j = i;
57427       }else{
57428         for(j=0; j<pColumn->nId; j++){
57429           if( pColumn->a[j].idx==i ) break;
57430         }
57431       }
57432       if( pColumn && j>=pColumn->nId ){
57433         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
57434       }else if( useTempTable ){
57435         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 
57436       }else{
57437         assert( pSelect==0 ); /* Otherwise useTempTable is true */
57438         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
57439       }
57440     }
57441     regRec = sqlite3GetTempReg(pParse);
57442     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
57443
57444     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
57445     ** do not attempt any conversions before assembling the record.
57446     ** If this is a real table, attempt conversions as required by the
57447     ** table column affinities.
57448     */
57449     if( !isView ){
57450       sqlite3TableAffinityStr(v, pTab);
57451     }
57452     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
57453     sqlite3ReleaseTempReg(pParse, regRec);
57454     sqlite3ReleaseTempReg(pParse, regRowid);
57455     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
57456
57457     /* Fire BEFORE or INSTEAD OF triggers */
57458     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
57459         newIdx, -1, onError, endOfLoop, 0, 0) ){
57460       goto insert_cleanup;
57461     }
57462   }
57463
57464   /* Push the record number for the new entry onto the stack.  The
57465   ** record number is a randomly generate integer created by NewRowid
57466   ** except when the table has an INTEGER PRIMARY KEY column, in which
57467   ** case the record number is the same as that column. 
57468   */
57469   if( !isView ){
57470     if( IsVirtual(pTab) ){
57471       /* The row that the VUpdate opcode will delete: none */
57472       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
57473     }
57474     if( keyColumn>=0 ){
57475       if( useTempTable ){
57476         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
57477       }else if( pSelect ){
57478         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
57479       }else{
57480         VdbeOp *pOp;
57481         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
57482         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
57483         if( pOp && pOp->opcode==OP_Null ){
57484           appendFlag = 1;
57485           pOp->opcode = OP_NewRowid;
57486           pOp->p1 = baseCur;
57487           pOp->p2 = regRowid;
57488           pOp->p3 = regAutoinc;
57489         }
57490       }
57491       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
57492       ** to generate a unique primary key value.
57493       */
57494       if( !appendFlag ){
57495         int j1;
57496         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
57497         sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
57498         sqlite3VdbeJumpHere(v, j1);
57499         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
57500       }
57501     }else if( IsVirtual(pTab) ){
57502       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
57503     }else{
57504       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
57505       appendFlag = 1;
57506     }
57507     autoIncStep(pParse, regAutoinc, regRowid);
57508
57509     /* Push onto the stack, data for all columns of the new entry, beginning
57510     ** with the first column.
57511     */
57512     nHidden = 0;
57513     for(i=0; i<pTab->nCol; i++){
57514       int iRegStore = regRowid+1+i;
57515       if( i==pTab->iPKey ){
57516         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
57517         ** Whenever this column is read, the record number will be substituted
57518         ** in its place.  So will fill this column with a NULL to avoid
57519         ** taking up data space with information that will never be used. */
57520         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
57521         continue;
57522       }
57523       if( pColumn==0 ){
57524         if( IsHiddenColumn(&pTab->aCol[i]) ){
57525           assert( IsVirtual(pTab) );
57526           j = -1;
57527           nHidden++;
57528         }else{
57529           j = i - nHidden;
57530         }
57531       }else{
57532         for(j=0; j<pColumn->nId; j++){
57533           if( pColumn->a[j].idx==i ) break;
57534         }
57535       }
57536       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
57537         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
57538       }else if( useTempTable ){
57539         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
57540       }else if( pSelect ){
57541         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
57542       }else{
57543         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
57544       }
57545     }
57546
57547     /* Generate code to check constraints and generate index keys and
57548     ** do the insertion.
57549     */
57550 #ifndef SQLITE_OMIT_VIRTUALTABLE
57551     if( IsVirtual(pTab) ){
57552       pParse->pVirtualLock = pTab;
57553       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
57554                      (const char*)pTab->pVtab, P4_VTAB);
57555     }else
57556 #endif
57557     {
57558       sqlite3GenerateConstraintChecks(
57559           pParse,
57560           pTab,
57561           baseCur,
57562           regIns,
57563           aRegIdx,
57564           keyColumn>=0,
57565           0,
57566           onError,
57567           endOfLoop
57568       );
57569       sqlite3CompleteInsertion(
57570           pParse,
57571           pTab,
57572           baseCur,
57573           regIns,
57574           aRegIdx,
57575           0,
57576           0,
57577           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
57578           appendFlag
57579        );
57580     }
57581   }
57582
57583   /* Update the count of rows that are inserted
57584   */
57585   if( (db->flags & SQLITE_CountRows)!=0 ){
57586     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
57587   }
57588
57589   if( triggers_exist ){
57590     /* Code AFTER triggers */
57591     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
57592           newIdx, -1, onError, endOfLoop, 0, 0) ){
57593       goto insert_cleanup;
57594     }
57595   }
57596
57597   /* The bottom of the loop, if the data source is a SELECT statement
57598   */
57599   sqlite3VdbeResolveLabel(v, endOfLoop);
57600   if( useTempTable ){
57601     sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
57602     sqlite3VdbeResolveLabel(v, iBreak);
57603     sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
57604   }else if( pSelect ){
57605     sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
57606     sqlite3VdbeResolveLabel(v, iCleanup);
57607   }
57608
57609   if( !IsVirtual(pTab) && !isView ){
57610     /* Close all tables opened */
57611     sqlite3VdbeAddOp2(v, OP_Close, baseCur, 0);
57612     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
57613       sqlite3VdbeAddOp2(v, OP_Close, idx+baseCur, 0);
57614     }
57615   }
57616
57617   /* Update the sqlite_sequence table by storing the content of the
57618   ** counter value in memory regAutoinc back into the sqlite_sequence
57619   ** table.
57620   */
57621   autoIncEnd(pParse, iDb, pTab, regAutoinc);
57622
57623   /*
57624   ** Return the number of rows inserted. If this routine is 
57625   ** generating code because of a call to sqlite3NestedParse(), do not
57626   ** invoke the callback function.
57627   */
57628   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
57629     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
57630     sqlite3VdbeSetNumCols(v, 1);
57631     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
57632   }
57633
57634 insert_cleanup:
57635   sqlite3SrcListDelete(pTabList);
57636   sqlite3ExprListDelete(pList);
57637   sqlite3SelectDelete(pSelect);
57638   sqlite3IdListDelete(pColumn);
57639   sqlite3_free(aRegIdx);
57640 }
57641
57642 /*
57643 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
57644 **
57645 ** The input is a range of consecutive registers as follows:
57646 **
57647 **    1.  The rowid of the row to be updated before the update.  This
57648 **        value is omitted unless we are doing an UPDATE that involves a
57649 **        change to the record number or writing to a virtual table.
57650 **
57651 **    2.  The rowid of the row after the update.
57652 **
57653 **    3.  The data in the first column of the entry after the update.
57654 **
57655 **    i.  Data from middle columns...
57656 **
57657 **    N.  The data in the last column of the entry after the update.
57658 **
57659 ** The regRowid parameter is the index of the register containing (2).
57660 **
57661 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
57662 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
57663 ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
57664 ** the update or insert statement.  If rowidChng is false, it means that
57665 ** the rowid is computed automatically in an insert or that the rowid value
57666 ** is not modified by the update.
57667 **
57668 ** The code generated by this routine store new index entries into
57669 ** registers identified by aRegIdx[].  No index entry is created for
57670 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
57671 ** the same as the order of indices on the linked list of indices
57672 ** attached to the table.
57673 **
57674 ** This routine also generates code to check constraints.  NOT NULL,
57675 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
57676 ** then the appropriate action is performed.  There are five possible
57677 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
57678 **
57679 **  Constraint type  Action       What Happens
57680 **  ---------------  ----------   ----------------------------------------
57681 **  any              ROLLBACK     The current transaction is rolled back and
57682 **                                sqlite3_exec() returns immediately with a
57683 **                                return code of SQLITE_CONSTRAINT.
57684 **
57685 **  any              ABORT        Back out changes from the current command
57686 **                                only (do not do a complete rollback) then
57687 **                                cause sqlite3_exec() to return immediately
57688 **                                with SQLITE_CONSTRAINT.
57689 **
57690 **  any              FAIL         Sqlite_exec() returns immediately with a
57691 **                                return code of SQLITE_CONSTRAINT.  The
57692 **                                transaction is not rolled back and any
57693 **                                prior changes are retained.
57694 **
57695 **  any              IGNORE       The record number and data is popped from
57696 **                                the stack and there is an immediate jump
57697 **                                to label ignoreDest.
57698 **
57699 **  NOT NULL         REPLACE      The NULL value is replace by the default
57700 **                                value for that column.  If the default value
57701 **                                is NULL, the action is the same as ABORT.
57702 **
57703 **  UNIQUE           REPLACE      The other row that conflicts with the row
57704 **                                being inserted is removed.
57705 **
57706 **  CHECK            REPLACE      Illegal.  The results in an exception.
57707 **
57708 ** Which action to take is determined by the overrideError parameter.
57709 ** Or if overrideError==OE_Default, then the pParse->onError parameter
57710 ** is used.  Or if pParse->onError==OE_Default then the onError value
57711 ** for the constraint is used.
57712 **
57713 ** The calling routine must open a read/write cursor for pTab with
57714 ** cursor number "baseCur".  All indices of pTab must also have open
57715 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
57716 ** Except, if there is no possibility of a REPLACE action then
57717 ** cursors do not need to be open for indices where aRegIdx[i]==0.
57718 */
57719 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
57720   Parse *pParse,      /* The parser context */
57721   Table *pTab,        /* the table into which we are inserting */
57722   int baseCur,        /* Index of a read/write cursor pointing at pTab */
57723   int regRowid,       /* Index of the range of input registers */
57724   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
57725   int rowidChng,      /* True if the rowid might collide with existing entry */
57726   int isUpdate,       /* True for UPDATE, False for INSERT */
57727   int overrideError,  /* Override onError to this if not OE_Default */
57728   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
57729 ){
57730   int i;
57731   Vdbe *v;
57732   int nCol;
57733   int onError;
57734   int j1, j2, j3;     /* Addresses of jump instructions */
57735   int regData;        /* Register containing first data column */
57736   int iCur;
57737   Index *pIdx;
57738   int seenReplace = 0;
57739   int hasTwoRowids = (isUpdate && rowidChng);
57740
57741   v = sqlite3GetVdbe(pParse);
57742   assert( v!=0 );
57743   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
57744   nCol = pTab->nCol;
57745   regData = regRowid + 1;
57746
57747
57748   /* Test all NOT NULL constraints.
57749   */
57750   for(i=0; i<nCol; i++){
57751     if( i==pTab->iPKey ){
57752       continue;
57753     }
57754     onError = pTab->aCol[i].notNull;
57755     if( onError==OE_None ) continue;
57756     if( overrideError!=OE_Default ){
57757       onError = overrideError;
57758     }else if( onError==OE_Default ){
57759       onError = OE_Abort;
57760     }
57761     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
57762       onError = OE_Abort;
57763     }
57764     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
57765     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
57766         || onError==OE_Ignore || onError==OE_Replace );
57767     switch( onError ){
57768       case OE_Rollback:
57769       case OE_Abort:
57770       case OE_Fail: {
57771         char *zMsg = 0;
57772         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
57773         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
57774                         " may not be NULL", (char*)0);
57775         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
57776         break;
57777       }
57778       case OE_Ignore: {
57779         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
57780         break;
57781       }
57782       case OE_Replace: {
57783         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
57784         break;
57785       }
57786     }
57787     sqlite3VdbeJumpHere(v, j1);
57788   }
57789
57790   /* Test all CHECK constraints
57791   */
57792 #ifndef SQLITE_OMIT_CHECK
57793   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
57794     int allOk = sqlite3VdbeMakeLabel(v);
57795     pParse->ckBase = regData;
57796     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
57797     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
57798     if( onError==OE_Ignore ){
57799       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
57800     }else{
57801       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
57802     }
57803     sqlite3VdbeResolveLabel(v, allOk);
57804   }
57805 #endif /* !defined(SQLITE_OMIT_CHECK) */
57806
57807   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
57808   ** of the new record does not previously exist.  Except, if this
57809   ** is an UPDATE and the primary key is not changing, that is OK.
57810   */
57811   if( rowidChng ){
57812     onError = pTab->keyConf;
57813     if( overrideError!=OE_Default ){
57814       onError = overrideError;
57815     }else if( onError==OE_Default ){
57816       onError = OE_Abort;
57817     }
57818     
57819     if( onError!=OE_Replace || pTab->pIndex ){
57820       if( isUpdate ){
57821         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
57822       }
57823       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
57824       switch( onError ){
57825         default: {
57826           onError = OE_Abort;
57827           /* Fall thru into the next case */
57828         }
57829         case OE_Rollback:
57830         case OE_Abort:
57831         case OE_Fail: {
57832           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
57833                            "PRIMARY KEY must be unique", P4_STATIC);
57834           break;
57835         }
57836         case OE_Replace: {
57837           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
57838           seenReplace = 1;
57839           break;
57840         }
57841         case OE_Ignore: {
57842           assert( seenReplace==0 );
57843           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
57844           break;
57845         }
57846       }
57847       sqlite3VdbeJumpHere(v, j3);
57848       if( isUpdate ){
57849         sqlite3VdbeJumpHere(v, j2);
57850       }
57851     }
57852   }
57853
57854   /* Test all UNIQUE constraints by creating entries for each UNIQUE
57855   ** index and making sure that duplicate entries do not already exist.
57856   ** Add the new records to the indices as we go.
57857   */
57858   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
57859     int regIdx;
57860     int regR;
57861
57862     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
57863
57864     /* Create a key for accessing the index entry */
57865     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
57866     for(i=0; i<pIdx->nColumn; i++){
57867       int idx = pIdx->aiColumn[i];
57868       if( idx==pTab->iPKey ){
57869         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
57870       }else{
57871         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
57872       }
57873     }
57874     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
57875     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
57876     sqlite3IndexAffinityStr(v, pIdx);
57877     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
57878
57879     /* Find out what action to take in case there is an indexing conflict */
57880     onError = pIdx->onError;
57881     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
57882     if( overrideError!=OE_Default ){
57883       onError = overrideError;
57884     }else if( onError==OE_Default ){
57885       onError = OE_Abort;
57886     }
57887     if( seenReplace ){
57888       if( onError==OE_Ignore ) onError = OE_Replace;
57889       else if( onError==OE_Fail ) onError = OE_Abort;
57890     }
57891     
57892
57893     /* Check to see if the new index entry will be unique */
57894     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
57895     regR = sqlite3GetTempReg(pParse);
57896     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
57897     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
57898                            regR, (char*)(sqlite3_intptr_t)aRegIdx[iCur],
57899                            P4_INT32);
57900
57901     /* Generate code that executes if the new index entry is not unique */
57902     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
57903         || onError==OE_Ignore || onError==OE_Replace );
57904     switch( onError ){
57905       case OE_Rollback:
57906       case OE_Abort:
57907       case OE_Fail: {
57908         int j, n1, n2;
57909         char zErrMsg[200];
57910         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
57911                          pIdx->nColumn>1 ? "columns " : "column ");
57912         n1 = strlen(zErrMsg);
57913         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
57914           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
57915           n2 = strlen(zCol);
57916           if( j>0 ){
57917             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
57918             n1 += 2;
57919           }
57920           if( n1+n2>sizeof(zErrMsg)-30 ){
57921             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
57922             n1 += 3;
57923             break;
57924           }else{
57925             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
57926             n1 += n2;
57927           }
57928         }
57929         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 
57930             pIdx->nColumn>1 ? " are not unique" : " is not unique");
57931         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
57932         break;
57933       }
57934       case OE_Ignore: {
57935         assert( seenReplace==0 );
57936         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
57937         break;
57938       }
57939       case OE_Replace: {
57940         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
57941         seenReplace = 1;
57942         break;
57943       }
57944     }
57945     sqlite3VdbeJumpHere(v, j2);
57946     sqlite3VdbeJumpHere(v, j3);
57947     sqlite3ReleaseTempReg(pParse, regR);
57948   }
57949 }
57950
57951 /*
57952 ** This routine generates code to finish the INSERT or UPDATE operation
57953 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
57954 ** A consecutive range of registers starting at regRowid contains the
57955 ** rowid and the content to be inserted.
57956 **
57957 ** The arguments to this routine should be the same as the first six
57958 ** arguments to sqlite3GenerateConstraintChecks.
57959 */
57960 SQLITE_PRIVATE void sqlite3CompleteInsertion(
57961   Parse *pParse,      /* The parser context */
57962   Table *pTab,        /* the table into which we are inserting */
57963   int baseCur,        /* Index of a read/write cursor pointing at pTab */
57964   int regRowid,       /* Range of content */
57965   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
57966   int rowidChng,      /* True if the record number will change */
57967   int isUpdate,       /* True for UPDATE, False for INSERT */
57968   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
57969   int appendBias      /* True if this is likely to be an append */
57970 ){
57971   int i;
57972   Vdbe *v;
57973   int nIdx;
57974   Index *pIdx;
57975   int pik_flags;
57976   int regData;
57977   int regRec;
57978
57979   v = sqlite3GetVdbe(pParse);
57980   assert( v!=0 );
57981   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
57982   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
57983   for(i=nIdx-1; i>=0; i--){
57984     if( aRegIdx[i]==0 ) continue;
57985     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
57986   }
57987   regData = regRowid + 1;
57988   regRec = sqlite3GetTempReg(pParse);
57989   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
57990   sqlite3TableAffinityStr(v, pTab);
57991 #ifndef SQLITE_OMIT_TRIGGER
57992   if( newIdx>=0 ){
57993     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
57994   }
57995 #endif
57996   if( pParse->nested ){
57997     pik_flags = 0;
57998   }else{
57999     pik_flags = OPFLAG_NCHANGE;
58000     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
58001   }
58002   if( appendBias ){
58003     pik_flags |= OPFLAG_APPEND;
58004   }
58005   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
58006   if( !pParse->nested ){
58007     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
58008   }
58009   sqlite3VdbeChangeP5(v, pik_flags);
58010 }
58011
58012 /*
58013 ** Generate code that will open cursors for a table and for all
58014 ** indices of that table.  The "baseCur" parameter is the cursor number used
58015 ** for the table.  Indices are opened on subsequent cursors.
58016 **
58017 ** Return the number of indices on the table.
58018 */
58019 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
58020   Parse *pParse,   /* Parsing context */
58021   Table *pTab,     /* Table to be opened */
58022   int baseCur,        /* Cursor number assigned to the table */
58023   int op           /* OP_OpenRead or OP_OpenWrite */
58024 ){
58025   int i;
58026   int iDb;
58027   Index *pIdx;
58028   Vdbe *v;
58029
58030   if( IsVirtual(pTab) ) return 0;
58031   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
58032   v = sqlite3GetVdbe(pParse);
58033   assert( v!=0 );
58034   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
58035   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
58036     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
58037     assert( pIdx->pSchema==pTab->pSchema );
58038     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
58039                       (char*)pKey, P4_KEYINFO_HANDOFF);
58040     VdbeComment((v, "%s", pIdx->zName));
58041   }
58042   if( pParse->nTab<=baseCur+i ){
58043     pParse->nTab = baseCur+i;
58044   }
58045   return i-1;
58046 }
58047
58048
58049 #ifdef SQLITE_TEST
58050 /*
58051 ** The following global variable is incremented whenever the
58052 ** transfer optimization is used.  This is used for testing
58053 ** purposes only - to make sure the transfer optimization really
58054 ** is happening when it is suppose to.
58055 */
58056 SQLITE_API int sqlite3_xferopt_count;
58057 #endif /* SQLITE_TEST */
58058
58059
58060 #ifndef SQLITE_OMIT_XFER_OPT
58061 /*
58062 ** Check to collation names to see if they are compatible.
58063 */
58064 static int xferCompatibleCollation(const char *z1, const char *z2){
58065   if( z1==0 ){
58066     return z2==0;
58067   }
58068   if( z2==0 ){
58069     return 0;
58070   }
58071   return sqlite3StrICmp(z1, z2)==0;
58072 }
58073
58074
58075 /*
58076 ** Check to see if index pSrc is compatible as a source of data
58077 ** for index pDest in an insert transfer optimization.  The rules
58078 ** for a compatible index:
58079 **
58080 **    *   The index is over the same set of columns
58081 **    *   The same DESC and ASC markings occurs on all columns
58082 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
58083 **    *   The same collating sequence on each column
58084 */
58085 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
58086   int i;
58087   assert( pDest && pSrc );
58088   assert( pDest->pTable!=pSrc->pTable );
58089   if( pDest->nColumn!=pSrc->nColumn ){
58090     return 0;   /* Different number of columns */
58091   }
58092   if( pDest->onError!=pSrc->onError ){
58093     return 0;   /* Different conflict resolution strategies */
58094   }
58095   for(i=0; i<pSrc->nColumn; i++){
58096     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
58097       return 0;   /* Different columns indexed */
58098     }
58099     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
58100       return 0;   /* Different sort orders */
58101     }
58102     if( pSrc->azColl[i]!=pDest->azColl[i] ){
58103       return 0;   /* Different collating sequences */
58104     }
58105   }
58106
58107   /* If no test above fails then the indices must be compatible */
58108   return 1;
58109 }
58110
58111 /*
58112 ** Attempt the transfer optimization on INSERTs of the form
58113 **
58114 **     INSERT INTO tab1 SELECT * FROM tab2;
58115 **
58116 ** This optimization is only attempted if
58117 **
58118 **    (1)  tab1 and tab2 have identical schemas including all the
58119 **         same indices and constraints
58120 **
58121 **    (2)  tab1 and tab2 are different tables
58122 **
58123 **    (3)  There must be no triggers on tab1
58124 **
58125 **    (4)  The result set of the SELECT statement is "*"
58126 **
58127 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
58128 **         or LIMIT clause.
58129 **
58130 **    (6)  The SELECT statement is a simple (not a compound) select that
58131 **         contains only tab2 in its FROM clause
58132 **
58133 ** This method for implementing the INSERT transfers raw records from
58134 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
58135 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
58136 ** the resulting tab1 has much less fragmentation.
58137 **
58138 ** This routine returns TRUE if the optimization is attempted.  If any
58139 ** of the conditions above fail so that the optimization should not
58140 ** be attempted, then this routine returns FALSE.
58141 */
58142 static int xferOptimization(
58143   Parse *pParse,        /* Parser context */
58144   Table *pDest,         /* The table we are inserting into */
58145   Select *pSelect,      /* A SELECT statement to use as the data source */
58146   int onError,          /* How to handle constraint errors */
58147   int iDbDest           /* The database of pDest */
58148 ){
58149   ExprList *pEList;                /* The result set of the SELECT */
58150   Table *pSrc;                     /* The table in the FROM clause of SELECT */
58151   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
58152   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
58153   int i;                           /* Loop counter */
58154   int iDbSrc;                      /* The database of pSrc */
58155   int iSrc, iDest;                 /* Cursors from source and destination */
58156   int addr1, addr2;                /* Loop addresses */
58157   int emptyDestTest;               /* Address of test for empty pDest */
58158   int emptySrcTest;                /* Address of test for empty pSrc */
58159   Vdbe *v;                         /* The VDBE we are building */
58160   KeyInfo *pKey;                   /* Key information for an index */
58161   int regAutoinc;                  /* Memory register used by AUTOINC */
58162   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
58163   int regData, regRowid;           /* Registers holding data and rowid */
58164
58165   if( pSelect==0 ){
58166     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
58167   }
58168   if( pDest->pTrigger ){
58169     return 0;   /* tab1 must not have triggers */
58170   }
58171 #ifndef SQLITE_OMIT_VIRTUALTABLE
58172   if( pDest->isVirtual ){
58173     return 0;   /* tab1 must not be a virtual table */
58174   }
58175 #endif
58176   if( onError==OE_Default ){
58177     onError = OE_Abort;
58178   }
58179   if( onError!=OE_Abort && onError!=OE_Rollback ){
58180     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
58181   }
58182   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
58183   if( pSelect->pSrc->nSrc!=1 ){
58184     return 0;   /* FROM clause must have exactly one term */
58185   }
58186   if( pSelect->pSrc->a[0].pSelect ){
58187     return 0;   /* FROM clause cannot contain a subquery */
58188   }
58189   if( pSelect->pWhere ){
58190     return 0;   /* SELECT may not have a WHERE clause */
58191   }
58192   if( pSelect->pOrderBy ){
58193     return 0;   /* SELECT may not have an ORDER BY clause */
58194   }
58195   /* Do not need to test for a HAVING clause.  If HAVING is present but
58196   ** there is no ORDER BY, we will get an error. */
58197   if( pSelect->pGroupBy ){
58198     return 0;   /* SELECT may not have a GROUP BY clause */
58199   }
58200   if( pSelect->pLimit ){
58201     return 0;   /* SELECT may not have a LIMIT clause */
58202   }
58203   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
58204   if( pSelect->pPrior ){
58205     return 0;   /* SELECT may not be a compound query */
58206   }
58207   if( pSelect->isDistinct ){
58208     return 0;   /* SELECT may not be DISTINCT */
58209   }
58210   pEList = pSelect->pEList;
58211   assert( pEList!=0 );
58212   if( pEList->nExpr!=1 ){
58213     return 0;   /* The result set must have exactly one column */
58214   }
58215   assert( pEList->a[0].pExpr );
58216   if( pEList->a[0].pExpr->op!=TK_ALL ){
58217     return 0;   /* The result set must be the special operator "*" */
58218   }
58219
58220   /* At this point we have established that the statement is of the
58221   ** correct syntactic form to participate in this optimization.  Now
58222   ** we have to check the semantics.
58223   */
58224   pItem = pSelect->pSrc->a;
58225   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
58226   if( pSrc==0 ){
58227     return 0;   /* FROM clause does not contain a real table */
58228   }
58229   if( pSrc==pDest ){
58230     return 0;   /* tab1 and tab2 may not be the same table */
58231   }
58232 #ifndef SQLITE_OMIT_VIRTUALTABLE
58233   if( pSrc->isVirtual ){
58234     return 0;   /* tab2 must not be a virtual table */
58235   }
58236 #endif
58237   if( pSrc->pSelect ){
58238     return 0;   /* tab2 may not be a view */
58239   }
58240   if( pDest->nCol!=pSrc->nCol ){
58241     return 0;   /* Number of columns must be the same in tab1 and tab2 */
58242   }
58243   if( pDest->iPKey!=pSrc->iPKey ){
58244     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
58245   }
58246   for(i=0; i<pDest->nCol; i++){
58247     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
58248       return 0;    /* Affinity must be the same on all columns */
58249     }
58250     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
58251       return 0;    /* Collating sequence must be the same on all columns */
58252     }
58253     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
58254       return 0;    /* tab2 must be NOT NULL if tab1 is */
58255     }
58256   }
58257   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
58258     if( pDestIdx->onError!=OE_None ){
58259       destHasUniqueIdx = 1;
58260     }
58261     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
58262       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
58263     }
58264     if( pSrcIdx==0 ){
58265       return 0;    /* pDestIdx has no corresponding index in pSrc */
58266     }
58267   }
58268 #ifndef SQLITE_OMIT_CHECK
58269   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
58270     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
58271   }
58272 #endif
58273
58274   /* If we get this far, it means either:
58275   **
58276   **    *   We can always do the transfer if the table contains an
58277   **        an integer primary key
58278   **
58279   **    *   We can conditionally do the transfer if the destination
58280   **        table is empty.
58281   */
58282 #ifdef SQLITE_TEST
58283   sqlite3_xferopt_count++;
58284 #endif
58285   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
58286   v = sqlite3GetVdbe(pParse);
58287   sqlite3CodeVerifySchema(pParse, iDbSrc);
58288   iSrc = pParse->nTab++;
58289   iDest = pParse->nTab++;
58290   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
58291   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
58292   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
58293     /* If tables do not have an INTEGER PRIMARY KEY and there
58294     ** are indices to be copied and the destination is not empty,
58295     ** we have to disallow the transfer optimization because the
58296     ** the rowids might change which will mess up indexing.
58297     **
58298     ** Or if the destination has a UNIQUE index and is not empty,
58299     ** we also disallow the transfer optimization because we cannot
58300     ** insure that all entries in the union of DEST and SRC will be
58301     ** unique.
58302     */
58303     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
58304     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
58305     sqlite3VdbeJumpHere(v, addr1);
58306   }else{
58307     emptyDestTest = 0;
58308   }
58309   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
58310   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
58311   regData = sqlite3GetTempReg(pParse);
58312   regRowid = sqlite3GetTempReg(pParse);
58313   if( pDest->iPKey>=0 ){
58314     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
58315     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
58316     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
58317                       "PRIMARY KEY must be unique", P4_STATIC);
58318     sqlite3VdbeJumpHere(v, addr2);
58319     autoIncStep(pParse, regAutoinc, regRowid);
58320   }else if( pDest->pIndex==0 ){
58321     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
58322   }else{
58323     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
58324     assert( pDest->autoInc==0 );
58325   }
58326   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
58327   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
58328   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
58329   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
58330   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
58331   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
58332   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
58333     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
58334       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
58335     }
58336     assert( pSrcIdx );
58337     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
58338     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
58339     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
58340     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
58341                       (char*)pKey, P4_KEYINFO_HANDOFF);
58342     VdbeComment((v, "%s", pSrcIdx->zName));
58343     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
58344     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
58345                       (char*)pKey, P4_KEYINFO_HANDOFF);
58346     VdbeComment((v, "%s", pDestIdx->zName));
58347     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
58348     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
58349     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
58350     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
58351     sqlite3VdbeJumpHere(v, addr1);
58352   }
58353   sqlite3VdbeJumpHere(v, emptySrcTest);
58354   sqlite3ReleaseTempReg(pParse, regRowid);
58355   sqlite3ReleaseTempReg(pParse, regData);
58356   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
58357   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
58358   if( emptyDestTest ){
58359     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
58360     sqlite3VdbeJumpHere(v, emptyDestTest);
58361     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
58362     return 0;
58363   }else{
58364     return 1;
58365   }
58366 }
58367 #endif /* SQLITE_OMIT_XFER_OPT */
58368
58369 /************** End of insert.c **********************************************/
58370 /************** Begin file legacy.c ******************************************/
58371 /*
58372 ** 2001 September 15
58373 **
58374 ** The author disclaims copyright to this source code.  In place of
58375 ** a legal notice, here is a blessing:
58376 **
58377 **    May you do good and not evil.
58378 **    May you find forgiveness for yourself and forgive others.
58379 **    May you share freely, never taking more than you give.
58380 **
58381 *************************************************************************
58382 ** Main file for the SQLite library.  The routines in this file
58383 ** implement the programmer interface to the library.  Routines in
58384 ** other files are for internal use by SQLite and should not be
58385 ** accessed by users of the library.
58386 **
58387 ** $Id: legacy.c,v 1.23 2008/02/13 18:25:27 danielk1977 Exp $
58388 */
58389
58390
58391 /*
58392 ** Execute SQL code.  Return one of the SQLITE_ success/failure
58393 ** codes.  Also write an error message into memory obtained from
58394 ** malloc() and make *pzErrMsg point to that message.
58395 **
58396 ** If the SQL is a query, then for each row in the query result
58397 ** the xCallback() function is called.  pArg becomes the first
58398 ** argument to xCallback().  If xCallback=NULL then no callback
58399 ** is invoked, even for queries.
58400 */
58401 SQLITE_API int sqlite3_exec(
58402   sqlite3 *db,                /* The database on which the SQL executes */
58403   const char *zSql,           /* The SQL to be executed */
58404   sqlite3_callback xCallback, /* Invoke this callback routine */
58405   void *pArg,                 /* First argument to xCallback() */
58406   char **pzErrMsg             /* Write error messages here */
58407 ){
58408   int rc = SQLITE_OK;
58409   const char *zLeftover;
58410   sqlite3_stmt *pStmt = 0;
58411   char **azCols = 0;
58412
58413   int nRetry = 0;
58414   int nCallback;
58415
58416   if( zSql==0 ) return SQLITE_OK;
58417
58418   sqlite3_mutex_enter(db->mutex);
58419   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
58420     int nCol;
58421     char **azVals = 0;
58422
58423     pStmt = 0;
58424     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
58425     assert( rc==SQLITE_OK || pStmt==0 );
58426     if( rc!=SQLITE_OK ){
58427       continue;
58428     }
58429     if( !pStmt ){
58430       /* this happens for a comment or white-space */
58431       zSql = zLeftover;
58432       continue;
58433     }
58434
58435     nCallback = 0;
58436
58437     nCol = sqlite3_column_count(pStmt);
58438     azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char *) + 1);
58439     if( azCols==0 ){
58440       goto exec_out;
58441     }
58442
58443     while( 1 ){
58444       int i;
58445       rc = sqlite3_step(pStmt);
58446
58447       /* Invoke the callback function if required */
58448       if( xCallback && (SQLITE_ROW==rc || 
58449           (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
58450         if( 0==nCallback ){
58451           for(i=0; i<nCol; i++){
58452             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
58453             if( !azCols[i] ){
58454               db->mallocFailed = 1;
58455               goto exec_out;
58456             }
58457           }
58458           nCallback++;
58459         }
58460         if( rc==SQLITE_ROW ){
58461           azVals = &azCols[nCol];
58462           for(i=0; i<nCol; i++){
58463             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
58464             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
58465               db->mallocFailed = 1;
58466               goto exec_out;
58467             }
58468           }
58469         }
58470         if( xCallback(pArg, nCol, azVals, azCols) ){
58471           rc = SQLITE_ABORT;
58472           goto exec_out;
58473         }
58474       }
58475
58476       if( rc!=SQLITE_ROW ){
58477         rc = sqlite3_finalize(pStmt);
58478         pStmt = 0;
58479         if( rc!=SQLITE_SCHEMA ){
58480           nRetry = 0;
58481           zSql = zLeftover;
58482           while( isspace((unsigned char)zSql[0]) ) zSql++;
58483         }
58484         break;
58485       }
58486     }
58487
58488     sqlite3_free(azCols);
58489     azCols = 0;
58490   }
58491
58492 exec_out:
58493   if( pStmt ) sqlite3_finalize(pStmt);
58494   if( azCols ) sqlite3_free(azCols);
58495
58496   rc = sqlite3ApiExit(db, rc);
58497   if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
58498     int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
58499     *pzErrMsg = sqlite3_malloc(nErrMsg);
58500     if( *pzErrMsg ){
58501       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
58502     }
58503   }else if( pzErrMsg ){
58504     *pzErrMsg = 0;
58505   }
58506
58507   assert( (rc&db->errMask)==rc );
58508   sqlite3_mutex_leave(db->mutex);
58509   return rc;
58510 }
58511
58512 /************** End of legacy.c **********************************************/
58513 /************** Begin file loadext.c *****************************************/
58514 /*
58515 ** 2006 June 7
58516 **
58517 ** The author disclaims copyright to this source code.  In place of
58518 ** a legal notice, here is a blessing:
58519 **
58520 **    May you do good and not evil.
58521 **    May you find forgiveness for yourself and forgive others.
58522 **    May you share freely, never taking more than you give.
58523 **
58524 *************************************************************************
58525 ** This file contains code used to dynamically load extensions into
58526 ** the SQLite library.
58527 */
58528 #ifndef SQLITE_OMIT_LOAD_EXTENSION
58529
58530 #ifndef SQLITE_CORE
58531   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
58532 #endif
58533 /************** Include sqlite3ext.h in the middle of loadext.c **************/
58534 /************** Begin file sqlite3ext.h **************************************/
58535 /*
58536 ** 2006 June 7
58537 **
58538 ** The author disclaims copyright to this source code.  In place of
58539 ** a legal notice, here is a blessing:
58540 **
58541 **    May you do good and not evil.
58542 **    May you find forgiveness for yourself and forgive others.
58543 **    May you share freely, never taking more than you give.
58544 **
58545 *************************************************************************
58546 ** This header file defines the SQLite interface for use by
58547 ** shared libraries that want to be imported as extensions into
58548 ** an SQLite instance.  Shared libraries that intend to be loaded
58549 ** as extensions by SQLite should #include this file instead of 
58550 ** sqlite3.h.
58551 **
58552 ** @(#) $Id: sqlite3ext.h,v 1.18 2008/03/02 03:32:05 mlcreech Exp $
58553 */
58554 #ifndef _SQLITE3EXT_H_
58555 #define _SQLITE3EXT_H_
58556
58557 typedef struct sqlite3_api_routines sqlite3_api_routines;
58558
58559 /*
58560 ** The following structure holds pointers to all of the SQLite API
58561 ** routines.
58562 **
58563 ** WARNING:  In order to maintain backwards compatibility, add new
58564 ** interfaces to the end of this structure only.  If you insert new
58565 ** interfaces in the middle of this structure, then older different
58566 ** versions of SQLite will not be able to load each others' shared
58567 ** libraries!
58568 */
58569 struct sqlite3_api_routines {
58570   void * (*aggregate_context)(sqlite3_context*,int nBytes);
58571   int  (*aggregate_count)(sqlite3_context*);
58572   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
58573   int  (*bind_double)(sqlite3_stmt*,int,double);
58574   int  (*bind_int)(sqlite3_stmt*,int,int);
58575   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
58576   int  (*bind_null)(sqlite3_stmt*,int);
58577   int  (*bind_parameter_count)(sqlite3_stmt*);
58578   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
58579   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
58580   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
58581   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
58582   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
58583   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
58584   int  (*busy_timeout)(sqlite3*,int ms);
58585   int  (*changes)(sqlite3*);
58586   int  (*close)(sqlite3*);
58587   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
58588   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
58589   const void * (*column_blob)(sqlite3_stmt*,int iCol);
58590   int  (*column_bytes)(sqlite3_stmt*,int iCol);
58591   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
58592   int  (*column_count)(sqlite3_stmt*pStmt);
58593   const char * (*column_database_name)(sqlite3_stmt*,int);
58594   const void * (*column_database_name16)(sqlite3_stmt*,int);
58595   const char * (*column_decltype)(sqlite3_stmt*,int i);
58596   const void * (*column_decltype16)(sqlite3_stmt*,int);
58597   double  (*column_double)(sqlite3_stmt*,int iCol);
58598   int  (*column_int)(sqlite3_stmt*,int iCol);
58599   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
58600   const char * (*column_name)(sqlite3_stmt*,int);
58601   const void * (*column_name16)(sqlite3_stmt*,int);
58602   const char * (*column_origin_name)(sqlite3_stmt*,int);
58603   const void * (*column_origin_name16)(sqlite3_stmt*,int);
58604   const char * (*column_table_name)(sqlite3_stmt*,int);
58605   const void * (*column_table_name16)(sqlite3_stmt*,int);
58606   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
58607   const void * (*column_text16)(sqlite3_stmt*,int iCol);
58608   int  (*column_type)(sqlite3_stmt*,int iCol);
58609   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
58610   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
58611   int  (*complete)(const char*sql);
58612   int  (*complete16)(const void*sql);
58613   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
58614   int  (*create_collation16)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
58615   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*));
58616   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*));
58617   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
58618   int  (*data_count)(sqlite3_stmt*pStmt);
58619   sqlite3 * (*db_handle)(sqlite3_stmt*);
58620   int (*declare_vtab)(sqlite3*,const char*);
58621   int  (*enable_shared_cache)(int);
58622   int  (*errcode)(sqlite3*db);
58623   const char * (*errmsg)(sqlite3*);
58624   const void * (*errmsg16)(sqlite3*);
58625   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
58626   int  (*expired)(sqlite3_stmt*);
58627   int  (*finalize)(sqlite3_stmt*pStmt);
58628   void  (*free)(void*);
58629   void  (*free_table)(char**result);
58630   int  (*get_autocommit)(sqlite3*);
58631   void * (*get_auxdata)(sqlite3_context*,int);
58632   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
58633   int  (*global_recover)(void);
58634   void  (*interruptx)(sqlite3*);
58635   sqlite_int64  (*last_insert_rowid)(sqlite3*);
58636   const char * (*libversion)(void);
58637   int  (*libversion_number)(void);
58638   void *(*malloc)(int);
58639   char * (*mprintf)(const char*,...);
58640   int  (*open)(const char*,sqlite3**);
58641   int  (*open16)(const void*,sqlite3**);
58642   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
58643   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
58644   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
58645   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
58646   void *(*realloc)(void*,int);
58647   int  (*reset)(sqlite3_stmt*pStmt);
58648   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
58649   void  (*result_double)(sqlite3_context*,double);
58650   void  (*result_error)(sqlite3_context*,const char*,int);
58651   void  (*result_error16)(sqlite3_context*,const void*,int);
58652   void  (*result_int)(sqlite3_context*,int);
58653   void  (*result_int64)(sqlite3_context*,sqlite_int64);
58654   void  (*result_null)(sqlite3_context*);
58655   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
58656   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
58657   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
58658   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
58659   void  (*result_value)(sqlite3_context*,sqlite3_value*);
58660   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
58661   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
58662   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
58663   char * (*snprintf)(int,char*,const char*,...);
58664   int  (*step)(sqlite3_stmt*);
58665   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
58666   void  (*thread_cleanup)(void);
58667   int  (*total_changes)(sqlite3*);
58668   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
58669   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
58670   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
58671   void * (*user_data)(sqlite3_context*);
58672   const void * (*value_blob)(sqlite3_value*);
58673   int  (*value_bytes)(sqlite3_value*);
58674   int  (*value_bytes16)(sqlite3_value*);
58675   double  (*value_double)(sqlite3_value*);
58676   int  (*value_int)(sqlite3_value*);
58677   sqlite_int64  (*value_int64)(sqlite3_value*);
58678   int  (*value_numeric_type)(sqlite3_value*);
58679   const unsigned char * (*value_text)(sqlite3_value*);
58680   const void * (*value_text16)(sqlite3_value*);
58681   const void * (*value_text16be)(sqlite3_value*);
58682   const void * (*value_text16le)(sqlite3_value*);
58683   int  (*value_type)(sqlite3_value*);
58684   char *(*vmprintf)(const char*,va_list);
58685   /* Added ??? */
58686   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
58687   /* Added by 3.3.13 */
58688   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
58689   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
58690   int (*clear_bindings)(sqlite3_stmt*);
58691   /* Added by 3.4.1 */
58692   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
58693   /* Added by 3.5.0 */
58694   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
58695   int (*blob_bytes)(sqlite3_blob*);
58696   int (*blob_close)(sqlite3_blob*);
58697   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
58698   int (*blob_read)(sqlite3_blob*,void*,int,int);
58699   int (*blob_write)(sqlite3_blob*,const void*,int,int);
58700   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
58701   int (*file_control)(sqlite3*,const char*,int,void*);
58702   sqlite3_int64 (*memory_highwater)(int);
58703   sqlite3_int64 (*memory_used)(void);
58704   sqlite3_mutex *(*mutex_alloc)(int);
58705   void (*mutex_enter)(sqlite3_mutex*);
58706   void (*mutex_free)(sqlite3_mutex*);
58707   void (*mutex_leave)(sqlite3_mutex*);
58708   int (*mutex_try)(sqlite3_mutex*);
58709   int (*open_v2)(const char*,sqlite3**,int,const char*);
58710   int (*release_memory)(int);
58711   void (*result_error_nomem)(sqlite3_context*);
58712   void (*result_error_toobig)(sqlite3_context*);
58713   int (*sleep)(int);
58714   void (*soft_heap_limit)(int);
58715   sqlite3_vfs *(*vfs_find)(const char*);
58716   int (*vfs_register)(sqlite3_vfs*,int);
58717   int (*vfs_unregister)(sqlite3_vfs*);
58718 };
58719
58720 /*
58721 ** The following macros redefine the API routines so that they are
58722 ** redirected throught the global sqlite3_api structure.
58723 **
58724 ** This header file is also used by the loadext.c source file
58725 ** (part of the main SQLite library - not an extension) so that
58726 ** it can get access to the sqlite3_api_routines structure
58727 ** definition.  But the main library does not want to redefine
58728 ** the API.  So the redefinition macros are only valid if the
58729 ** SQLITE_CORE macros is undefined.
58730 */
58731 #ifndef SQLITE_CORE
58732 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
58733 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
58734 #define sqlite3_bind_blob              sqlite3_api->bind_blob
58735 #define sqlite3_bind_double            sqlite3_api->bind_double
58736 #define sqlite3_bind_int               sqlite3_api->bind_int
58737 #define sqlite3_bind_int64             sqlite3_api->bind_int64
58738 #define sqlite3_bind_null              sqlite3_api->bind_null
58739 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
58740 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
58741 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
58742 #define sqlite3_bind_text              sqlite3_api->bind_text
58743 #define sqlite3_bind_text16            sqlite3_api->bind_text16
58744 #define sqlite3_bind_value             sqlite3_api->bind_value
58745 #define sqlite3_busy_handler           sqlite3_api->busy_handler
58746 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
58747 #define sqlite3_changes                sqlite3_api->changes
58748 #define sqlite3_close                  sqlite3_api->close
58749 #define sqlite3_collation_needed       sqlite3_api->collation_needed
58750 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
58751 #define sqlite3_column_blob            sqlite3_api->column_blob
58752 #define sqlite3_column_bytes           sqlite3_api->column_bytes
58753 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
58754 #define sqlite3_column_count           sqlite3_api->column_count
58755 #define sqlite3_column_database_name   sqlite3_api->column_database_name
58756 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
58757 #define sqlite3_column_decltype        sqlite3_api->column_decltype
58758 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
58759 #define sqlite3_column_double          sqlite3_api->column_double
58760 #define sqlite3_column_int             sqlite3_api->column_int
58761 #define sqlite3_column_int64           sqlite3_api->column_int64
58762 #define sqlite3_column_name            sqlite3_api->column_name
58763 #define sqlite3_column_name16          sqlite3_api->column_name16
58764 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
58765 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
58766 #define sqlite3_column_table_name      sqlite3_api->column_table_name
58767 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
58768 #define sqlite3_column_text            sqlite3_api->column_text
58769 #define sqlite3_column_text16          sqlite3_api->column_text16
58770 #define sqlite3_column_type            sqlite3_api->column_type
58771 #define sqlite3_column_value           sqlite3_api->column_value
58772 #define sqlite3_commit_hook            sqlite3_api->commit_hook
58773 #define sqlite3_complete               sqlite3_api->complete
58774 #define sqlite3_complete16             sqlite3_api->complete16
58775 #define sqlite3_create_collation       sqlite3_api->create_collation
58776 #define sqlite3_create_collation16     sqlite3_api->create_collation16
58777 #define sqlite3_create_function        sqlite3_api->create_function
58778 #define sqlite3_create_function16      sqlite3_api->create_function16
58779 #define sqlite3_create_module          sqlite3_api->create_module
58780 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
58781 #define sqlite3_data_count             sqlite3_api->data_count
58782 #define sqlite3_db_handle              sqlite3_api->db_handle
58783 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
58784 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
58785 #define sqlite3_errcode                sqlite3_api->errcode
58786 #define sqlite3_errmsg                 sqlite3_api->errmsg
58787 #define sqlite3_errmsg16               sqlite3_api->errmsg16
58788 #define sqlite3_exec                   sqlite3_api->exec
58789 #define sqlite3_expired                sqlite3_api->expired
58790 #define sqlite3_finalize               sqlite3_api->finalize
58791 #define sqlite3_free                   sqlite3_api->free
58792 #define sqlite3_free_table             sqlite3_api->free_table
58793 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
58794 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
58795 #define sqlite3_get_table              sqlite3_api->get_table
58796 #define sqlite3_global_recover         sqlite3_api->global_recover
58797 #define sqlite3_interrupt              sqlite3_api->interruptx
58798 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
58799 #define sqlite3_libversion             sqlite3_api->libversion
58800 #define sqlite3_libversion_number      sqlite3_api->libversion_number
58801 #define sqlite3_malloc                 sqlite3_api->malloc
58802 #define sqlite3_mprintf                sqlite3_api->mprintf
58803 #define sqlite3_open                   sqlite3_api->open
58804 #define sqlite3_open16                 sqlite3_api->open16
58805 #define sqlite3_prepare                sqlite3_api->prepare
58806 #define sqlite3_prepare16              sqlite3_api->prepare16
58807 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
58808 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
58809 #define sqlite3_profile                sqlite3_api->profile
58810 #define sqlite3_progress_handler       sqlite3_api->progress_handler
58811 #define sqlite3_realloc                sqlite3_api->realloc
58812 #define sqlite3_reset                  sqlite3_api->reset
58813 #define sqlite3_result_blob            sqlite3_api->result_blob
58814 #define sqlite3_result_double          sqlite3_api->result_double
58815 #define sqlite3_result_error           sqlite3_api->result_error
58816 #define sqlite3_result_error16         sqlite3_api->result_error16
58817 #define sqlite3_result_int             sqlite3_api->result_int
58818 #define sqlite3_result_int64           sqlite3_api->result_int64
58819 #define sqlite3_result_null            sqlite3_api->result_null
58820 #define sqlite3_result_text            sqlite3_api->result_text
58821 #define sqlite3_result_text16          sqlite3_api->result_text16
58822 #define sqlite3_result_text16be        sqlite3_api->result_text16be
58823 #define sqlite3_result_text16le        sqlite3_api->result_text16le
58824 #define sqlite3_result_value           sqlite3_api->result_value
58825 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
58826 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
58827 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
58828 #define sqlite3_snprintf               sqlite3_api->snprintf
58829 #define sqlite3_step                   sqlite3_api->step
58830 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
58831 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
58832 #define sqlite3_total_changes          sqlite3_api->total_changes
58833 #define sqlite3_trace                  sqlite3_api->trace
58834 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
58835 #define sqlite3_update_hook            sqlite3_api->update_hook
58836 #define sqlite3_user_data              sqlite3_api->user_data
58837 #define sqlite3_value_blob             sqlite3_api->value_blob
58838 #define sqlite3_value_bytes            sqlite3_api->value_bytes
58839 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
58840 #define sqlite3_value_double           sqlite3_api->value_double
58841 #define sqlite3_value_int              sqlite3_api->value_int
58842 #define sqlite3_value_int64            sqlite3_api->value_int64
58843 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
58844 #define sqlite3_value_text             sqlite3_api->value_text
58845 #define sqlite3_value_text16           sqlite3_api->value_text16
58846 #define sqlite3_value_text16be         sqlite3_api->value_text16be
58847 #define sqlite3_value_text16le         sqlite3_api->value_text16le
58848 #define sqlite3_value_type             sqlite3_api->value_type
58849 #define sqlite3_vmprintf               sqlite3_api->vmprintf
58850 #define sqlite3_overload_function      sqlite3_api->overload_function
58851 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
58852 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
58853 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
58854 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
58855 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
58856 #define sqlite3_blob_close             sqlite3_api->blob_close
58857 #define sqlite3_blob_open              sqlite3_api->blob_open
58858 #define sqlite3_blob_read              sqlite3_api->blob_read
58859 #define sqlite3_blob_write             sqlite3_api->blob_write
58860 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
58861 #define sqlite3_file_control           sqlite3_api->file_control
58862 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
58863 #define sqlite3_memory_used            sqlite3_api->memory_used
58864 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
58865 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
58866 #define sqlite3_mutex_free             sqlite3_api->mutex_free
58867 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
58868 #define sqlite3_mutex_try              sqlite3_api->mutex_try
58869 #define sqlite3_open_v2                sqlite3_api->open_v2
58870 #define sqlite3_release_memory         sqlite3_api->release_memory
58871 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
58872 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
58873 #define sqlite3_sleep                  sqlite3_api->sleep
58874 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
58875 #define sqlite3_vfs_find               sqlite3_api->vfs_find
58876 #define sqlite3_vfs_register           sqlite3_api->vfs_register
58877 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
58878 #endif /* SQLITE_CORE */
58879
58880 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api;
58881 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
58882
58883 #endif /* _SQLITE3EXT_H_ */
58884
58885 /************** End of sqlite3ext.h ******************************************/
58886 /************** Continuing where we left off in loadext.c ********************/
58887
58888 /*
58889 ** Some API routines are omitted when various features are
58890 ** excluded from a build of SQLite.  Substitute a NULL pointer
58891 ** for any missing APIs.
58892 */
58893 #ifndef SQLITE_ENABLE_COLUMN_METADATA
58894 # define sqlite3_column_database_name   0
58895 # define sqlite3_column_database_name16 0
58896 # define sqlite3_column_table_name      0
58897 # define sqlite3_column_table_name16    0
58898 # define sqlite3_column_origin_name     0
58899 # define sqlite3_column_origin_name16   0
58900 # define sqlite3_table_column_metadata  0
58901 #endif
58902
58903 #ifdef SQLITE_OMIT_AUTHORIZATION
58904 # define sqlite3_set_authorizer         0
58905 #endif
58906
58907 #ifdef SQLITE_OMIT_UTF16
58908 # define sqlite3_bind_text16            0
58909 # define sqlite3_collation_needed16     0
58910 # define sqlite3_column_decltype16      0
58911 # define sqlite3_column_name16          0
58912 # define sqlite3_column_text16          0
58913 # define sqlite3_complete16             0
58914 # define sqlite3_create_collation16     0
58915 # define sqlite3_create_function16      0
58916 # define sqlite3_errmsg16               0
58917 # define sqlite3_open16                 0
58918 # define sqlite3_prepare16              0
58919 # define sqlite3_prepare16_v2           0
58920 # define sqlite3_result_error16         0
58921 # define sqlite3_result_text16          0
58922 # define sqlite3_result_text16be        0
58923 # define sqlite3_result_text16le        0
58924 # define sqlite3_value_text16           0
58925 # define sqlite3_value_text16be         0
58926 # define sqlite3_value_text16le         0
58927 # define sqlite3_column_database_name16 0
58928 # define sqlite3_column_table_name16    0
58929 # define sqlite3_column_origin_name16   0
58930 #endif
58931
58932 #ifdef SQLITE_OMIT_COMPLETE
58933 # define sqlite3_complete 0
58934 # define sqlite3_complete16 0
58935 #endif
58936
58937 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
58938 # define sqlite3_progress_handler 0
58939 #endif
58940
58941 #ifdef SQLITE_OMIT_VIRTUALTABLE
58942 # define sqlite3_create_module 0
58943 # define sqlite3_create_module_v2 0
58944 # define sqlite3_declare_vtab 0
58945 #endif
58946
58947 #ifdef SQLITE_OMIT_SHARED_CACHE
58948 # define sqlite3_enable_shared_cache 0
58949 #endif
58950
58951 #ifdef SQLITE_OMIT_TRACE
58952 # define sqlite3_profile       0
58953 # define sqlite3_trace         0
58954 #endif
58955
58956 #ifdef SQLITE_OMIT_GET_TABLE
58957 # define sqlite3_free_table    0
58958 # define sqlite3_get_table     0
58959 #endif
58960
58961 #ifdef SQLITE_OMIT_INCRBLOB
58962 #define sqlite3_bind_zeroblob  0
58963 #define sqlite3_blob_bytes     0
58964 #define sqlite3_blob_close     0
58965 #define sqlite3_blob_open      0
58966 #define sqlite3_blob_read      0
58967 #define sqlite3_blob_write     0
58968 #endif
58969
58970 /*
58971 ** The following structure contains pointers to all SQLite API routines.
58972 ** A pointer to this structure is passed into extensions when they are
58973 ** loaded so that the extension can make calls back into the SQLite
58974 ** library.
58975 **
58976 ** When adding new APIs, add them to the bottom of this structure
58977 ** in order to preserve backwards compatibility.
58978 **
58979 ** Extensions that use newer APIs should first call the
58980 ** sqlite3_libversion_number() to make sure that the API they
58981 ** intend to use is supported by the library.  Extensions should
58982 ** also check to make sure that the pointer to the function is
58983 ** not NULL before calling it.
58984 */
58985 SQLITE_PRIVATE const sqlite3_api_routines sqlite3Apis = {
58986   sqlite3_aggregate_context,
58987   sqlite3_aggregate_count,
58988   sqlite3_bind_blob,
58989   sqlite3_bind_double,
58990   sqlite3_bind_int,
58991   sqlite3_bind_int64,
58992   sqlite3_bind_null,
58993   sqlite3_bind_parameter_count,
58994   sqlite3_bind_parameter_index,
58995   sqlite3_bind_parameter_name,
58996   sqlite3_bind_text,
58997   sqlite3_bind_text16,
58998   sqlite3_bind_value,
58999   sqlite3_busy_handler,
59000   sqlite3_busy_timeout,
59001   sqlite3_changes,
59002   sqlite3_close,
59003   sqlite3_collation_needed,
59004   sqlite3_collation_needed16,
59005   sqlite3_column_blob,
59006   sqlite3_column_bytes,
59007   sqlite3_column_bytes16,
59008   sqlite3_column_count,
59009   sqlite3_column_database_name,
59010   sqlite3_column_database_name16,
59011   sqlite3_column_decltype,
59012   sqlite3_column_decltype16,
59013   sqlite3_column_double,
59014   sqlite3_column_int,
59015   sqlite3_column_int64,
59016   sqlite3_column_name,
59017   sqlite3_column_name16,
59018   sqlite3_column_origin_name,
59019   sqlite3_column_origin_name16,
59020   sqlite3_column_table_name,
59021   sqlite3_column_table_name16,
59022   sqlite3_column_text,
59023   sqlite3_column_text16,
59024   sqlite3_column_type,
59025   sqlite3_column_value,
59026   sqlite3_commit_hook,
59027   sqlite3_complete,
59028   sqlite3_complete16,
59029   sqlite3_create_collation,
59030   sqlite3_create_collation16,
59031   sqlite3_create_function,
59032   sqlite3_create_function16,
59033   sqlite3_create_module,
59034   sqlite3_data_count,
59035   sqlite3_db_handle,
59036   sqlite3_declare_vtab,
59037   sqlite3_enable_shared_cache,
59038   sqlite3_errcode,
59039   sqlite3_errmsg,
59040   sqlite3_errmsg16,
59041   sqlite3_exec,
59042   sqlite3_expired,
59043   sqlite3_finalize,
59044   sqlite3_free,
59045   sqlite3_free_table,
59046   sqlite3_get_autocommit,
59047   sqlite3_get_auxdata,
59048   sqlite3_get_table,
59049   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
59050   sqlite3_interrupt,
59051   sqlite3_last_insert_rowid,
59052   sqlite3_libversion,
59053   sqlite3_libversion_number,
59054   sqlite3_malloc,
59055   sqlite3_mprintf,
59056   sqlite3_open,
59057   sqlite3_open16,
59058   sqlite3_prepare,
59059   sqlite3_prepare16,
59060   sqlite3_profile,
59061   sqlite3_progress_handler,
59062   sqlite3_realloc,
59063   sqlite3_reset,
59064   sqlite3_result_blob,
59065   sqlite3_result_double,
59066   sqlite3_result_error,
59067   sqlite3_result_error16,
59068   sqlite3_result_int,
59069   sqlite3_result_int64,
59070   sqlite3_result_null,
59071   sqlite3_result_text,
59072   sqlite3_result_text16,
59073   sqlite3_result_text16be,
59074   sqlite3_result_text16le,
59075   sqlite3_result_value,
59076   sqlite3_rollback_hook,
59077   sqlite3_set_authorizer,
59078   sqlite3_set_auxdata,
59079   sqlite3_snprintf,
59080   sqlite3_step,
59081   sqlite3_table_column_metadata,
59082   sqlite3_thread_cleanup,
59083   sqlite3_total_changes,
59084   sqlite3_trace,
59085   sqlite3_transfer_bindings,
59086   sqlite3_update_hook,
59087   sqlite3_user_data,
59088   sqlite3_value_blob,
59089   sqlite3_value_bytes,
59090   sqlite3_value_bytes16,
59091   sqlite3_value_double,
59092   sqlite3_value_int,
59093   sqlite3_value_int64,
59094   sqlite3_value_numeric_type,
59095   sqlite3_value_text,
59096   sqlite3_value_text16,
59097   sqlite3_value_text16be,
59098   sqlite3_value_text16le,
59099   sqlite3_value_type,
59100   sqlite3_vmprintf,
59101   /*
59102   ** The original API set ends here.  All extensions can call any
59103   ** of the APIs above provided that the pointer is not NULL.  But
59104   ** before calling APIs that follow, extension should check the
59105   ** sqlite3_libversion_number() to make sure they are dealing with
59106   ** a library that is new enough to support that API.
59107   *************************************************************************
59108   */
59109   sqlite3_overload_function,
59110
59111   /*
59112   ** Added after 3.3.13
59113   */
59114   sqlite3_prepare_v2,
59115   sqlite3_prepare16_v2,
59116   sqlite3_clear_bindings,
59117
59118   /*
59119   ** Added for 3.4.1
59120   */
59121   sqlite3_create_module_v2,
59122
59123   /*
59124   ** Added for 3.5.0
59125   */
59126   sqlite3_bind_zeroblob,
59127   sqlite3_blob_bytes,
59128   sqlite3_blob_close,
59129   sqlite3_blob_open,
59130   sqlite3_blob_read,
59131   sqlite3_blob_write,
59132   sqlite3_create_collation_v2,
59133   sqlite3_file_control,
59134   sqlite3_memory_highwater,
59135   sqlite3_memory_used,
59136 #ifdef SQLITE_MUTEX_NOOP
59137   0, 
59138   0, 
59139   0,
59140   0,
59141   0,
59142 #else
59143   sqlite3_mutex_alloc,
59144   sqlite3_mutex_enter,
59145   sqlite3_mutex_free,
59146   sqlite3_mutex_leave,
59147   sqlite3_mutex_try,
59148 #endif
59149   sqlite3_open_v2,
59150   sqlite3_release_memory,
59151   sqlite3_result_error_nomem,
59152   sqlite3_result_error_toobig,
59153   sqlite3_sleep,
59154   sqlite3_soft_heap_limit,
59155   sqlite3_vfs_find,
59156   sqlite3_vfs_register,
59157   sqlite3_vfs_unregister,
59158 };
59159
59160 /*
59161 ** Attempt to load an SQLite extension library contained in the file
59162 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
59163 ** default entry point name (sqlite3_extension_init) is used.  Use
59164 ** of the default name is recommended.
59165 **
59166 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
59167 **
59168 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
59169 ** error message text.  The calling function should free this memory
59170 ** by calling sqlite3_free().
59171 */
59172 static int sqlite3LoadExtension(
59173   sqlite3 *db,          /* Load the extension into this database connection */
59174   const char *zFile,    /* Name of the shared library containing extension */
59175   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
59176   char **pzErrMsg       /* Put error message here if not 0 */
59177 ){
59178   sqlite3_vfs *pVfs = db->pVfs;
59179   void *handle;
59180   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
59181   char *zErrmsg = 0;
59182   void **aHandle;
59183
59184   /* Ticket #1863.  To avoid a creating security problems for older
59185   ** applications that relink against newer versions of SQLite, the
59186   ** ability to run load_extension is turned off by default.  One
59187   ** must call sqlite3_enable_load_extension() to turn on extension
59188   ** loading.  Otherwise you get the following error.
59189   */
59190   if( (db->flags & SQLITE_LoadExtension)==0 ){
59191     if( pzErrMsg ){
59192       *pzErrMsg = sqlite3_mprintf("not authorized");
59193     }
59194     return SQLITE_ERROR;
59195   }
59196
59197   if( zProc==0 ){
59198     zProc = "sqlite3_extension_init";
59199   }
59200
59201   handle = sqlite3OsDlOpen(pVfs, zFile);
59202   if( handle==0 ){
59203     if( pzErrMsg ){
59204       char zErr[256];
59205       zErr[sizeof(zErr)-1] = '\0';
59206       sqlite3_snprintf(sizeof(zErr)-1, zErr, 
59207           "unable to open shared library [%s]", zFile);
59208       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
59209       *pzErrMsg = sqlite3DbStrDup(db, zErr);
59210     }
59211     return SQLITE_ERROR;
59212   }
59213   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
59214                    sqlite3OsDlSym(pVfs, handle, zProc);
59215   if( xInit==0 ){
59216     if( pzErrMsg ){
59217       char zErr[256];
59218       zErr[sizeof(zErr)-1] = '\0';
59219       sqlite3_snprintf(sizeof(zErr)-1, zErr,
59220           "no entry point [%s] in shared library [%s]", zProc,zFile);
59221       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
59222       *pzErrMsg = sqlite3DbStrDup(db, zErr);
59223       sqlite3OsDlClose(pVfs, handle);
59224     }
59225     return SQLITE_ERROR;
59226   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
59227     if( pzErrMsg ){
59228       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
59229     }
59230     sqlite3_free(zErrmsg);
59231     sqlite3OsDlClose(pVfs, handle);
59232     return SQLITE_ERROR;
59233   }
59234
59235   /* Append the new shared library handle to the db->aExtension array. */
59236   db->nExtension++;
59237   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db->nExtension);
59238   if( aHandle==0 ){
59239     return SQLITE_NOMEM;
59240   }
59241   if( db->nExtension>0 ){
59242     memcpy(aHandle, db->aExtension, sizeof(handle)*(db->nExtension-1));
59243   }
59244   sqlite3_free(db->aExtension);
59245   db->aExtension = aHandle;
59246
59247   db->aExtension[db->nExtension-1] = handle;
59248   return SQLITE_OK;
59249 }
59250 SQLITE_API int sqlite3_load_extension(
59251   sqlite3 *db,          /* Load the extension into this database connection */
59252   const char *zFile,    /* Name of the shared library containing extension */
59253   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
59254   char **pzErrMsg       /* Put error message here if not 0 */
59255 ){
59256   int rc;
59257   sqlite3_mutex_enter(db->mutex);
59258   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
59259   sqlite3_mutex_leave(db->mutex);
59260   return rc;
59261 }
59262
59263 /*
59264 ** Call this routine when the database connection is closing in order
59265 ** to clean up loaded extensions
59266 */
59267 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
59268   int i;
59269   assert( sqlite3_mutex_held(db->mutex) );
59270   for(i=0; i<db->nExtension; i++){
59271     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
59272   }
59273   sqlite3_free(db->aExtension);
59274 }
59275
59276 /*
59277 ** Enable or disable extension loading.  Extension loading is disabled by
59278 ** default so as not to open security holes in older applications.
59279 */
59280 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
59281   sqlite3_mutex_enter(db->mutex);
59282   if( onoff ){
59283     db->flags |= SQLITE_LoadExtension;
59284   }else{
59285     db->flags &= ~SQLITE_LoadExtension;
59286   }
59287   sqlite3_mutex_leave(db->mutex);
59288   return SQLITE_OK;
59289 }
59290
59291 /*
59292 ** The following object holds the list of automatically loaded
59293 ** extensions.
59294 **
59295 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
59296 ** mutex must be held while accessing this list.
59297 */
59298 static struct {
59299   int nExt;        /* Number of entries in aExt[] */          
59300   void **aExt;     /* Pointers to the extension init functions */
59301 } autoext = { 0, 0 };
59302
59303
59304 /*
59305 ** Register a statically linked extension that is automatically
59306 ** loaded by every new database connection.
59307 */
59308 SQLITE_API int sqlite3_auto_extension(void *xInit){
59309   int i;
59310   int rc = SQLITE_OK;
59311   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
59312   sqlite3_mutex_enter(mutex);
59313   for(i=0; i<autoext.nExt; i++){
59314     if( autoext.aExt[i]==xInit ) break;
59315   }
59316   if( i==autoext.nExt ){
59317     int nByte = (autoext.nExt+1)*sizeof(autoext.aExt[0]);
59318     void **aNew;
59319     aNew = sqlite3_realloc(autoext.aExt, nByte);
59320     if( aNew==0 ){
59321       rc = SQLITE_NOMEM;
59322     }else{
59323       autoext.aExt = aNew;
59324       autoext.aExt[autoext.nExt] = xInit;
59325       autoext.nExt++;
59326     }
59327   }
59328   sqlite3_mutex_leave(mutex);
59329   assert( (rc&0xff)==rc );
59330   return rc;
59331 }
59332
59333 /*
59334 ** Reset the automatic extension loading mechanism.
59335 */
59336 SQLITE_API void sqlite3_reset_auto_extension(void){
59337   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
59338   sqlite3_mutex_enter(mutex);
59339   sqlite3_free(autoext.aExt);
59340   autoext.aExt = 0;
59341   autoext.nExt = 0;
59342   sqlite3_mutex_leave(mutex);
59343 }
59344
59345 /*
59346 ** Load all automatic extensions.
59347 */
59348 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
59349   int i;
59350   int go = 1;
59351   int rc = SQLITE_OK;
59352   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
59353
59354   if( autoext.nExt==0 ){
59355     /* Common case: early out without every having to acquire a mutex */
59356     return SQLITE_OK;
59357   }
59358   for(i=0; go; i++){
59359     char *zErrmsg = 0;
59360     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
59361     sqlite3_mutex_enter(mutex);
59362     if( i>=autoext.nExt ){
59363       xInit = 0;
59364       go = 0;
59365     }else{
59366       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
59367               autoext.aExt[i];
59368     }
59369     sqlite3_mutex_leave(mutex);
59370     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
59371       sqlite3Error(db, SQLITE_ERROR,
59372             "automatic extension loading failed: %s", zErrmsg);
59373       go = 0;
59374       rc = SQLITE_ERROR;
59375       sqlite3_free(zErrmsg);
59376     }
59377   }
59378   return rc;
59379 }
59380
59381 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
59382
59383 /************** End of loadext.c *********************************************/
59384 /************** Begin file pragma.c ******************************************/
59385 /*
59386 ** 2003 April 6
59387 **
59388 ** The author disclaims copyright to this source code.  In place of
59389 ** a legal notice, here is a blessing:
59390 **
59391 **    May you do good and not evil.
59392 **    May you find forgiveness for yourself and forgive others.
59393 **    May you share freely, never taking more than you give.
59394 **
59395 *************************************************************************
59396 ** This file contains code used to implement the PRAGMA command.
59397 **
59398 ** $Id: pragma.c,v 1.170 2008/02/13 18:25:27 danielk1977 Exp $
59399 */
59400
59401 /* Ignore this whole file if pragmas are disabled
59402 */
59403 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
59404
59405 /*
59406 ** Interpret the given string as a safety level.  Return 0 for OFF,
59407 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
59408 ** unrecognized string argument.
59409 **
59410 ** Note that the values returned are one less that the values that
59411 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
59412 ** to support legacy SQL code.  The safety level used to be boolean
59413 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
59414 */
59415 static int getSafetyLevel(const char *z){
59416                              /* 123456789 123456789 */
59417   static const char zText[] = "onoffalseyestruefull";
59418   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
59419   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
59420   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
59421   int i, n;
59422   if( isdigit(*z) ){
59423     return atoi(z);
59424   }
59425   n = strlen(z);
59426   for(i=0; i<sizeof(iLength); i++){
59427     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
59428       return iValue[i];
59429     }
59430   }
59431   return 1;
59432 }
59433
59434 /*
59435 ** Interpret the given string as a boolean value.
59436 */
59437 static int getBoolean(const char *z){
59438   return getSafetyLevel(z)&1;
59439 }
59440
59441 /*
59442 ** Interpret the given string as a locking mode value.
59443 */
59444 static int getLockingMode(const char *z){
59445   if( z ){
59446     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
59447     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
59448   }
59449   return PAGER_LOCKINGMODE_QUERY;
59450 }
59451
59452 #ifndef SQLITE_OMIT_AUTOVACUUM
59453 /*
59454 ** Interpret the given string as an auto-vacuum mode value.
59455 **
59456 ** The following strings, "none", "full" and "incremental" are 
59457 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
59458 */
59459 static int getAutoVacuum(const char *z){
59460   int i;
59461   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
59462   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
59463   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
59464   i = atoi(z);
59465   return ((i>=0&&i<=2)?i:0);
59466 }
59467 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
59468
59469 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
59470 /*
59471 ** Interpret the given string as a temp db location. Return 1 for file
59472 ** backed temporary databases, 2 for the Red-Black tree in memory database
59473 ** and 0 to use the compile-time default.
59474 */
59475 static int getTempStore(const char *z){
59476   if( z[0]>='0' && z[0]<='2' ){
59477     return z[0] - '0';
59478   }else if( sqlite3StrICmp(z, "file")==0 ){
59479     return 1;
59480   }else if( sqlite3StrICmp(z, "memory")==0 ){
59481     return 2;
59482   }else{
59483     return 0;
59484   }
59485 }
59486 #endif /* SQLITE_PAGER_PRAGMAS */
59487
59488 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
59489 /*
59490 ** Invalidate temp storage, either when the temp storage is changed
59491 ** from default, or when 'file' and the temp_store_directory has changed
59492 */
59493 static int invalidateTempStorage(Parse *pParse){
59494   sqlite3 *db = pParse->db;
59495   if( db->aDb[1].pBt!=0 ){
59496     if( !db->autoCommit ){
59497       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
59498         "from within a transaction");
59499       return SQLITE_ERROR;
59500     }
59501     sqlite3BtreeClose(db->aDb[1].pBt);
59502     db->aDb[1].pBt = 0;
59503     sqlite3ResetInternalSchema(db, 0);
59504   }
59505   return SQLITE_OK;
59506 }
59507 #endif /* SQLITE_PAGER_PRAGMAS */
59508
59509 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
59510 /*
59511 ** If the TEMP database is open, close it and mark the database schema
59512 ** as needing reloading.  This must be done when using the TEMP_STORE
59513 ** or DEFAULT_TEMP_STORE pragmas.
59514 */
59515 static int changeTempStorage(Parse *pParse, const char *zStorageType){
59516   int ts = getTempStore(zStorageType);
59517   sqlite3 *db = pParse->db;
59518   if( db->temp_store==ts ) return SQLITE_OK;
59519   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
59520     return SQLITE_ERROR;
59521   }
59522   db->temp_store = ts;
59523   return SQLITE_OK;
59524 }
59525 #endif /* SQLITE_PAGER_PRAGMAS */
59526
59527 /*
59528 ** Generate code to return a single integer value.
59529 */
59530 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
59531   Vdbe *v = sqlite3GetVdbe(pParse);
59532   int mem = ++pParse->nMem;
59533   sqlite3VdbeAddOp2(v, OP_Integer, value, mem);
59534   if( pParse->explain==0 ){
59535     sqlite3VdbeSetNumCols(v, 1);
59536     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P4_STATIC);
59537   }
59538   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
59539 }
59540
59541 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
59542 /*
59543 ** Check to see if zRight and zLeft refer to a pragma that queries
59544 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
59545 ** Also, implement the pragma.
59546 */
59547 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
59548   static const struct sPragmaType {
59549     const char *zName;  /* Name of the pragma */
59550     int mask;           /* Mask for the db->flags value */
59551   } aPragma[] = {
59552     { "full_column_names",        SQLITE_FullColNames  },
59553     { "short_column_names",       SQLITE_ShortColNames },
59554     { "count_changes",            SQLITE_CountRows     },
59555     { "empty_result_callbacks",   SQLITE_NullCallback  },
59556     { "legacy_file_format",       SQLITE_LegacyFileFmt },
59557     { "fullfsync",                SQLITE_FullFSync     },
59558 #ifdef SQLITE_DEBUG
59559     { "sql_trace",                SQLITE_SqlTrace      },
59560     { "vdbe_listing",             SQLITE_VdbeListing   },
59561     { "vdbe_trace",               SQLITE_VdbeTrace     },
59562 #endif
59563 #ifndef SQLITE_OMIT_CHECK
59564     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
59565 #endif
59566     /* The following is VERY experimental */
59567     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
59568     { "omit_readlock",            SQLITE_NoReadlock    },
59569
59570     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
59571     ** flag if there are any active statements. */
59572     { "read_uncommitted",         SQLITE_ReadUncommitted },
59573   };
59574   int i;
59575   const struct sPragmaType *p;
59576   for(i=0, p=aPragma; i<sizeof(aPragma)/sizeof(aPragma[0]); i++, p++){
59577     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
59578       sqlite3 *db = pParse->db;
59579       Vdbe *v;
59580       v = sqlite3GetVdbe(pParse);
59581       if( v ){
59582         if( zRight==0 ){
59583           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
59584         }else{
59585           if( getBoolean(zRight) ){
59586             db->flags |= p->mask;
59587           }else{
59588             db->flags &= ~p->mask;
59589           }
59590
59591           /* Many of the flag-pragmas modify the code generated by the SQL 
59592           ** compiler (eg. count_changes). So add an opcode to expire all
59593           ** compiled SQL statements after modifying a pragma value.
59594           */
59595           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
59596         }
59597       }
59598
59599       return 1;
59600     }
59601   }
59602   return 0;
59603 }
59604 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
59605
59606 /*
59607 ** Process a pragma statement.  
59608 **
59609 ** Pragmas are of this form:
59610 **
59611 **      PRAGMA [database.]id [= value]
59612 **
59613 ** The identifier might also be a string.  The value is a string, and
59614 ** identifier, or a number.  If minusFlag is true, then the value is
59615 ** a number that was preceded by a minus sign.
59616 **
59617 ** If the left side is "database.id" then pId1 is the database name
59618 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
59619 ** id and pId2 is any empty string.
59620 */
59621 SQLITE_PRIVATE void sqlite3Pragma(
59622   Parse *pParse, 
59623   Token *pId1,        /* First part of [database.]id field */
59624   Token *pId2,        /* Second part of [database.]id field, or NULL */
59625   Token *pValue,      /* Token for <value>, or NULL */
59626   int minusFlag       /* True if a '-' sign preceded <value> */
59627 ){
59628   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
59629   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
59630   const char *zDb = 0;   /* The database name */
59631   Token *pId;            /* Pointer to <id> token */
59632   int iDb;               /* Database index for <database> */
59633   sqlite3 *db = pParse->db;
59634   Db *pDb;
59635   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
59636   if( v==0 ) return;
59637   pParse->nMem = 2;
59638
59639   /* Interpret the [database.] part of the pragma statement. iDb is the
59640   ** index of the database this pragma is being applied to in db.aDb[]. */
59641   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
59642   if( iDb<0 ) return;
59643   pDb = &db->aDb[iDb];
59644
59645   /* If the temp database has been explicitly named as part of the 
59646   ** pragma, make sure it is open. 
59647   */
59648   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
59649     return;
59650   }
59651
59652   zLeft = sqlite3NameFromToken(db, pId);
59653   if( !zLeft ) return;
59654   if( minusFlag ){
59655     zRight = sqlite3MPrintf(db, "-%T", pValue);
59656   }else{
59657     zRight = sqlite3NameFromToken(db, pValue);
59658   }
59659
59660   zDb = ((iDb>0)?pDb->zName:0);
59661   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
59662     goto pragma_out;
59663   }
59664  
59665 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
59666   /*
59667   **  PRAGMA [database.]default_cache_size
59668   **  PRAGMA [database.]default_cache_size=N
59669   **
59670   ** The first form reports the current persistent setting for the
59671   ** page cache size.  The value returned is the maximum number of
59672   ** pages in the page cache.  The second form sets both the current
59673   ** page cache size value and the persistent page cache size value
59674   ** stored in the database file.
59675   **
59676   ** The default cache size is stored in meta-value 2 of page 1 of the
59677   ** database file.  The cache size is actually the absolute value of
59678   ** this memory location.  The sign of meta-value 2 determines the
59679   ** synchronous setting.  A negative value means synchronous is off
59680   ** and a positive value means synchronous is on.
59681   */
59682   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
59683     static const VdbeOpList getCacheSize[] = {
59684       { OP_ReadCookie,  0, 1,        2},  /* 0 */
59685       { OP_IfPos,       1, 6,        0},
59686       { OP_Integer,     0, 2,        0},
59687       { OP_Subtract,    1, 2,        1},
59688       { OP_IfPos,       1, 6,        0},
59689       { OP_Integer,     0, 1,        0},  /* 5 */
59690       { OP_ResultRow,   1, 1,        0},
59691     };
59692     int addr;
59693     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
59694     sqlite3VdbeUsesBtree(v, iDb);
59695     if( !zRight ){
59696       sqlite3VdbeSetNumCols(v, 1);
59697       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P4_STATIC);
59698       pParse->nMem += 2;
59699       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
59700       sqlite3VdbeChangeP1(v, addr, iDb);
59701       sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
59702     }else{
59703       int size = atoi(zRight);
59704       if( size<0 ) size = -size;
59705       sqlite3BeginWriteOperation(pParse, 0, iDb);
59706       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
59707       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
59708       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
59709       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
59710       sqlite3VdbeJumpHere(v, addr);
59711       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
59712       pDb->pSchema->cache_size = size;
59713       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
59714     }
59715   }else
59716
59717   /*
59718   **  PRAGMA [database.]page_size
59719   **  PRAGMA [database.]page_size=N
59720   **
59721   ** The first form reports the current setting for the
59722   ** database page size in bytes.  The second form sets the
59723   ** database page size value.  The value can only be set if
59724   ** the database has not yet been created.
59725   */
59726   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
59727     Btree *pBt = pDb->pBt;
59728     if( !zRight ){
59729       int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
59730       returnSingleInt(pParse, "page_size", size);
59731     }else{
59732       /* Malloc may fail when setting the page-size, as there is an internal
59733       ** buffer that the pager module resizes using sqlite3_realloc().
59734       */
59735       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, atoi(zRight), -1) ){
59736         db->mallocFailed = 1;
59737       }
59738     }
59739   }else
59740
59741   /*
59742   **  PRAGMA [database.]max_page_count
59743   **  PRAGMA [database.]max_page_count=N
59744   **
59745   ** The first form reports the current setting for the
59746   ** maximum number of pages in the database file.  The 
59747   ** second form attempts to change this setting.  Both
59748   ** forms return the current setting.
59749   */
59750   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
59751     Btree *pBt = pDb->pBt;
59752     int newMax = 0;
59753     if( zRight ){
59754       newMax = atoi(zRight);
59755     }
59756     if( pBt ){
59757       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
59758     }
59759     returnSingleInt(pParse, "max_page_count", newMax);
59760   }else
59761
59762   /*
59763   **  PRAGMA [database.]locking_mode
59764   **  PRAGMA [database.]locking_mode = (normal|exclusive)
59765   */
59766   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
59767     const char *zRet = "normal";
59768     int eMode = getLockingMode(zRight);
59769
59770     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
59771       /* Simple "PRAGMA locking_mode;" statement. This is a query for
59772       ** the current default locking mode (which may be different to
59773       ** the locking-mode of the main database).
59774       */
59775       eMode = db->dfltLockMode;
59776     }else{
59777       Pager *pPager;
59778       if( pId2->n==0 ){
59779         /* This indicates that no database name was specified as part
59780         ** of the PRAGMA command. In this case the locking-mode must be
59781         ** set on all attached databases, as well as the main db file.
59782         **
59783         ** Also, the sqlite3.dfltLockMode variable is set so that
59784         ** any subsequently attached databases also use the specified
59785         ** locking mode.
59786         */
59787         int ii;
59788         assert(pDb==&db->aDb[0]);
59789         for(ii=2; ii<db->nDb; ii++){
59790           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
59791           sqlite3PagerLockingMode(pPager, eMode);
59792         }
59793         db->dfltLockMode = eMode;
59794       }
59795       pPager = sqlite3BtreePager(pDb->pBt);
59796       eMode = sqlite3PagerLockingMode(pPager, eMode);
59797     }
59798
59799     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
59800     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
59801       zRet = "exclusive";
59802     }
59803     sqlite3VdbeSetNumCols(v, 1);
59804     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P4_STATIC);
59805     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
59806     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
59807   }else
59808 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
59809
59810   /*
59811   **  PRAGMA [database.]auto_vacuum
59812   **  PRAGMA [database.]auto_vacuum=N
59813   **
59814   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
59815   */
59816 #ifndef SQLITE_OMIT_AUTOVACUUM
59817   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
59818     Btree *pBt = pDb->pBt;
59819     if( sqlite3ReadSchema(pParse) ){
59820       goto pragma_out;
59821     }
59822     if( !zRight ){
59823       int auto_vacuum = 
59824           pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
59825       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
59826     }else{
59827       int eAuto = getAutoVacuum(zRight);
59828       db->nextAutovac = eAuto;
59829       if( eAuto>=0 ){
59830         /* Call SetAutoVacuum() to set initialize the internal auto and
59831         ** incr-vacuum flags. This is required in case this connection
59832         ** creates the database file. It is important that it is created
59833         ** as an auto-vacuum capable db.
59834         */
59835         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
59836         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
59837           /* When setting the auto_vacuum mode to either "full" or 
59838           ** "incremental", write the value of meta[6] in the database
59839           ** file. Before writing to meta[6], check that meta[3] indicates
59840           ** that this really is an auto-vacuum capable database.
59841           */
59842           static const VdbeOpList setMeta6[] = {
59843             { OP_Transaction,    0,               1,        0},    /* 0 */
59844             { OP_ReadCookie,     0,               1,        3},    /* 1 */
59845             { OP_If,             1,               0,        0},    /* 2 */
59846             { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
59847             { OP_Integer,        0,               1,        0},    /* 4 */
59848             { OP_SetCookie,      0,               6,        1},    /* 5 */
59849           };
59850           int iAddr;
59851           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
59852           sqlite3VdbeChangeP1(v, iAddr, iDb);
59853           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
59854           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
59855           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
59856           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
59857           sqlite3VdbeUsesBtree(v, iDb);
59858         }
59859       }
59860     }
59861   }else
59862 #endif
59863
59864   /*
59865   **  PRAGMA [database.]incremental_vacuum(N)
59866   **
59867   ** Do N steps of incremental vacuuming on a database.
59868   */
59869 #ifndef SQLITE_OMIT_AUTOVACUUM
59870   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
59871     int iLimit, addr;
59872     if( sqlite3ReadSchema(pParse) ){
59873       goto pragma_out;
59874     }
59875     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
59876       iLimit = 0x7fffffff;
59877     }
59878     sqlite3BeginWriteOperation(pParse, 0, iDb);
59879     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
59880     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
59881     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
59882     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
59883     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
59884     sqlite3VdbeJumpHere(v, addr);
59885   }else
59886 #endif
59887
59888 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
59889   /*
59890   **  PRAGMA [database.]cache_size
59891   **  PRAGMA [database.]cache_size=N
59892   **
59893   ** The first form reports the current local setting for the
59894   ** page cache size.  The local setting can be different from
59895   ** the persistent cache size value that is stored in the database
59896   ** file itself.  The value returned is the maximum number of
59897   ** pages in the page cache.  The second form sets the local
59898   ** page cache size value.  It does not change the persistent
59899   ** cache size stored on the disk so the cache size will revert
59900   ** to its default value when the database is closed and reopened.
59901   ** N should be a positive integer.
59902   */
59903   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
59904     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
59905     if( !zRight ){
59906       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
59907     }else{
59908       int size = atoi(zRight);
59909       if( size<0 ) size = -size;
59910       pDb->pSchema->cache_size = size;
59911       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
59912     }
59913   }else
59914
59915   /*
59916   **   PRAGMA temp_store
59917   **   PRAGMA temp_store = "default"|"memory"|"file"
59918   **
59919   ** Return or set the local value of the temp_store flag.  Changing
59920   ** the local value does not make changes to the disk file and the default
59921   ** value will be restored the next time the database is opened.
59922   **
59923   ** Note that it is possible for the library compile-time options to
59924   ** override this setting
59925   */
59926   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
59927     if( !zRight ){
59928       returnSingleInt(pParse, "temp_store", db->temp_store);
59929     }else{
59930       changeTempStorage(pParse, zRight);
59931     }
59932   }else
59933
59934   /*
59935   **   PRAGMA temp_store_directory
59936   **   PRAGMA temp_store_directory = ""|"directory_name"
59937   **
59938   ** Return or set the local value of the temp_store_directory flag.  Changing
59939   ** the value sets a specific directory to be used for temporary files.
59940   ** Setting to a null string reverts to the default temporary directory search.
59941   ** If temporary directory is changed, then invalidateTempStorage.
59942   **
59943   */
59944   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
59945     if( !zRight ){
59946       if( sqlite3_temp_directory ){
59947         sqlite3VdbeSetNumCols(v, 1);
59948         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
59949             "temp_store_directory", P4_STATIC);
59950         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
59951         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
59952       }
59953     }else{
59954       if( zRight[0] 
59955        && !sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE) 
59956       ){
59957         sqlite3ErrorMsg(pParse, "not a writable directory");
59958         goto pragma_out;
59959       }
59960       if( TEMP_STORE==0
59961        || (TEMP_STORE==1 && db->temp_store<=1)
59962        || (TEMP_STORE==2 && db->temp_store==1)
59963       ){
59964         invalidateTempStorage(pParse);
59965       }
59966       sqlite3_free(sqlite3_temp_directory);
59967       if( zRight[0] ){
59968         sqlite3_temp_directory = zRight;
59969         zRight = 0;
59970       }else{
59971         sqlite3_temp_directory = 0;
59972       }
59973     }
59974   }else
59975
59976   /*
59977   **   PRAGMA [database.]synchronous
59978   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
59979   **
59980   ** Return or set the local value of the synchronous flag.  Changing
59981   ** the local value does not make changes to the disk file and the
59982   ** default value will be restored the next time the database is
59983   ** opened.
59984   */
59985   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
59986     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
59987     if( !zRight ){
59988       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
59989     }else{
59990       if( !db->autoCommit ){
59991         sqlite3ErrorMsg(pParse, 
59992             "Safety level may not be changed inside a transaction");
59993       }else{
59994         pDb->safety_level = getSafetyLevel(zRight)+1;
59995       }
59996     }
59997   }else
59998 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
59999
60000 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
60001   if( flagPragma(pParse, zLeft, zRight) ){
60002     /* The flagPragma() subroutine also generates any necessary code
60003     ** there is nothing more to do here */
60004   }else
60005 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
60006
60007 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
60008   /*
60009   **   PRAGMA table_info(<table>)
60010   **
60011   ** Return a single row for each column of the named table. The columns of
60012   ** the returned data set are:
60013   **
60014   ** cid:        Column id (numbered from left to right, starting at 0)
60015   ** name:       Column name
60016   ** type:       Column declaration type.
60017   ** notnull:    True if 'NOT NULL' is part of column declaration
60018   ** dflt_value: The default value for the column, if any.
60019   */
60020   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
60021     Table *pTab;
60022     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
60023     pTab = sqlite3FindTable(db, zRight, zDb);
60024     if( pTab ){
60025       int i;
60026       int nHidden = 0;
60027       Column *pCol;
60028       sqlite3VdbeSetNumCols(v, 6);
60029       pParse->nMem = 6;
60030       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P4_STATIC);
60031       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
60032       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P4_STATIC);
60033       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P4_STATIC);
60034       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P4_STATIC);
60035       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P4_STATIC);
60036       sqlite3ViewGetColumnNames(pParse, pTab);
60037       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
60038         const Token *pDflt;
60039         if( IsHiddenColumn(pCol) ){
60040           nHidden++;
60041           continue;
60042         }
60043         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
60044         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
60045         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
60046            pCol->zType ? pCol->zType : "", 0);
60047         sqlite3VdbeAddOp2(v, OP_Integer, pCol->notNull, 4);
60048         if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
60049           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n);
60050         }else{
60051           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
60052         }
60053         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
60054         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
60055       }
60056     }
60057   }else
60058
60059   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
60060     Index *pIdx;
60061     Table *pTab;
60062     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
60063     pIdx = sqlite3FindIndex(db, zRight, zDb);
60064     if( pIdx ){
60065       int i;
60066       pTab = pIdx->pTable;
60067       sqlite3VdbeSetNumCols(v, 3);
60068       pParse->nMem = 3;
60069       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P4_STATIC);
60070       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P4_STATIC);
60071       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P4_STATIC);
60072       for(i=0; i<pIdx->nColumn; i++){
60073         int cnum = pIdx->aiColumn[i];
60074         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
60075         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
60076         assert( pTab->nCol>cnum );
60077         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
60078         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
60079       }
60080     }
60081   }else
60082
60083   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
60084     Index *pIdx;
60085     Table *pTab;
60086     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
60087     pTab = sqlite3FindTable(db, zRight, zDb);
60088     if( pTab ){
60089       v = sqlite3GetVdbe(pParse);
60090       pIdx = pTab->pIndex;
60091       if( pIdx ){
60092         int i = 0; 
60093         sqlite3VdbeSetNumCols(v, 3);
60094         pParse->nMem = 3;
60095         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
60096         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
60097         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P4_STATIC);
60098         while(pIdx){
60099           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
60100           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
60101           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
60102           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
60103           ++i;
60104           pIdx = pIdx->pNext;
60105         }
60106       }
60107     }
60108   }else
60109
60110   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
60111     int i;
60112     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
60113     sqlite3VdbeSetNumCols(v, 3);
60114     pParse->nMem = 3;
60115     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
60116     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
60117     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P4_STATIC);
60118     for(i=0; i<db->nDb; i++){
60119       if( db->aDb[i].pBt==0 ) continue;
60120       assert( db->aDb[i].zName!=0 );
60121       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
60122       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
60123       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
60124            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
60125       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
60126     }
60127   }else
60128
60129   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
60130     int i = 0;
60131     HashElem *p;
60132     sqlite3VdbeSetNumCols(v, 2);
60133     pParse->nMem = 2;
60134     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
60135     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
60136     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
60137       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
60138       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
60139       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
60140       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
60141     }
60142   }else
60143 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
60144
60145 #ifndef SQLITE_OMIT_FOREIGN_KEY
60146   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
60147     FKey *pFK;
60148     Table *pTab;
60149     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
60150     pTab = sqlite3FindTable(db, zRight, zDb);
60151     if( pTab ){
60152       v = sqlite3GetVdbe(pParse);
60153       pFK = pTab->pFKey;
60154       if( pFK ){
60155         int i = 0; 
60156         sqlite3VdbeSetNumCols(v, 5);
60157         pParse->nMem = 5;
60158         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P4_STATIC);
60159         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P4_STATIC);
60160         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P4_STATIC);
60161         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P4_STATIC);
60162         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P4_STATIC);
60163         while(pFK){
60164           int j;
60165           for(j=0; j<pFK->nCol; j++){
60166             char *zCol = pFK->aCol[j].zCol;
60167             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
60168             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
60169             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
60170             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
60171                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
60172             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
60173             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
60174           }
60175           ++i;
60176           pFK = pFK->pNextFrom;
60177         }
60178       }
60179     }
60180   }else
60181 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
60182
60183 #ifndef NDEBUG
60184   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
60185     if( zRight ){
60186       if( getBoolean(zRight) ){
60187         sqlite3ParserTrace(stderr, "parser: ");
60188       }else{
60189         sqlite3ParserTrace(0, 0);
60190       }
60191     }
60192   }else
60193 #endif
60194
60195   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
60196   ** used will be case sensitive or not depending on the RHS.
60197   */
60198   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
60199     if( zRight ){
60200       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
60201     }
60202   }else
60203
60204 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
60205 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
60206 #endif
60207
60208 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60209   /* Pragma "quick_check" is an experimental reduced version of 
60210   ** integrity_check designed to detect most database corruption
60211   ** without most of the overhead of a full integrity-check.
60212   */
60213   if( sqlite3StrICmp(zLeft, "integrity_check")==0
60214    || sqlite3StrICmp(zLeft, "quick_check")==0 
60215   ){
60216     int i, j, addr, mxErr;
60217
60218     /* Code that appears at the end of the integrity check.  If no error
60219     ** messages have been generated, output OK.  Otherwise output the
60220     ** error message
60221     */
60222     static const VdbeOpList endCode[] = {
60223       { OP_AddImm,      1, 0,        0},    /* 0 */
60224       { OP_IfNeg,       1, 0,        0},    /* 1 */
60225       { OP_String8,     0, 3,        0},    /* 2 */
60226       { OP_ResultRow,   3, 1,        0},
60227     };
60228
60229     int isQuick = (zLeft[0]=='q');
60230
60231     /* Initialize the VDBE program */
60232     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
60233     pParse->nMem = 6;
60234     sqlite3VdbeSetNumCols(v, 1);
60235     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P4_STATIC);
60236
60237     /* Set the maximum error count */
60238     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
60239     if( zRight ){
60240       mxErr = atoi(zRight);
60241       if( mxErr<=0 ){
60242         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
60243       }
60244     }
60245     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
60246
60247     /* Do an integrity check on each database file */
60248     for(i=0; i<db->nDb; i++){
60249       HashElem *x;
60250       Hash *pTbls;
60251       int cnt = 0;
60252
60253       if( OMIT_TEMPDB && i==1 ) continue;
60254
60255       sqlite3CodeVerifySchema(pParse, i);
60256       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
60257       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
60258       sqlite3VdbeJumpHere(v, addr);
60259
60260       /* Do an integrity check of the B-Tree
60261       **
60262       ** Begin by filling registers 2, 3, ... with the root pages numbers
60263       ** for all tables and indices in the database.
60264       */
60265       pTbls = &db->aDb[i].pSchema->tblHash;
60266       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
60267         Table *pTab = sqliteHashData(x);
60268         Index *pIdx;
60269         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
60270         cnt++;
60271         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
60272           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
60273           cnt++;
60274         }
60275       }
60276       if( cnt==0 ) continue;
60277
60278       /* Make sure sufficient number of registers have been allocated */
60279       if( pParse->nMem < cnt+4 ){
60280         pParse->nMem = cnt+4;
60281       }
60282
60283       /* Do the b-tree integrity checks */
60284       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
60285       sqlite3VdbeChangeP5(v, i);
60286       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
60287       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
60288          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
60289          P4_DYNAMIC);
60290       sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
60291       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
60292       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
60293       sqlite3VdbeJumpHere(v, addr);
60294
60295       /* Make sure all the indices are constructed correctly.
60296       */
60297       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
60298         Table *pTab = sqliteHashData(x);
60299         Index *pIdx;
60300         int loopTop;
60301
60302         if( pTab->pIndex==0 ) continue;
60303         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
60304         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
60305         sqlite3VdbeJumpHere(v, addr);
60306         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
60307         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
60308         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
60309         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
60310         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
60311           int jmp2;
60312           static const VdbeOpList idxErr[] = {
60313             { OP_AddImm,      1, -1,  0},
60314             { OP_String8,     0,  3,  0},    /* 1 */
60315             { OP_Rowid,       1,  4,  0},
60316             { OP_String8,     0,  5,  0},    /* 3 */
60317             { OP_String8,     0,  6,  0},    /* 4 */
60318             { OP_Concat,      4,  3,  3},
60319             { OP_Concat,      5,  3,  3},
60320             { OP_Concat,      6,  3,  3},
60321             { OP_ResultRow,   3,  1,  0},
60322           };
60323           sqlite3GenerateIndexKey(pParse, pIdx, 1, 3);
60324           jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
60325           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
60326           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
60327           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
60328           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
60329           sqlite3VdbeJumpHere(v, jmp2);
60330         }
60331         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
60332         sqlite3VdbeJumpHere(v, loopTop);
60333         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
60334           static const VdbeOpList cntIdx[] = {
60335              { OP_Integer,      0,  3,  0},
60336              { OP_Rewind,       0,  0,  0},  /* 1 */
60337              { OP_AddImm,       3,  1,  0},
60338              { OP_Next,         0,  0,  0},  /* 3 */
60339              { OP_Eq,           2,  0,  3},  /* 4 */
60340              { OP_AddImm,       1, -1,  0},
60341              { OP_String8,      0,  2,  0},  /* 6 */
60342              { OP_String8,      0,  3,  0},  /* 7 */
60343              { OP_Concat,       3,  2,  2},
60344              { OP_ResultRow,    2,  1,  0},
60345           };
60346           if( pIdx->tnum==0 ) continue;
60347           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
60348           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
60349           sqlite3VdbeJumpHere(v, addr);
60350           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
60351           sqlite3VdbeChangeP1(v, addr+1, j+2);
60352           sqlite3VdbeChangeP2(v, addr+1, addr+4);
60353           sqlite3VdbeChangeP1(v, addr+3, j+2);
60354           sqlite3VdbeChangeP2(v, addr+3, addr+2);
60355           sqlite3VdbeJumpHere(v, addr+4);
60356           sqlite3VdbeChangeP4(v, addr+6, 
60357                      "wrong # of entries in index ", P4_STATIC);
60358           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
60359         }
60360       } 
60361     }
60362     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
60363     sqlite3VdbeChangeP2(v, addr, -mxErr);
60364     sqlite3VdbeJumpHere(v, addr+1);
60365     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
60366   }else
60367 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60368
60369 #ifndef SQLITE_OMIT_UTF16
60370   /*
60371   **   PRAGMA encoding
60372   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
60373   **
60374   ** In its first form, this pragma returns the encoding of the main
60375   ** database. If the database is not initialized, it is initialized now.
60376   **
60377   ** The second form of this pragma is a no-op if the main database file
60378   ** has not already been initialized. In this case it sets the default
60379   ** encoding that will be used for the main database file if a new file
60380   ** is created. If an existing main database file is opened, then the
60381   ** default text encoding for the existing database is used.
60382   ** 
60383   ** In all cases new databases created using the ATTACH command are
60384   ** created to use the same default text encoding as the main database. If
60385   ** the main database has not been initialized and/or created when ATTACH
60386   ** is executed, this is done before the ATTACH operation.
60387   **
60388   ** In the second form this pragma sets the text encoding to be used in
60389   ** new database files created using this database handle. It is only
60390   ** useful if invoked immediately after the main database i
60391   */
60392   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
60393     static const struct EncName {
60394       char *zName;
60395       u8 enc;
60396     } encnames[] = {
60397       { "UTF-8",    SQLITE_UTF8        },
60398       { "UTF8",     SQLITE_UTF8        },
60399       { "UTF-16le", SQLITE_UTF16LE     },
60400       { "UTF16le",  SQLITE_UTF16LE     },
60401       { "UTF-16be", SQLITE_UTF16BE     },
60402       { "UTF16be",  SQLITE_UTF16BE     },
60403       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
60404       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
60405       { 0, 0 }
60406     };
60407     const struct EncName *pEnc;
60408     if( !zRight ){    /* "PRAGMA encoding" */
60409       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
60410       sqlite3VdbeSetNumCols(v, 1);
60411       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P4_STATIC);
60412       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
60413       for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
60414         if( pEnc->enc==ENC(pParse->db) ){
60415           sqlite3VdbeChangeP4(v, -1, pEnc->zName, P4_STATIC);
60416           break;
60417         }
60418       }
60419       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
60420     }else{                        /* "PRAGMA encoding = XXX" */
60421       /* Only change the value of sqlite.enc if the database handle is not
60422       ** initialized. If the main database exists, the new sqlite.enc value
60423       ** will be overwritten when the schema is next loaded. If it does not
60424       ** already exists, it will be created to use the new encoding value.
60425       */
60426       if( 
60427         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
60428         DbHasProperty(db, 0, DB_Empty) 
60429       ){
60430         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
60431           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
60432             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
60433             break;
60434           }
60435         }
60436         if( !pEnc->zName ){
60437           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
60438         }
60439       }
60440     }
60441   }else
60442 #endif /* SQLITE_OMIT_UTF16 */
60443
60444 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
60445   /*
60446   **   PRAGMA [database.]schema_version
60447   **   PRAGMA [database.]schema_version = <integer>
60448   **
60449   **   PRAGMA [database.]user_version
60450   **   PRAGMA [database.]user_version = <integer>
60451   **
60452   ** The pragma's schema_version and user_version are used to set or get
60453   ** the value of the schema-version and user-version, respectively. Both
60454   ** the schema-version and the user-version are 32-bit signed integers
60455   ** stored in the database header.
60456   **
60457   ** The schema-cookie is usually only manipulated internally by SQLite. It
60458   ** is incremented by SQLite whenever the database schema is modified (by
60459   ** creating or dropping a table or index). The schema version is used by
60460   ** SQLite each time a query is executed to ensure that the internal cache
60461   ** of the schema used when compiling the SQL query matches the schema of
60462   ** the database against which the compiled query is actually executed.
60463   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
60464   ** the schema-version is potentially dangerous and may lead to program
60465   ** crashes or database corruption. Use with caution!
60466   **
60467   ** The user-version is not used internally by SQLite. It may be used by
60468   ** applications for any purpose.
60469   */
60470   if( sqlite3StrICmp(zLeft, "schema_version")==0 
60471    || sqlite3StrICmp(zLeft, "user_version")==0 
60472    || sqlite3StrICmp(zLeft, "freelist_count")==0 
60473   ){
60474
60475     int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
60476     sqlite3VdbeUsesBtree(v, iDb);
60477     switch( zLeft[0] ){
60478       case 's': case 'S':
60479         iCookie = 0;
60480         break;
60481       case 'f': case 'F':
60482         iCookie = 1;
60483         iDb = (-1*(iDb+1));
60484         assert(iDb<=0);
60485         break;
60486       default:
60487         iCookie = 5;
60488         break;
60489     }
60490
60491     if( zRight && iDb>=0 ){
60492       /* Write the specified cookie value */
60493       static const VdbeOpList setCookie[] = {
60494         { OP_Transaction,    0,  1,  0},    /* 0 */
60495         { OP_Integer,        0,  1,  0},    /* 1 */
60496         { OP_SetCookie,      0,  0,  1},    /* 2 */
60497       };
60498       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
60499       sqlite3VdbeChangeP1(v, addr, iDb);
60500       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
60501       sqlite3VdbeChangeP1(v, addr+2, iDb);
60502       sqlite3VdbeChangeP2(v, addr+2, iCookie);
60503     }else{
60504       /* Read the specified cookie value */
60505       static const VdbeOpList readCookie[] = {
60506         { OP_ReadCookie,      0,  1,  0},    /* 0 */
60507         { OP_ResultRow,       1,  1,  0}
60508       };
60509       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
60510       sqlite3VdbeChangeP1(v, addr, iDb);
60511       sqlite3VdbeChangeP3(v, addr, iCookie);
60512       sqlite3VdbeSetNumCols(v, 1);
60513       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P4_TRANSIENT);
60514     }
60515   }else
60516 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
60517
60518 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
60519   /*
60520   ** Report the current state of file logs for all databases
60521   */
60522   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
60523     static const char *const azLockName[] = {
60524       "unlocked", "shared", "reserved", "pending", "exclusive"
60525     };
60526     int i;
60527     Vdbe *v = sqlite3GetVdbe(pParse);
60528     sqlite3VdbeSetNumCols(v, 2);
60529     pParse->nMem = 2;
60530     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P4_STATIC);
60531     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P4_STATIC);
60532     for(i=0; i<db->nDb; i++){
60533       Btree *pBt;
60534       Pager *pPager;
60535       const char *zState = "unknown";
60536       int j;
60537       if( db->aDb[i].zName==0 ) continue;
60538       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
60539       pBt = db->aDb[i].pBt;
60540       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
60541         zState = "closed";
60542       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
60543                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
60544          zState = azLockName[j];
60545       }
60546       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
60547       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
60548     }
60549   }else
60550 #endif
60551
60552 #ifdef SQLITE_SSE
60553   /*
60554   ** Check to see if the sqlite_statements table exists.  Create it
60555   ** if it does not.
60556   */
60557   if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
60558     extern int sqlite3CreateStatementsTable(Parse*);
60559     sqlite3CreateStatementsTable(pParse);
60560   }else
60561 #endif
60562
60563 #if SQLITE_HAS_CODEC
60564   if( sqlite3StrICmp(zLeft, "key")==0 ){
60565     sqlite3_key(db, zRight, strlen(zRight));
60566   }else
60567 #endif
60568 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
60569   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
60570 #if SQLITE_HAS_CODEC
60571     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
60572       extern void sqlite3_activate_see(const char*);
60573       sqlite3_activate_see(&zRight[4]);
60574     }
60575 #endif
60576 #ifdef SQLITE_ENABLE_CEROD
60577     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
60578       extern void sqlite3_activate_cerod(const char*);
60579       sqlite3_activate_cerod(&zRight[6]);
60580     }
60581 #endif
60582   }
60583 #endif
60584
60585   {}
60586
60587   if( v ){
60588     /* Code an OP_Expire at the end of each PRAGMA program to cause
60589     ** the VDBE implementing the pragma to expire. Most (all?) pragmas
60590     ** are only valid for a single execution.
60591     */
60592     sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
60593
60594     /*
60595     ** Reset the safety level, in case the fullfsync flag or synchronous
60596     ** setting changed.
60597     */
60598 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
60599     if( db->autoCommit ){
60600       sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
60601                  (db->flags&SQLITE_FullFSync)!=0);
60602     }
60603 #endif
60604   }
60605 pragma_out:
60606   sqlite3_free(zLeft);
60607   sqlite3_free(zRight);
60608 }
60609
60610 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
60611
60612 /************** End of pragma.c **********************************************/
60613 /************** Begin file prepare.c *****************************************/
60614 /*
60615 ** 2005 May 25
60616 **
60617 ** The author disclaims copyright to this source code.  In place of
60618 ** a legal notice, here is a blessing:
60619 **
60620 **    May you do good and not evil.
60621 **    May you find forgiveness for yourself and forgive others.
60622 **    May you share freely, never taking more than you give.
60623 **
60624 *************************************************************************
60625 ** This file contains the implementation of the sqlite3_prepare()
60626 ** interface, and routines that contribute to loading the database schema
60627 ** from disk.
60628 **
60629 ** $Id: prepare.c,v 1.78 2008/03/08 12:23:31 drh Exp $
60630 */
60631
60632 /*
60633 ** Fill the InitData structure with an error message that indicates
60634 ** that the database is corrupt.
60635 */
60636 static void corruptSchema(InitData *pData, const char *zExtra){
60637   if( !pData->db->mallocFailed ){
60638     sqlite3SetString(pData->pzErrMsg, "malformed database schema",
60639        zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
60640   }
60641   pData->rc = SQLITE_CORRUPT;
60642 }
60643
60644 /*
60645 ** This is the callback routine for the code that initializes the
60646 ** database.  See sqlite3Init() below for additional information.
60647 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
60648 **
60649 ** Each callback contains the following information:
60650 **
60651 **     argv[0] = name of thing being created
60652 **     argv[1] = root page number for table or index. 0 for trigger or view.
60653 **     argv[2] = SQL text for the CREATE statement.
60654 **
60655 */
60656 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
60657   InitData *pData = (InitData*)pInit;
60658   sqlite3 *db = pData->db;
60659   int iDb = pData->iDb;
60660
60661   assert( sqlite3_mutex_held(db->mutex) );
60662   pData->rc = SQLITE_OK;
60663   DbClearProperty(db, iDb, DB_Empty);
60664   if( db->mallocFailed ){
60665     corruptSchema(pData, 0);
60666     return SQLITE_NOMEM;
60667   }
60668
60669   assert( argc==3 );
60670   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
60671   if( argv[1]==0 ){
60672     corruptSchema(pData, 0);
60673     return 1;
60674   }
60675   assert( iDb>=0 && iDb<db->nDb );
60676   if( argv[2] && argv[2][0] ){
60677     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
60678     ** But because db->init.busy is set to 1, no VDBE code is generated
60679     ** or executed.  All the parser does is build the internal data
60680     ** structures that describe the table, index, or view.
60681     */
60682     char *zErr;
60683     int rc;
60684     assert( db->init.busy );
60685     db->init.iDb = iDb;
60686     db->init.newTnum = atoi(argv[1]);
60687     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
60688     db->init.iDb = 0;
60689     assert( rc!=SQLITE_OK || zErr==0 );
60690     if( SQLITE_OK!=rc ){
60691       pData->rc = rc;
60692       if( rc==SQLITE_NOMEM ){
60693         db->mallocFailed = 1;
60694       }else if( rc!=SQLITE_INTERRUPT ){
60695         corruptSchema(pData, zErr);
60696       }
60697       sqlite3_free(zErr);
60698       return 1;
60699     }
60700   }else if( argv[0]==0 ){
60701     corruptSchema(pData, 0);
60702   }else{
60703     /* If the SQL column is blank it means this is an index that
60704     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
60705     ** constraint for a CREATE TABLE.  The index should have already
60706     ** been created when we processed the CREATE TABLE.  All we have
60707     ** to do here is record the root page number for that index.
60708     */
60709     Index *pIndex;
60710     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
60711     if( pIndex==0 || pIndex->tnum!=0 ){
60712       /* This can occur if there exists an index on a TEMP table which
60713       ** has the same name as another index on a permanent index.  Since
60714       ** the permanent table is hidden by the TEMP table, we can also
60715       ** safely ignore the index on the permanent table.
60716       */
60717       /* Do Nothing */;
60718     }else{
60719       pIndex->tnum = atoi(argv[1]);
60720     }
60721   }
60722   return 0;
60723 }
60724
60725 /*
60726 ** Attempt to read the database schema and initialize internal
60727 ** data structures for a single database file.  The index of the
60728 ** database file is given by iDb.  iDb==0 is used for the main
60729 ** database.  iDb==1 should never be used.  iDb>=2 is used for
60730 ** auxiliary databases.  Return one of the SQLITE_ error codes to
60731 ** indicate success or failure.
60732 */
60733 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
60734   int rc;
60735   BtCursor *curMain;
60736   int size;
60737   Table *pTab;
60738   Db *pDb;
60739   char const *azArg[4];
60740   int meta[10];
60741   InitData initData;
60742   char const *zMasterSchema;
60743   char const *zMasterName = SCHEMA_TABLE(iDb);
60744
60745   /*
60746   ** The master database table has a structure like this
60747   */
60748   static const char master_schema[] = 
60749      "CREATE TABLE sqlite_master(\n"
60750      "  type text,\n"
60751      "  name text,\n"
60752      "  tbl_name text,\n"
60753      "  rootpage integer,\n"
60754      "  sql text\n"
60755      ")"
60756   ;
60757 #ifndef SQLITE_OMIT_TEMPDB
60758   static const char temp_master_schema[] = 
60759      "CREATE TEMP TABLE sqlite_temp_master(\n"
60760      "  type text,\n"
60761      "  name text,\n"
60762      "  tbl_name text,\n"
60763      "  rootpage integer,\n"
60764      "  sql text\n"
60765      ")"
60766   ;
60767 #else
60768   #define temp_master_schema 0
60769 #endif
60770
60771   assert( iDb>=0 && iDb<db->nDb );
60772   assert( db->aDb[iDb].pSchema );
60773   assert( sqlite3_mutex_held(db->mutex) );
60774   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
60775
60776   /* zMasterSchema and zInitScript are set to point at the master schema
60777   ** and initialisation script appropriate for the database being
60778   ** initialised. zMasterName is the name of the master table.
60779   */
60780   if( !OMIT_TEMPDB && iDb==1 ){
60781     zMasterSchema = temp_master_schema;
60782   }else{
60783     zMasterSchema = master_schema;
60784   }
60785   zMasterName = SCHEMA_TABLE(iDb);
60786
60787   /* Construct the schema tables.  */
60788   azArg[0] = zMasterName;
60789   azArg[1] = "1";
60790   azArg[2] = zMasterSchema;
60791   azArg[3] = 0;
60792   initData.db = db;
60793   initData.iDb = iDb;
60794   initData.pzErrMsg = pzErrMsg;
60795   (void)sqlite3SafetyOff(db);
60796   rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
60797   (void)sqlite3SafetyOn(db);
60798   if( rc ){
60799     rc = initData.rc;
60800     goto error_out;
60801   }
60802   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
60803   if( pTab ){
60804     pTab->readOnly = 1;
60805   }
60806
60807   /* Create a cursor to hold the database open
60808   */
60809   pDb = &db->aDb[iDb];
60810   if( pDb->pBt==0 ){
60811     if( !OMIT_TEMPDB && iDb==1 ){
60812       DbSetProperty(db, 1, DB_SchemaLoaded);
60813     }
60814     return SQLITE_OK;
60815   }
60816   sqlite3BtreeEnter(pDb->pBt);
60817   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, 0, &curMain);
60818   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
60819     sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
60820     sqlite3BtreeLeave(pDb->pBt);
60821     goto error_out;
60822   }
60823
60824   /* Get the database meta information.
60825   **
60826   ** Meta values are as follows:
60827   **    meta[0]   Schema cookie.  Changes with each schema change.
60828   **    meta[1]   File format of schema layer.
60829   **    meta[2]   Size of the page cache.
60830   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
60831   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
60832   **    meta[5]   The user cookie. Used by the application.
60833   **    meta[6]   Incremental-vacuum flag.
60834   **    meta[7]
60835   **    meta[8]
60836   **    meta[9]
60837   **
60838   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
60839   ** the possible values of meta[4].
60840   */
60841   if( rc==SQLITE_OK ){
60842     int i;
60843     for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){
60844       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
60845     }
60846     if( rc ){
60847       sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
60848       sqlite3BtreeCloseCursor(curMain);
60849       sqlite3BtreeLeave(pDb->pBt);
60850       goto error_out;
60851     }
60852   }else{
60853     memset(meta, 0, sizeof(meta));
60854   }
60855   pDb->pSchema->schema_cookie = meta[0];
60856
60857   /* If opening a non-empty database, check the text encoding. For the
60858   ** main database, set sqlite3.enc to the encoding of the main database.
60859   ** For an attached db, it is an error if the encoding is not the same
60860   ** as sqlite3.enc.
60861   */
60862   if( meta[4] ){  /* text encoding */
60863     if( iDb==0 ){
60864       /* If opening the main database, set ENC(db). */
60865       ENC(db) = (u8)meta[4];
60866       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
60867     }else{
60868       /* If opening an attached database, the encoding much match ENC(db) */
60869       if( meta[4]!=ENC(db) ){
60870         sqlite3BtreeCloseCursor(curMain);
60871         sqlite3SetString(pzErrMsg, "attached databases must use the same"
60872             " text encoding as main database", (char*)0);
60873         sqlite3BtreeLeave(pDb->pBt);
60874         return SQLITE_ERROR;
60875       }
60876     }
60877   }else{
60878     DbSetProperty(db, iDb, DB_Empty);
60879   }
60880   pDb->pSchema->enc = ENC(db);
60881
60882   size = meta[2];
60883   if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
60884   if( size<0 ) size = -size;
60885   pDb->pSchema->cache_size = size;
60886   sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
60887
60888   /*
60889   ** file_format==1    Version 3.0.0.
60890   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
60891   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
60892   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
60893   */
60894   pDb->pSchema->file_format = meta[1];
60895   if( pDb->pSchema->file_format==0 ){
60896     pDb->pSchema->file_format = 1;
60897   }
60898   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
60899     sqlite3BtreeCloseCursor(curMain);
60900     sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);
60901     sqlite3BtreeLeave(pDb->pBt);
60902     return SQLITE_ERROR;
60903   }
60904
60905   /* Ticket #2804:  When we open a database in the newer file format,
60906   ** clear the legacy_file_format pragma flag so that a VACUUM will
60907   ** not downgrade the database and thus invalidate any descending
60908   ** indices that the user might have created.
60909   */
60910   if( iDb==0 && meta[1]>=4 ){
60911     db->flags &= ~SQLITE_LegacyFileFmt;
60912   }
60913
60914   /* Read the schema information out of the schema tables
60915   */
60916   assert( db->init.busy );
60917   if( rc==SQLITE_EMPTY ){
60918     /* For an empty database, there is nothing to read */
60919     rc = SQLITE_OK;
60920   }else{
60921     char *zSql;
60922     zSql = sqlite3MPrintf(db, 
60923         "SELECT name, rootpage, sql FROM '%q'.%s",
60924         db->aDb[iDb].zName, zMasterName);
60925     (void)sqlite3SafetyOff(db);
60926 #ifndef SQLITE_OMIT_AUTHORIZATION
60927     {
60928       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
60929       xAuth = db->xAuth;
60930       db->xAuth = 0;
60931 #endif
60932       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
60933 #ifndef SQLITE_OMIT_AUTHORIZATION
60934       db->xAuth = xAuth;
60935     }
60936 #endif
60937     if( rc==SQLITE_ABORT ) rc = initData.rc;
60938     (void)sqlite3SafetyOn(db);
60939     sqlite3_free(zSql);
60940 #ifndef SQLITE_OMIT_ANALYZE
60941     if( rc==SQLITE_OK ){
60942       sqlite3AnalysisLoad(db, iDb);
60943     }
60944 #endif
60945     sqlite3BtreeCloseCursor(curMain);
60946   }
60947   if( db->mallocFailed ){
60948     /* sqlite3SetString(pzErrMsg, "out of memory", (char*)0); */
60949     rc = SQLITE_NOMEM;
60950     sqlite3ResetInternalSchema(db, 0);
60951   }
60952   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
60953     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
60954     ** the schema loaded, even if errors occured. In this situation the 
60955     ** current sqlite3_prepare() operation will fail, but the following one
60956     ** will attempt to compile the supplied statement against whatever subset
60957     ** of the schema was loaded before the error occured. The primary
60958     ** purpose of this is to allow access to the sqlite_master table
60959     ** even when its contents have been corrupted.
60960     */
60961     DbSetProperty(db, iDb, DB_SchemaLoaded);
60962     rc = SQLITE_OK;
60963   }
60964   sqlite3BtreeLeave(pDb->pBt);
60965
60966 error_out:
60967   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
60968     db->mallocFailed = 1;
60969   }
60970   return rc;
60971 }
60972
60973 /*
60974 ** Initialize all database files - the main database file, the file
60975 ** used to store temporary tables, and any additional database files
60976 ** created using ATTACH statements.  Return a success code.  If an
60977 ** error occurs, write an error message into *pzErrMsg.
60978 **
60979 ** After a database is initialized, the DB_SchemaLoaded bit is set
60980 ** bit is set in the flags field of the Db structure. If the database
60981 ** file was of zero-length, then the DB_Empty flag is also set.
60982 */
60983 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
60984   int i, rc;
60985   int commit_internal = !(db->flags&SQLITE_InternChanges);
60986   
60987   assert( sqlite3_mutex_held(db->mutex) );
60988   if( db->init.busy ) return SQLITE_OK;
60989   rc = SQLITE_OK;
60990   db->init.busy = 1;
60991   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60992     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
60993     rc = sqlite3InitOne(db, i, pzErrMsg);
60994     if( rc ){
60995       sqlite3ResetInternalSchema(db, i);
60996     }
60997   }
60998
60999   /* Once all the other databases have been initialised, load the schema
61000   ** for the TEMP database. This is loaded last, as the TEMP database
61001   ** schema may contain references to objects in other databases.
61002   */
61003 #ifndef SQLITE_OMIT_TEMPDB
61004   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
61005     rc = sqlite3InitOne(db, 1, pzErrMsg);
61006     if( rc ){
61007       sqlite3ResetInternalSchema(db, 1);
61008     }
61009   }
61010 #endif
61011
61012   db->init.busy = 0;
61013   if( rc==SQLITE_OK && commit_internal ){
61014     sqlite3CommitInternalChanges(db);
61015   }
61016
61017   return rc; 
61018 }
61019
61020 /*
61021 ** This routine is a no-op if the database schema is already initialised.
61022 ** Otherwise, the schema is loaded. An error code is returned.
61023 */
61024 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
61025   int rc = SQLITE_OK;
61026   sqlite3 *db = pParse->db;
61027   assert( sqlite3_mutex_held(db->mutex) );
61028   if( !db->init.busy ){
61029     rc = sqlite3Init(db, &pParse->zErrMsg);
61030   }
61031   if( rc!=SQLITE_OK ){
61032     pParse->rc = rc;
61033     pParse->nErr++;
61034   }
61035   return rc;
61036 }
61037
61038
61039 /*
61040 ** Check schema cookies in all databases.  If any cookie is out
61041 ** of date, return 0.  If all schema cookies are current, return 1.
61042 */
61043 static int schemaIsValid(sqlite3 *db){
61044   int iDb;
61045   int rc;
61046   BtCursor *curTemp;
61047   int cookie;
61048   int allOk = 1;
61049
61050   assert( sqlite3_mutex_held(db->mutex) );
61051   for(iDb=0; allOk && iDb<db->nDb; iDb++){
61052     Btree *pBt;
61053     pBt = db->aDb[iDb].pBt;
61054     if( pBt==0 ) continue;
61055     rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp);
61056     if( rc==SQLITE_OK ){
61057       rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
61058       if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
61059         allOk = 0;
61060       }
61061       sqlite3BtreeCloseCursor(curTemp);
61062     }
61063     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
61064       db->mallocFailed = 1;
61065     }
61066   }
61067   return allOk;
61068 }
61069
61070 /*
61071 ** Convert a schema pointer into the iDb index that indicates
61072 ** which database file in db->aDb[] the schema refers to.
61073 **
61074 ** If the same database is attached more than once, the first
61075 ** attached database is returned.
61076 */
61077 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
61078   int i = -1000000;
61079
61080   /* If pSchema is NULL, then return -1000000. This happens when code in 
61081   ** expr.c is trying to resolve a reference to a transient table (i.e. one
61082   ** created by a sub-select). In this case the return value of this 
61083   ** function should never be used.
61084   **
61085   ** We return -1000000 instead of the more usual -1 simply because using
61086   ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much 
61087   ** more likely to cause a segfault than -1 (of course there are assert()
61088   ** statements too, but it never hurts to play the odds).
61089   */
61090   assert( sqlite3_mutex_held(db->mutex) );
61091   if( pSchema ){
61092     for(i=0; i<db->nDb; i++){
61093       if( db->aDb[i].pSchema==pSchema ){
61094         break;
61095       }
61096     }
61097     assert( i>=0 &&i>=0 &&  i<db->nDb );
61098   }
61099   return i;
61100 }
61101
61102 /*
61103 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
61104 */
61105 static int sqlite3Prepare(
61106   sqlite3 *db,              /* Database handle. */
61107   const char *zSql,         /* UTF-8 encoded SQL statement. */
61108   int nBytes,               /* Length of zSql in bytes. */
61109   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
61110   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
61111   const char **pzTail       /* OUT: End of parsed string */
61112 ){
61113   Parse sParse;
61114   char *zErrMsg = 0;
61115   int rc = SQLITE_OK;
61116   int i;
61117
61118   assert( ppStmt );
61119   *ppStmt = 0;
61120   if( sqlite3SafetyOn(db) ){
61121     return SQLITE_MISUSE;
61122   }
61123   assert( !db->mallocFailed );
61124   assert( sqlite3_mutex_held(db->mutex) );
61125
61126   /* If any attached database schemas are locked, do not proceed with
61127   ** compilation. Instead return SQLITE_LOCKED immediately.
61128   */
61129   for(i=0; i<db->nDb; i++) {
61130     Btree *pBt = db->aDb[i].pBt;
61131     if( pBt ){
61132       int rc;
61133       rc = sqlite3BtreeSchemaLocked(pBt);
61134       if( rc ){
61135         const char *zDb = db->aDb[i].zName;
61136         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
61137         (void)sqlite3SafetyOff(db);
61138         return SQLITE_LOCKED;
61139       }
61140     }
61141   }
61142   
61143   memset(&sParse, 0, sizeof(sParse));
61144   sParse.db = db;
61145   if( nBytes>=0 && zSql[nBytes]!=0 ){
61146     char *zSqlCopy;
61147     if( SQLITE_MAX_SQL_LENGTH>0 && nBytes>SQLITE_MAX_SQL_LENGTH ){
61148       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
61149       (void)sqlite3SafetyOff(db);
61150       return SQLITE_TOOBIG;
61151     }
61152     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
61153     if( zSqlCopy ){
61154       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
61155       sqlite3_free(zSqlCopy);
61156     }
61157     sParse.zTail = &zSql[nBytes];
61158   }else{
61159     sqlite3RunParser(&sParse, zSql, &zErrMsg);
61160   }
61161
61162   if( db->mallocFailed ){
61163     sParse.rc = SQLITE_NOMEM;
61164   }
61165   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
61166   if( sParse.checkSchema && !schemaIsValid(db) ){
61167     sParse.rc = SQLITE_SCHEMA;
61168   }
61169   if( sParse.rc==SQLITE_SCHEMA ){
61170     sqlite3ResetInternalSchema(db, 0);
61171   }
61172   if( db->mallocFailed ){
61173     sParse.rc = SQLITE_NOMEM;
61174   }
61175   if( pzTail ){
61176     *pzTail = sParse.zTail;
61177   }
61178   rc = sParse.rc;
61179
61180 #ifndef SQLITE_OMIT_EXPLAIN
61181   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
61182     if( sParse.explain==2 ){
61183       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
61184       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P4_STATIC);
61185       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P4_STATIC);
61186       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P4_STATIC);
61187     }else{
61188       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
61189       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P4_STATIC);
61190       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P4_STATIC);
61191       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P4_STATIC);
61192       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P4_STATIC);
61193       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P4_STATIC);
61194       sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", P4_STATIC);
61195       sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", P4_STATIC);
61196       sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment",P4_STATIC);
61197     }
61198   }
61199 #endif
61200
61201   if( sqlite3SafetyOff(db) ){
61202     rc = SQLITE_MISUSE;
61203   }
61204
61205   if( saveSqlFlag ){
61206     sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
61207   }
61208   if( rc!=SQLITE_OK || db->mallocFailed ){
61209     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
61210     assert(!(*ppStmt));
61211   }else{
61212     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
61213   }
61214
61215   if( zErrMsg ){
61216     sqlite3Error(db, rc, "%s", zErrMsg);
61217     sqlite3_free(zErrMsg);
61218   }else{
61219     sqlite3Error(db, rc, 0);
61220   }
61221
61222   rc = sqlite3ApiExit(db, rc);
61223   assert( (rc&db->errMask)==rc );
61224   return rc;
61225 }
61226 static int sqlite3LockAndPrepare(
61227   sqlite3 *db,              /* Database handle. */
61228   const char *zSql,         /* UTF-8 encoded SQL statement. */
61229   int nBytes,               /* Length of zSql in bytes. */
61230   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
61231   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
61232   const char **pzTail       /* OUT: End of parsed string */
61233 ){
61234   int rc;
61235   if( !sqlite3SafetyCheckOk(db) ){
61236     return SQLITE_MISUSE;
61237   }
61238   sqlite3_mutex_enter(db->mutex);
61239   sqlite3BtreeEnterAll(db);
61240   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
61241   sqlite3BtreeLeaveAll(db);
61242   sqlite3_mutex_leave(db->mutex);
61243   return rc;
61244 }
61245
61246 /*
61247 ** Rerun the compilation of a statement after a schema change.
61248 ** Return true if the statement was recompiled successfully.
61249 ** Return false if there is an error of some kind.
61250 */
61251 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
61252   int rc;
61253   sqlite3_stmt *pNew;
61254   const char *zSql;
61255   sqlite3 *db;
61256
61257   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
61258   zSql = sqlite3_sql((sqlite3_stmt *)p);
61259   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
61260   db = sqlite3VdbeDb(p);
61261   assert( sqlite3_mutex_held(db->mutex) );
61262   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
61263   if( rc ){
61264     if( rc==SQLITE_NOMEM ){
61265       db->mallocFailed = 1;
61266     }
61267     assert( pNew==0 );
61268     return 0;
61269   }else{
61270     assert( pNew!=0 );
61271   }
61272   sqlite3VdbeSwap((Vdbe*)pNew, p);
61273   sqlite3_transfer_bindings(pNew, (sqlite3_stmt*)p);
61274   sqlite3VdbeResetStepResult((Vdbe*)pNew);
61275   sqlite3VdbeFinalize((Vdbe*)pNew);
61276   return 1;
61277 }
61278
61279
61280 /*
61281 ** Two versions of the official API.  Legacy and new use.  In the legacy
61282 ** version, the original SQL text is not saved in the prepared statement
61283 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
61284 ** sqlite3_step().  In the new version, the original SQL text is retained
61285 ** and the statement is automatically recompiled if an schema change
61286 ** occurs.
61287 */
61288 SQLITE_API int sqlite3_prepare(
61289   sqlite3 *db,              /* Database handle. */
61290   const char *zSql,         /* UTF-8 encoded SQL statement. */
61291   int nBytes,               /* Length of zSql in bytes. */
61292   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
61293   const char **pzTail       /* OUT: End of parsed string */
61294 ){
61295   int rc;
61296   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
61297   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
61298   return rc;
61299 }
61300 SQLITE_API int sqlite3_prepare_v2(
61301   sqlite3 *db,              /* Database handle. */
61302   const char *zSql,         /* UTF-8 encoded SQL statement. */
61303   int nBytes,               /* Length of zSql in bytes. */
61304   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
61305   const char **pzTail       /* OUT: End of parsed string */
61306 ){
61307   int rc;
61308   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
61309   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
61310   return rc;
61311 }
61312
61313
61314 #ifndef SQLITE_OMIT_UTF16
61315 /*
61316 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
61317 */
61318 static int sqlite3Prepare16(
61319   sqlite3 *db,              /* Database handle. */ 
61320   const void *zSql,         /* UTF-8 encoded SQL statement. */
61321   int nBytes,               /* Length of zSql in bytes. */
61322   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
61323   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
61324   const void **pzTail       /* OUT: End of parsed string */
61325 ){
61326   /* This function currently works by first transforming the UTF-16
61327   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
61328   ** tricky bit is figuring out the pointer to return in *pzTail.
61329   */
61330   char *zSql8;
61331   const char *zTail8 = 0;
61332   int rc = SQLITE_OK;
61333
61334   if( !sqlite3SafetyCheckOk(db) ){
61335     return SQLITE_MISUSE;
61336   }
61337   sqlite3_mutex_enter(db->mutex);
61338   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
61339   if( zSql8 ){
61340     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
61341   }
61342
61343   if( zTail8 && pzTail ){
61344     /* If sqlite3_prepare returns a tail pointer, we calculate the
61345     ** equivalent pointer into the UTF-16 string by counting the unicode
61346     ** characters between zSql8 and zTail8, and then returning a pointer
61347     ** the same number of characters into the UTF-16 string.
61348     */
61349     int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
61350     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
61351   }
61352   sqlite3_free(zSql8); 
61353   rc = sqlite3ApiExit(db, rc);
61354   sqlite3_mutex_leave(db->mutex);
61355   return rc;
61356 }
61357
61358 /*
61359 ** Two versions of the official API.  Legacy and new use.  In the legacy
61360 ** version, the original SQL text is not saved in the prepared statement
61361 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
61362 ** sqlite3_step().  In the new version, the original SQL text is retained
61363 ** and the statement is automatically recompiled if an schema change
61364 ** occurs.
61365 */
61366 SQLITE_API int sqlite3_prepare16(
61367   sqlite3 *db,              /* Database handle. */ 
61368   const void *zSql,         /* UTF-8 encoded SQL statement. */
61369   int nBytes,               /* Length of zSql in bytes. */
61370   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
61371   const void **pzTail       /* OUT: End of parsed string */
61372 ){
61373   int rc;
61374   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
61375   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
61376   return rc;
61377 }
61378 SQLITE_API int sqlite3_prepare16_v2(
61379   sqlite3 *db,              /* Database handle. */ 
61380   const void *zSql,         /* UTF-8 encoded SQL statement. */
61381   int nBytes,               /* Length of zSql in bytes. */
61382   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
61383   const void **pzTail       /* OUT: End of parsed string */
61384 ){
61385   int rc;
61386   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
61387   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
61388   return rc;
61389 }
61390
61391 #endif /* SQLITE_OMIT_UTF16 */
61392
61393 /************** End of prepare.c *********************************************/
61394 /************** Begin file select.c ******************************************/
61395 /*
61396 ** 2001 September 15
61397 **
61398 ** The author disclaims copyright to this source code.  In place of
61399 ** a legal notice, here is a blessing:
61400 **
61401 **    May you do good and not evil.
61402 **    May you find forgiveness for yourself and forgive others.
61403 **    May you share freely, never taking more than you give.
61404 **
61405 *************************************************************************
61406 ** This file contains C code routines that are called by the parser
61407 ** to handle SELECT statements in SQLite.
61408 **
61409 ** $Id: select.c,v 1.415 2008/03/04 17:45:01 mlcreech Exp $
61410 */
61411
61412
61413 /*
61414 ** Delete all the content of a Select structure but do not deallocate
61415 ** the select structure itself.
61416 */
61417 static void clearSelect(Select *p){
61418   sqlite3ExprListDelete(p->pEList);
61419   sqlite3SrcListDelete(p->pSrc);
61420   sqlite3ExprDelete(p->pWhere);
61421   sqlite3ExprListDelete(p->pGroupBy);
61422   sqlite3ExprDelete(p->pHaving);
61423   sqlite3ExprListDelete(p->pOrderBy);
61424   sqlite3SelectDelete(p->pPrior);
61425   sqlite3ExprDelete(p->pLimit);
61426   sqlite3ExprDelete(p->pOffset);
61427 }
61428
61429 /*
61430 ** Initialize a SelectDest structure.
61431 */
61432 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
61433   pDest->eDest = eDest;
61434   pDest->iParm = iParm;
61435   pDest->affinity = 0;
61436   pDest->iMem = 0;
61437 }
61438
61439
61440 /*
61441 ** Allocate a new Select structure and return a pointer to that
61442 ** structure.
61443 */
61444 SQLITE_PRIVATE Select *sqlite3SelectNew(
61445   Parse *pParse,        /* Parsing context */
61446   ExprList *pEList,     /* which columns to include in the result */
61447   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
61448   Expr *pWhere,         /* the WHERE clause */
61449   ExprList *pGroupBy,   /* the GROUP BY clause */
61450   Expr *pHaving,        /* the HAVING clause */
61451   ExprList *pOrderBy,   /* the ORDER BY clause */
61452   int isDistinct,       /* true if the DISTINCT keyword is present */
61453   Expr *pLimit,         /* LIMIT value.  NULL means not used */
61454   Expr *pOffset         /* OFFSET value.  NULL means no offset */
61455 ){
61456   Select *pNew;
61457   Select standin;
61458   sqlite3 *db = pParse->db;
61459   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
61460   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
61461   if( pNew==0 ){
61462     pNew = &standin;
61463     memset(pNew, 0, sizeof(*pNew));
61464   }
61465   if( pEList==0 ){
61466     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
61467   }
61468   pNew->pEList = pEList;
61469   pNew->pSrc = pSrc;
61470   pNew->pWhere = pWhere;
61471   pNew->pGroupBy = pGroupBy;
61472   pNew->pHaving = pHaving;
61473   pNew->pOrderBy = pOrderBy;
61474   pNew->isDistinct = isDistinct;
61475   pNew->op = TK_SELECT;
61476   assert( pOffset==0 || pLimit!=0 );
61477   pNew->pLimit = pLimit;
61478   pNew->pOffset = pOffset;
61479   pNew->iLimit = -1;
61480   pNew->iOffset = -1;
61481   pNew->addrOpenEphm[0] = -1;
61482   pNew->addrOpenEphm[1] = -1;
61483   pNew->addrOpenEphm[2] = -1;
61484   if( pNew==&standin) {
61485     clearSelect(pNew);
61486     pNew = 0;
61487   }
61488   return pNew;
61489 }
61490
61491 /*
61492 ** Delete the given Select structure and all of its substructures.
61493 */
61494 SQLITE_PRIVATE void sqlite3SelectDelete(Select *p){
61495   if( p ){
61496     clearSelect(p);
61497     sqlite3_free(p);
61498   }
61499 }
61500
61501 /*
61502 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
61503 ** type of join.  Return an integer constant that expresses that type
61504 ** in terms of the following bit values:
61505 **
61506 **     JT_INNER
61507 **     JT_CROSS
61508 **     JT_OUTER
61509 **     JT_NATURAL
61510 **     JT_LEFT
61511 **     JT_RIGHT
61512 **
61513 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
61514 **
61515 ** If an illegal or unsupported join type is seen, then still return
61516 ** a join type, but put an error in the pParse structure.
61517 */
61518 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
61519   int jointype = 0;
61520   Token *apAll[3];
61521   Token *p;
61522   static const struct {
61523     const char zKeyword[8];
61524     u8 nChar;
61525     u8 code;
61526   } keywords[] = {
61527     { "natural", 7, JT_NATURAL },
61528     { "left",    4, JT_LEFT|JT_OUTER },
61529     { "right",   5, JT_RIGHT|JT_OUTER },
61530     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
61531     { "outer",   5, JT_OUTER },
61532     { "inner",   5, JT_INNER },
61533     { "cross",   5, JT_INNER|JT_CROSS },
61534   };
61535   int i, j;
61536   apAll[0] = pA;
61537   apAll[1] = pB;
61538   apAll[2] = pC;
61539   for(i=0; i<3 && apAll[i]; i++){
61540     p = apAll[i];
61541     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
61542       if( p->n==keywords[j].nChar 
61543           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
61544         jointype |= keywords[j].code;
61545         break;
61546       }
61547     }
61548     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
61549       jointype |= JT_ERROR;
61550       break;
61551     }
61552   }
61553   if(
61554      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
61555      (jointype & JT_ERROR)!=0
61556   ){
61557     const char *zSp1 = " ";
61558     const char *zSp2 = " ";
61559     if( pB==0 ){ zSp1++; }
61560     if( pC==0 ){ zSp2++; }
61561     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
61562        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
61563     jointype = JT_INNER;
61564   }else if( jointype & JT_RIGHT ){
61565     sqlite3ErrorMsg(pParse, 
61566       "RIGHT and FULL OUTER JOINs are not currently supported");
61567     jointype = JT_INNER;
61568   }
61569   return jointype;
61570 }
61571
61572 /*
61573 ** Return the index of a column in a table.  Return -1 if the column
61574 ** is not contained in the table.
61575 */
61576 static int columnIndex(Table *pTab, const char *zCol){
61577   int i;
61578   for(i=0; i<pTab->nCol; i++){
61579     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
61580   }
61581   return -1;
61582 }
61583
61584 /*
61585 ** Set the value of a token to a '\000'-terminated string.
61586 */
61587 static void setToken(Token *p, const char *z){
61588   p->z = (u8*)z;
61589   p->n = z ? strlen(z) : 0;
61590   p->dyn = 0;
61591 }
61592
61593 /*
61594 ** Set the token to the double-quoted and escaped version of the string pointed
61595 ** to by z. For example;
61596 **
61597 **    {a"bc}  ->  {"a""bc"}
61598 */
61599 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
61600   p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z);
61601   p->dyn = 1;
61602   if( p->z ){
61603     p->n = strlen((char *)p->z);
61604   }else{
61605     pParse->db->mallocFailed = 1;
61606   }
61607 }
61608
61609 /*
61610 ** Create an expression node for an identifier with the name of zName
61611 */
61612 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
61613   Token dummy;
61614   setToken(&dummy, zName);
61615   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
61616 }
61617
61618
61619 /*
61620 ** Add a term to the WHERE expression in *ppExpr that requires the
61621 ** zCol column to be equal in the two tables pTab1 and pTab2.
61622 */
61623 static void addWhereTerm(
61624   Parse *pParse,           /* Parsing context */
61625   const char *zCol,        /* Name of the column */
61626   const Table *pTab1,      /* First table */
61627   const char *zAlias1,     /* Alias for first table.  May be NULL */
61628   const Table *pTab2,      /* Second table */
61629   const char *zAlias2,     /* Alias for second table.  May be NULL */
61630   int iRightJoinTable,     /* VDBE cursor for the right table */
61631   Expr **ppExpr            /* Add the equality term to this expression */
61632 ){
61633   Expr *pE1a, *pE1b, *pE1c;
61634   Expr *pE2a, *pE2b, *pE2c;
61635   Expr *pE;
61636
61637   pE1a = sqlite3CreateIdExpr(pParse, zCol);
61638   pE2a = sqlite3CreateIdExpr(pParse, zCol);
61639   if( zAlias1==0 ){
61640     zAlias1 = pTab1->zName;
61641   }
61642   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
61643   if( zAlias2==0 ){
61644     zAlias2 = pTab2->zName;
61645   }
61646   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
61647   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
61648   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
61649   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
61650   if( pE ){
61651     ExprSetProperty(pE, EP_FromJoin);
61652     pE->iRightJoinTable = iRightJoinTable;
61653   }
61654   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
61655 }
61656
61657 /*
61658 ** Set the EP_FromJoin property on all terms of the given expression.
61659 ** And set the Expr.iRightJoinTable to iTable for every term in the
61660 ** expression.
61661 **
61662 ** The EP_FromJoin property is used on terms of an expression to tell
61663 ** the LEFT OUTER JOIN processing logic that this term is part of the
61664 ** join restriction specified in the ON or USING clause and not a part
61665 ** of the more general WHERE clause.  These terms are moved over to the
61666 ** WHERE clause during join processing but we need to remember that they
61667 ** originated in the ON or USING clause.
61668 **
61669 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
61670 ** expression depends on table iRightJoinTable even if that table is not
61671 ** explicitly mentioned in the expression.  That information is needed
61672 ** for cases like this:
61673 **
61674 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
61675 **
61676 ** The where clause needs to defer the handling of the t1.x=5
61677 ** term until after the t2 loop of the join.  In that way, a
61678 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
61679 ** defer the handling of t1.x=5, it will be processed immediately
61680 ** after the t1 loop and rows with t1.x!=5 will never appear in
61681 ** the output, which is incorrect.
61682 */
61683 static void setJoinExpr(Expr *p, int iTable){
61684   while( p ){
61685     ExprSetProperty(p, EP_FromJoin);
61686     p->iRightJoinTable = iTable;
61687     setJoinExpr(p->pLeft, iTable);
61688     p = p->pRight;
61689   } 
61690 }
61691
61692 /*
61693 ** This routine processes the join information for a SELECT statement.
61694 ** ON and USING clauses are converted into extra terms of the WHERE clause.
61695 ** NATURAL joins also create extra WHERE clause terms.
61696 **
61697 ** The terms of a FROM clause are contained in the Select.pSrc structure.
61698 ** The left most table is the first entry in Select.pSrc.  The right-most
61699 ** table is the last entry.  The join operator is held in the entry to
61700 ** the left.  Thus entry 0 contains the join operator for the join between
61701 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
61702 ** also attached to the left entry.
61703 **
61704 ** This routine returns the number of errors encountered.
61705 */
61706 static int sqliteProcessJoin(Parse *pParse, Select *p){
61707   SrcList *pSrc;                  /* All tables in the FROM clause */
61708   int i, j;                       /* Loop counters */
61709   struct SrcList_item *pLeft;     /* Left table being joined */
61710   struct SrcList_item *pRight;    /* Right table being joined */
61711
61712   pSrc = p->pSrc;
61713   pLeft = &pSrc->a[0];
61714   pRight = &pLeft[1];
61715   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
61716     Table *pLeftTab = pLeft->pTab;
61717     Table *pRightTab = pRight->pTab;
61718
61719     if( pLeftTab==0 || pRightTab==0 ) continue;
61720
61721     /* When the NATURAL keyword is present, add WHERE clause terms for
61722     ** every column that the two tables have in common.
61723     */
61724     if( pRight->jointype & JT_NATURAL ){
61725       if( pRight->pOn || pRight->pUsing ){
61726         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
61727            "an ON or USING clause", 0);
61728         return 1;
61729       }
61730       for(j=0; j<pLeftTab->nCol; j++){
61731         char *zName = pLeftTab->aCol[j].zName;
61732         if( columnIndex(pRightTab, zName)>=0 ){
61733           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
61734                               pRightTab, pRight->zAlias,
61735                               pRight->iCursor, &p->pWhere);
61736           
61737         }
61738       }
61739     }
61740
61741     /* Disallow both ON and USING clauses in the same join
61742     */
61743     if( pRight->pOn && pRight->pUsing ){
61744       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
61745         "clauses in the same join");
61746       return 1;
61747     }
61748
61749     /* Add the ON clause to the end of the WHERE clause, connected by
61750     ** an AND operator.
61751     */
61752     if( pRight->pOn ){
61753       setJoinExpr(pRight->pOn, pRight->iCursor);
61754       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
61755       pRight->pOn = 0;
61756     }
61757
61758     /* Create extra terms on the WHERE clause for each column named
61759     ** in the USING clause.  Example: If the two tables to be joined are 
61760     ** A and B and the USING clause names X, Y, and Z, then add this
61761     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
61762     ** Report an error if any column mentioned in the USING clause is
61763     ** not contained in both tables to be joined.
61764     */
61765     if( pRight->pUsing ){
61766       IdList *pList = pRight->pUsing;
61767       for(j=0; j<pList->nId; j++){
61768         char *zName = pList->a[j].zName;
61769         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
61770           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
61771             "not present in both tables", zName);
61772           return 1;
61773         }
61774         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
61775                             pRightTab, pRight->zAlias,
61776                             pRight->iCursor, &p->pWhere);
61777       }
61778     }
61779   }
61780   return 0;
61781 }
61782
61783 /*
61784 ** Insert code into "v" that will push the record on the top of the
61785 ** stack into the sorter.
61786 */
61787 static void pushOntoSorter(
61788   Parse *pParse,         /* Parser context */
61789   ExprList *pOrderBy,    /* The ORDER BY clause */
61790   Select *pSelect,       /* The whole SELECT statement */
61791   int regData            /* Register holding data to be sorted */
61792 ){
61793   Vdbe *v = pParse->pVdbe;
61794   int nExpr = pOrderBy->nExpr;
61795   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
61796   int regRecord = sqlite3GetTempReg(pParse);
61797   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase);
61798   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
61799   sqlite3VdbeAddOp2(v, OP_Move, regData, regBase+nExpr+1);
61800   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
61801   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
61802   sqlite3ReleaseTempReg(pParse, regRecord);
61803   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
61804   if( pSelect->iLimit>=0 ){
61805     int addr1, addr2;
61806     int iLimit;
61807     if( pSelect->pOffset ){
61808       iLimit = pSelect->iOffset+1;
61809     }else{
61810       iLimit = pSelect->iLimit;
61811     }
61812     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
61813     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
61814     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
61815     sqlite3VdbeJumpHere(v, addr1);
61816     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
61817     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
61818     sqlite3VdbeJumpHere(v, addr2);
61819     pSelect->iLimit = -1;
61820   }
61821 }
61822
61823 /*
61824 ** Add code to implement the OFFSET
61825 */
61826 static void codeOffset(
61827   Vdbe *v,          /* Generate code into this VM */
61828   Select *p,        /* The SELECT statement being coded */
61829   int iContinue     /* Jump here to skip the current record */
61830 ){
61831   if( p->iOffset>=0 && iContinue!=0 ){
61832     int addr;
61833     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
61834     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
61835     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
61836     VdbeComment((v, "skip OFFSET records"));
61837     sqlite3VdbeJumpHere(v, addr);
61838   }
61839 }
61840
61841 /*
61842 ** Add code that will check to make sure the N registers starting at iMem
61843 ** form a distinct entry.  iTab is a sorting index that holds previously
61844 ** seen combinations of the N values.  A new entry is made in iTab
61845 ** if the current N values are new.
61846 **
61847 ** A jump to addrRepeat is made and the N+1 values are popped from the
61848 ** stack if the top N elements are not distinct.
61849 */
61850 static void codeDistinct(
61851   Parse *pParse,     /* Parsing and code generating context */
61852   int iTab,          /* A sorting index used to test for distinctness */
61853   int addrRepeat,    /* Jump to here if not distinct */
61854   int N,             /* Number of elements */
61855   int iMem           /* First element */
61856 ){
61857   Vdbe *v;
61858   int r1;
61859
61860   v = pParse->pVdbe;
61861   r1 = sqlite3GetTempReg(pParse);
61862   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
61863   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
61864   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
61865   sqlite3ReleaseTempReg(pParse, r1);
61866 }
61867
61868 /*
61869 ** Generate an error message when a SELECT is used within a subexpression
61870 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
61871 ** column.  We do this in a subroutine because the error occurs in multiple
61872 ** places.
61873 */
61874 static int checkForMultiColumnSelectError(
61875   Parse *pParse,       /* Parse context. */
61876   SelectDest *pDest,   /* Destination of SELECT results */
61877   int nExpr            /* Number of result columns returned by SELECT */
61878 ){
61879   int eDest = pDest->eDest;
61880   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
61881     sqlite3ErrorMsg(pParse, "only a single result allowed for "
61882        "a SELECT that is part of an expression");
61883     return 1;
61884   }else{
61885     return 0;
61886   }
61887 }
61888
61889 /*
61890 ** This routine generates the code for the inside of the inner loop
61891 ** of a SELECT.
61892 **
61893 ** If srcTab and nColumn are both zero, then the pEList expressions
61894 ** are evaluated in order to get the data for this row.  If nColumn>0
61895 ** then data is pulled from srcTab and pEList is used only to get the
61896 ** datatypes for each column.
61897 */
61898 static void selectInnerLoop(
61899   Parse *pParse,          /* The parser context */
61900   Select *p,              /* The complete select statement being coded */
61901   ExprList *pEList,       /* List of values being extracted */
61902   int srcTab,             /* Pull data from this table */
61903   int nColumn,            /* Number of columns in the source table */
61904   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
61905   int distinct,           /* If >=0, make sure results are distinct */
61906   SelectDest *pDest,      /* How to dispose of the results */
61907   int iContinue,          /* Jump here to continue with next row */
61908   int iBreak,             /* Jump here to break out of the inner loop */
61909   char *aff               /* affinity string if eDest is SRT_Union */
61910 ){
61911   Vdbe *v = pParse->pVdbe;
61912   int i;
61913   int hasDistinct;        /* True if the DISTINCT keyword is present */
61914   int regResult;              /* Start of memory holding result set */
61915   int eDest = pDest->eDest;   /* How to dispose of results */
61916   int iParm = pDest->iParm;   /* First argument to disposal method */
61917   int nResultCol;             /* Number of result columns */
61918
61919   if( v==0 ) return;
61920   assert( pEList!=0 );
61921
61922   /* If there was a LIMIT clause on the SELECT statement, then do the check
61923   ** to see if this row should be output.
61924   */
61925   hasDistinct = distinct>=0 && pEList->nExpr>0;
61926   if( pOrderBy==0 && !hasDistinct ){
61927     codeOffset(v, p, iContinue);
61928   }
61929
61930   /* Pull the requested columns.
61931   */
61932   if( nColumn>0 ){
61933     nResultCol = nColumn;
61934   }else{
61935     nResultCol = pEList->nExpr;
61936   }
61937   if( pDest->iMem==0 ){
61938     pDest->iMem = sqlite3GetTempRange(pParse, nResultCol);
61939   }
61940   regResult = pDest->iMem;
61941   if( nColumn>0 ){
61942     for(i=0; i<nColumn; i++){
61943       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
61944     }
61945   }else if( eDest!=SRT_Exists ){
61946     /* If the destination is an EXISTS(...) expression, the actual
61947     ** values returned by the SELECT are not required.
61948     */
61949     for(i=0; i<nResultCol; i++){
61950       sqlite3ExprCode(pParse, pEList->a[i].pExpr, regResult+i);
61951     }
61952   }
61953   nColumn = nResultCol;
61954
61955   /* If the DISTINCT keyword was present on the SELECT statement
61956   ** and this row has been seen before, then do not make this row
61957   ** part of the result.
61958   */
61959   if( hasDistinct ){
61960     assert( pEList!=0 );
61961     assert( pEList->nExpr==nColumn );
61962     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
61963     if( pOrderBy==0 ){
61964       codeOffset(v, p, iContinue);
61965     }
61966   }
61967
61968   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
61969     return;
61970   }
61971
61972   switch( eDest ){
61973     /* In this mode, write each query result to the key of the temporary
61974     ** table iParm.
61975     */
61976 #ifndef SQLITE_OMIT_COMPOUND_SELECT
61977     case SRT_Union: {
61978       int r1;
61979       r1 = sqlite3GetTempReg(pParse);
61980       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
61981       if( aff ){
61982         sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC);
61983       }
61984       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
61985       sqlite3ReleaseTempReg(pParse, r1);
61986       break;
61987     }
61988
61989     /* Construct a record from the query result, but instead of
61990     ** saving that record, use it as a key to delete elements from
61991     ** the temporary table iParm.
61992     */
61993     case SRT_Except: {
61994       int r1;
61995       r1 = sqlite3GetTempReg(pParse);
61996       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
61997       sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC);
61998       sqlite3VdbeAddOp2(v, OP_IdxDelete, iParm, r1);
61999       sqlite3ReleaseTempReg(pParse, r1);
62000       break;
62001     }
62002 #endif
62003
62004     /* Store the result as data using a unique key.
62005     */
62006     case SRT_Table:
62007     case SRT_EphemTab: {
62008       int r1 = sqlite3GetTempReg(pParse);
62009       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
62010       if( pOrderBy ){
62011         pushOntoSorter(pParse, pOrderBy, p, r1);
62012       }else{
62013         int r2 = sqlite3GetTempReg(pParse);
62014         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
62015         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
62016         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
62017         sqlite3ReleaseTempReg(pParse, r2);
62018       }
62019       sqlite3ReleaseTempReg(pParse, r1);
62020       break;
62021     }
62022
62023 #ifndef SQLITE_OMIT_SUBQUERY
62024     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
62025     ** then there should be a single item on the stack.  Write this
62026     ** item into the set table with bogus data.
62027     */
62028     case SRT_Set: {
62029       int addr2;
62030
62031       assert( nColumn==1 );
62032       addr2 = sqlite3VdbeAddOp1(v, OP_IsNull, regResult);
62033       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
62034       if( pOrderBy ){
62035         /* At first glance you would think we could optimize out the
62036         ** ORDER BY in this case since the order of entries in the set
62037         ** does not matter.  But there might be a LIMIT clause, in which
62038         ** case the order does matter */
62039         pushOntoSorter(pParse, pOrderBy, p, regResult);
62040       }else{
62041         int r1 = sqlite3GetTempReg(pParse);
62042         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
62043         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
62044         sqlite3ReleaseTempReg(pParse, r1);
62045       }
62046       sqlite3VdbeJumpHere(v, addr2);
62047       break;
62048     }
62049
62050     /* If any row exist in the result set, record that fact and abort.
62051     */
62052     case SRT_Exists: {
62053       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
62054       /* The LIMIT clause will terminate the loop for us */
62055       break;
62056     }
62057
62058     /* If this is a scalar select that is part of an expression, then
62059     ** store the results in the appropriate memory cell and break out
62060     ** of the scan loop.
62061     */
62062     case SRT_Mem: {
62063       assert( nColumn==1 );
62064       if( pOrderBy ){
62065         pushOntoSorter(pParse, pOrderBy, p, regResult);
62066       }else{
62067         sqlite3VdbeAddOp2(v, OP_Move, regResult, iParm);
62068         /* The LIMIT clause will jump out of the loop for us */
62069       }
62070       break;
62071     }
62072 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
62073
62074     /* Send the data to the callback function or to a subroutine.  In the
62075     ** case of a subroutine, the subroutine itself is responsible for
62076     ** popping the data from the stack.
62077     */
62078     case SRT_Subroutine:
62079     case SRT_Callback: {
62080       if( pOrderBy ){
62081         int r1 = sqlite3GetTempReg(pParse);
62082         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
62083         pushOntoSorter(pParse, pOrderBy, p, r1);
62084         sqlite3ReleaseTempReg(pParse, r1);
62085       }else if( eDest==SRT_Subroutine ){
62086         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
62087       }else{
62088         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
62089       }
62090       break;
62091     }
62092
62093 #if !defined(SQLITE_OMIT_TRIGGER)
62094     /* Discard the results.  This is used for SELECT statements inside
62095     ** the body of a TRIGGER.  The purpose of such selects is to call
62096     ** user-defined functions that have side effects.  We do not care
62097     ** about the actual results of the select.
62098     */
62099     default: {
62100       assert( eDest==SRT_Discard );
62101       break;
62102     }
62103 #endif
62104   }
62105
62106   /* Jump to the end of the loop if the LIMIT is reached.
62107   */
62108   if( p->iLimit>=0 && pOrderBy==0 ){
62109     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
62110     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
62111   }
62112 }
62113
62114 /*
62115 ** Given an expression list, generate a KeyInfo structure that records
62116 ** the collating sequence for each expression in that expression list.
62117 **
62118 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
62119 ** KeyInfo structure is appropriate for initializing a virtual index to
62120 ** implement that clause.  If the ExprList is the result set of a SELECT
62121 ** then the KeyInfo structure is appropriate for initializing a virtual
62122 ** index to implement a DISTINCT test.
62123 **
62124 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
62125 ** function is responsible for seeing that this structure is eventually
62126 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
62127 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
62128 */
62129 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
62130   sqlite3 *db = pParse->db;
62131   int nExpr;
62132   KeyInfo *pInfo;
62133   struct ExprList_item *pItem;
62134   int i;
62135
62136   nExpr = pList->nExpr;
62137   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
62138   if( pInfo ){
62139     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
62140     pInfo->nField = nExpr;
62141     pInfo->enc = ENC(db);
62142     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
62143       CollSeq *pColl;
62144       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
62145       if( !pColl ){
62146         pColl = db->pDfltColl;
62147       }
62148       pInfo->aColl[i] = pColl;
62149       pInfo->aSortOrder[i] = pItem->sortOrder;
62150     }
62151   }
62152   return pInfo;
62153 }
62154
62155
62156 /*
62157 ** If the inner loop was generated using a non-null pOrderBy argument,
62158 ** then the results were placed in a sorter.  After the loop is terminated
62159 ** we need to run the sorter and output the results.  The following
62160 ** routine generates the code needed to do that.
62161 */
62162 static void generateSortTail(
62163   Parse *pParse,    /* Parsing context */
62164   Select *p,        /* The SELECT statement */
62165   Vdbe *v,          /* Generate code into this VDBE */
62166   int nColumn,      /* Number of columns of data */
62167   SelectDest *pDest /* Write the sorted results here */
62168 ){
62169   int brk = sqlite3VdbeMakeLabel(v);
62170   int cont = sqlite3VdbeMakeLabel(v);
62171   int addr;
62172   int iTab;
62173   int pseudoTab = 0;
62174   ExprList *pOrderBy = p->pOrderBy;
62175
62176   int eDest = pDest->eDest;
62177   int iParm = pDest->iParm;
62178
62179   int regRow;
62180   int regRowid;
62181
62182   iTab = pOrderBy->iECursor;
62183   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
62184     pseudoTab = pParse->nTab++;
62185     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, 0);
62186     sqlite3VdbeAddOp2(v, OP_SetNumColumns, pseudoTab, nColumn);
62187   }
62188   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
62189   codeOffset(v, p, cont);
62190   regRow = sqlite3GetTempReg(pParse);
62191   regRowid = sqlite3GetTempReg(pParse);
62192   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
62193   switch( eDest ){
62194     case SRT_Table:
62195     case SRT_EphemTab: {
62196       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
62197       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
62198       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
62199       break;
62200     }
62201 #ifndef SQLITE_OMIT_SUBQUERY
62202     case SRT_Set: {
62203       int j1;
62204       assert( nColumn==1 );
62205       j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regRow);
62206       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
62207       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
62208       sqlite3VdbeJumpHere(v, j1);
62209       break;
62210     }
62211     case SRT_Mem: {
62212       assert( nColumn==1 );
62213       sqlite3VdbeAddOp2(v, OP_Move, regRow, iParm);
62214       /* The LIMIT clause will terminate the loop for us */
62215       break;
62216     }
62217 #endif
62218     case SRT_Callback:
62219     case SRT_Subroutine: {
62220       int i;
62221       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
62222       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
62223       for(i=0; i<nColumn; i++){
62224         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
62225       }
62226       if( eDest==SRT_Callback ){
62227         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
62228       }else{
62229         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
62230       }
62231       break;
62232     }
62233     default: {
62234       /* Do nothing */
62235       break;
62236     }
62237   }
62238   sqlite3ReleaseTempReg(pParse, regRow);
62239   sqlite3ReleaseTempReg(pParse, regRowid);
62240
62241   /* Jump to the end of the loop when the LIMIT is reached
62242   */
62243   if( p->iLimit>=0 ){
62244     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
62245     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, brk);
62246   }
62247
62248   /* The bottom of the loop
62249   */
62250   sqlite3VdbeResolveLabel(v, cont);
62251   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
62252   sqlite3VdbeResolveLabel(v, brk);
62253   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
62254     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
62255   }
62256
62257 }
62258
62259 /*
62260 ** Return a pointer to a string containing the 'declaration type' of the
62261 ** expression pExpr. The string may be treated as static by the caller.
62262 **
62263 ** The declaration type is the exact datatype definition extracted from the
62264 ** original CREATE TABLE statement if the expression is a column. The
62265 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
62266 ** is considered a column can be complex in the presence of subqueries. The
62267 ** result-set expression in all of the following SELECT statements is 
62268 ** considered a column by this function.
62269 **
62270 **   SELECT col FROM tbl;
62271 **   SELECT (SELECT col FROM tbl;
62272 **   SELECT (SELECT col FROM tbl);
62273 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
62274 ** 
62275 ** The declaration type for any expression other than a column is NULL.
62276 */
62277 static const char *columnType(
62278   NameContext *pNC, 
62279   Expr *pExpr,
62280   const char **pzOriginDb,
62281   const char **pzOriginTab,
62282   const char **pzOriginCol
62283 ){
62284   char const *zType = 0;
62285   char const *zOriginDb = 0;
62286   char const *zOriginTab = 0;
62287   char const *zOriginCol = 0;
62288   int j;
62289   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
62290
62291   switch( pExpr->op ){
62292     case TK_AGG_COLUMN:
62293     case TK_COLUMN: {
62294       /* The expression is a column. Locate the table the column is being
62295       ** extracted from in NameContext.pSrcList. This table may be real
62296       ** database table or a subquery.
62297       */
62298       Table *pTab = 0;            /* Table structure column is extracted from */
62299       Select *pS = 0;             /* Select the column is extracted from */
62300       int iCol = pExpr->iColumn;  /* Index of column in pTab */
62301       while( pNC && !pTab ){
62302         SrcList *pTabList = pNC->pSrcList;
62303         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
62304         if( j<pTabList->nSrc ){
62305           pTab = pTabList->a[j].pTab;
62306           pS = pTabList->a[j].pSelect;
62307         }else{
62308           pNC = pNC->pNext;
62309         }
62310       }
62311
62312       if( pTab==0 ){
62313         /* FIX ME:
62314         ** This can occurs if you have something like "SELECT new.x;" inside
62315         ** a trigger.  In other words, if you reference the special "new"
62316         ** table in the result set of a select.  We do not have a good way
62317         ** to find the actual table type, so call it "TEXT".  This is really
62318         ** something of a bug, but I do not know how to fix it.
62319         **
62320         ** This code does not produce the correct answer - it just prevents
62321         ** a segfault.  See ticket #1229.
62322         */
62323         zType = "TEXT";
62324         break;
62325       }
62326
62327       assert( pTab );
62328       if( pS ){
62329         /* The "table" is actually a sub-select or a view in the FROM clause
62330         ** of the SELECT statement. Return the declaration type and origin
62331         ** data for the result-set column of the sub-select.
62332         */
62333         if( iCol>=0 && iCol<pS->pEList->nExpr ){
62334           /* If iCol is less than zero, then the expression requests the
62335           ** rowid of the sub-select or view. This expression is legal (see 
62336           ** test case misc2.2.2) - it always evaluates to NULL.
62337           */
62338           NameContext sNC;
62339           Expr *p = pS->pEList->a[iCol].pExpr;
62340           sNC.pSrcList = pS->pSrc;
62341           sNC.pNext = 0;
62342           sNC.pParse = pNC->pParse;
62343           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
62344         }
62345       }else if( pTab->pSchema ){
62346         /* A real table */
62347         assert( !pS );
62348         if( iCol<0 ) iCol = pTab->iPKey;
62349         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
62350         if( iCol<0 ){
62351           zType = "INTEGER";
62352           zOriginCol = "rowid";
62353         }else{
62354           zType = pTab->aCol[iCol].zType;
62355           zOriginCol = pTab->aCol[iCol].zName;
62356         }
62357         zOriginTab = pTab->zName;
62358         if( pNC->pParse ){
62359           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
62360           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
62361         }
62362       }
62363       break;
62364     }
62365 #ifndef SQLITE_OMIT_SUBQUERY
62366     case TK_SELECT: {
62367       /* The expression is a sub-select. Return the declaration type and
62368       ** origin info for the single column in the result set of the SELECT
62369       ** statement.
62370       */
62371       NameContext sNC;
62372       Select *pS = pExpr->pSelect;
62373       Expr *p = pS->pEList->a[0].pExpr;
62374       sNC.pSrcList = pS->pSrc;
62375       sNC.pNext = pNC;
62376       sNC.pParse = pNC->pParse;
62377       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
62378       break;
62379     }
62380 #endif
62381   }
62382   
62383   if( pzOriginDb ){
62384     assert( pzOriginTab && pzOriginCol );
62385     *pzOriginDb = zOriginDb;
62386     *pzOriginTab = zOriginTab;
62387     *pzOriginCol = zOriginCol;
62388   }
62389   return zType;
62390 }
62391
62392 /*
62393 ** Generate code that will tell the VDBE the declaration types of columns
62394 ** in the result set.
62395 */
62396 static void generateColumnTypes(
62397   Parse *pParse,      /* Parser context */
62398   SrcList *pTabList,  /* List of tables */
62399   ExprList *pEList    /* Expressions defining the result set */
62400 ){
62401   Vdbe *v = pParse->pVdbe;
62402   int i;
62403   NameContext sNC;
62404   sNC.pSrcList = pTabList;
62405   sNC.pParse = pParse;
62406   for(i=0; i<pEList->nExpr; i++){
62407     Expr *p = pEList->a[i].pExpr;
62408     const char *zOrigDb = 0;
62409     const char *zOrigTab = 0;
62410     const char *zOrigCol = 0;
62411     const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
62412
62413     /* The vdbe must make its own copy of the column-type and other 
62414     ** column specific strings, in case the schema is reset before this
62415     ** virtual machine is deleted.
62416     */
62417     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
62418     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
62419     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
62420     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
62421   }
62422 }
62423
62424 /*
62425 ** Generate code that will tell the VDBE the names of columns
62426 ** in the result set.  This information is used to provide the
62427 ** azCol[] values in the callback.
62428 */
62429 static void generateColumnNames(
62430   Parse *pParse,      /* Parser context */
62431   SrcList *pTabList,  /* List of tables */
62432   ExprList *pEList    /* Expressions defining the result set */
62433 ){
62434   Vdbe *v = pParse->pVdbe;
62435   int i, j;
62436   sqlite3 *db = pParse->db;
62437   int fullNames, shortNames;
62438
62439 #ifndef SQLITE_OMIT_EXPLAIN
62440   /* If this is an EXPLAIN, skip this step */
62441   if( pParse->explain ){
62442     return;
62443   }
62444 #endif
62445
62446   assert( v!=0 );
62447   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
62448   pParse->colNamesSet = 1;
62449   fullNames = (db->flags & SQLITE_FullColNames)!=0;
62450   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
62451   sqlite3VdbeSetNumCols(v, pEList->nExpr);
62452   for(i=0; i<pEList->nExpr; i++){
62453     Expr *p;
62454     p = pEList->a[i].pExpr;
62455     if( p==0 ) continue;
62456     if( pEList->a[i].zName ){
62457       char *zName = pEList->a[i].zName;
62458       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
62459       continue;
62460     }
62461     if( p->op==TK_COLUMN && pTabList ){
62462       Table *pTab;
62463       char *zCol;
62464       int iCol = p->iColumn;
62465       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
62466       assert( j<pTabList->nSrc );
62467       pTab = pTabList->a[j].pTab;
62468       if( iCol<0 ) iCol = pTab->iPKey;
62469       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
62470       if( iCol<0 ){
62471         zCol = "rowid";
62472       }else{
62473         zCol = pTab->aCol[iCol].zName;
62474       }
62475       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
62476         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
62477       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
62478         char *zName = 0;
62479         char *zTab;
62480  
62481         zTab = pTabList->a[j].zAlias;
62482         if( fullNames || zTab==0 ) zTab = pTab->zName;
62483         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
62484         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
62485       }else{
62486         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
62487       }
62488     }else if( p->span.z && p->span.z[0] ){
62489       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
62490       /* sqlite3VdbeCompressSpace(v, addr); */
62491     }else{
62492       char zName[30];
62493       assert( p->op!=TK_COLUMN || pTabList==0 );
62494       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
62495       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
62496     }
62497   }
62498   generateColumnTypes(pParse, pTabList, pEList);
62499 }
62500
62501 #ifndef SQLITE_OMIT_COMPOUND_SELECT
62502 /*
62503 ** Name of the connection operator, used for error messages.
62504 */
62505 static const char *selectOpName(int id){
62506   char *z;
62507   switch( id ){
62508     case TK_ALL:       z = "UNION ALL";   break;
62509     case TK_INTERSECT: z = "INTERSECT";   break;
62510     case TK_EXCEPT:    z = "EXCEPT";      break;
62511     default:           z = "UNION";       break;
62512   }
62513   return z;
62514 }
62515 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
62516
62517 /*
62518 ** Forward declaration
62519 */
62520 static int prepSelectStmt(Parse*, Select*);
62521
62522 /*
62523 ** Given a SELECT statement, generate a Table structure that describes
62524 ** the result set of that SELECT.
62525 */
62526 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
62527   Table *pTab;
62528   int i, j;
62529   ExprList *pEList;
62530   Column *aCol, *pCol;
62531   sqlite3 *db = pParse->db;
62532
62533   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
62534   if( prepSelectStmt(pParse, pSelect) ){
62535     return 0;
62536   }
62537   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
62538     return 0;
62539   }
62540   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
62541   if( pTab==0 ){
62542     return 0;
62543   }
62544   pTab->nRef = 1;
62545   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
62546   pEList = pSelect->pEList;
62547   pTab->nCol = pEList->nExpr;
62548   assert( pTab->nCol>0 );
62549   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
62550   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
62551     Expr *p, *pR;
62552     char *zType;
62553     char *zName;
62554     int nName;
62555     CollSeq *pColl;
62556     int cnt;
62557     NameContext sNC;
62558     
62559     /* Get an appropriate name for the column
62560     */
62561     p = pEList->a[i].pExpr;
62562     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
62563     if( (zName = pEList->a[i].zName)!=0 ){
62564       /* If the column contains an "AS <name>" phrase, use <name> as the name */
62565       zName = sqlite3DbStrDup(db, zName);
62566     }else if( p->op==TK_DOT 
62567               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
62568       /* For columns of the from A.B use B as the name */
62569       zName = sqlite3MPrintf(db, "%T", &pR->token);
62570     }else if( p->span.z && p->span.z[0] ){
62571       /* Use the original text of the column expression as its name */
62572       zName = sqlite3MPrintf(db, "%T", &p->span);
62573     }else{
62574       /* If all else fails, make up a name */
62575       zName = sqlite3MPrintf(db, "column%d", i+1);
62576     }
62577     if( !zName || db->mallocFailed ){
62578       db->mallocFailed = 1;
62579       sqlite3_free(zName);
62580       sqlite3DeleteTable(pTab);
62581       return 0;
62582     }
62583     sqlite3Dequote(zName);
62584
62585     /* Make sure the column name is unique.  If the name is not unique,
62586     ** append a integer to the name so that it becomes unique.
62587     */
62588     nName = strlen(zName);
62589     for(j=cnt=0; j<i; j++){
62590       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
62591         zName[nName] = 0;
62592         zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
62593         j = -1;
62594         if( zName==0 ) break;
62595       }
62596     }
62597     pCol->zName = zName;
62598
62599     /* Get the typename, type affinity, and collating sequence for the
62600     ** column.
62601     */
62602     memset(&sNC, 0, sizeof(sNC));
62603     sNC.pSrcList = pSelect->pSrc;
62604     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
62605     pCol->zType = zType;
62606     pCol->affinity = sqlite3ExprAffinity(p);
62607     pColl = sqlite3ExprCollSeq(pParse, p);
62608     if( pColl ){
62609       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
62610     }
62611   }
62612   pTab->iPKey = -1;
62613   return pTab;
62614 }
62615
62616 /*
62617 ** Prepare a SELECT statement for processing by doing the following
62618 ** things:
62619 **
62620 **    (1)  Make sure VDBE cursor numbers have been assigned to every
62621 **         element of the FROM clause.
62622 **
62623 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
62624 **         defines FROM clause.  When views appear in the FROM clause,
62625 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
62626 **         that implements the view.  A copy is made of the view's SELECT
62627 **         statement so that we can freely modify or delete that statement
62628 **         without worrying about messing up the presistent representation
62629 **         of the view.
62630 **
62631 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
62632 **         on joins and the ON and USING clause of joins.
62633 **
62634 **    (4)  Scan the list of columns in the result set (pEList) looking
62635 **         for instances of the "*" operator or the TABLE.* operator.
62636 **         If found, expand each "*" to be every column in every table
62637 **         and TABLE.* to be every column in TABLE.
62638 **
62639 ** Return 0 on success.  If there are problems, leave an error message
62640 ** in pParse and return non-zero.
62641 */
62642 static int prepSelectStmt(Parse *pParse, Select *p){
62643   int i, j, k, rc;
62644   SrcList *pTabList;
62645   ExprList *pEList;
62646   struct SrcList_item *pFrom;
62647   sqlite3 *db = pParse->db;
62648
62649   if( p==0 || p->pSrc==0 || db->mallocFailed ){
62650     return 1;
62651   }
62652   pTabList = p->pSrc;
62653   pEList = p->pEList;
62654
62655   /* Make sure cursor numbers have been assigned to all entries in
62656   ** the FROM clause of the SELECT statement.
62657   */
62658   sqlite3SrcListAssignCursors(pParse, p->pSrc);
62659
62660   /* Look up every table named in the FROM clause of the select.  If
62661   ** an entry of the FROM clause is a subquery instead of a table or view,
62662   ** then create a transient table structure to describe the subquery.
62663   */
62664   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
62665     Table *pTab;
62666     if( pFrom->pTab!=0 ){
62667       /* This statement has already been prepared.  There is no need
62668       ** to go further. */
62669       assert( i==0 );
62670       return 0;
62671     }
62672     if( pFrom->zName==0 ){
62673 #ifndef SQLITE_OMIT_SUBQUERY
62674       /* A sub-query in the FROM clause of a SELECT */
62675       assert( pFrom->pSelect!=0 );
62676       if( pFrom->zAlias==0 ){
62677         pFrom->zAlias =
62678           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
62679       }
62680       assert( pFrom->pTab==0 );
62681       pFrom->pTab = pTab = 
62682         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
62683       if( pTab==0 ){
62684         return 1;
62685       }
62686       /* The isEphem flag indicates that the Table structure has been
62687       ** dynamically allocated and may be freed at any time.  In other words,
62688       ** pTab is not pointing to a persistent table structure that defines
62689       ** part of the schema. */
62690       pTab->isEphem = 1;
62691 #endif
62692     }else{
62693       /* An ordinary table or view name in the FROM clause */
62694       assert( pFrom->pTab==0 );
62695       pFrom->pTab = pTab = 
62696         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
62697       if( pTab==0 ){
62698         return 1;
62699       }
62700       pTab->nRef++;
62701 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
62702       if( pTab->pSelect || IsVirtual(pTab) ){
62703         /* We reach here if the named table is a really a view */
62704         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
62705           return 1;
62706         }
62707         /* If pFrom->pSelect!=0 it means we are dealing with a
62708         ** view within a view.  The SELECT structure has already been
62709         ** copied by the outer view so we can skip the copy step here
62710         ** in the inner view.
62711         */
62712         if( pFrom->pSelect==0 ){
62713           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
62714         }
62715       }
62716 #endif
62717     }
62718   }
62719
62720   /* Process NATURAL keywords, and ON and USING clauses of joins.
62721   */
62722   if( sqliteProcessJoin(pParse, p) ) return 1;
62723
62724   /* For every "*" that occurs in the column list, insert the names of
62725   ** all columns in all tables.  And for every TABLE.* insert the names
62726   ** of all columns in TABLE.  The parser inserted a special expression
62727   ** with the TK_ALL operator for each "*" that it found in the column list.
62728   ** The following code just has to locate the TK_ALL expressions and expand
62729   ** each one to the list of all columns in all tables.
62730   **
62731   ** The first loop just checks to see if there are any "*" operators
62732   ** that need expanding.
62733   */
62734   for(k=0; k<pEList->nExpr; k++){
62735     Expr *pE = pEList->a[k].pExpr;
62736     if( pE->op==TK_ALL ) break;
62737     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
62738          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
62739   }
62740   rc = 0;
62741   if( k<pEList->nExpr ){
62742     /*
62743     ** If we get here it means the result set contains one or more "*"
62744     ** operators that need to be expanded.  Loop through each expression
62745     ** in the result set and expand them one by one.
62746     */
62747     struct ExprList_item *a = pEList->a;
62748     ExprList *pNew = 0;
62749     int flags = pParse->db->flags;
62750     int longNames = (flags & SQLITE_FullColNames)!=0 &&
62751                       (flags & SQLITE_ShortColNames)==0;
62752
62753     for(k=0; k<pEList->nExpr; k++){
62754       Expr *pE = a[k].pExpr;
62755       if( pE->op!=TK_ALL &&
62756            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
62757         /* This particular expression does not need to be expanded.
62758         */
62759         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
62760         if( pNew ){
62761           pNew->a[pNew->nExpr-1].zName = a[k].zName;
62762         }else{
62763           rc = 1;
62764         }
62765         a[k].pExpr = 0;
62766         a[k].zName = 0;
62767       }else{
62768         /* This expression is a "*" or a "TABLE.*" and needs to be
62769         ** expanded. */
62770         int tableSeen = 0;      /* Set to 1 when TABLE matches */
62771         char *zTName;            /* text of name of TABLE */
62772         if( pE->op==TK_DOT && pE->pLeft ){
62773           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
62774         }else{
62775           zTName = 0;
62776         }
62777         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
62778           Table *pTab = pFrom->pTab;
62779           char *zTabName = pFrom->zAlias;
62780           if( zTabName==0 || zTabName[0]==0 ){ 
62781             zTabName = pTab->zName;
62782           }
62783           if( zTName && (zTabName==0 || zTabName[0]==0 || 
62784                  sqlite3StrICmp(zTName, zTabName)!=0) ){
62785             continue;
62786           }
62787           tableSeen = 1;
62788           for(j=0; j<pTab->nCol; j++){
62789             Expr *pExpr, *pRight;
62790             char *zName = pTab->aCol[j].zName;
62791
62792             /* If a column is marked as 'hidden' (currently only possible
62793             ** for virtual tables), do not include it in the expanded
62794             ** result-set list.
62795             */
62796             if( IsHiddenColumn(&pTab->aCol[j]) ){
62797               assert(IsVirtual(pTab));
62798               continue;
62799             }
62800
62801             if( i>0 ){
62802               struct SrcList_item *pLeft = &pTabList->a[i-1];
62803               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
62804                         columnIndex(pLeft->pTab, zName)>=0 ){
62805                 /* In a NATURAL join, omit the join columns from the 
62806                 ** table on the right */
62807                 continue;
62808               }
62809               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
62810                 /* In a join with a USING clause, omit columns in the
62811                 ** using clause from the table on the right. */
62812                 continue;
62813               }
62814             }
62815             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
62816             if( pRight==0 ) break;
62817             setQuotedToken(pParse, &pRight->token, zName);
62818             if( zTabName && (longNames || pTabList->nSrc>1) ){
62819               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
62820               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
62821               if( pExpr==0 ) break;
62822               setQuotedToken(pParse, &pLeft->token, zTabName);
62823               setToken(&pExpr->span, 
62824                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
62825               pExpr->span.dyn = 1;
62826               pExpr->token.z = 0;
62827               pExpr->token.n = 0;
62828               pExpr->token.dyn = 0;
62829             }else{
62830               pExpr = pRight;
62831               pExpr->span = pExpr->token;
62832               pExpr->span.dyn = 0;
62833             }
62834             if( longNames ){
62835               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
62836             }else{
62837               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
62838             }
62839           }
62840         }
62841         if( !tableSeen ){
62842           if( zTName ){
62843             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
62844           }else{
62845             sqlite3ErrorMsg(pParse, "no tables specified");
62846           }
62847           rc = 1;
62848         }
62849         sqlite3_free(zTName);
62850       }
62851     }
62852     sqlite3ExprListDelete(pEList);
62853     p->pEList = pNew;
62854   }
62855   if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
62856     sqlite3ErrorMsg(pParse, "too many columns in result set");
62857     rc = SQLITE_ERROR;
62858   }
62859   if( db->mallocFailed ){
62860     rc = SQLITE_NOMEM;
62861   }
62862   return rc;
62863 }
62864
62865 /*
62866 ** pE is a pointer to an expression which is a single term in
62867 ** ORDER BY or GROUP BY clause.
62868 **
62869 ** If pE evaluates to an integer constant i, then return i.
62870 ** This is an indication to the caller that it should sort
62871 ** by the i-th column of the result set.
62872 **
62873 ** If pE is a well-formed expression and the SELECT statement
62874 ** is not compound, then return 0.  This indicates to the
62875 ** caller that it should sort by the value of the ORDER BY
62876 ** expression.
62877 **
62878 ** If the SELECT is compound, then attempt to match pE against
62879 ** result set columns in the left-most SELECT statement.  Return
62880 ** the index i of the matching column, as an indication to the 
62881 ** caller that it should sort by the i-th column.  If there is
62882 ** no match, return -1 and leave an error message in pParse.
62883 */
62884 static int matchOrderByTermToExprList(
62885   Parse *pParse,     /* Parsing context for error messages */
62886   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
62887   Expr *pE,          /* The specific ORDER BY term */
62888   int idx,           /* When ORDER BY term is this */
62889   int isCompound,    /* True if this is a compound SELECT */
62890   u8 *pHasAgg        /* True if expression contains aggregate functions */
62891 ){
62892   int i;             /* Loop counter */
62893   ExprList *pEList;  /* The columns of the result set */
62894   NameContext nc;    /* Name context for resolving pE */
62895
62896
62897   /* If the term is an integer constant, return the value of that
62898   ** constant */
62899   pEList = pSelect->pEList;
62900   if( sqlite3ExprIsInteger(pE, &i) ){
62901     if( i<=0 ){
62902       /* If i is too small, make it too big.  That way the calling
62903       ** function still sees a value that is out of range, but does
62904       ** not confuse the column number with 0 or -1 result code.
62905       */
62906       i = pEList->nExpr+1;
62907     }
62908     return i;
62909   }
62910
62911   /* If the term is a simple identifier that try to match that identifier
62912   ** against a column name in the result set.
62913   */
62914   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
62915     sqlite3 *db = pParse->db;
62916     char *zCol = sqlite3NameFromToken(db, &pE->token);
62917     if( zCol==0 ){
62918       return -1;
62919     }
62920     for(i=0; i<pEList->nExpr; i++){
62921       char *zAs = pEList->a[i].zName;
62922       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
62923         sqlite3_free(zCol);
62924         return i+1;
62925       }
62926     }
62927     sqlite3_free(zCol);
62928   }
62929
62930   /* Resolve all names in the ORDER BY term expression
62931   */
62932   memset(&nc, 0, sizeof(nc));
62933   nc.pParse = pParse;
62934   nc.pSrcList = pSelect->pSrc;
62935   nc.pEList = pEList;
62936   nc.allowAgg = 1;
62937   nc.nErr = 0;
62938   if( sqlite3ExprResolveNames(&nc, pE) ){
62939     if( isCompound ){
62940       sqlite3ErrorClear(pParse);
62941       return 0;
62942     }else{
62943       return -1;
62944     }
62945   }
62946   if( nc.hasAgg && pHasAgg ){
62947     *pHasAgg = 1;
62948   }
62949
62950   /* For a compound SELECT, we need to try to match the ORDER BY
62951   ** expression against an expression in the result set
62952   */
62953   if( isCompound ){
62954     for(i=0; i<pEList->nExpr; i++){
62955       if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
62956         return i+1;
62957       }
62958     }
62959   }
62960   return 0;
62961 }
62962
62963
62964 /*
62965 ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
62966 ** Return the number of errors seen.
62967 **
62968 ** Every term of the ORDER BY or GROUP BY clause needs to be an
62969 ** expression.  If any expression is an integer constant, then
62970 ** that expression is replaced by the corresponding 
62971 ** expression from the result set.
62972 */
62973 static int processOrderGroupBy(
62974   Parse *pParse,        /* Parsing context.  Leave error messages here */
62975   Select *pSelect,      /* The SELECT statement containing the clause */
62976   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
62977   int isOrder,          /* 1 for ORDER BY.  0 for GROUP BY */
62978   u8 *pHasAgg           /* Set to TRUE if any term contains an aggregate */
62979 ){
62980   int i;
62981   sqlite3 *db = pParse->db;
62982   ExprList *pEList;
62983
62984   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
62985   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
62986     const char *zType = isOrder ? "ORDER" : "GROUP";
62987     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
62988     return 1;
62989   }
62990   pEList = pSelect->pEList;
62991   if( pEList==0 ){
62992     return 0;
62993   }
62994   for(i=0; i<pOrderBy->nExpr; i++){
62995     int iCol;
62996     Expr *pE = pOrderBy->a[i].pExpr;
62997     iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
62998     if( iCol<0 ){
62999       return 1;
63000     }
63001     if( iCol>pEList->nExpr ){
63002       const char *zType = isOrder ? "ORDER" : "GROUP";
63003       sqlite3ErrorMsg(pParse, 
63004          "%r %s BY term out of range - should be "
63005          "between 1 and %d", i+1, zType, pEList->nExpr);
63006       return 1;
63007     }
63008     if( iCol>0 ){
63009       CollSeq *pColl = pE->pColl;
63010       int flags = pE->flags & EP_ExpCollate;
63011       sqlite3ExprDelete(pE);
63012       pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
63013       pOrderBy->a[i].pExpr = pE;
63014       if( pE && pColl && flags ){
63015         pE->pColl = pColl;
63016         pE->flags |= flags;
63017       }
63018     }
63019   }
63020   return 0;
63021 }
63022
63023 /*
63024 ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
63025 ** the number of errors seen.
63026 **
63027 ** The processing depends on whether the SELECT is simple or compound.
63028 ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY
63029 ** clause needs to be an expression.  If any expression is an integer
63030 ** constant, then that expression is replaced by the corresponding 
63031 ** expression from the result set.
63032 **
63033 ** For compound SELECT statements, every expression needs to be of
63034 ** type TK_COLUMN with a iTable value as given in the 4th parameter.
63035 ** If any expression is an integer, that becomes the column number.
63036 ** Otherwise, match the expression against result set columns from
63037 ** the left-most SELECT.
63038 */
63039 static int processCompoundOrderBy(
63040   Parse *pParse,        /* Parsing context.  Leave error messages here */
63041   Select *pSelect,      /* The SELECT statement containing the ORDER BY */
63042   int iTable            /* Output table for compound SELECT statements */
63043 ){
63044   int i;
63045   ExprList *pOrderBy;
63046   ExprList *pEList;
63047   sqlite3 *db;
63048   int moreToDo = 1;
63049
63050   pOrderBy = pSelect->pOrderBy;
63051   if( pOrderBy==0 ) return 0;
63052   if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
63053     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
63054     return 1;
63055   }
63056   db = pParse->db;
63057   for(i=0; i<pOrderBy->nExpr; i++){
63058     pOrderBy->a[i].done = 0;
63059   }
63060   while( pSelect->pPrior ){
63061     pSelect = pSelect->pPrior;
63062   }
63063   while( pSelect && moreToDo ){
63064     moreToDo = 0;
63065     for(i=0; i<pOrderBy->nExpr; i++){
63066       int iCol = -1;
63067       Expr *pE, *pDup;
63068       if( pOrderBy->a[i].done ) continue;
63069       pE = pOrderBy->a[i].pExpr;
63070       pDup = sqlite3ExprDup(db, pE);
63071       if( !db->mallocFailed ){
63072         assert(pDup);
63073         iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
63074       }
63075       sqlite3ExprDelete(pDup);
63076       if( iCol<0 ){
63077         return 1;
63078       }
63079       pEList = pSelect->pEList;
63080       if( pEList==0 ){
63081         return 1;
63082       }
63083       if( iCol>pEList->nExpr ){
63084         sqlite3ErrorMsg(pParse, 
63085            "%r ORDER BY term out of range - should be "
63086            "between 1 and %d", i+1, pEList->nExpr);
63087         return 1;
63088       }
63089       if( iCol>0 ){
63090         pE->op = TK_COLUMN;
63091         pE->iTable = iTable;
63092         pE->iAgg = -1;
63093         pE->iColumn = iCol-1;
63094         pE->pTab = 0;
63095         pOrderBy->a[i].done = 1;
63096       }else{
63097         moreToDo = 1;
63098       }
63099     }
63100     pSelect = pSelect->pNext;
63101   }
63102   for(i=0; i<pOrderBy->nExpr; i++){
63103     if( pOrderBy->a[i].done==0 ){
63104       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
63105             "column in the result set", i+1);
63106       return 1;
63107     }
63108   }
63109   return 0;
63110 }
63111
63112 /*
63113 ** Get a VDBE for the given parser context.  Create a new one if necessary.
63114 ** If an error occurs, return NULL and leave a message in pParse.
63115 */
63116 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
63117   Vdbe *v = pParse->pVdbe;
63118   if( v==0 ){
63119     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
63120 #ifndef SQLITE_OMIT_TRACE
63121     if( v ){
63122       sqlite3VdbeAddOp0(v, OP_Trace);
63123     }
63124 #endif
63125   }
63126   return v;
63127 }
63128
63129
63130 /*
63131 ** Compute the iLimit and iOffset fields of the SELECT based on the
63132 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
63133 ** that appear in the original SQL statement after the LIMIT and OFFSET
63134 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
63135 ** are the integer memory register numbers for counters used to compute 
63136 ** the limit and offset.  If there is no limit and/or offset, then 
63137 ** iLimit and iOffset are negative.
63138 **
63139 ** This routine changes the values of iLimit and iOffset only if
63140 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
63141 ** iOffset should have been preset to appropriate default values
63142 ** (usually but not always -1) prior to calling this routine.
63143 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
63144 ** redefined.  The UNION ALL operator uses this property to force
63145 ** the reuse of the same limit and offset registers across multiple
63146 ** SELECT statements.
63147 */
63148 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
63149   Vdbe *v = 0;
63150   int iLimit = 0;
63151   int iOffset;
63152   int addr1;
63153
63154   /* 
63155   ** "LIMIT -1" always shows all rows.  There is some
63156   ** contraversy about what the correct behavior should be.
63157   ** The current implementation interprets "LIMIT 0" to mean
63158   ** no rows.
63159   */
63160   if( p->pLimit ){
63161     p->iLimit = iLimit = ++pParse->nMem;
63162     v = sqlite3GetVdbe(pParse);
63163     if( v==0 ) return;
63164     sqlite3ExprCode(pParse, p->pLimit, iLimit);
63165     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
63166     VdbeComment((v, "LIMIT counter"));
63167     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
63168   }
63169   if( p->pOffset ){
63170     p->iOffset = iOffset = ++pParse->nMem;
63171     if( p->pLimit ){
63172       pParse->nMem++;   /* Allocate an extra register for limit+offset */
63173     }
63174     v = sqlite3GetVdbe(pParse);
63175     if( v==0 ) return;
63176     sqlite3ExprCode(pParse, p->pOffset, iOffset);
63177     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
63178     VdbeComment((v, "OFFSET counter"));
63179     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
63180     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
63181     sqlite3VdbeJumpHere(v, addr1);
63182     if( p->pLimit ){
63183       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
63184       VdbeComment((v, "LIMIT+OFFSET"));
63185       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
63186       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
63187       sqlite3VdbeJumpHere(v, addr1);
63188     }
63189   }
63190 }
63191
63192 /*
63193 ** Allocate a virtual index to use for sorting.
63194 */
63195 static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
63196   if( pOrderBy ){
63197     int addr;
63198     assert( pOrderBy->iECursor==0 );
63199     pOrderBy->iECursor = pParse->nTab++;
63200     addr = sqlite3VdbeAddOp2(pParse->pVdbe, OP_OpenEphemeral,
63201                             pOrderBy->iECursor, pOrderBy->nExpr+1);
63202     assert( p->addrOpenEphm[2] == -1 );
63203     p->addrOpenEphm[2] = addr;
63204   }
63205 }
63206
63207 #ifndef SQLITE_OMIT_COMPOUND_SELECT
63208 /*
63209 ** Return the appropriate collating sequence for the iCol-th column of
63210 ** the result set for the compound-select statement "p".  Return NULL if
63211 ** the column has no default collating sequence.
63212 **
63213 ** The collating sequence for the compound select is taken from the
63214 ** left-most term of the select that has a collating sequence.
63215 */
63216 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
63217   CollSeq *pRet;
63218   if( p->pPrior ){
63219     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
63220   }else{
63221     pRet = 0;
63222   }
63223   if( pRet==0 ){
63224     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
63225   }
63226   return pRet;
63227 }
63228 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
63229
63230 #ifndef SQLITE_OMIT_COMPOUND_SELECT
63231 /*
63232 ** This routine is called to process a query that is really the union
63233 ** or intersection of two or more separate queries.
63234 **
63235 ** "p" points to the right-most of the two queries.  the query on the
63236 ** left is p->pPrior.  The left query could also be a compound query
63237 ** in which case this routine will be called recursively. 
63238 **
63239 ** The results of the total query are to be written into a destination
63240 ** of type eDest with parameter iParm.
63241 **
63242 ** Example 1:  Consider a three-way compound SQL statement.
63243 **
63244 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
63245 **
63246 ** This statement is parsed up as follows:
63247 **
63248 **     SELECT c FROM t3
63249 **      |
63250 **      `----->  SELECT b FROM t2
63251 **                |
63252 **                `------>  SELECT a FROM t1
63253 **
63254 ** The arrows in the diagram above represent the Select.pPrior pointer.
63255 ** So if this routine is called with p equal to the t3 query, then
63256 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
63257 **
63258 ** Notice that because of the way SQLite parses compound SELECTs, the
63259 ** individual selects always group from left to right.
63260 */
63261 static int multiSelect(
63262   Parse *pParse,        /* Parsing context */
63263   Select *p,            /* The right-most of SELECTs to be coded */
63264   SelectDest *pDest,    /* What to do with query results */
63265   char *aff             /* If eDest is SRT_Union, the affinity string */
63266 ){
63267   int rc = SQLITE_OK;   /* Success code from a subroutine */
63268   Select *pPrior;       /* Another SELECT immediately to our left */
63269   Vdbe *v;              /* Generate code to this VDBE */
63270   int nCol;             /* Number of columns in the result set */
63271   ExprList *pOrderBy;   /* The ORDER BY clause on p */
63272   int aSetP2[2];        /* Set P2 value of these op to number of columns */
63273   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
63274   SelectDest dest;      /* Alternative data destination */
63275
63276   dest = *pDest;
63277
63278   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
63279   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
63280   */
63281   if( p==0 || p->pPrior==0 ){
63282     rc = 1;
63283     goto multi_select_end;
63284   }
63285   pPrior = p->pPrior;
63286   assert( pPrior->pRightmost!=pPrior );
63287   assert( pPrior->pRightmost==p->pRightmost );
63288   if( pPrior->pOrderBy ){
63289     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
63290       selectOpName(p->op));
63291     rc = 1;
63292     goto multi_select_end;
63293   }
63294   if( pPrior->pLimit ){
63295     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
63296       selectOpName(p->op));
63297     rc = 1;
63298     goto multi_select_end;
63299   }
63300
63301   /* Make sure we have a valid query engine.  If not, create a new one.
63302   */
63303   v = sqlite3GetVdbe(pParse);
63304   if( v==0 ){
63305     rc = 1;
63306     goto multi_select_end;
63307   }
63308
63309   /* Create the destination temporary table if necessary
63310   */
63311   if( dest.eDest==SRT_EphemTab ){
63312     assert( p->pEList );
63313     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
63314     aSetP2[nSetP2++] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, 0);
63315     dest.eDest = SRT_Table;
63316   }
63317
63318   /* Generate code for the left and right SELECT statements.
63319   */
63320   pOrderBy = p->pOrderBy;
63321   switch( p->op ){
63322     case TK_ALL: {
63323       if( pOrderBy==0 ){
63324         int addr = 0;
63325         assert( !pPrior->pLimit );
63326         pPrior->pLimit = p->pLimit;
63327         pPrior->pOffset = p->pOffset;
63328         rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0, aff);
63329         p->pLimit = 0;
63330         p->pOffset = 0;
63331         if( rc ){
63332           goto multi_select_end;
63333         }
63334         p->pPrior = 0;
63335         p->iLimit = pPrior->iLimit;
63336         p->iOffset = pPrior->iOffset;
63337         if( p->iLimit>=0 ){
63338           addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
63339           VdbeComment((v, "Jump ahead if LIMIT reached"));
63340         }
63341         rc = sqlite3Select(pParse, p, &dest, 0, 0, 0, aff);
63342         p->pPrior = pPrior;
63343         if( rc ){
63344           goto multi_select_end;
63345         }
63346         if( addr ){
63347           sqlite3VdbeJumpHere(v, addr);
63348         }
63349         break;
63350       }
63351       /* For UNION ALL ... ORDER BY fall through to the next case */
63352     }
63353     case TK_EXCEPT:
63354     case TK_UNION: {
63355       int unionTab;    /* Cursor number of the temporary table holding result */
63356       int op = 0;      /* One of the SRT_ operations to apply to self */
63357       int priorOp;     /* The SRT_ operation to apply to prior selects */
63358       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
63359       int addr;
63360       SelectDest uniondest;
63361
63362       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
63363       if( dest.eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
63364         /* We can reuse a temporary table generated by a SELECT to our
63365         ** right.
63366         */
63367         unionTab = dest.iParm;
63368       }else{
63369         /* We will need to create our own temporary table to hold the
63370         ** intermediate results.
63371         */
63372         unionTab = pParse->nTab++;
63373         if( processCompoundOrderBy(pParse, p, unionTab) ){
63374           rc = 1;
63375           goto multi_select_end;
63376         }
63377         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
63378         if( priorOp==SRT_Table ){
63379           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
63380           aSetP2[nSetP2++] = addr;
63381         }else{
63382           assert( p->addrOpenEphm[0] == -1 );
63383           p->addrOpenEphm[0] = addr;
63384           p->pRightmost->usesEphm = 1;
63385         }
63386         createSortingIndex(pParse, p, pOrderBy);
63387         assert( p->pEList );
63388       }
63389
63390       /* Code the SELECT statements to our left
63391       */
63392       assert( !pPrior->pOrderBy );
63393       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
63394       rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0, aff);
63395       if( rc ){
63396         goto multi_select_end;
63397       }
63398
63399       /* Code the current SELECT statement
63400       */
63401       switch( p->op ){
63402          case TK_EXCEPT:  op = SRT_Except;   break;
63403          case TK_UNION:   op = SRT_Union;    break;
63404          case TK_ALL:     op = SRT_Table;    break;
63405       }
63406       p->pPrior = 0;
63407       p->pOrderBy = 0;
63408       p->disallowOrderBy = pOrderBy!=0;
63409       pLimit = p->pLimit;
63410       p->pLimit = 0;
63411       pOffset = p->pOffset;
63412       p->pOffset = 0;
63413       uniondest.eDest = op;
63414       rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0, aff);
63415       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
63416       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
63417       sqlite3ExprListDelete(p->pOrderBy);
63418       p->pPrior = pPrior;
63419       p->pOrderBy = pOrderBy;
63420       sqlite3ExprDelete(p->pLimit);
63421       p->pLimit = pLimit;
63422       p->pOffset = pOffset;
63423       p->iLimit = -1;
63424       p->iOffset = -1;
63425       if( rc ){
63426         goto multi_select_end;
63427       }
63428
63429
63430       /* Convert the data in the temporary table into whatever form
63431       ** it is that we currently need.
63432       */      
63433       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
63434         int iCont, iBreak, iStart;
63435         assert( p->pEList );
63436         if( dest.eDest==SRT_Callback ){
63437           Select *pFirst = p;
63438           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
63439           generateColumnNames(pParse, 0, pFirst->pEList);
63440         }
63441         iBreak = sqlite3VdbeMakeLabel(v);
63442         iCont = sqlite3VdbeMakeLabel(v);
63443         computeLimitRegisters(pParse, p, iBreak);
63444         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
63445         iStart = sqlite3VdbeCurrentAddr(v);
63446         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
63447                         pOrderBy, -1, &dest, iCont, iBreak, 0);
63448         sqlite3VdbeResolveLabel(v, iCont);
63449         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
63450         sqlite3VdbeResolveLabel(v, iBreak);
63451         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
63452       }
63453       break;
63454     }
63455     case TK_INTERSECT: {
63456       int tab1, tab2;
63457       int iCont, iBreak, iStart;
63458       Expr *pLimit, *pOffset;
63459       int addr;
63460       SelectDest intersectdest;
63461       int r1;
63462
63463       /* INTERSECT is different from the others since it requires
63464       ** two temporary tables.  Hence it has its own case.  Begin
63465       ** by allocating the tables we will need.
63466       */
63467       tab1 = pParse->nTab++;
63468       tab2 = pParse->nTab++;
63469       if( processCompoundOrderBy(pParse, p, tab1) ){
63470         rc = 1;
63471         goto multi_select_end;
63472       }
63473       createSortingIndex(pParse, p, pOrderBy);
63474
63475       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
63476       assert( p->addrOpenEphm[0] == -1 );
63477       p->addrOpenEphm[0] = addr;
63478       p->pRightmost->usesEphm = 1;
63479       assert( p->pEList );
63480
63481       /* Code the SELECTs to our left into temporary table "tab1".
63482       */
63483       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
63484       rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0, aff);
63485       if( rc ){
63486         goto multi_select_end;
63487       }
63488
63489       /* Code the current SELECT into temporary table "tab2"
63490       */
63491       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
63492       assert( p->addrOpenEphm[1] == -1 );
63493       p->addrOpenEphm[1] = addr;
63494       p->pPrior = 0;
63495       pLimit = p->pLimit;
63496       p->pLimit = 0;
63497       pOffset = p->pOffset;
63498       p->pOffset = 0;
63499       intersectdest.iParm = tab2;
63500       rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0, aff);
63501       p->pPrior = pPrior;
63502       sqlite3ExprDelete(p->pLimit);
63503       p->pLimit = pLimit;
63504       p->pOffset = pOffset;
63505       if( rc ){
63506         goto multi_select_end;
63507       }
63508
63509       /* Generate code to take the intersection of the two temporary
63510       ** tables.
63511       */
63512       assert( p->pEList );
63513       if( dest.eDest==SRT_Callback ){
63514         Select *pFirst = p;
63515         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
63516         generateColumnNames(pParse, 0, pFirst->pEList);
63517       }
63518       iBreak = sqlite3VdbeMakeLabel(v);
63519       iCont = sqlite3VdbeMakeLabel(v);
63520       computeLimitRegisters(pParse, p, iBreak);
63521       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
63522       r1 = sqlite3GetTempReg(pParse);
63523       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
63524       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
63525       sqlite3ReleaseTempReg(pParse, r1);
63526       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
63527                       pOrderBy, -1, &dest, iCont, iBreak, 0);
63528       sqlite3VdbeResolveLabel(v, iCont);
63529       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
63530       sqlite3VdbeResolveLabel(v, iBreak);
63531       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
63532       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
63533       break;
63534     }
63535   }
63536
63537   /* Make sure all SELECTs in the statement have the same number of elements
63538   ** in their result sets.
63539   */
63540   assert( p->pEList && pPrior->pEList );
63541   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
63542     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
63543       " do not have the same number of result columns", selectOpName(p->op));
63544     rc = 1;
63545     goto multi_select_end;
63546   }
63547
63548   /* Set the number of columns in temporary tables
63549   */
63550   nCol = p->pEList->nExpr;
63551   while( nSetP2 ){
63552     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
63553   }
63554
63555   /* Compute collating sequences used by either the ORDER BY clause or
63556   ** by any temporary tables needed to implement the compound select.
63557   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
63558   ** ORDER BY processing if there is an ORDER BY clause.
63559   **
63560   ** This section is run by the right-most SELECT statement only.
63561   ** SELECT statements to the left always skip this part.  The right-most
63562   ** SELECT might also skip this part if it has no ORDER BY clause and
63563   ** no temp tables are required.
63564   */
63565   if( pOrderBy || p->usesEphm ){
63566     int i;                        /* Loop counter */
63567     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
63568     Select *pLoop;                /* For looping through SELECT statements */
63569     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
63570     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
63571     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
63572
63573     assert( p->pRightmost==p );
63574     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
63575     pKeyInfo = sqlite3DbMallocZero(pParse->db,
63576                        sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
63577     if( !pKeyInfo ){
63578       rc = SQLITE_NOMEM;
63579       goto multi_select_end;
63580     }
63581
63582     pKeyInfo->enc = ENC(pParse->db);
63583     pKeyInfo->nField = nCol;
63584
63585     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
63586       *apColl = multiSelectCollSeq(pParse, p, i);
63587       if( 0==*apColl ){
63588         *apColl = pParse->db->pDfltColl;
63589       }
63590     }
63591
63592     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
63593       for(i=0; i<2; i++){
63594         int addr = pLoop->addrOpenEphm[i];
63595         if( addr<0 ){
63596           /* If [0] is unused then [1] is also unused.  So we can
63597           ** always safely abort as soon as the first unused slot is found */
63598           assert( pLoop->addrOpenEphm[1]<0 );
63599           break;
63600         }
63601         sqlite3VdbeChangeP2(v, addr, nCol);
63602         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
63603         pLoop->addrOpenEphm[i] = -1;
63604       }
63605     }
63606
63607     if( pOrderBy ){
63608       struct ExprList_item *pOTerm = pOrderBy->a;
63609       int nOrderByExpr = pOrderBy->nExpr;
63610       int addr;
63611       u8 *pSortOrder;
63612
63613       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
63614       ** the compound select statements.  Except we have to change out the
63615       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
63616       ** reused when constructing the pKeyInfo for the ORDER BY, so make
63617       ** a copy.  Sufficient space to hold both the nCol entries for
63618       ** the compound select and the nOrderbyExpr entries for the ORDER BY
63619       ** was allocated above.  But we need to move the compound select
63620       ** entries out of the way before constructing the ORDER BY entries.
63621       ** Move the compound select entries into aCopy[] where they can be
63622       ** accessed and reused when constructing the ORDER BY entries.
63623       ** Because nCol might be greater than or less than nOrderByExpr
63624       ** we have to use memmove() when doing the copy.
63625       */
63626       aCopy = &pKeyInfo->aColl[nOrderByExpr];
63627       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
63628       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
63629
63630       apColl = pKeyInfo->aColl;
63631       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
63632         Expr *pExpr = pOTerm->pExpr;
63633         if( (pExpr->flags & EP_ExpCollate) ){
63634           assert( pExpr->pColl!=0 );
63635           *apColl = pExpr->pColl;
63636         }else{
63637           *apColl = aCopy[pExpr->iColumn];
63638         }
63639         *pSortOrder = pOTerm->sortOrder;
63640       }
63641       assert( p->pRightmost==p );
63642       assert( p->addrOpenEphm[2]>=0 );
63643       addr = p->addrOpenEphm[2];
63644       sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
63645       pKeyInfo->nField = nOrderByExpr;
63646       sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
63647       pKeyInfo = 0;
63648       generateSortTail(pParse, p, v, p->pEList->nExpr, &dest);
63649     }
63650
63651     sqlite3_free(pKeyInfo);
63652   }
63653
63654 multi_select_end:
63655   pDest->iMem = dest.iMem;
63656   return rc;
63657 }
63658 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
63659
63660 #ifndef SQLITE_OMIT_VIEW
63661 /* Forward Declarations */
63662 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
63663 static void substSelect(sqlite3*, Select *, int, ExprList *);
63664
63665 /*
63666 ** Scan through the expression pExpr.  Replace every reference to
63667 ** a column in table number iTable with a copy of the iColumn-th
63668 ** entry in pEList.  (But leave references to the ROWID column 
63669 ** unchanged.)
63670 **
63671 ** This routine is part of the flattening procedure.  A subquery
63672 ** whose result set is defined by pEList appears as entry in the
63673 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
63674 ** FORM clause entry is iTable.  This routine make the necessary 
63675 ** changes to pExpr so that it refers directly to the source table
63676 ** of the subquery rather the result set of the subquery.
63677 */
63678 static void substExpr(
63679   sqlite3 *db,        /* Report malloc errors to this connection */
63680   Expr *pExpr,        /* Expr in which substitution occurs */
63681   int iTable,         /* Table to be substituted */
63682   ExprList *pEList    /* Substitute expressions */
63683 ){
63684   if( pExpr==0 ) return;
63685   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
63686     if( pExpr->iColumn<0 ){
63687       pExpr->op = TK_NULL;
63688     }else{
63689       Expr *pNew;
63690       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
63691       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
63692       pNew = pEList->a[pExpr->iColumn].pExpr;
63693       assert( pNew!=0 );
63694       pExpr->op = pNew->op;
63695       assert( pExpr->pLeft==0 );
63696       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
63697       assert( pExpr->pRight==0 );
63698       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
63699       assert( pExpr->pList==0 );
63700       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
63701       pExpr->iTable = pNew->iTable;
63702       pExpr->pTab = pNew->pTab;
63703       pExpr->iColumn = pNew->iColumn;
63704       pExpr->iAgg = pNew->iAgg;
63705       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
63706       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
63707       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
63708       pExpr->flags = pNew->flags;
63709     }
63710   }else{
63711     substExpr(db, pExpr->pLeft, iTable, pEList);
63712     substExpr(db, pExpr->pRight, iTable, pEList);
63713     substSelect(db, pExpr->pSelect, iTable, pEList);
63714     substExprList(db, pExpr->pList, iTable, pEList);
63715   }
63716 }
63717 static void substExprList(
63718   sqlite3 *db,         /* Report malloc errors here */
63719   ExprList *pList,     /* List to scan and in which to make substitutes */
63720   int iTable,          /* Table to be substituted */
63721   ExprList *pEList     /* Substitute values */
63722 ){
63723   int i;
63724   if( pList==0 ) return;
63725   for(i=0; i<pList->nExpr; i++){
63726     substExpr(db, pList->a[i].pExpr, iTable, pEList);
63727   }
63728 }
63729 static void substSelect(
63730   sqlite3 *db,         /* Report malloc errors here */
63731   Select *p,           /* SELECT statement in which to make substitutions */
63732   int iTable,          /* Table to be replaced */
63733   ExprList *pEList     /* Substitute values */
63734 ){
63735   if( !p ) return;
63736   substExprList(db, p->pEList, iTable, pEList);
63737   substExprList(db, p->pGroupBy, iTable, pEList);
63738   substExprList(db, p->pOrderBy, iTable, pEList);
63739   substExpr(db, p->pHaving, iTable, pEList);
63740   substExpr(db, p->pWhere, iTable, pEList);
63741   substSelect(db, p->pPrior, iTable, pEList);
63742 }
63743 #endif /* !defined(SQLITE_OMIT_VIEW) */
63744
63745 #ifndef SQLITE_OMIT_VIEW
63746 /*
63747 ** This routine attempts to flatten subqueries in order to speed
63748 ** execution.  It returns 1 if it makes changes and 0 if no flattening
63749 ** occurs.
63750 **
63751 ** To understand the concept of flattening, consider the following
63752 ** query:
63753 **
63754 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
63755 **
63756 ** The default way of implementing this query is to execute the
63757 ** subquery first and store the results in a temporary table, then
63758 ** run the outer query on that temporary table.  This requires two
63759 ** passes over the data.  Furthermore, because the temporary table
63760 ** has no indices, the WHERE clause on the outer query cannot be
63761 ** optimized.
63762 **
63763 ** This routine attempts to rewrite queries such as the above into
63764 ** a single flat select, like this:
63765 **
63766 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
63767 **
63768 ** The code generated for this simpification gives the same result
63769 ** but only has to scan the data once.  And because indices might 
63770 ** exist on the table t1, a complete scan of the data might be
63771 ** avoided.
63772 **
63773 ** Flattening is only attempted if all of the following are true:
63774 **
63775 **   (1)  The subquery and the outer query do not both use aggregates.
63776 **
63777 **   (2)  The subquery is not an aggregate or the outer query is not a join.
63778 **
63779 **   (3)  The subquery is not the right operand of a left outer join, or
63780 **        the subquery is not itself a join.  (Ticket #306)
63781 **
63782 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
63783 **
63784 **   (5)  The subquery is not DISTINCT or the outer query does not use
63785 **        aggregates.
63786 **
63787 **   (6)  The subquery does not use aggregates or the outer query is not
63788 **        DISTINCT.
63789 **
63790 **   (7)  The subquery has a FROM clause.
63791 **
63792 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
63793 **
63794 **   (9)  The subquery does not use LIMIT or the outer query does not use
63795 **        aggregates.
63796 **
63797 **  (10)  The subquery does not use aggregates or the outer query does not
63798 **        use LIMIT.
63799 **
63800 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
63801 **
63802 **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
63803 **        subquery has no WHERE clause.  (added by ticket #350)
63804 **
63805 **  (13)  The subquery and outer query do not both use LIMIT
63806 **
63807 **  (14)  The subquery does not use OFFSET
63808 **
63809 **  (15)  The outer query is not part of a compound select or the
63810 **        subquery does not have both an ORDER BY and a LIMIT clause.
63811 **        (See ticket #2339)
63812 **
63813 **  (16)  The outer query is not an aggregate or the subquery does
63814 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
63815 **        until we introduced the group_concat() function.  
63816 **
63817 ** In this routine, the "p" parameter is a pointer to the outer query.
63818 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
63819 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
63820 **
63821 ** If flattening is not attempted, this routine is a no-op and returns 0.
63822 ** If flattening is attempted this routine returns 1.
63823 **
63824 ** All of the expression analysis must occur on both the outer query and
63825 ** the subquery before this routine runs.
63826 */
63827 static int flattenSubquery(
63828   sqlite3 *db,         /* Database connection */
63829   Select *p,           /* The parent or outer SELECT statement */
63830   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
63831   int isAgg,           /* True if outer SELECT uses aggregate functions */
63832   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
63833 ){
63834   Select *pSub;       /* The inner query or "subquery" */
63835   SrcList *pSrc;      /* The FROM clause of the outer query */
63836   SrcList *pSubSrc;   /* The FROM clause of the subquery */
63837   ExprList *pList;    /* The result set of the outer query */
63838   int iParent;        /* VDBE cursor number of the pSub result set temp table */
63839   int i;              /* Loop counter */
63840   Expr *pWhere;                    /* The WHERE clause */
63841   struct SrcList_item *pSubitem;   /* The subquery */
63842
63843   /* Check to see if flattening is permitted.  Return 0 if not.
63844   */
63845   if( p==0 ) return 0;
63846   pSrc = p->pSrc;
63847   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
63848   pSubitem = &pSrc->a[iFrom];
63849   pSub = pSubitem->pSelect;
63850   assert( pSub!=0 );
63851   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
63852   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
63853   pSubSrc = pSub->pSrc;
63854   assert( pSubSrc );
63855   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
63856   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
63857   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
63858   ** became arbitrary expressions, we were forced to add restrictions (13)
63859   ** and (14). */
63860   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
63861   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
63862   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
63863     return 0;                                            /* Restriction (15) */
63864   }
63865   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
63866   if( (pSub->isDistinct || pSub->pLimit) 
63867          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
63868      return 0;       
63869   }
63870   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
63871   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
63872      return 0;                                           /* Restriction (11) */
63873   }
63874   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
63875
63876   /* Restriction 3:  If the subquery is a join, make sure the subquery is 
63877   ** not used as the right operand of an outer join.  Examples of why this
63878   ** is not allowed:
63879   **
63880   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
63881   **
63882   ** If we flatten the above, we would get
63883   **
63884   **         (t1 LEFT OUTER JOIN t2) JOIN t3
63885   **
63886   ** which is not at all the same thing.
63887   */
63888   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
63889     return 0;
63890   }
63891
63892   /* Restriction 12:  If the subquery is the right operand of a left outer
63893   ** join, make sure the subquery has no WHERE clause.
63894   ** An examples of why this is not allowed:
63895   **
63896   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
63897   **
63898   ** If we flatten the above, we would get
63899   **
63900   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
63901   **
63902   ** But the t2.x>0 test will always fail on a NULL row of t2, which
63903   ** effectively converts the OUTER JOIN into an INNER JOIN.
63904   */
63905   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
63906     return 0;
63907   }
63908
63909   /* If we reach this point, it means flattening is permitted for the
63910   ** iFrom-th entry of the FROM clause in the outer query.
63911   */
63912
63913   /* Move all of the FROM elements of the subquery into the
63914   ** the FROM clause of the outer query.  Before doing this, remember
63915   ** the cursor number for the original outer query FROM element in
63916   ** iParent.  The iParent cursor will never be used.  Subsequent code
63917   ** will scan expressions looking for iParent references and replace
63918   ** those references with expressions that resolve to the subquery FROM
63919   ** elements we are now copying in.
63920   */
63921   iParent = pSubitem->iCursor;
63922   {
63923     int nSubSrc = pSubSrc->nSrc;
63924     int jointype = pSubitem->jointype;
63925
63926     sqlite3DeleteTable(pSubitem->pTab);
63927     sqlite3_free(pSubitem->zDatabase);
63928     sqlite3_free(pSubitem->zName);
63929     sqlite3_free(pSubitem->zAlias);
63930     pSubitem->pTab = 0;
63931     pSubitem->zDatabase = 0;
63932     pSubitem->zName = 0;
63933     pSubitem->zAlias = 0;
63934     if( nSubSrc>1 ){
63935       int extra = nSubSrc - 1;
63936       for(i=1; i<nSubSrc; i++){
63937         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
63938         if( pSrc==0 ){
63939           p->pSrc = 0;
63940           return 1;
63941         }
63942       }
63943       p->pSrc = pSrc;
63944       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
63945         pSrc->a[i] = pSrc->a[i-extra];
63946       }
63947     }
63948     for(i=0; i<nSubSrc; i++){
63949       pSrc->a[i+iFrom] = pSubSrc->a[i];
63950       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
63951     }
63952     pSrc->a[iFrom].jointype = jointype;
63953   }
63954
63955   /* Now begin substituting subquery result set expressions for 
63956   ** references to the iParent in the outer query.
63957   ** 
63958   ** Example:
63959   **
63960   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
63961   **   \                     \_____________ subquery __________/          /
63962   **    \_____________________ outer query ______________________________/
63963   **
63964   ** We look at every expression in the outer query and every place we see
63965   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
63966   */
63967   pList = p->pEList;
63968   for(i=0; i<pList->nExpr; i++){
63969     Expr *pExpr;
63970     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
63971       pList->a[i].zName = 
63972              sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
63973     }
63974   }
63975   substExprList(db, p->pEList, iParent, pSub->pEList);
63976   if( isAgg ){
63977     substExprList(db, p->pGroupBy, iParent, pSub->pEList);
63978     substExpr(db, p->pHaving, iParent, pSub->pEList);
63979   }
63980   if( pSub->pOrderBy ){
63981     assert( p->pOrderBy==0 );
63982     p->pOrderBy = pSub->pOrderBy;
63983     pSub->pOrderBy = 0;
63984   }else if( p->pOrderBy ){
63985     substExprList(db, p->pOrderBy, iParent, pSub->pEList);
63986   }
63987   if( pSub->pWhere ){
63988     pWhere = sqlite3ExprDup(db, pSub->pWhere);
63989   }else{
63990     pWhere = 0;
63991   }
63992   if( subqueryIsAgg ){
63993     assert( p->pHaving==0 );
63994     p->pHaving = p->pWhere;
63995     p->pWhere = pWhere;
63996     substExpr(db, p->pHaving, iParent, pSub->pEList);
63997     p->pHaving = sqlite3ExprAnd(db, p->pHaving, 
63998                                 sqlite3ExprDup(db, pSub->pHaving));
63999     assert( p->pGroupBy==0 );
64000     p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
64001   }else{
64002     substExpr(db, p->pWhere, iParent, pSub->pEList);
64003     p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
64004   }
64005
64006   /* The flattened query is distinct if either the inner or the
64007   ** outer query is distinct. 
64008   */
64009   p->isDistinct = p->isDistinct || pSub->isDistinct;
64010
64011   /*
64012   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
64013   **
64014   ** One is tempted to try to add a and b to combine the limits.  But this
64015   ** does not work if either limit is negative.
64016   */
64017   if( pSub->pLimit ){
64018     p->pLimit = pSub->pLimit;
64019     pSub->pLimit = 0;
64020   }
64021
64022   /* Finially, delete what is left of the subquery and return
64023   ** success.
64024   */
64025   sqlite3SelectDelete(pSub);
64026   return 1;
64027 }
64028 #endif /* SQLITE_OMIT_VIEW */
64029
64030 /*
64031 ** Analyze the SELECT statement passed as an argument to see if it
64032 ** is a min() or max() query. Return ORDERBY_MIN or ORDERBY_MAX if 
64033 ** it is, or 0 otherwise. At present, a query is considered to be
64034 ** a min()/max() query if:
64035 **
64036 **   1. There is a single object in the FROM clause.
64037 **
64038 **   2. There is a single expression in the result set, and it is
64039 **      either min(x) or max(x), where x is a column reference.
64040 */
64041 static int minMaxQuery(Parse *pParse, Select *p){
64042   Expr *pExpr;
64043   ExprList *pEList = p->pEList;
64044
64045   if( pEList->nExpr!=1 ) return ORDERBY_NORMAL;
64046   pExpr = pEList->a[0].pExpr;
64047   pEList = pExpr->pList;
64048   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
64049   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return ORDERBY_NORMAL;
64050   if( pExpr->token.n!=3 ) return ORDERBY_NORMAL;
64051   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
64052     return ORDERBY_MIN;
64053   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
64054     return ORDERBY_MAX;
64055   }
64056   return ORDERBY_NORMAL;
64057 }
64058
64059 /*
64060 ** This routine resolves any names used in the result set of the
64061 ** supplied SELECT statement. If the SELECT statement being resolved
64062 ** is a sub-select, then pOuterNC is a pointer to the NameContext 
64063 ** of the parent SELECT.
64064 */
64065 SQLITE_PRIVATE int sqlite3SelectResolve(
64066   Parse *pParse,         /* The parser context */
64067   Select *p,             /* The SELECT statement being coded. */
64068   NameContext *pOuterNC  /* The outer name context. May be NULL. */
64069 ){
64070   ExprList *pEList;          /* Result set. */
64071   int i;                     /* For-loop variable used in multiple places */
64072   NameContext sNC;           /* Local name-context */
64073   ExprList *pGroupBy;        /* The group by clause */
64074
64075   /* If this routine has run before, return immediately. */
64076   if( p->isResolved ){
64077     assert( !pOuterNC );
64078     return SQLITE_OK;
64079   }
64080   p->isResolved = 1;
64081
64082   /* If there have already been errors, do nothing. */
64083   if( pParse->nErr>0 ){
64084     return SQLITE_ERROR;
64085   }
64086
64087   /* Prepare the select statement. This call will allocate all cursors
64088   ** required to handle the tables and subqueries in the FROM clause.
64089   */
64090   if( prepSelectStmt(pParse, p) ){
64091     return SQLITE_ERROR;
64092   }
64093
64094   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
64095   ** are not allowed to refer to any names, so pass an empty NameContext.
64096   */
64097   memset(&sNC, 0, sizeof(sNC));
64098   sNC.pParse = pParse;
64099   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
64100       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
64101     return SQLITE_ERROR;
64102   }
64103
64104   /* Set up the local name-context to pass to ExprResolveNames() to
64105   ** resolve the expression-list.
64106   */
64107   sNC.allowAgg = 1;
64108   sNC.pSrcList = p->pSrc;
64109   sNC.pNext = pOuterNC;
64110
64111   /* Resolve names in the result set. */
64112   pEList = p->pEList;
64113   if( !pEList ) return SQLITE_ERROR;
64114   for(i=0; i<pEList->nExpr; i++){
64115     Expr *pX = pEList->a[i].pExpr;
64116     if( sqlite3ExprResolveNames(&sNC, pX) ){
64117       return SQLITE_ERROR;
64118     }
64119   }
64120
64121   /* If there are no aggregate functions in the result-set, and no GROUP BY 
64122   ** expression, do not allow aggregates in any of the other expressions.
64123   */
64124   assert( !p->isAgg );
64125   pGroupBy = p->pGroupBy;
64126   if( pGroupBy || sNC.hasAgg ){
64127     p->isAgg = 1;
64128   }else{
64129     sNC.allowAgg = 0;
64130   }
64131
64132   /* If a HAVING clause is present, then there must be a GROUP BY clause.
64133   */
64134   if( p->pHaving && !pGroupBy ){
64135     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
64136     return SQLITE_ERROR;
64137   }
64138
64139   /* Add the expression list to the name-context before parsing the
64140   ** other expressions in the SELECT statement. This is so that
64141   ** expressions in the WHERE clause (etc.) can refer to expressions by
64142   ** aliases in the result set.
64143   **
64144   ** Minor point: If this is the case, then the expression will be
64145   ** re-evaluated for each reference to it.
64146   */
64147   sNC.pEList = p->pEList;
64148   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
64149      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
64150     return SQLITE_ERROR;
64151   }
64152   if( p->pPrior==0 ){
64153     if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
64154       return SQLITE_ERROR;
64155     }
64156   }
64157   if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
64158     return SQLITE_ERROR;
64159   }
64160
64161   if( pParse->db->mallocFailed ){
64162     return SQLITE_NOMEM;
64163   }
64164
64165   /* Make sure the GROUP BY clause does not contain aggregate functions.
64166   */
64167   if( pGroupBy ){
64168     struct ExprList_item *pItem;
64169   
64170     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
64171       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
64172         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
64173             "the GROUP BY clause");
64174         return SQLITE_ERROR;
64175       }
64176     }
64177   }
64178
64179   /* If this is one SELECT of a compound, be sure to resolve names
64180   ** in the other SELECTs.
64181   */
64182   if( p->pPrior ){
64183     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
64184   }else{
64185     return SQLITE_OK;
64186   }
64187 }
64188
64189 /*
64190 ** Reset the aggregate accumulator.
64191 **
64192 ** The aggregate accumulator is a set of memory cells that hold
64193 ** intermediate results while calculating an aggregate.  This
64194 ** routine simply stores NULLs in all of those memory cells.
64195 */
64196 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
64197   Vdbe *v = pParse->pVdbe;
64198   int i;
64199   struct AggInfo_func *pFunc;
64200   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
64201     return;
64202   }
64203   for(i=0; i<pAggInfo->nColumn; i++){
64204     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
64205   }
64206   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
64207     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
64208     if( pFunc->iDistinct>=0 ){
64209       Expr *pE = pFunc->pExpr;
64210       if( pE->pList==0 || pE->pList->nExpr!=1 ){
64211         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
64212            "by an expression");
64213         pFunc->iDistinct = -1;
64214       }else{
64215         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
64216         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
64217                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
64218       }
64219     }
64220   }
64221 }
64222
64223 /*
64224 ** Invoke the OP_AggFinalize opcode for every aggregate function
64225 ** in the AggInfo structure.
64226 */
64227 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
64228   Vdbe *v = pParse->pVdbe;
64229   int i;
64230   struct AggInfo_func *pF;
64231   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
64232     ExprList *pList = pF->pExpr->pList;
64233     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
64234                       (void*)pF->pFunc, P4_FUNCDEF);
64235   }
64236 }
64237
64238 /*
64239 ** Update the accumulator memory cells for an aggregate based on
64240 ** the current cursor position.
64241 */
64242 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
64243   Vdbe *v = pParse->pVdbe;
64244   int i;
64245   struct AggInfo_func *pF;
64246   struct AggInfo_col *pC;
64247
64248   pAggInfo->directMode = 1;
64249   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
64250     int nArg;
64251     int addrNext = 0;
64252     int regAgg;
64253     ExprList *pList = pF->pExpr->pList;
64254     if( pList ){
64255       nArg = pList->nExpr;
64256       regAgg = sqlite3GetTempRange(pParse, nArg);
64257       sqlite3ExprCodeExprList(pParse, pList, regAgg);
64258     }else{
64259       nArg = 0;
64260       regAgg = 0;
64261     }
64262     if( pF->iDistinct>=0 ){
64263       addrNext = sqlite3VdbeMakeLabel(v);
64264       assert( nArg==1 );
64265       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
64266     }
64267     if( pF->pFunc->needCollSeq ){
64268       CollSeq *pColl = 0;
64269       struct ExprList_item *pItem;
64270       int j;
64271       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
64272       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
64273         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
64274       }
64275       if( !pColl ){
64276         pColl = pParse->db->pDfltColl;
64277       }
64278       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
64279     }
64280     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
64281                       (void*)pF->pFunc, P4_FUNCDEF);
64282     sqlite3VdbeChangeP5(v, nArg);
64283     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
64284     if( addrNext ){
64285       sqlite3VdbeResolveLabel(v, addrNext);
64286     }
64287   }
64288   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
64289     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
64290   }
64291   pAggInfo->directMode = 0;
64292 }
64293
64294 #ifndef SQLITE_OMIT_TRIGGER
64295 /*
64296 ** This function is used when a SELECT statement is used to create a
64297 ** temporary table for iterating through when running an INSTEAD OF
64298 ** UPDATE or INSTEAD OF DELETE trigger. 
64299 **
64300 ** If possible, the SELECT statement is modified so that NULL values
64301 ** are stored in the temporary table for all columns for which the 
64302 ** corresponding bit in argument mask is not set. If mask takes the
64303 ** special value 0xffffffff, then all columns are populated.
64304 */
64305 SQLITE_PRIVATE void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){
64306   if( p && !p->pPrior && !p->isDistinct && mask!=0xffffffff ){
64307     ExprList *pEList;
64308     int i;
64309     sqlite3SelectResolve(pParse, p, 0);
64310     pEList = p->pEList;
64311     for(i=0; pEList && i<pEList->nExpr && i<32; i++){
64312       if( !(mask&((u32)1<<i)) ){
64313         sqlite3ExprDelete(pEList->a[i].pExpr);
64314         pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0);
64315       }
64316     }
64317   }
64318 }
64319 #endif
64320
64321 /*
64322 ** Generate code for the given SELECT statement.
64323 **
64324 ** The results are distributed in various ways depending on the
64325 ** contents of the SelectDest structure pointed to by argument pDest
64326 ** as follows:
64327 **
64328 **     pDest->eDest    Result
64329 **     ------------    -------------------------------------------
64330 **     SRT_Callback    Invoke the callback for each row of the result.
64331 **
64332 **     SRT_Mem         Store first result in memory cell pDest->iParm
64333 **
64334 **     SRT_Set         Store non-null results as keys of table pDest->iParm. 
64335 **                     Apply the affinity pDest->affinity before storing them.
64336 **
64337 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
64338 **
64339 **     SRT_Except      Remove results from the temporary table pDest->iParm.
64340 **
64341 **     SRT_Table       Store results in temporary table pDest->iParm
64342 **
64343 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
64344 **                     the result there. The cursor is left open after
64345 **                     returning.
64346 **
64347 **     SRT_Subroutine  For each row returned, push the results onto the
64348 **                     vdbe stack and call the subroutine (via OP_Gosub)
64349 **                     at address pDest->iParm.
64350 **
64351 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
64352 **                     set is not empty.
64353 **
64354 **     SRT_Discard     Throw the results away.
64355 **
64356 ** See the selectInnerLoop() function for a canonical listing of the 
64357 ** allowed values of eDest and their meanings.
64358 **
64359 ** This routine returns the number of errors.  If any errors are
64360 ** encountered, then an appropriate error message is left in
64361 ** pParse->zErrMsg.
64362 **
64363 ** This routine does NOT free the Select structure passed in.  The
64364 ** calling function needs to do that.
64365 **
64366 ** The pParent, parentTab, and *pParentAgg fields are filled in if this
64367 ** SELECT is a subquery.  This routine may try to combine this SELECT
64368 ** with its parent to form a single flat query.  In so doing, it might
64369 ** change the parent query from a non-aggregate to an aggregate query.
64370 ** For that reason, the pParentAgg flag is passed as a pointer, so it
64371 ** can be changed.
64372 **
64373 ** Example 1:   The meaning of the pParent parameter.
64374 **
64375 **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
64376 **    \                      \_______ subquery _______/        /
64377 **     \                                                      /
64378 **      \____________________ outer query ___________________/
64379 **
64380 ** This routine is called for the outer query first.   For that call,
64381 ** pParent will be NULL.  During the processing of the outer query, this 
64382 ** routine is called recursively to handle the subquery.  For the recursive
64383 ** call, pParent will point to the outer query.  Because the subquery is
64384 ** the second element in a three-way join, the parentTab parameter will
64385 ** be 1 (the 2nd value of a 0-indexed array.)
64386 */
64387 SQLITE_PRIVATE int sqlite3Select(
64388   Parse *pParse,         /* The parser context */
64389   Select *p,             /* The SELECT statement being coded. */
64390   SelectDest *pDest,     /* What to do with the query results */
64391   Select *pParent,       /* Another SELECT for which this is a sub-query */
64392   int parentTab,         /* Index in pParent->pSrc of this query */
64393   int *pParentAgg,       /* True if pParent uses aggregate functions */
64394   char *aff              /* If eDest is SRT_Union, the affinity string */
64395 ){
64396   int i, j;              /* Loop counters */
64397   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
64398   Vdbe *v;               /* The virtual machine under construction */
64399   int isAgg;             /* True for select lists like "count(*)" */
64400   ExprList *pEList;      /* List of columns to extract. */
64401   SrcList *pTabList;     /* List of tables to select from */
64402   Expr *pWhere;          /* The WHERE clause.  May be NULL */
64403   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
64404   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
64405   Expr *pHaving;         /* The HAVING clause.  May be NULL */
64406   int isDistinct;        /* True if the DISTINCT keyword is present */
64407   int distinct;          /* Table to use for the distinct set */
64408   int rc = 1;            /* Value to return from this function */
64409   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
64410   AggInfo sAggInfo;      /* Information used by aggregate queries */
64411   int iEnd;              /* Address of the end of the query */
64412   sqlite3 *db;           /* The database connection */
64413
64414   db = pParse->db;
64415   if( p==0 || db->mallocFailed || pParse->nErr ){
64416     return 1;
64417   }
64418   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
64419   memset(&sAggInfo, 0, sizeof(sAggInfo));
64420
64421   pOrderBy = p->pOrderBy;
64422   if( IgnorableOrderby(pDest) ){
64423     p->pOrderBy = 0;
64424
64425     /* In these cases the DISTINCT operator makes no difference to the
64426     ** results, so remove it if it were specified.
64427     */
64428     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
64429            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
64430     p->isDistinct = 0;
64431   }
64432   if( sqlite3SelectResolve(pParse, p, 0) ){
64433     goto select_end;
64434   }
64435   p->pOrderBy = pOrderBy;
64436
64437 #ifndef SQLITE_OMIT_COMPOUND_SELECT
64438   /* If there is are a sequence of queries, do the earlier ones first.
64439   */
64440   if( p->pPrior ){
64441     if( p->pRightmost==0 ){
64442       Select *pLoop, *pRight = 0;
64443       int cnt = 0;
64444       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
64445         pLoop->pRightmost = p;
64446         pLoop->pNext = pRight;
64447         pRight = pLoop;
64448       }
64449       if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
64450         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
64451         return 1;
64452       }
64453     }
64454     return multiSelect(pParse, p, pDest, aff);
64455   }
64456 #endif
64457
64458   /* Make local copies of the parameters for this query.
64459   */
64460   pTabList = p->pSrc;
64461   pWhere = p->pWhere;
64462   pGroupBy = p->pGroupBy;
64463   pHaving = p->pHaving;
64464   isAgg = p->isAgg;
64465   isDistinct = p->isDistinct;
64466   pEList = p->pEList;
64467   if( pEList==0 ) goto select_end;
64468
64469   /* 
64470   ** Do not even attempt to generate any code if we have already seen
64471   ** errors before this routine starts.
64472   */
64473   if( pParse->nErr>0 ) goto select_end;
64474
64475   /* If writing to memory or generating a set
64476   ** only a single column may be output.
64477   */
64478 #ifndef SQLITE_OMIT_SUBQUERY
64479   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
64480     goto select_end;
64481   }
64482 #endif
64483
64484   /* ORDER BY is ignored for some destinations.
64485   */
64486   if( IgnorableOrderby(pDest) ){
64487     pOrderBy = 0;
64488   }
64489
64490   /* Begin generating code.
64491   */
64492   v = sqlite3GetVdbe(pParse);
64493   if( v==0 ) goto select_end;
64494
64495   /* Generate code for all sub-queries in the FROM clause
64496   */
64497 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
64498   for(i=0; i<pTabList->nSrc; i++){
64499     const char *zSavedAuthContext = 0;
64500     int needRestoreContext;
64501     struct SrcList_item *pItem = &pTabList->a[i];
64502     SelectDest dest;
64503
64504     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
64505     if( pItem->zName!=0 ){
64506       zSavedAuthContext = pParse->zAuthContext;
64507       pParse->zAuthContext = pItem->zName;
64508       needRestoreContext = 1;
64509     }else{
64510       needRestoreContext = 0;
64511     }
64512 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
64513     /* Increment Parse.nHeight by the height of the largest expression
64514     ** tree refered to by this, the parent select. The child select
64515     ** may contain expression trees of at most
64516     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
64517     ** more conservative than necessary, but much easier than enforcing
64518     ** an exact limit.
64519     */
64520     pParse->nHeight += sqlite3SelectExprHeight(p);
64521 #endif
64522     sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
64523     sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0);
64524     if( db->mallocFailed ){
64525       goto select_end;
64526     }
64527 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
64528     pParse->nHeight -= sqlite3SelectExprHeight(p);
64529 #endif
64530     if( needRestoreContext ){
64531       pParse->zAuthContext = zSavedAuthContext;
64532     }
64533     pTabList = p->pSrc;
64534     pWhere = p->pWhere;
64535     if( !IgnorableOrderby(pDest) ){
64536       pOrderBy = p->pOrderBy;
64537     }
64538     pGroupBy = p->pGroupBy;
64539     pHaving = p->pHaving;
64540     isDistinct = p->isDistinct;
64541   }
64542 #endif
64543
64544   /* Check to see if this is a subquery that can be "flattened" into its parent.
64545   ** If flattening is a possiblity, do so and return immediately.  
64546   */
64547 #ifndef SQLITE_OMIT_VIEW
64548   if( pParent && pParentAgg &&
64549       flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
64550     if( isAgg ) *pParentAgg = 1;
64551     goto select_end;
64552   }
64553 #endif
64554
64555   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
64556   ** GROUP BY may use an index, DISTINCT never does.
64557   */
64558   if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
64559     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
64560     pGroupBy = p->pGroupBy;
64561     p->isDistinct = 0;
64562     isDistinct = 0;
64563   }
64564
64565   /* If there is an ORDER BY clause, then this sorting
64566   ** index might end up being unused if the data can be 
64567   ** extracted in pre-sorted order.  If that is the case, then the
64568   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
64569   ** we figure out that the sorting index is not needed.  The addrSortIndex
64570   ** variable is used to facilitate that change.
64571   */
64572   if( pOrderBy ){
64573     KeyInfo *pKeyInfo;
64574     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
64575     pOrderBy->iECursor = pParse->nTab++;
64576     p->addrOpenEphm[2] = addrSortIndex =
64577       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
64578                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
64579                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
64580   }else{
64581     addrSortIndex = -1;
64582   }
64583
64584   /* If the output is destined for a temporary table, open that table.
64585   */
64586   if( pDest->eDest==SRT_EphemTab ){
64587     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
64588   }
64589
64590   /* Set the limiter.
64591   */
64592   iEnd = sqlite3VdbeMakeLabel(v);
64593   computeLimitRegisters(pParse, p, iEnd);
64594
64595   /* Open a virtual index to use for the distinct set.
64596   */
64597   if( isDistinct ){
64598     KeyInfo *pKeyInfo;
64599     assert( isAgg || pGroupBy );
64600     distinct = pParse->nTab++;
64601     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
64602     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
64603                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
64604   }else{
64605     distinct = -1;
64606   }
64607
64608   /* Aggregate and non-aggregate queries are handled differently */
64609   if( !isAgg && pGroupBy==0 ){
64610     /* This case is for non-aggregate queries
64611     ** Begin the database scan
64612     */
64613     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
64614     if( pWInfo==0 ) goto select_end;
64615
64616     /* If sorting index that was created by a prior OP_OpenEphemeral 
64617     ** instruction ended up not being needed, then change the OP_OpenEphemeral
64618     ** into an OP_Noop.
64619     */
64620     if( addrSortIndex>=0 && pOrderBy==0 ){
64621       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
64622       p->addrOpenEphm[2] = -1;
64623     }
64624
64625     /* Use the standard inner loop
64626     */
64627     assert(!isDistinct);
64628     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
64629                     pWInfo->iContinue, pWInfo->iBreak, aff);
64630
64631     /* End the database scan loop.
64632     */
64633     sqlite3WhereEnd(pWInfo);
64634   }else{
64635     /* This is the processing for aggregate queries */
64636     NameContext sNC;    /* Name context for processing aggregate information */
64637     int iAMem;          /* First Mem address for storing current GROUP BY */
64638     int iBMem;          /* First Mem address for previous GROUP BY */
64639     int iUseFlag;       /* Mem address holding flag indicating that at least
64640                         ** one row of the input to the aggregator has been
64641                         ** processed */
64642     int iAbortFlag;     /* Mem address which causes query abort if positive */
64643     int groupBySort;    /* Rows come from source in GROUP BY order */
64644
64645
64646     /* The following variables hold addresses or labels for parts of the
64647     ** virtual machine program we are putting together */
64648     int addrOutputRow;      /* Start of subroutine that outputs a result row */
64649     int addrSetAbort;       /* Set the abort flag and return */
64650     int addrInitializeLoop; /* Start of code that initializes the input loop */
64651     int addrTopOfLoop;      /* Top of the input loop */
64652     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
64653     int addrProcessRow;     /* Code to process a single input row */
64654     int addrEnd;            /* End of all processing */
64655     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
64656     int addrReset;          /* Subroutine for resetting the accumulator */
64657
64658     addrEnd = sqlite3VdbeMakeLabel(v);
64659
64660     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
64661     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
64662     ** SELECT statement.
64663     */
64664     memset(&sNC, 0, sizeof(sNC));
64665     sNC.pParse = pParse;
64666     sNC.pSrcList = pTabList;
64667     sNC.pAggInfo = &sAggInfo;
64668     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
64669     sAggInfo.pGroupBy = pGroupBy;
64670     sqlite3ExprAnalyzeAggList(&sNC, pEList);
64671     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
64672     if( pHaving ){
64673       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
64674     }
64675     sAggInfo.nAccumulator = sAggInfo.nColumn;
64676     for(i=0; i<sAggInfo.nFunc; i++){
64677       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
64678     }
64679     if( db->mallocFailed ) goto select_end;
64680
64681     /* Processing for aggregates with GROUP BY is very different and
64682     ** much more complex than aggregates without a GROUP BY.
64683     */
64684     if( pGroupBy ){
64685       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
64686
64687       /* Create labels that we will be needing
64688       */
64689      
64690       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
64691       addrGroupByChange = sqlite3VdbeMakeLabel(v);
64692       addrProcessRow = sqlite3VdbeMakeLabel(v);
64693
64694       /* If there is a GROUP BY clause we might need a sorting index to
64695       ** implement it.  Allocate that sorting index now.  If it turns out
64696       ** that we do not need it after all, the OpenEphemeral instruction
64697       ** will be converted into a Noop.  
64698       */
64699       sAggInfo.sortingIdx = pParse->nTab++;
64700       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
64701       addrSortingIdx =
64702           sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
64703                          sAggInfo.nSortingColumn, 0,
64704                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
64705
64706       /* Initialize memory locations used by GROUP BY aggregate processing
64707       */
64708       iUseFlag = ++pParse->nMem;
64709       iAbortFlag = ++pParse->nMem;
64710       iAMem = pParse->nMem + 1;
64711       pParse->nMem += pGroupBy->nExpr;
64712       iBMem = pParse->nMem + 1;
64713       pParse->nMem += pGroupBy->nExpr;
64714       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
64715       VdbeComment((v, "clear abort flag"));
64716       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
64717       VdbeComment((v, "indicate accumulator empty"));
64718       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop);
64719
64720       /* Generate a subroutine that outputs a single row of the result
64721       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
64722       ** is less than or equal to zero, the subroutine is a no-op.  If
64723       ** the processing calls for the query to abort, this subroutine
64724       ** increments the iAbortFlag memory location before returning in
64725       ** order to signal the caller to abort.
64726       */
64727       addrSetAbort = sqlite3VdbeCurrentAddr(v);
64728       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
64729       VdbeComment((v, "set abort flag"));
64730       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
64731       addrOutputRow = sqlite3VdbeCurrentAddr(v);
64732       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
64733       VdbeComment((v, "Groupby result generator entry point"));
64734       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
64735       finalizeAggFunctions(pParse, &sAggInfo);
64736       if( pHaving ){
64737         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
64738       }
64739       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
64740                       distinct, pDest,
64741                       addrOutputRow+1, addrSetAbort, aff);
64742       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
64743       VdbeComment((v, "end groupby result generator"));
64744
64745       /* Generate a subroutine that will reset the group-by accumulator
64746       */
64747       addrReset = sqlite3VdbeCurrentAddr(v);
64748       resetAccumulator(pParse, &sAggInfo);
64749       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
64750
64751       /* Begin a loop that will extract all source rows in GROUP BY order.
64752       ** This might involve two separate loops with an OP_Sort in between, or
64753       ** it might be a single loop that uses an index to extract information
64754       ** in the right order to begin with.
64755       */
64756       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
64757       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
64758       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
64759       if( pWInfo==0 ) goto select_end;
64760       if( pGroupBy==0 ){
64761         /* The optimizer is able to deliver rows in group by order so
64762         ** we do not have to sort.  The OP_OpenEphemeral table will be
64763         ** cancelled later because we still need to use the pKeyInfo
64764         */
64765         pGroupBy = p->pGroupBy;
64766         groupBySort = 0;
64767       }else{
64768         /* Rows are coming out in undetermined order.  We have to push
64769         ** each row into a sorting index, terminate the first loop,
64770         ** then loop over the sorting index in order to get the output
64771         ** in sorted order
64772         */
64773         int regBase;
64774         int regRecord;
64775         int nCol;
64776         int nGroupBy;
64777
64778         groupBySort = 1;
64779         nGroupBy = pGroupBy->nExpr;
64780         nCol = nGroupBy + 1;
64781         j = nGroupBy+1;
64782         for(i=0; i<sAggInfo.nColumn; i++){
64783           if( sAggInfo.aCol[i].iSorterColumn>=j ){
64784             nCol++;
64785             j++;
64786           }
64787         }
64788         regBase = sqlite3GetTempRange(pParse, nCol);
64789         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase);
64790         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
64791         j = nGroupBy+1;
64792         for(i=0; i<sAggInfo.nColumn; i++){
64793           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
64794           if( pCol->iSorterColumn>=j ){
64795             sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable,
64796                                      j + regBase);
64797             j++;
64798           }
64799         }
64800         regRecord = sqlite3GetTempReg(pParse);
64801         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
64802         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
64803         sqlite3ReleaseTempReg(pParse, regRecord);
64804         sqlite3ReleaseTempRange(pParse, regBase, nCol);
64805         sqlite3WhereEnd(pWInfo);
64806         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
64807         VdbeComment((v, "GROUP BY sort"));
64808         sAggInfo.useSortingIdx = 1;
64809       }
64810
64811       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
64812       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
64813       ** Then compare the current GROUP BY terms against the GROUP BY terms
64814       ** from the previous row currently stored in a0, a1, a2...
64815       */
64816       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
64817       for(j=0; j<pGroupBy->nExpr; j++){
64818         if( groupBySort ){
64819           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
64820         }else{
64821           sAggInfo.directMode = 1;
64822           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
64823         }
64824       }
64825       for(j=pGroupBy->nExpr-1; j>=0; j--){
64826         if( j==0 ){
64827           sqlite3VdbeAddOp3(v, OP_Eq, iAMem+j, addrProcessRow, iBMem+j);
64828         }else{
64829           sqlite3VdbeAddOp3(v, OP_Ne, iAMem+j, addrGroupByChange, iBMem+j);
64830         }
64831         sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ);
64832         sqlite3VdbeChangeP5(v, SQLITE_NULLEQUAL);
64833       }
64834
64835       /* Generate code that runs whenever the GROUP BY changes.
64836       ** Change in the GROUP BY are detected by the previous code
64837       ** block.  If there were no changes, this block is skipped.
64838       **
64839       ** This code copies current group by terms in b0,b1,b2,...
64840       ** over to a0,a1,a2.  It then calls the output subroutine
64841       ** and resets the aggregate accumulator registers in preparation
64842       ** for the next GROUP BY batch.
64843       */
64844       sqlite3VdbeResolveLabel(v, addrGroupByChange);
64845       for(j=0; j<pGroupBy->nExpr; j++){
64846         sqlite3VdbeAddOp2(v, OP_Move, iBMem+j, iAMem+j);
64847       }
64848       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
64849       VdbeComment((v, "output one row"));
64850       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
64851       VdbeComment((v, "check abort flag"));
64852       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
64853       VdbeComment((v, "reset accumulator"));
64854
64855       /* Update the aggregate accumulators based on the content of
64856       ** the current row
64857       */
64858       sqlite3VdbeResolveLabel(v, addrProcessRow);
64859       updateAccumulator(pParse, &sAggInfo);
64860       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
64861       VdbeComment((v, "indicate data in accumulator"));
64862
64863       /* End of the loop
64864       */
64865       if( groupBySort ){
64866         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
64867       }else{
64868         sqlite3WhereEnd(pWInfo);
64869         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
64870       }
64871
64872       /* Output the final row of result
64873       */
64874       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
64875       VdbeComment((v, "output final row"));
64876       
64877     } /* endif pGroupBy */
64878     else {
64879       ExprList *pMinMax = 0;
64880       ExprList *pDel = 0;
64881       u8 flag;
64882
64883       /* Check if the query is of one of the following forms:
64884       **
64885       **   SELECT min(x) FROM ...
64886       **   SELECT max(x) FROM ...
64887       **
64888       ** If it is, then ask the code in where.c to attempt to sort results
64889       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
64890       ** If where.c is able to produce results sorted in this order, then
64891       ** add vdbe code to break out of the processing loop after the 
64892       ** first iteration (since the first iteration of the loop is 
64893       ** guaranteed to operate on the row with the minimum or maximum 
64894       ** value of x, the only row required).
64895       **
64896       ** A special flag must be passed to sqlite3WhereBegin() to slightly
64897       ** modify behaviour as follows:
64898       **
64899       **   + If the query is a "SELECT min(x)", then the loop coded by
64900       **     where.c should not iterate over any values with a NULL value
64901       **     for x.
64902       **
64903       **   + The optimizer code in where.c (the thing that decides which
64904       **     index or indices to use) should place a different priority on 
64905       **     satisfying the 'ORDER BY' clause than it does in other cases.
64906       **     Refer to code and comments in where.c for details.
64907       */
64908       flag = minMaxQuery(pParse, p);
64909       if( flag ){
64910         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
64911         if( pMinMax && !db->mallocFailed ){
64912           pMinMax->a[0].sortOrder = ((flag==ORDERBY_MIN)?0:1);
64913           pMinMax->a[0].pExpr->op = TK_COLUMN;
64914         }
64915       }
64916
64917       /* This case runs if the aggregate has no GROUP BY clause.  The
64918       ** processing is much simpler since there is only a single row
64919       ** of output.
64920       */
64921       resetAccumulator(pParse, &sAggInfo);
64922       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
64923       if( pWInfo==0 ){
64924         sqlite3ExprListDelete(pDel);
64925         goto select_end;
64926       }
64927       updateAccumulator(pParse, &sAggInfo);
64928       if( !pMinMax && flag ){
64929         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
64930         VdbeComment((v, "%s() by index", (flag==ORDERBY_MIN?"min":"max")));
64931       }
64932       sqlite3WhereEnd(pWInfo);
64933       finalizeAggFunctions(pParse, &sAggInfo);
64934       pOrderBy = 0;
64935       if( pHaving ){
64936         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
64937       }
64938       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
64939                       pDest, addrEnd, addrEnd, aff);
64940
64941       sqlite3ExprListDelete(pDel);
64942     }
64943     sqlite3VdbeResolveLabel(v, addrEnd);
64944     
64945   } /* endif aggregate query */
64946
64947   /* If there is an ORDER BY clause, then we need to sort the results
64948   ** and send them to the callback one by one.
64949   */
64950   if( pOrderBy ){
64951     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
64952   }
64953
64954 #ifndef SQLITE_OMIT_SUBQUERY
64955   /* If this was a subquery, we have now converted the subquery into a
64956   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
64957   ** this subquery from being evaluated again and to force the use of
64958   ** the temporary table.
64959   */
64960   if( pParent ){
64961     assert( pParent->pSrc->nSrc>parentTab );
64962     assert( pParent->pSrc->a[parentTab].pSelect==p );
64963     pParent->pSrc->a[parentTab].isPopulated = 1;
64964   }
64965 #endif
64966
64967   /* Jump here to skip this query
64968   */
64969   sqlite3VdbeResolveLabel(v, iEnd);
64970
64971   /* The SELECT was successfully coded.   Set the return code to 0
64972   ** to indicate no errors.
64973   */
64974   rc = 0;
64975
64976   /* Control jumps to here if an error is encountered above, or upon
64977   ** successful coding of the SELECT.
64978   */
64979 select_end:
64980
64981   /* Identify column names if we will be using them in a callback.  This
64982   ** step is skipped if the output is going to some other destination.
64983   */
64984   if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){
64985     generateColumnNames(pParse, pTabList, pEList);
64986   }
64987
64988   sqlite3_free(sAggInfo.aCol);
64989   sqlite3_free(sAggInfo.aFunc);
64990   return rc;
64991 }
64992
64993 #if defined(SQLITE_DEBUG)
64994 /*
64995 *******************************************************************************
64996 ** The following code is used for testing and debugging only.  The code
64997 ** that follows does not appear in normal builds.
64998 **
64999 ** These routines are used to print out the content of all or part of a 
65000 ** parse structures such as Select or Expr.  Such printouts are useful
65001 ** for helping to understand what is happening inside the code generator
65002 ** during the execution of complex SELECT statements.
65003 **
65004 ** These routine are not called anywhere from within the normal
65005 ** code base.  Then are intended to be called from within the debugger
65006 ** or from temporary "printf" statements inserted for debugging.
65007 */
65008 static void sqlite3PrintExpr(Expr *p){
65009   if( p->token.z && p->token.n>0 ){
65010     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
65011   }else{
65012     sqlite3DebugPrintf("(%d", p->op);
65013   }
65014   if( p->pLeft ){
65015     sqlite3DebugPrintf(" ");
65016     sqlite3PrintExpr(p->pLeft);
65017   }
65018   if( p->pRight ){
65019     sqlite3DebugPrintf(" ");
65020     sqlite3PrintExpr(p->pRight);
65021   }
65022   sqlite3DebugPrintf(")");
65023 }
65024 static void sqlite3PrintExprList(ExprList *pList){
65025   int i;
65026   for(i=0; i<pList->nExpr; i++){
65027     sqlite3PrintExpr(pList->a[i].pExpr);
65028     if( i<pList->nExpr-1 ){
65029       sqlite3DebugPrintf(", ");
65030     }
65031   }
65032 }
65033 static void sqlite3PrintSelect(Select *p, int indent){
65034   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
65035   sqlite3PrintExprList(p->pEList);
65036   sqlite3DebugPrintf("\n");
65037   if( p->pSrc ){
65038     char *zPrefix;
65039     int i;
65040     zPrefix = "FROM";
65041     for(i=0; i<p->pSrc->nSrc; i++){
65042       struct SrcList_item *pItem = &p->pSrc->a[i];
65043       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
65044       zPrefix = "";
65045       if( pItem->pSelect ){
65046         sqlite3DebugPrintf("(\n");
65047         sqlite3PrintSelect(pItem->pSelect, indent+10);
65048         sqlite3DebugPrintf("%*s)", indent+8, "");
65049       }else if( pItem->zName ){
65050         sqlite3DebugPrintf("%s", pItem->zName);
65051       }
65052       if( pItem->pTab ){
65053         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
65054       }
65055       if( pItem->zAlias ){
65056         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
65057       }
65058       if( i<p->pSrc->nSrc-1 ){
65059         sqlite3DebugPrintf(",");
65060       }
65061       sqlite3DebugPrintf("\n");
65062     }
65063   }
65064   if( p->pWhere ){
65065     sqlite3DebugPrintf("%*s WHERE ", indent, "");
65066     sqlite3PrintExpr(p->pWhere);
65067     sqlite3DebugPrintf("\n");
65068   }
65069   if( p->pGroupBy ){
65070     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
65071     sqlite3PrintExprList(p->pGroupBy);
65072     sqlite3DebugPrintf("\n");
65073   }
65074   if( p->pHaving ){
65075     sqlite3DebugPrintf("%*s HAVING ", indent, "");
65076     sqlite3PrintExpr(p->pHaving);
65077     sqlite3DebugPrintf("\n");
65078   }
65079   if( p->pOrderBy ){
65080     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
65081     sqlite3PrintExprList(p->pOrderBy);
65082     sqlite3DebugPrintf("\n");
65083   }
65084 }
65085 /* End of the structure debug printing code
65086 *****************************************************************************/
65087 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
65088
65089 /************** End of select.c **********************************************/
65090 /************** Begin file table.c *******************************************/
65091 /*
65092 ** 2001 September 15
65093 **
65094 ** The author disclaims copyright to this source code.  In place of
65095 ** a legal notice, here is a blessing:
65096 **
65097 **    May you do good and not evil.
65098 **    May you find forgiveness for yourself and forgive others.
65099 **    May you share freely, never taking more than you give.
65100 **
65101 *************************************************************************
65102 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
65103 ** interface routines.  These are just wrappers around the main
65104 ** interface routine of sqlite3_exec().
65105 **
65106 ** These routines are in a separate files so that they will not be linked
65107 ** if they are not used.
65108 */
65109
65110 #ifndef SQLITE_OMIT_GET_TABLE
65111
65112 /*
65113 ** This structure is used to pass data from sqlite3_get_table() through
65114 ** to the callback function is uses to build the result.
65115 */
65116 typedef struct TabResult {
65117   char **azResult;
65118   char *zErrMsg;
65119   int nResult;
65120   int nAlloc;
65121   int nRow;
65122   int nColumn;
65123   int nData;
65124   int rc;
65125 } TabResult;
65126
65127 /*
65128 ** This routine is called once for each row in the result table.  Its job
65129 ** is to fill in the TabResult structure appropriately, allocating new
65130 ** memory as necessary.
65131 */
65132 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
65133   TabResult *p = (TabResult*)pArg;
65134   int need;
65135   int i;
65136   char *z;
65137
65138   /* Make sure there is enough space in p->azResult to hold everything
65139   ** we need to remember from this invocation of the callback.
65140   */
65141   if( p->nRow==0 && argv!=0 ){
65142     need = nCol*2;
65143   }else{
65144     need = nCol;
65145   }
65146   if( p->nData + need >= p->nAlloc ){
65147     char **azNew;
65148     p->nAlloc = p->nAlloc*2 + need + 1;
65149     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
65150     if( azNew==0 ) goto malloc_failed;
65151     p->azResult = azNew;
65152   }
65153
65154   /* If this is the first row, then generate an extra row containing
65155   ** the names of all columns.
65156   */
65157   if( p->nRow==0 ){
65158     p->nColumn = nCol;
65159     for(i=0; i<nCol; i++){
65160       z = sqlite3_mprintf("%s", colv[i]);
65161       if( z==0 ) goto malloc_failed;
65162       p->azResult[p->nData++] = z;
65163     }
65164   }else if( p->nColumn!=nCol ){
65165     sqlite3_free(p->zErrMsg);
65166     p->zErrMsg = sqlite3_mprintf(
65167        "sqlite3_get_table() called with two or more incompatible queries"
65168     );
65169     p->rc = SQLITE_ERROR;
65170     return 1;
65171   }
65172
65173   /* Copy over the row data
65174   */
65175   if( argv!=0 ){
65176     for(i=0; i<nCol; i++){
65177       if( argv[i]==0 ){
65178         z = 0;
65179       }else{
65180         int n = strlen(argv[i])+1;
65181         z = sqlite3_malloc( n );
65182         if( z==0 ) goto malloc_failed;
65183         memcpy(z, argv[i], n);
65184       }
65185       p->azResult[p->nData++] = z;
65186     }
65187     p->nRow++;
65188   }
65189   return 0;
65190
65191 malloc_failed:
65192   p->rc = SQLITE_NOMEM;
65193   return 1;
65194 }
65195
65196 /*
65197 ** Query the database.  But instead of invoking a callback for each row,
65198 ** malloc() for space to hold the result and return the entire results
65199 ** at the conclusion of the call.
65200 **
65201 ** The result that is written to ***pazResult is held in memory obtained
65202 ** from malloc().  But the caller cannot free this memory directly.  
65203 ** Instead, the entire table should be passed to sqlite3_free_table() when
65204 ** the calling procedure is finished using it.
65205 */
65206 SQLITE_API int sqlite3_get_table(
65207   sqlite3 *db,                /* The database on which the SQL executes */
65208   const char *zSql,           /* The SQL to be executed */
65209   char ***pazResult,          /* Write the result table here */
65210   int *pnRow,                 /* Write the number of rows in the result here */
65211   int *pnColumn,              /* Write the number of columns of result here */
65212   char **pzErrMsg             /* Write error messages here */
65213 ){
65214   int rc;
65215   TabResult res;
65216
65217   *pazResult = 0;
65218   if( pnColumn ) *pnColumn = 0;
65219   if( pnRow ) *pnRow = 0;
65220   res.zErrMsg = 0;
65221   res.nResult = 0;
65222   res.nRow = 0;
65223   res.nColumn = 0;
65224   res.nData = 1;
65225   res.nAlloc = 20;
65226   res.rc = SQLITE_OK;
65227   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
65228   if( res.azResult==0 ){
65229      db->errCode = SQLITE_NOMEM;
65230      return SQLITE_NOMEM;
65231   }
65232   res.azResult[0] = 0;
65233   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
65234   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
65235   res.azResult[0] = (char*)(sqlite3_intptr_t)res.nData;
65236   if( (rc&0xff)==SQLITE_ABORT ){
65237     sqlite3_free_table(&res.azResult[1]);
65238     if( res.zErrMsg ){
65239       if( pzErrMsg ){
65240         sqlite3_free(*pzErrMsg);
65241         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
65242       }
65243       sqlite3_free(res.zErrMsg);
65244     }
65245     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
65246     return res.rc;
65247   }
65248   sqlite3_free(res.zErrMsg);
65249   if( rc!=SQLITE_OK ){
65250     sqlite3_free_table(&res.azResult[1]);
65251     return rc;
65252   }
65253   if( res.nAlloc>res.nData ){
65254     char **azNew;
65255     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
65256     if( azNew==0 ){
65257       sqlite3_free_table(&res.azResult[1]);
65258       db->errCode = SQLITE_NOMEM;
65259       return SQLITE_NOMEM;
65260     }
65261     res.nAlloc = res.nData+1;
65262     res.azResult = azNew;
65263   }
65264   *pazResult = &res.azResult[1];
65265   if( pnColumn ) *pnColumn = res.nColumn;
65266   if( pnRow ) *pnRow = res.nRow;
65267   return rc;
65268 }
65269
65270 /*
65271 ** This routine frees the space the sqlite3_get_table() malloced.
65272 */
65273 SQLITE_API void sqlite3_free_table(
65274   char **azResult            /* Result returned from from sqlite3_get_table() */
65275 ){
65276   if( azResult ){
65277     sqlite3_intptr_t i, n;
65278     azResult--;
65279     assert( azResult!=0 );
65280     n = (sqlite3_intptr_t)azResult[0];
65281     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
65282     sqlite3_free(azResult);
65283   }
65284 }
65285
65286 #endif /* SQLITE_OMIT_GET_TABLE */
65287
65288 /************** End of table.c ***********************************************/
65289 /************** Begin file trigger.c *****************************************/
65290 /*
65291 **
65292 ** The author disclaims copyright to this source code.  In place of
65293 ** a legal notice, here is a blessing:
65294 **
65295 **    May you do good and not evil.
65296 **    May you find forgiveness for yourself and forgive others.
65297 **    May you share freely, never taking more than you give.
65298 **
65299 *************************************************************************
65300 *
65301 */
65302
65303 #ifndef SQLITE_OMIT_TRIGGER
65304 /*
65305 ** Delete a linked list of TriggerStep structures.
65306 */
65307 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
65308   while( pTriggerStep ){
65309     TriggerStep * pTmp = pTriggerStep;
65310     pTriggerStep = pTriggerStep->pNext;
65311
65312     if( pTmp->target.dyn ) sqlite3_free((char*)pTmp->target.z);
65313     sqlite3ExprDelete(pTmp->pWhere);
65314     sqlite3ExprListDelete(pTmp->pExprList);
65315     sqlite3SelectDelete(pTmp->pSelect);
65316     sqlite3IdListDelete(pTmp->pIdList);
65317
65318     sqlite3_free(pTmp);
65319   }
65320 }
65321
65322 /*
65323 ** This is called by the parser when it sees a CREATE TRIGGER statement
65324 ** up to the point of the BEGIN before the trigger actions.  A Trigger
65325 ** structure is generated based on the information available and stored
65326 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
65327 ** sqlite3FinishTrigger() function is called to complete the trigger
65328 ** construction process.
65329 */
65330 SQLITE_PRIVATE void sqlite3BeginTrigger(
65331   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
65332   Token *pName1,      /* The name of the trigger */
65333   Token *pName2,      /* The name of the trigger */
65334   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
65335   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
65336   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
65337   SrcList *pTableName,/* The name of the table/view the trigger applies to */
65338   Expr *pWhen,        /* WHEN clause */
65339   int isTemp,         /* True if the TEMPORARY keyword is present */
65340   int noErr           /* Suppress errors if the trigger already exists */
65341 ){
65342   Trigger *pTrigger = 0;
65343   Table *pTab;
65344   char *zName = 0;        /* Name of the trigger */
65345   sqlite3 *db = pParse->db;
65346   int iDb;                /* The database to store the trigger in */
65347   Token *pName;           /* The unqualified db name */
65348   DbFixer sFix;
65349   int iTabDb;
65350
65351   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
65352   assert( pName2!=0 );
65353   if( isTemp ){
65354     /* If TEMP was specified, then the trigger name may not be qualified. */
65355     if( pName2->n>0 ){
65356       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
65357       goto trigger_cleanup;
65358     }
65359     iDb = 1;
65360     pName = pName1;
65361   }else{
65362     /* Figure out the db that the the trigger will be created in */
65363     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
65364     if( iDb<0 ){
65365       goto trigger_cleanup;
65366     }
65367   }
65368
65369   /* If the trigger name was unqualified, and the table is a temp table,
65370   ** then set iDb to 1 to create the trigger in the temporary database.
65371   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
65372   ** exist, the error is caught by the block below.
65373   */
65374   if( !pTableName || db->mallocFailed ){
65375     goto trigger_cleanup;
65376   }
65377   pTab = sqlite3SrcListLookup(pParse, pTableName);
65378   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
65379     iDb = 1;
65380   }
65381
65382   /* Ensure the table name matches database name and that the table exists */
65383   if( db->mallocFailed ) goto trigger_cleanup;
65384   assert( pTableName->nSrc==1 );
65385   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
65386       sqlite3FixSrcList(&sFix, pTableName) ){
65387     goto trigger_cleanup;
65388   }
65389   pTab = sqlite3SrcListLookup(pParse, pTableName);
65390   if( !pTab ){
65391     /* The table does not exist. */
65392     goto trigger_cleanup;
65393   }
65394   if( IsVirtual(pTab) ){
65395     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
65396     goto trigger_cleanup;
65397   }
65398
65399   /* Check that the trigger name is not reserved and that no trigger of the
65400   ** specified name exists */
65401   zName = sqlite3NameFromToken(db, pName);
65402   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
65403     goto trigger_cleanup;
65404   }
65405   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
65406     if( !noErr ){
65407       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
65408     }
65409     goto trigger_cleanup;
65410   }
65411
65412   /* Do not create a trigger on a system table */
65413   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
65414     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
65415     pParse->nErr++;
65416     goto trigger_cleanup;
65417   }
65418
65419   /* INSTEAD of triggers are only for views and views only support INSTEAD
65420   ** of triggers.
65421   */
65422   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
65423     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
65424         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
65425     goto trigger_cleanup;
65426   }
65427   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
65428     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
65429         " trigger on table: %S", pTableName, 0);
65430     goto trigger_cleanup;
65431   }
65432   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65433
65434 #ifndef SQLITE_OMIT_AUTHORIZATION
65435   {
65436     int code = SQLITE_CREATE_TRIGGER;
65437     const char *zDb = db->aDb[iTabDb].zName;
65438     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
65439     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
65440     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
65441       goto trigger_cleanup;
65442     }
65443     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
65444       goto trigger_cleanup;
65445     }
65446   }
65447 #endif
65448
65449   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
65450   ** cannot appear on views.  So we might as well translate every
65451   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
65452   ** elsewhere.
65453   */
65454   if (tr_tm == TK_INSTEAD){
65455     tr_tm = TK_BEFORE;
65456   }
65457
65458   /* Build the Trigger object */
65459   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
65460   if( pTrigger==0 ) goto trigger_cleanup;
65461   pTrigger->name = zName;
65462   zName = 0;
65463   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
65464   pTrigger->pSchema = db->aDb[iDb].pSchema;
65465   pTrigger->pTabSchema = pTab->pSchema;
65466   pTrigger->op = op;
65467   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
65468   pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
65469   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
65470   sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
65471   assert( pParse->pNewTrigger==0 );
65472   pParse->pNewTrigger = pTrigger;
65473
65474 trigger_cleanup:
65475   sqlite3_free(zName);
65476   sqlite3SrcListDelete(pTableName);
65477   sqlite3IdListDelete(pColumns);
65478   sqlite3ExprDelete(pWhen);
65479   if( !pParse->pNewTrigger ){
65480     sqlite3DeleteTrigger(pTrigger);
65481   }else{
65482     assert( pParse->pNewTrigger==pTrigger );
65483   }
65484 }
65485
65486 /*
65487 ** This routine is called after all of the trigger actions have been parsed
65488 ** in order to complete the process of building the trigger.
65489 */
65490 SQLITE_PRIVATE void sqlite3FinishTrigger(
65491   Parse *pParse,          /* Parser context */
65492   TriggerStep *pStepList, /* The triggered program */
65493   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
65494 ){
65495   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
65496   sqlite3 *db = pParse->db;  /* The database */
65497   DbFixer sFix;
65498   int iDb;                   /* Database containing the trigger */
65499
65500   pTrig = pParse->pNewTrigger;
65501   pParse->pNewTrigger = 0;
65502   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
65503   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
65504   pTrig->step_list = pStepList;
65505   while( pStepList ){
65506     pStepList->pTrig = pTrig;
65507     pStepList = pStepList->pNext;
65508   }
65509   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
65510           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
65511     goto triggerfinish_cleanup;
65512   }
65513
65514   /* if we are not initializing, and this trigger is not on a TEMP table, 
65515   ** build the sqlite_master entry
65516   */
65517   if( !db->init.busy ){
65518     Vdbe *v;
65519     char *z;
65520
65521     /* Make an entry in the sqlite_master table */
65522     v = sqlite3GetVdbe(pParse);
65523     if( v==0 ) goto triggerfinish_cleanup;
65524     sqlite3BeginWriteOperation(pParse, 0, iDb);
65525     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
65526     sqlite3NestedParse(pParse,
65527        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
65528        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
65529        pTrig->table, z);
65530     sqlite3_free(z);
65531     sqlite3ChangeCookie(pParse, iDb);
65532     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
65533         db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
65534     );
65535   }
65536
65537   if( db->init.busy ){
65538     int n;
65539     Table *pTab;
65540     Trigger *pDel;
65541     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
65542                      pTrig->name, strlen(pTrig->name), pTrig);
65543     if( pDel ){
65544       assert( pDel==pTrig );
65545       db->mallocFailed = 1;
65546       goto triggerfinish_cleanup;
65547     }
65548     n = strlen(pTrig->table) + 1;
65549     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
65550     assert( pTab!=0 );
65551     pTrig->pNext = pTab->pTrigger;
65552     pTab->pTrigger = pTrig;
65553     pTrig = 0;
65554   }
65555
65556 triggerfinish_cleanup:
65557   sqlite3DeleteTrigger(pTrig);
65558   assert( !pParse->pNewTrigger );
65559   sqlite3DeleteTriggerStep(pStepList);
65560 }
65561
65562 /*
65563 ** Make a copy of all components of the given trigger step.  This has
65564 ** the effect of copying all Expr.token.z values into memory obtained
65565 ** from sqlite3_malloc().  As initially created, the Expr.token.z values
65566 ** all point to the input string that was fed to the parser.  But that
65567 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
65568 ** call that started the parser exits.  This routine makes a persistent
65569 ** copy of all the Expr.token.z strings so that the TriggerStep structure
65570 ** will be valid even after the sqlite3_exec() call returns.
65571 */
65572 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
65573   if( p->target.z ){
65574     p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
65575     p->target.dyn = 1;
65576   }
65577   if( p->pSelect ){
65578     Select *pNew = sqlite3SelectDup(db, p->pSelect);
65579     sqlite3SelectDelete(p->pSelect);
65580     p->pSelect = pNew;
65581   }
65582   if( p->pWhere ){
65583     Expr *pNew = sqlite3ExprDup(db, p->pWhere);
65584     sqlite3ExprDelete(p->pWhere);
65585     p->pWhere = pNew;
65586   }
65587   if( p->pExprList ){
65588     ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
65589     sqlite3ExprListDelete(p->pExprList);
65590     p->pExprList = pNew;
65591   }
65592   if( p->pIdList ){
65593     IdList *pNew = sqlite3IdListDup(db, p->pIdList);
65594     sqlite3IdListDelete(p->pIdList);
65595     p->pIdList = pNew;
65596   }
65597 }
65598
65599 /*
65600 ** Turn a SELECT statement (that the pSelect parameter points to) into
65601 ** a trigger step.  Return a pointer to a TriggerStep structure.
65602 **
65603 ** The parser calls this routine when it finds a SELECT statement in
65604 ** body of a TRIGGER.  
65605 */
65606 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
65607   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
65608   if( pTriggerStep==0 ) {
65609     sqlite3SelectDelete(pSelect);
65610     return 0;
65611   }
65612
65613   pTriggerStep->op = TK_SELECT;
65614   pTriggerStep->pSelect = pSelect;
65615   pTriggerStep->orconf = OE_Default;
65616   sqlitePersistTriggerStep(db, pTriggerStep);
65617
65618   return pTriggerStep;
65619 }
65620
65621 /*
65622 ** Build a trigger step out of an INSERT statement.  Return a pointer
65623 ** to the new trigger step.
65624 **
65625 ** The parser calls this routine when it sees an INSERT inside the
65626 ** body of a trigger.
65627 */
65628 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
65629   sqlite3 *db,        /* The database connection */
65630   Token *pTableName,  /* Name of the table into which we insert */
65631   IdList *pColumn,    /* List of columns in pTableName to insert into */
65632   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
65633   Select *pSelect,    /* A SELECT statement that supplies values */
65634   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
65635 ){
65636   TriggerStep *pTriggerStep;
65637
65638   assert(pEList == 0 || pSelect == 0);
65639   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
65640
65641   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
65642   if( pTriggerStep ){
65643     pTriggerStep->op = TK_INSERT;
65644     pTriggerStep->pSelect = pSelect;
65645     pTriggerStep->target  = *pTableName;
65646     pTriggerStep->pIdList = pColumn;
65647     pTriggerStep->pExprList = pEList;
65648     pTriggerStep->orconf = orconf;
65649     sqlitePersistTriggerStep(db, pTriggerStep);
65650   }else{
65651     sqlite3IdListDelete(pColumn);
65652     sqlite3ExprListDelete(pEList);
65653     sqlite3SelectDelete(pSelect);
65654   }
65655
65656   return pTriggerStep;
65657 }
65658
65659 /*
65660 ** Construct a trigger step that implements an UPDATE statement and return
65661 ** a pointer to that trigger step.  The parser calls this routine when it
65662 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
65663 */
65664 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
65665   sqlite3 *db,         /* The database connection */
65666   Token *pTableName,   /* Name of the table to be updated */
65667   ExprList *pEList,    /* The SET clause: list of column and new values */
65668   Expr *pWhere,        /* The WHERE clause */
65669   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
65670 ){
65671   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
65672   if( pTriggerStep==0 ){
65673      sqlite3ExprListDelete(pEList);
65674      sqlite3ExprDelete(pWhere);
65675      return 0;
65676   }
65677
65678   pTriggerStep->op = TK_UPDATE;
65679   pTriggerStep->target  = *pTableName;
65680   pTriggerStep->pExprList = pEList;
65681   pTriggerStep->pWhere = pWhere;
65682   pTriggerStep->orconf = orconf;
65683   sqlitePersistTriggerStep(db, pTriggerStep);
65684
65685   return pTriggerStep;
65686 }
65687
65688 /*
65689 ** Construct a trigger step that implements a DELETE statement and return
65690 ** a pointer to that trigger step.  The parser calls this routine when it
65691 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
65692 */
65693 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
65694   sqlite3 *db,            /* Database connection */
65695   Token *pTableName,      /* The table from which rows are deleted */
65696   Expr *pWhere            /* The WHERE clause */
65697 ){
65698   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
65699   if( pTriggerStep==0 ){
65700     sqlite3ExprDelete(pWhere);
65701     return 0;
65702   }
65703
65704   pTriggerStep->op = TK_DELETE;
65705   pTriggerStep->target  = *pTableName;
65706   pTriggerStep->pWhere = pWhere;
65707   pTriggerStep->orconf = OE_Default;
65708   sqlitePersistTriggerStep(db, pTriggerStep);
65709
65710   return pTriggerStep;
65711 }
65712
65713 /* 
65714 ** Recursively delete a Trigger structure
65715 */
65716 SQLITE_PRIVATE void sqlite3DeleteTrigger(Trigger *pTrigger){
65717   if( pTrigger==0 ) return;
65718   sqlite3DeleteTriggerStep(pTrigger->step_list);
65719   sqlite3_free(pTrigger->name);
65720   sqlite3_free(pTrigger->table);
65721   sqlite3ExprDelete(pTrigger->pWhen);
65722   sqlite3IdListDelete(pTrigger->pColumns);
65723   if( pTrigger->nameToken.dyn ) sqlite3_free((char*)pTrigger->nameToken.z);
65724   sqlite3_free(pTrigger);
65725 }
65726
65727 /*
65728 ** This function is called to drop a trigger from the database schema. 
65729 **
65730 ** This may be called directly from the parser and therefore identifies
65731 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
65732 ** same job as this routine except it takes a pointer to the trigger
65733 ** instead of the trigger name.
65734 **/
65735 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
65736   Trigger *pTrigger = 0;
65737   int i;
65738   const char *zDb;
65739   const char *zName;
65740   int nName;
65741   sqlite3 *db = pParse->db;
65742
65743   if( db->mallocFailed ) goto drop_trigger_cleanup;
65744   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
65745     goto drop_trigger_cleanup;
65746   }
65747
65748   assert( pName->nSrc==1 );
65749   zDb = pName->a[0].zDatabase;
65750   zName = pName->a[0].zName;
65751   nName = strlen(zName);
65752   for(i=OMIT_TEMPDB; i<db->nDb; i++){
65753     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
65754     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
65755     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
65756     if( pTrigger ) break;
65757   }
65758   if( !pTrigger ){
65759     if( !noErr ){
65760       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
65761     }
65762     goto drop_trigger_cleanup;
65763   }
65764   sqlite3DropTriggerPtr(pParse, pTrigger);
65765
65766 drop_trigger_cleanup:
65767   sqlite3SrcListDelete(pName);
65768 }
65769
65770 /*
65771 ** Return a pointer to the Table structure for the table that a trigger
65772 ** is set on.
65773 */
65774 static Table *tableOfTrigger(Trigger *pTrigger){
65775   int n = strlen(pTrigger->table) + 1;
65776   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
65777 }
65778
65779
65780 /*
65781 ** Drop a trigger given a pointer to that trigger. 
65782 */
65783 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
65784   Table   *pTable;
65785   Vdbe *v;
65786   sqlite3 *db = pParse->db;
65787   int iDb;
65788
65789   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
65790   assert( iDb>=0 && iDb<db->nDb );
65791   pTable = tableOfTrigger(pTrigger);
65792   assert( pTable );
65793   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
65794 #ifndef SQLITE_OMIT_AUTHORIZATION
65795   {
65796     int code = SQLITE_DROP_TRIGGER;
65797     const char *zDb = db->aDb[iDb].zName;
65798     const char *zTab = SCHEMA_TABLE(iDb);
65799     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
65800     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
65801       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
65802       return;
65803     }
65804   }
65805 #endif
65806
65807   /* Generate code to destroy the database record of the trigger.
65808   */
65809   assert( pTable!=0 );
65810   if( (v = sqlite3GetVdbe(pParse))!=0 ){
65811     int base;
65812     static const VdbeOpList dropTrigger[] = {
65813       { OP_Rewind,     0, ADDR(9),  0},
65814       { OP_String8,    0, 1,        0}, /* 1 */
65815       { OP_Column,     0, 1,        2},
65816       { OP_Ne,         2, ADDR(8),  1},
65817       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
65818       { OP_Column,     0, 0,        2},
65819       { OP_Ne,         2, ADDR(8),  1},
65820       { OP_Delete,     0, 0,        0},
65821       { OP_Next,       0, ADDR(1),  0}, /* 8 */
65822     };
65823
65824     sqlite3BeginWriteOperation(pParse, 0, iDb);
65825     sqlite3OpenMasterTable(pParse, iDb);
65826     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
65827     sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
65828     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
65829     sqlite3ChangeCookie(pParse, iDb);
65830     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
65831     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
65832   }
65833 }
65834
65835 /*
65836 ** Remove a trigger from the hash tables of the sqlite* pointer.
65837 */
65838 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
65839   Trigger *pTrigger;
65840   int nName = strlen(zName);
65841   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
65842                                zName, nName, 0);
65843   if( pTrigger ){
65844     Table *pTable = tableOfTrigger(pTrigger);
65845     assert( pTable!=0 );
65846     if( pTable->pTrigger == pTrigger ){
65847       pTable->pTrigger = pTrigger->pNext;
65848     }else{
65849       Trigger *cc = pTable->pTrigger;
65850       while( cc ){ 
65851         if( cc->pNext == pTrigger ){
65852           cc->pNext = cc->pNext->pNext;
65853           break;
65854         }
65855         cc = cc->pNext;
65856       }
65857       assert(cc);
65858     }
65859     sqlite3DeleteTrigger(pTrigger);
65860     db->flags |= SQLITE_InternChanges;
65861   }
65862 }
65863
65864 /*
65865 ** pEList is the SET clause of an UPDATE statement.  Each entry
65866 ** in pEList is of the format <id>=<expr>.  If any of the entries
65867 ** in pEList have an <id> which matches an identifier in pIdList,
65868 ** then return TRUE.  If pIdList==NULL, then it is considered a
65869 ** wildcard that matches anything.  Likewise if pEList==NULL then
65870 ** it matches anything so always return true.  Return false only
65871 ** if there is no match.
65872 */
65873 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
65874   int e;
65875   if( !pIdList || !pEList ) return 1;
65876   for(e=0; e<pEList->nExpr; e++){
65877     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
65878   }
65879   return 0; 
65880 }
65881
65882 /*
65883 ** Return a bit vector to indicate what kind of triggers exist for operation
65884 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
65885 ** that are being updated.  Triggers only match if the ON clause of the
65886 ** trigger definition overlaps the set of columns being updated.
65887 **
65888 ** The returned bit vector is some combination of TRIGGER_BEFORE and
65889 ** TRIGGER_AFTER.
65890 */
65891 SQLITE_PRIVATE int sqlite3TriggersExist(
65892   Parse *pParse,          /* Used to check for recursive triggers */
65893   Table *pTab,            /* The table the contains the triggers */
65894   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
65895   ExprList *pChanges      /* Columns that change in an UPDATE statement */
65896 ){
65897   Trigger *pTrigger;
65898   int mask = 0;
65899
65900   pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
65901   while( pTrigger ){
65902     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
65903       mask |= pTrigger->tr_tm;
65904     }
65905     pTrigger = pTrigger->pNext;
65906   }
65907   return mask;
65908 }
65909
65910 /*
65911 ** Convert the pStep->target token into a SrcList and return a pointer
65912 ** to that SrcList.
65913 **
65914 ** This routine adds a specific database name, if needed, to the target when
65915 ** forming the SrcList.  This prevents a trigger in one database from
65916 ** referring to a target in another database.  An exception is when the
65917 ** trigger is in TEMP in which case it can refer to any other database it
65918 ** wants.
65919 */
65920 static SrcList *targetSrcList(
65921   Parse *pParse,       /* The parsing context */
65922   TriggerStep *pStep   /* The trigger containing the target token */
65923 ){
65924   Token sDb;           /* Dummy database name token */
65925   int iDb;             /* Index of the database to use */
65926   SrcList *pSrc;       /* SrcList to be returned */
65927
65928   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
65929   if( iDb==0 || iDb>=2 ){
65930     assert( iDb<pParse->db->nDb );
65931     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
65932     sDb.n = strlen((char*)sDb.z);
65933     pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
65934   } else {
65935     pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
65936   }
65937   return pSrc;
65938 }
65939
65940 /*
65941 ** Generate VDBE code for zero or more statements inside the body of a
65942 ** trigger.  
65943 */
65944 static int codeTriggerProgram(
65945   Parse *pParse,            /* The parser context */
65946   TriggerStep *pStepList,   /* List of statements inside the trigger body */
65947   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
65948 ){
65949   TriggerStep * pTriggerStep = pStepList;
65950   int orconf;
65951   Vdbe *v = pParse->pVdbe;
65952   sqlite3 *db = pParse->db;
65953
65954   assert( pTriggerStep!=0 );
65955   assert( v!=0 );
65956   sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
65957   VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
65958   while( pTriggerStep ){
65959     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
65960     pParse->trigStack->orconf = orconf;
65961     switch( pTriggerStep->op ){
65962       case TK_SELECT: {
65963         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
65964         if( ss ){
65965           SelectDest dest;
65966
65967           sqlite3SelectDestInit(&dest, SRT_Discard, 0);
65968           sqlite3SelectResolve(pParse, ss, 0);
65969           sqlite3Select(pParse, ss, &dest, 0, 0, 0, 0);
65970           sqlite3SelectDelete(ss);
65971         }
65972         break;
65973       }
65974       case TK_UPDATE: {
65975         SrcList *pSrc;
65976         pSrc = targetSrcList(pParse, pTriggerStep);
65977         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
65978         sqlite3Update(pParse, pSrc,
65979                 sqlite3ExprListDup(db, pTriggerStep->pExprList), 
65980                 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
65981         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
65982         break;
65983       }
65984       case TK_INSERT: {
65985         SrcList *pSrc;
65986         pSrc = targetSrcList(pParse, pTriggerStep);
65987         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
65988         sqlite3Insert(pParse, pSrc,
65989           sqlite3ExprListDup(db, pTriggerStep->pExprList), 
65990           sqlite3SelectDup(db, pTriggerStep->pSelect), 
65991           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
65992         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
65993         break;
65994       }
65995       case TK_DELETE: {
65996         SrcList *pSrc;
65997         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
65998         pSrc = targetSrcList(pParse, pTriggerStep);
65999         sqlite3DeleteFrom(pParse, pSrc, 
66000                           sqlite3ExprDup(db, pTriggerStep->pWhere));
66001         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
66002         break;
66003       }
66004       default:
66005         assert(0);
66006     } 
66007     pTriggerStep = pTriggerStep->pNext;
66008   }
66009   sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
66010   VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
66011
66012   return 0;
66013 }
66014
66015 /*
66016 ** This is called to code FOR EACH ROW triggers.
66017 **
66018 ** When the code that this function generates is executed, the following 
66019 ** must be true:
66020 **
66021 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
66022 **    can be indices of cursors in temporary tables.  See below.)
66023 **
66024 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
66025 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
66026 **    a row containing values to be substituted for new.* expressions in the
66027 **    trigger program(s).
66028 **
66029 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
66030 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
66031 **    a row containing values to be substituted for old.* expressions in the
66032 **    trigger program(s).
66033 **
66034 ** If they are not NULL, the piOldColMask and piNewColMask output variables
66035 ** are set to values that describe the columns used by the trigger program
66036 ** in the OLD.* and NEW.* tables respectively. If column N of the 
66037 ** pseudo-table is read at least once, the corresponding bit of the output
66038 ** mask is set. If a column with an index greater than 32 is read, the
66039 ** output mask is set to the special value 0xffffffff.
66040 **
66041 */
66042 SQLITE_PRIVATE int sqlite3CodeRowTrigger(
66043   Parse *pParse,       /* Parse context */
66044   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
66045   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
66046   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
66047   Table *pTab,         /* The table to code triggers from */
66048   int newIdx,          /* The indice of the "new" row to access */
66049   int oldIdx,          /* The indice of the "old" row to access */
66050   int orconf,          /* ON CONFLICT policy */
66051   int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
66052   u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
66053   u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
66054 ){
66055   Trigger *p;
66056   sqlite3 *db = pParse->db;
66057   TriggerStack trigStackEntry;
66058
66059   trigStackEntry.oldColMask = 0;
66060   trigStackEntry.newColMask = 0;
66061
66062   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
66063   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
66064
66065   assert(newIdx != -1 || oldIdx != -1);
66066
66067   for(p=pTab->pTrigger; p; p=p->pNext){
66068     int fire_this = 0;
66069
66070     /* Determine whether we should code this trigger */
66071     if( 
66072       p->op==op && 
66073       p->tr_tm==tr_tm && 
66074       (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
66075       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
66076     ){
66077       TriggerStack *pS;      /* Pointer to trigger-stack entry */
66078       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
66079       if( !pS ){
66080         fire_this = 1;
66081       }
66082 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
66083       else{
66084         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
66085             p->name);
66086         return SQLITE_ERROR;
66087       }
66088 #endif
66089     }
66090  
66091     if( fire_this ){
66092       int endTrigger;
66093       Expr * whenExpr;
66094       AuthContext sContext;
66095       NameContext sNC;
66096
66097 #ifndef SQLITE_OMIT_TRACE
66098       sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
66099                         sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
66100                         P4_DYNAMIC);
66101 #endif
66102       memset(&sNC, 0, sizeof(sNC));
66103       sNC.pParse = pParse;
66104
66105       /* Push an entry on to the trigger stack */
66106       trigStackEntry.pTrigger = p;
66107       trigStackEntry.newIdx = newIdx;
66108       trigStackEntry.oldIdx = oldIdx;
66109       trigStackEntry.pTab = pTab;
66110       trigStackEntry.pNext = pParse->trigStack;
66111       trigStackEntry.ignoreJump = ignoreJump;
66112       pParse->trigStack = &trigStackEntry;
66113       sqlite3AuthContextPush(pParse, &sContext, p->name);
66114
66115       /* code the WHEN clause */
66116       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
66117       whenExpr = sqlite3ExprDup(db, p->pWhen);
66118       if( db->mallocFailed || sqlite3ExprResolveNames(&sNC, whenExpr) ){
66119         pParse->trigStack = trigStackEntry.pNext;
66120         sqlite3ExprDelete(whenExpr);
66121         return 1;
66122       }
66123       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
66124       sqlite3ExprDelete(whenExpr);
66125
66126       codeTriggerProgram(pParse, p->step_list, orconf); 
66127
66128       /* Pop the entry off the trigger stack */
66129       pParse->trigStack = trigStackEntry.pNext;
66130       sqlite3AuthContextPop(&sContext);
66131
66132       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
66133     }
66134   }
66135   if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
66136   if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
66137   return 0;
66138 }
66139 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
66140
66141 /************** End of trigger.c *********************************************/
66142 /************** Begin file update.c ******************************************/
66143 /*
66144 ** 2001 September 15
66145 **
66146 ** The author disclaims copyright to this source code.  In place of
66147 ** a legal notice, here is a blessing:
66148 **
66149 **    May you do good and not evil.
66150 **    May you find forgiveness for yourself and forgive others.
66151 **    May you share freely, never taking more than you give.
66152 **
66153 *************************************************************************
66154 ** This file contains C code routines that are called by the parser
66155 ** to handle UPDATE statements.
66156 **
66157 ** $Id: update.c,v 1.171 2008/02/12 16:52:14 drh Exp $
66158 */
66159
66160 #ifndef SQLITE_OMIT_VIRTUALTABLE
66161 /* Forward declaration */
66162 static void updateVirtualTable(
66163   Parse *pParse,       /* The parsing context */
66164   SrcList *pSrc,       /* The virtual table to be modified */
66165   Table *pTab,         /* The virtual table */
66166   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
66167   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
66168   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
66169   Expr *pWhere         /* WHERE clause of the UPDATE statement */
66170 );
66171 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66172
66173 /*
66174 ** The most recently coded instruction was an OP_Column to retrieve the
66175 ** i-th column of table pTab. This routine sets the P4 parameter of the 
66176 ** OP_Column to the default value, if any.
66177 **
66178 ** The default value of a column is specified by a DEFAULT clause in the 
66179 ** column definition. This was either supplied by the user when the table
66180 ** was created, or added later to the table definition by an ALTER TABLE
66181 ** command. If the latter, then the row-records in the table btree on disk
66182 ** may not contain a value for the column and the default value, taken
66183 ** from the P4 parameter of the OP_Column instruction, is returned instead.
66184 ** If the former, then all row-records are guaranteed to include a value
66185 ** for the column and the P4 value is not required.
66186 **
66187 ** Column definitions created by an ALTER TABLE command may only have 
66188 ** literal default values specified: a number, null or a string. (If a more
66189 ** complicated default expression value was provided, it is evaluated 
66190 ** when the ALTER TABLE is executed and one of the literal values written
66191 ** into the sqlite_master table.)
66192 **
66193 ** Therefore, the P4 parameter is only required if the default value for
66194 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
66195 ** function is capable of transforming these types of expressions into
66196 ** sqlite3_value objects.
66197 */
66198 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
66199   if( pTab && !pTab->pSelect ){
66200     sqlite3_value *pValue;
66201     u8 enc = ENC(sqlite3VdbeDb(v));
66202     Column *pCol = &pTab->aCol[i];
66203     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
66204     assert( i<pTab->nCol );
66205     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
66206                          pCol->affinity, &pValue);
66207     if( pValue ){
66208       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
66209     }
66210   }
66211 }
66212
66213 /*
66214 ** Process an UPDATE statement.
66215 **
66216 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
66217 **          \_______/ \________/     \______/       \________________/
66218 *            onError   pTabList      pChanges             pWhere
66219 */
66220 SQLITE_PRIVATE void sqlite3Update(
66221   Parse *pParse,         /* The parser context */
66222   SrcList *pTabList,     /* The table in which we should change things */
66223   ExprList *pChanges,    /* Things to be changed */
66224   Expr *pWhere,          /* The WHERE clause.  May be null */
66225   int onError            /* How to handle constraint errors */
66226 ){
66227   int i, j;              /* Loop counters */
66228   Table *pTab;           /* The table to be updated */
66229   int addr = 0;          /* VDBE instruction address of the start of the loop */
66230   WhereInfo *pWInfo;     /* Information about the WHERE clause */
66231   Vdbe *v;               /* The virtual database engine */
66232   Index *pIdx;           /* For looping over indices */
66233   int nIdx;              /* Number of indices that need updating */
66234   int iCur;              /* VDBE Cursor number of pTab */
66235   sqlite3 *db;           /* The database structure */
66236   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
66237   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
66238                          ** an expression for the i-th column of the table.
66239                          ** aXRef[i]==-1 if the i-th column is not changed. */
66240   int chngRowid;         /* True if the record number is being changed */
66241   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
66242   int openAll = 0;       /* True if all indices need to be opened */
66243   AuthContext sContext;  /* The authorization context */
66244   NameContext sNC;       /* The name-context to resolve expressions in */
66245   int iDb;               /* Database containing the table being updated */
66246   int j1;                /* Addresses of jump instructions */
66247
66248 #ifndef SQLITE_OMIT_TRIGGER
66249   int isView;                  /* Trying to update a view */
66250   int triggers_exist = 0;      /* True if any row triggers exist */
66251 #endif
66252   int iBeginAfterTrigger;      /* Address of after trigger program */
66253   int iEndAfterTrigger;        /* Exit of after trigger program */
66254   int iBeginBeforeTrigger;     /* Address of before trigger program */
66255   int iEndBeforeTrigger;       /* Exit of before trigger program */
66256   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
66257   u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
66258
66259   int newIdx      = -1;  /* index of trigger "new" temp table       */
66260   int oldIdx      = -1;  /* index of trigger "old" temp table       */
66261
66262   /* Register Allocations */
66263   int regRowCount = 0;   /* A count of rows changed */
66264   int regOldRowid;       /* The old rowid */
66265   int regNewRowid;       /* The new rowid */
66266   int regData;           /* New data for the row */
66267
66268   sContext.pParse = 0;
66269   db = pParse->db;
66270   if( pParse->nErr || db->mallocFailed ){
66271     goto update_cleanup;
66272   }
66273   assert( pTabList->nSrc==1 );
66274
66275   /* Locate the table which we want to update. 
66276   */
66277   pTab = sqlite3SrcListLookup(pParse, pTabList);
66278   if( pTab==0 ) goto update_cleanup;
66279   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
66280
66281   /* Figure out if we have any triggers and if the table being
66282   ** updated is a view
66283   */
66284 #ifndef SQLITE_OMIT_TRIGGER
66285   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
66286   isView = pTab->pSelect!=0;
66287 #else
66288 # define triggers_exist 0
66289 # define isView 0
66290 #endif
66291 #ifdef SQLITE_OMIT_VIEW
66292 # undef isView
66293 # define isView 0
66294 #endif
66295
66296   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
66297     goto update_cleanup;
66298   }
66299   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
66300     goto update_cleanup;
66301   }
66302   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
66303   if( aXRef==0 ) goto update_cleanup;
66304   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
66305
66306   /* If there are FOR EACH ROW triggers, allocate cursors for the
66307   ** special OLD and NEW tables
66308   */
66309   if( triggers_exist ){
66310     newIdx = pParse->nTab++;
66311     oldIdx = pParse->nTab++;
66312   }
66313
66314   /* Allocate a cursors for the main database table and for all indices.
66315   ** The index cursors might not be used, but if they are used they
66316   ** need to occur right after the database cursor.  So go ahead and
66317   ** allocate enough space, just in case.
66318   */
66319   pTabList->a[0].iCursor = iCur = pParse->nTab++;
66320   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
66321     pParse->nTab++;
66322   }
66323
66324   /* Initialize the name-context */
66325   memset(&sNC, 0, sizeof(sNC));
66326   sNC.pParse = pParse;
66327   sNC.pSrcList = pTabList;
66328
66329   /* Resolve the column names in all the expressions of the
66330   ** of the UPDATE statement.  Also find the column index
66331   ** for each column to be updated in the pChanges array.  For each
66332   ** column to be updated, make sure we have authorization to change
66333   ** that column.
66334   */
66335   chngRowid = 0;
66336   for(i=0; i<pChanges->nExpr; i++){
66337     if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
66338       goto update_cleanup;
66339     }
66340     for(j=0; j<pTab->nCol; j++){
66341       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
66342         if( j==pTab->iPKey ){
66343           chngRowid = 1;
66344           pRowidExpr = pChanges->a[i].pExpr;
66345         }
66346         aXRef[j] = i;
66347         break;
66348       }
66349     }
66350     if( j>=pTab->nCol ){
66351       if( sqlite3IsRowid(pChanges->a[i].zName) ){
66352         chngRowid = 1;
66353         pRowidExpr = pChanges->a[i].pExpr;
66354       }else{
66355         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
66356         goto update_cleanup;
66357       }
66358     }
66359 #ifndef SQLITE_OMIT_AUTHORIZATION
66360     {
66361       int rc;
66362       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
66363                            pTab->aCol[j].zName, db->aDb[iDb].zName);
66364       if( rc==SQLITE_DENY ){
66365         goto update_cleanup;
66366       }else if( rc==SQLITE_IGNORE ){
66367         aXRef[j] = -1;
66368       }
66369     }
66370 #endif
66371   }
66372
66373   /* Allocate memory for the array aRegIdx[].  There is one entry in the
66374   ** array for each index associated with table being updated.  Fill in
66375   ** the value with a register number for indices that are to be used
66376   ** and with zero for unused indices.
66377   */
66378   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
66379   if( nIdx>0 ){
66380     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
66381     if( aRegIdx==0 ) goto update_cleanup;
66382   }
66383   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
66384     int reg;
66385     if( chngRowid ){
66386       reg = ++pParse->nMem;
66387     }else{
66388       reg = 0;
66389       for(i=0; i<pIdx->nColumn; i++){
66390         if( aXRef[pIdx->aiColumn[i]]>=0 ){
66391           reg = ++pParse->nMem;
66392           break;
66393         }
66394       }
66395     }
66396     aRegIdx[j] = reg;
66397   }
66398
66399   /* Allocate a block of register used to store the change record
66400   ** sent to sqlite3GenerateConstraintChecks().  There are either
66401   ** one or two registers for holding the rowid.  One rowid register
66402   ** is used if chngRowid is false and two are used if chngRowid is
66403   ** true.  Following these are pTab->nCol register holding column
66404   ** data.
66405   */
66406   regOldRowid = regNewRowid = pParse->nMem + 1;
66407   pParse->nMem += pTab->nCol + 1;
66408   if( chngRowid ){
66409     regNewRowid++;
66410     pParse->nMem++;
66411   }
66412   regData = regNewRowid+1;
66413  
66414
66415   /* Begin generating code.
66416   */
66417   v = sqlite3GetVdbe(pParse);
66418   if( v==0 ) goto update_cleanup;
66419   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
66420   sqlite3BeginWriteOperation(pParse, 1, iDb);
66421
66422 #ifndef SQLITE_OMIT_VIRTUALTABLE
66423   /* Virtual tables must be handled separately */
66424   if( IsVirtual(pTab) ){
66425     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
66426                        pWhere);
66427     pWhere = 0;
66428     pTabList = 0;
66429     goto update_cleanup;
66430   }
66431 #endif
66432
66433   /* Start the view context
66434   */
66435   if( isView ){
66436     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
66437   }
66438
66439   /* Generate the code for triggers.
66440   */
66441   if( triggers_exist ){
66442     int iGoto;
66443
66444     /* Create pseudo-tables for NEW and OLD
66445     */
66446     sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
66447     sqlite3VdbeAddOp2(v, OP_SetNumColumns, oldIdx, pTab->nCol);
66448     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
66449     sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol);
66450
66451     iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
66452     addr = sqlite3VdbeMakeLabel(v);
66453     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
66454     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
66455           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
66456       goto update_cleanup;
66457     }
66458     iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
66459     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
66460     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
66461           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
66462       goto update_cleanup;
66463     }
66464     iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
66465     sqlite3VdbeJumpHere(v, iGoto);
66466   }
66467
66468   /* If we are trying to update a view, realize that view into
66469   ** a ephemeral table.
66470   */
66471   if( isView ){
66472     sqlite3MaterializeView(pParse, pTab->pSelect, pWhere,
66473                            old_col_mask|new_col_mask, iCur);
66474   }
66475
66476   /* Resolve the column names in all the expressions in the
66477   ** WHERE clause.
66478   */
66479   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
66480     goto update_cleanup;
66481   }
66482
66483   /* Begin the database scan
66484   */
66485   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
66486   if( pWInfo==0 ) goto update_cleanup;
66487
66488   /* Remember the rowid of every item to be updated.
66489   */
66490   sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid,iCur,regOldRowid);
66491   sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0);
66492
66493   /* End the database scan loop.
66494   */
66495   sqlite3WhereEnd(pWInfo);
66496
66497   /* Initialize the count of updated rows
66498   */
66499   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
66500     regRowCount = ++pParse->nMem;
66501     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
66502   }
66503
66504   if( !isView && !IsVirtual(pTab) ){
66505     /* 
66506     ** Open every index that needs updating.  Note that if any
66507     ** index could potentially invoke a REPLACE conflict resolution 
66508     ** action, then we need to open all indices because we might need
66509     ** to be deleting some records.
66510     */
66511     sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
66512     if( onError==OE_Replace ){
66513       openAll = 1;
66514     }else{
66515       openAll = 0;
66516       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
66517         if( pIdx->onError==OE_Replace ){
66518           openAll = 1;
66519           break;
66520         }
66521       }
66522     }
66523     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
66524       if( openAll || aRegIdx[i]>0 ){
66525         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
66526         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
66527                        (char*)pKey, P4_KEYINFO_HANDOFF);
66528         assert( pParse->nTab>iCur+i+1 );
66529       }
66530     }
66531   }
66532   
66533   /* Jump back to this point if a trigger encounters an IGNORE constraint. */
66534   if( triggers_exist ){
66535     sqlite3VdbeResolveLabel(v, addr);
66536   }
66537
66538   /* Top of the update loop */
66539   addr = sqlite3VdbeAddOp2(v, OP_FifoRead, regOldRowid, 0);
66540
66541   if( triggers_exist ){
66542     int regRowid;
66543     int regRow;
66544     int regCols;
66545
66546     /* Make cursor iCur point to the record that is being updated.
66547     */
66548     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
66549
66550     /* Generate the OLD table
66551     */
66552     regRowid = sqlite3GetTempReg(pParse);
66553     regRow = sqlite3GetTempReg(pParse);
66554     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
66555     if( !old_col_mask ){
66556       sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
66557     }else{
66558       sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
66559     }
66560     sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
66561
66562     /* Generate the NEW table
66563     */
66564     if( chngRowid ){
66565       sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
66566     }else{
66567       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
66568     }
66569     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
66570     for(i=0; i<pTab->nCol; i++){
66571       if( i==pTab->iPKey ){
66572         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
66573         continue;
66574       }
66575       j = aXRef[i];
66576       if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
66577         if( j<0 ){
66578           sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
66579           sqlite3ColumnDefault(v, pTab, i);
66580         }else{
66581           sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
66582         }
66583       }else{
66584         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
66585       }
66586     }
66587     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
66588     if( !isView ){
66589       sqlite3TableAffinityStr(v, pTab);
66590     }
66591     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
66592     if( pParse->nErr ) goto update_cleanup;
66593     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
66594     sqlite3ReleaseTempReg(pParse, regRowid);
66595     sqlite3ReleaseTempReg(pParse, regRow);
66596
66597     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
66598     sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
66599   }
66600
66601   if( !isView && !IsVirtual(pTab) ){
66602     /* Loop over every record that needs updating.  We have to load
66603     ** the old data for each record to be updated because some columns
66604     ** might not change and we will need to copy the old value.
66605     ** Also, the old data is needed to delete the old index entries.
66606     ** So make the cursor point at the old record.
66607     */
66608     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
66609
66610     /* If the record number will change, push the record number as it
66611     ** will be after the update. (The old record number is currently
66612     ** on top of the stack.)
66613     */
66614     if( chngRowid ){
66615       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
66616       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
66617     }
66618
66619     /* Compute new data for this record.  
66620     */
66621     for(i=0; i<pTab->nCol; i++){
66622       if( i==pTab->iPKey ){
66623         sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
66624         continue;
66625       }
66626       j = aXRef[i];
66627       if( j<0 ){
66628         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
66629         sqlite3ColumnDefault(v, pTab, i);
66630       }else{
66631         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
66632       }
66633     }
66634
66635     /* Do constraint checks
66636     */
66637     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
66638                                     aRegIdx, chngRowid, 1,
66639                                     onError, addr);
66640
66641     /* Delete the old indices for the current record.
66642     */
66643     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
66644     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
66645
66646     /* If changing the record number, delete the old record.
66647     */
66648     if( chngRowid ){
66649       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
66650     }
66651     sqlite3VdbeJumpHere(v, j1);
66652
66653     /* Create the new index entries and the new record.
66654     */
66655     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
66656                              aRegIdx, chngRowid, 1, -1, 0);
66657   }
66658
66659   /* Increment the row counter 
66660   */
66661   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
66662     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
66663   }
66664
66665   /* If there are triggers, close all the cursors after each iteration
66666   ** through the loop.  The fire the after triggers.
66667   */
66668   if( triggers_exist ){
66669     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
66670     sqlite3VdbeJumpHere(v, iEndAfterTrigger);
66671   }
66672
66673   /* Repeat the above with the next record to be updated, until
66674   ** all record selected by the WHERE clause have been updated.
66675   */
66676   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
66677   sqlite3VdbeJumpHere(v, addr);
66678
66679   /* Close all tables */
66680   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
66681     if( openAll || aRegIdx[i]>0 ){
66682       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
66683     }
66684   }
66685   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
66686   if( triggers_exist ){
66687     sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
66688     sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
66689   }
66690
66691   /*
66692   ** Return the number of rows that were changed. If this routine is 
66693   ** generating code because of a call to sqlite3NestedParse(), do not
66694   ** invoke the callback function.
66695   */
66696   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
66697     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
66698     sqlite3VdbeSetNumCols(v, 1);
66699     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P4_STATIC);
66700   }
66701
66702 update_cleanup:
66703   sqlite3AuthContextPop(&sContext);
66704   sqlite3_free(aRegIdx);
66705   sqlite3_free(aXRef);
66706   sqlite3SrcListDelete(pTabList);
66707   sqlite3ExprListDelete(pChanges);
66708   sqlite3ExprDelete(pWhere);
66709   return;
66710 }
66711
66712 #ifndef SQLITE_OMIT_VIRTUALTABLE
66713 /*
66714 ** Generate code for an UPDATE of a virtual table.
66715 **
66716 ** The strategy is that we create an ephemerial table that contains
66717 ** for each row to be changed:
66718 **
66719 **   (A)  The original rowid of that row.
66720 **   (B)  The revised rowid for the row. (note1)
66721 **   (C)  The content of every column in the row.
66722 **
66723 ** Then we loop over this ephemeral table and for each row in
66724 ** the ephermeral table call VUpdate.
66725 **
66726 ** When finished, drop the ephemeral table.
66727 **
66728 ** (note1) Actually, if we know in advance that (A) is always the same
66729 ** as (B) we only store (A), then duplicate (A) when pulling
66730 ** it out of the ephemeral table before calling VUpdate.
66731 */
66732 static void updateVirtualTable(
66733   Parse *pParse,       /* The parsing context */
66734   SrcList *pSrc,       /* The virtual table to be modified */
66735   Table *pTab,         /* The virtual table */
66736   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
66737   Expr *pRowid,        /* Expression used to recompute the rowid */
66738   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
66739   Expr *pWhere         /* WHERE clause of the UPDATE statement */
66740 ){
66741   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
66742   ExprList *pEList = 0;     /* The result set of the SELECT statement */
66743   Select *pSelect = 0;      /* The SELECT statement */
66744   Expr *pExpr;              /* Temporary expression */
66745   int ephemTab;             /* Table holding the result of the SELECT */
66746   int i;                    /* Loop counter */
66747   int addr;                 /* Address of top of loop */
66748   int iReg;                 /* First register in set passed to OP_VUpdate */
66749   sqlite3 *db = pParse->db; /* Database connection */
66750   const char *pVtab = (const char*)pTab->pVtab;
66751   SelectDest dest;
66752
66753   /* Construct the SELECT statement that will find the new values for
66754   ** all updated rows. 
66755   */
66756   pEList = sqlite3ExprListAppend(pParse, 0, 
66757                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
66758   if( pRowid ){
66759     pEList = sqlite3ExprListAppend(pParse, pEList,
66760                                    sqlite3ExprDup(db, pRowid), 0);
66761   }
66762   assert( pTab->iPKey<0 );
66763   for(i=0; i<pTab->nCol; i++){
66764     if( aXRef[i]>=0 ){
66765       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
66766     }else{
66767       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
66768     }
66769     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
66770   }
66771   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
66772   
66773   /* Create the ephemeral table into which the update results will
66774   ** be stored.
66775   */
66776   assert( v );
66777   ephemTab = pParse->nTab++;
66778   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
66779
66780   /* fill the ephemeral table 
66781   */
66782   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
66783   sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
66784
66785   /* Generate code to scan the ephemeral table and call VUpdate. */
66786   iReg = ++pParse->nMem;
66787   pParse->nMem += pTab->nCol+1;
66788   sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
66789   addr = sqlite3VdbeCurrentAddr(v);
66790   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
66791   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
66792   for(i=0; i<pTab->nCol; i++){
66793     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
66794   }
66795   pParse->pVirtualLock = pTab;
66796   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
66797   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
66798   sqlite3VdbeJumpHere(v, addr-1);
66799   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
66800
66801   /* Cleanup */
66802   sqlite3SelectDelete(pSelect);  
66803 }
66804 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66805
66806 /************** End of update.c **********************************************/
66807 /************** Begin file vacuum.c ******************************************/
66808 /*
66809 ** 2003 April 6
66810 **
66811 ** The author disclaims copyright to this source code.  In place of
66812 ** a legal notice, here is a blessing:
66813 **
66814 **    May you do good and not evil.
66815 **    May you find forgiveness for yourself and forgive others.
66816 **    May you share freely, never taking more than you give.
66817 **
66818 *************************************************************************
66819 ** This file contains code used to implement the VACUUM command.
66820 **
66821 ** Most of the code in this file may be omitted by defining the
66822 ** SQLITE_OMIT_VACUUM macro.
66823 **
66824 ** $Id: vacuum.c,v 1.76 2008/01/03 00:01:25 drh Exp $
66825 */
66826
66827 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
66828 /*
66829 ** Execute zSql on database db. Return an error code.
66830 */
66831 static int execSql(sqlite3 *db, const char *zSql){
66832   sqlite3_stmt *pStmt;
66833   if( !zSql ){
66834     return SQLITE_NOMEM;
66835   }
66836   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
66837     return sqlite3_errcode(db);
66838   }
66839   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
66840   return sqlite3_finalize(pStmt);
66841 }
66842
66843 /*
66844 ** Execute zSql on database db. The statement returns exactly
66845 ** one column. Execute this as SQL on the same database.
66846 */
66847 static int execExecSql(sqlite3 *db, const char *zSql){
66848   sqlite3_stmt *pStmt;
66849   int rc;
66850
66851   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
66852   if( rc!=SQLITE_OK ) return rc;
66853
66854   while( SQLITE_ROW==sqlite3_step(pStmt) ){
66855     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
66856     if( rc!=SQLITE_OK ){
66857       sqlite3_finalize(pStmt);
66858       return rc;
66859     }
66860   }
66861
66862   return sqlite3_finalize(pStmt);
66863 }
66864
66865 /*
66866 ** The non-standard VACUUM command is used to clean up the database,
66867 ** collapse free space, etc.  It is modelled after the VACUUM command
66868 ** in PostgreSQL.
66869 **
66870 ** In version 1.0.x of SQLite, the VACUUM command would call
66871 ** gdbm_reorganize() on all the database tables.  But beginning
66872 ** with 2.0.0, SQLite no longer uses GDBM so this command has
66873 ** become a no-op.
66874 */
66875 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
66876   Vdbe *v = sqlite3GetVdbe(pParse);
66877   if( v ){
66878     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
66879   }
66880   return;
66881 }
66882
66883 /*
66884 ** This routine implements the OP_Vacuum opcode of the VDBE.
66885 */
66886 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
66887   int rc = SQLITE_OK;     /* Return code from service routines */
66888   Btree *pMain;           /* The database being vacuumed */
66889   Btree *pTemp;           /* The temporary database we vacuum into */
66890   char *zSql = 0;         /* SQL statements */
66891   int saved_flags;        /* Saved value of the db->flags */
66892   Db *pDb = 0;            /* Database to detach at end of vacuum */
66893
66894   /* Save the current value of the write-schema flag before setting it. */
66895   saved_flags = db->flags;
66896   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
66897
66898   if( !db->autoCommit ){
66899     sqlite3SetString(pzErrMsg, "cannot VACUUM from within a transaction", 
66900        (char*)0);
66901     rc = SQLITE_ERROR;
66902     goto end_of_vacuum;
66903   }
66904   pMain = db->aDb[0].pBt;
66905
66906   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
66907   ** can be set to 'off' for this file, as it is not recovered if a crash
66908   ** occurs anyway. The integrity of the database is maintained by a
66909   ** (possibly synchronous) transaction opened on the main database before
66910   ** sqlite3BtreeCopyFile() is called.
66911   **
66912   ** An optimisation would be to use a non-journaled pager.
66913   */
66914   zSql = "ATTACH '' AS vacuum_db;";
66915   rc = execSql(db, zSql);
66916   if( rc!=SQLITE_OK ) goto end_of_vacuum;
66917   pDb = &db->aDb[db->nDb-1];
66918   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
66919   pTemp = db->aDb[db->nDb-1].pBt;
66920   sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain),
66921      sqlite3BtreeGetReserve(pMain));
66922   if( db->mallocFailed ){
66923     rc = SQLITE_NOMEM;
66924     goto end_of_vacuum;
66925   }
66926   assert( sqlite3BtreeGetPageSize(pTemp)==sqlite3BtreeGetPageSize(pMain) );
66927   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
66928   if( rc!=SQLITE_OK ){
66929     goto end_of_vacuum;
66930   }
66931
66932 #ifndef SQLITE_OMIT_AUTOVACUUM
66933   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
66934                                            sqlite3BtreeGetAutoVacuum(pMain));
66935 #endif
66936
66937   /* Begin a transaction */
66938   rc = execSql(db, "BEGIN EXCLUSIVE;");
66939   if( rc!=SQLITE_OK ) goto end_of_vacuum;
66940
66941   /* Query the schema of the main database. Create a mirror schema
66942   ** in the temporary database.
66943   */
66944   rc = execExecSql(db, 
66945       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
66946       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
66947       "   AND rootpage>0"
66948   );
66949   if( rc!=SQLITE_OK ) goto end_of_vacuum;
66950   rc = execExecSql(db, 
66951       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
66952       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
66953   if( rc!=SQLITE_OK ) goto end_of_vacuum;
66954   rc = execExecSql(db, 
66955       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
66956       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
66957   if( rc!=SQLITE_OK ) goto end_of_vacuum;
66958
66959   /* Loop through the tables in the main database. For each, do
66960   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
66961   ** the contents to the temporary database.
66962   */
66963   rc = execExecSql(db, 
66964       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
66965       "|| ' SELECT * FROM ' || quote(name) || ';'"
66966       "FROM sqlite_master "
66967       "WHERE type = 'table' AND name!='sqlite_sequence' "
66968       "  AND rootpage>0"
66969
66970   );
66971   if( rc!=SQLITE_OK ) goto end_of_vacuum;
66972
66973   /* Copy over the sequence table
66974   */
66975   rc = execExecSql(db, 
66976       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
66977       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
66978   );
66979   if( rc!=SQLITE_OK ) goto end_of_vacuum;
66980   rc = execExecSql(db, 
66981       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
66982       "|| ' SELECT * FROM ' || quote(name) || ';' "
66983       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
66984   );
66985   if( rc!=SQLITE_OK ) goto end_of_vacuum;
66986
66987
66988   /* Copy the triggers, views, and virtual tables from the main database
66989   ** over to the temporary database.  None of these objects has any
66990   ** associated storage, so all we have to do is copy their entries
66991   ** from the SQLITE_MASTER table.
66992   */
66993   rc = execSql(db,
66994       "INSERT INTO vacuum_db.sqlite_master "
66995       "  SELECT type, name, tbl_name, rootpage, sql"
66996       "    FROM sqlite_master"
66997       "   WHERE type='view' OR type='trigger'"
66998       "      OR (type='table' AND rootpage=0)"
66999   );
67000   if( rc ) goto end_of_vacuum;
67001
67002   /* At this point, unless the main db was completely empty, there is now a
67003   ** transaction open on the vacuum database, but not on the main database.
67004   ** Open a btree level transaction on the main database. This allows a
67005   ** call to sqlite3BtreeCopyFile(). The main database btree level
67006   ** transaction is then committed, so the SQL level never knows it was
67007   ** opened for writing. This way, the SQL transaction used to create the
67008   ** temporary database never needs to be committed.
67009   */
67010   if( rc==SQLITE_OK ){
67011     u32 meta;
67012     int i;
67013
67014     /* This array determines which meta meta values are preserved in the
67015     ** vacuum.  Even entries are the meta value number and odd entries
67016     ** are an increment to apply to the meta value after the vacuum.
67017     ** The increment is used to increase the schema cookie so that other
67018     ** connections to the same database will know to reread the schema.
67019     */
67020     static const unsigned char aCopy[] = {
67021        1, 1,    /* Add one to the old schema cookie */
67022        3, 0,    /* Preserve the default page cache size */
67023        5, 0,    /* Preserve the default text encoding */
67024        6, 0,    /* Preserve the user version */
67025     };
67026
67027     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
67028     assert( 1==sqlite3BtreeIsInTrans(pMain) );
67029
67030     /* Copy Btree meta values */
67031     for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
67032       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
67033       if( rc!=SQLITE_OK ) goto end_of_vacuum;
67034       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
67035       if( rc!=SQLITE_OK ) goto end_of_vacuum;
67036     }
67037
67038     rc = sqlite3BtreeCopyFile(pMain, pTemp);
67039     if( rc!=SQLITE_OK ) goto end_of_vacuum;
67040     rc = sqlite3BtreeCommit(pTemp);
67041     if( rc!=SQLITE_OK ) goto end_of_vacuum;
67042     rc = sqlite3BtreeCommit(pMain);
67043   }
67044
67045 end_of_vacuum:
67046   /* Restore the original value of db->flags */
67047   db->flags = saved_flags;
67048
67049   /* Currently there is an SQL level transaction open on the vacuum
67050   ** database. No locks are held on any other files (since the main file
67051   ** was committed at the btree level). So it safe to end the transaction
67052   ** by manually setting the autoCommit flag to true and detaching the
67053   ** vacuum database. The vacuum_db journal file is deleted when the pager
67054   ** is closed by the DETACH.
67055   */
67056   db->autoCommit = 1;
67057
67058   if( pDb ){
67059     sqlite3BtreeClose(pDb->pBt);
67060     pDb->pBt = 0;
67061     pDb->pSchema = 0;
67062   }
67063
67064   sqlite3ResetInternalSchema(db, 0);
67065
67066   return rc;
67067 }
67068 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
67069
67070 /************** End of vacuum.c **********************************************/
67071 /************** Begin file vtab.c ********************************************/
67072 /*
67073 ** 2006 June 10
67074 **
67075 ** The author disclaims copyright to this source code.  In place of
67076 ** a legal notice, here is a blessing:
67077 **
67078 **    May you do good and not evil.
67079 **    May you find forgiveness for yourself and forgive others.
67080 **    May you share freely, never taking more than you give.
67081 **
67082 *************************************************************************
67083 ** This file contains code used to help implement virtual tables.
67084 **
67085 ** $Id: vtab.c,v 1.65 2008/03/06 09:58:50 mlcreech Exp $
67086 */
67087 #ifndef SQLITE_OMIT_VIRTUALTABLE
67088
67089 static int createModule(
67090   sqlite3 *db,                    /* Database in which module is registered */
67091   const char *zName,              /* Name assigned to this module */
67092   const sqlite3_module *pModule,  /* The definition of the module */
67093   void *pAux,                     /* Context pointer for xCreate/xConnect */
67094   void (*xDestroy)(void *)        /* Module destructor function */
67095 ) {
67096   int rc, nName;
67097   Module *pMod;
67098
67099   sqlite3_mutex_enter(db->mutex);
67100   nName = strlen(zName);
67101   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
67102   if( pMod ){
67103     char *zCopy = (char *)(&pMod[1]);
67104     memcpy(zCopy, zName, nName+1);
67105     pMod->zName = zCopy;
67106     pMod->pModule = pModule;
67107     pMod->pAux = pAux;
67108     pMod->xDestroy = xDestroy;
67109     pMod = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
67110     if( pMod && pMod->xDestroy ){
67111       pMod->xDestroy(pMod->pAux);
67112     }
67113     sqlite3_free(pMod);
67114     sqlite3ResetInternalSchema(db, 0);
67115   }
67116   rc = sqlite3ApiExit(db, SQLITE_OK);
67117   sqlite3_mutex_leave(db->mutex);
67118   return rc;
67119 }
67120
67121
67122 /*
67123 ** External API function used to create a new virtual-table module.
67124 */
67125 SQLITE_API int sqlite3_create_module(
67126   sqlite3 *db,                    /* Database in which module is registered */
67127   const char *zName,              /* Name assigned to this module */
67128   const sqlite3_module *pModule,  /* The definition of the module */
67129   void *pAux                      /* Context pointer for xCreate/xConnect */
67130 ){
67131   return createModule(db, zName, pModule, pAux, 0);
67132 }
67133
67134 /*
67135 ** External API function used to create a new virtual-table module.
67136 */
67137 SQLITE_API int sqlite3_create_module_v2(
67138   sqlite3 *db,                    /* Database in which module is registered */
67139   const char *zName,              /* Name assigned to this module */
67140   const sqlite3_module *pModule,  /* The definition of the module */
67141   void *pAux,                     /* Context pointer for xCreate/xConnect */
67142   void (*xDestroy)(void *)        /* Module destructor function */
67143 ){
67144   return createModule(db, zName, pModule, pAux, xDestroy);
67145 }
67146
67147 /*
67148 ** Lock the virtual table so that it cannot be disconnected.
67149 ** Locks nest.  Every lock should have a corresponding unlock.
67150 ** If an unlock is omitted, resources leaks will occur.  
67151 **
67152 ** If a disconnect is attempted while a virtual table is locked,
67153 ** the disconnect is deferred until all locks have been removed.
67154 */
67155 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
67156   pVtab->nRef++;
67157 }
67158
67159 /*
67160 ** Unlock a virtual table.  When the last lock is removed,
67161 ** disconnect the virtual table.
67162 */
67163 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
67164   pVtab->nRef--;
67165   assert(db);
67166   assert( sqlite3SafetyCheckOk(db) );
67167   if( pVtab->nRef==0 ){
67168     if( db->magic==SQLITE_MAGIC_BUSY ){
67169       (void)sqlite3SafetyOff(db);
67170       pVtab->pModule->xDisconnect(pVtab);
67171       (void)sqlite3SafetyOn(db);
67172     } else {
67173       pVtab->pModule->xDisconnect(pVtab);
67174     }
67175   }
67176 }
67177
67178 /*
67179 ** Clear any and all virtual-table information from the Table record.
67180 ** This routine is called, for example, just before deleting the Table
67181 ** record.
67182 */
67183 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
67184   sqlite3_vtab *pVtab = p->pVtab;
67185   if( pVtab ){
67186     assert( p->pMod && p->pMod->pModule );
67187     sqlite3VtabUnlock(p->pSchema->db, pVtab);
67188     p->pVtab = 0;
67189   }
67190   if( p->azModuleArg ){
67191     int i;
67192     for(i=0; i<p->nModuleArg; i++){
67193       sqlite3_free(p->azModuleArg[i]);
67194     }
67195     sqlite3_free(p->azModuleArg);
67196   }
67197 }
67198
67199 /*
67200 ** Add a new module argument to pTable->azModuleArg[].
67201 ** The string is not copied - the pointer is stored.  The
67202 ** string will be freed automatically when the table is
67203 ** deleted.
67204 */
67205 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
67206   int i = pTable->nModuleArg++;
67207   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
67208   char **azModuleArg;
67209   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
67210   if( azModuleArg==0 ){
67211     int j;
67212     for(j=0; j<i; j++){
67213       sqlite3_free(pTable->azModuleArg[j]);
67214     }
67215     sqlite3_free(zArg);
67216     sqlite3_free(pTable->azModuleArg);
67217     pTable->nModuleArg = 0;
67218   }else{
67219     azModuleArg[i] = zArg;
67220     azModuleArg[i+1] = 0;
67221   }
67222   pTable->azModuleArg = azModuleArg;
67223 }
67224
67225 /*
67226 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
67227 ** statement.  The module name has been parsed, but the optional list
67228 ** of parameters that follow the module name are still pending.
67229 */
67230 SQLITE_PRIVATE void sqlite3VtabBeginParse(
67231   Parse *pParse,        /* Parsing context */
67232   Token *pName1,        /* Name of new table, or database name */
67233   Token *pName2,        /* Name of new table or NULL */
67234   Token *pModuleName    /* Name of the module for the virtual table */
67235 ){
67236   int iDb;              /* The database the table is being created in */
67237   Table *pTable;        /* The new virtual table */
67238   sqlite3 *db;          /* Database connection */
67239
67240   if( pParse->db->flags & SQLITE_SharedCache ){
67241     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
67242     return;
67243   }
67244
67245   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
67246   pTable = pParse->pNewTable;
67247   if( pTable==0 || pParse->nErr ) return;
67248   assert( 0==pTable->pIndex );
67249
67250   db = pParse->db;
67251   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
67252   assert( iDb>=0 );
67253
67254   pTable->isVirtual = 1;
67255   pTable->nModuleArg = 0;
67256   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
67257   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
67258   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
67259   pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
67260
67261 #ifndef SQLITE_OMIT_AUTHORIZATION
67262   /* Creating a virtual table invokes the authorization callback twice.
67263   ** The first invocation, to obtain permission to INSERT a row into the
67264   ** sqlite_master table, has already been made by sqlite3StartTable().
67265   ** The second call, to obtain permission to create the table, is made now.
67266   */
67267   if( pTable->azModuleArg ){
67268     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
67269             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
67270   }
67271 #endif
67272 }
67273
67274 /*
67275 ** This routine takes the module argument that has been accumulating
67276 ** in pParse->zArg[] and appends it to the list of arguments on the
67277 ** virtual table currently under construction in pParse->pTable.
67278 */
67279 static void addArgumentToVtab(Parse *pParse){
67280   if( pParse->sArg.z && pParse->pNewTable ){
67281     const char *z = (const char*)pParse->sArg.z;
67282     int n = pParse->sArg.n;
67283     sqlite3 *db = pParse->db;
67284     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
67285   }
67286 }
67287
67288 /*
67289 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
67290 ** has been completely parsed.
67291 */
67292 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
67293   Table *pTab;        /* The table being constructed */
67294   sqlite3 *db;        /* The database connection */
67295   char *zModule;      /* The module name of the table: USING modulename */
67296   Module *pMod = 0;
67297
67298   addArgumentToVtab(pParse);
67299   pParse->sArg.z = 0;
67300
67301   /* Lookup the module name. */
67302   pTab = pParse->pNewTable;
67303   if( pTab==0 ) return;
67304   db = pParse->db;
67305   if( pTab->nModuleArg<1 ) return;
67306   zModule = pTab->azModuleArg[0];
67307   pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
67308   pTab->pMod = pMod;
67309   
67310   /* If the CREATE VIRTUAL TABLE statement is being entered for the
67311   ** first time (in other words if the virtual table is actually being
67312   ** created now instead of just being read out of sqlite_master) then
67313   ** do additional initialization work and store the statement text
67314   ** in the sqlite_master table.
67315   */
67316   if( !db->init.busy ){
67317     char *zStmt;
67318     char *zWhere;
67319     int iDb;
67320     Vdbe *v;
67321
67322     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
67323     if( pEnd ){
67324       pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
67325     }
67326     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
67327
67328     /* A slot for the record has already been allocated in the 
67329     ** SQLITE_MASTER table.  We just need to update that slot with all
67330     ** the information we've collected.  
67331     **
67332     ** The VM register number pParse->regRowid holds the rowid of an
67333     ** entry in the sqlite_master table tht was created for this vtab
67334     ** by sqlite3StartTable().
67335     */
67336     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
67337     sqlite3NestedParse(pParse,
67338       "UPDATE %Q.%s "
67339          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
67340        "WHERE rowid=#%d",
67341       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
67342       pTab->zName,
67343       pTab->zName,
67344       zStmt,
67345       pParse->regRowid
67346     );
67347     sqlite3_free(zStmt);
67348     v = sqlite3GetVdbe(pParse);
67349     sqlite3ChangeCookie(pParse, iDb);
67350
67351     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
67352     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
67353     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
67354     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
67355                          pTab->zName, strlen(pTab->zName) + 1);
67356   }
67357
67358   /* If we are rereading the sqlite_master table create the in-memory
67359   ** record of the table. If the module has already been registered,
67360   ** also call the xConnect method here.
67361   */
67362   else {
67363     Table *pOld;
67364     Schema *pSchema = pTab->pSchema;
67365     const char *zName = pTab->zName;
67366     int nName = strlen(zName) + 1;
67367     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
67368     if( pOld ){
67369       db->mallocFailed = 1;
67370       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
67371       return;
67372     }
67373     pSchema->db = pParse->db;
67374     pParse->pNewTable = 0;
67375   }
67376 }
67377
67378 /*
67379 ** The parser calls this routine when it sees the first token
67380 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
67381 */
67382 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
67383   addArgumentToVtab(pParse);
67384   pParse->sArg.z = 0;
67385   pParse->sArg.n = 0;
67386 }
67387
67388 /*
67389 ** The parser calls this routine for each token after the first token
67390 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
67391 */
67392 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
67393   Token *pArg = &pParse->sArg;
67394   if( pArg->z==0 ){
67395     pArg->z = p->z;
67396     pArg->n = p->n;
67397   }else{
67398     assert(pArg->z < p->z);
67399     pArg->n = (p->z + p->n - pArg->z);
67400   }
67401 }
67402
67403 /*
67404 ** Invoke a virtual table constructor (either xCreate or xConnect). The
67405 ** pointer to the function to invoke is passed as the fourth parameter
67406 ** to this procedure.
67407 */
67408 static int vtabCallConstructor(
67409   sqlite3 *db, 
67410   Table *pTab,
67411   Module *pMod,
67412   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
67413   char **pzErr
67414 ){
67415   int rc;
67416   int rc2;
67417   sqlite3_vtab *pVtab = 0;
67418   const char *const*azArg = (const char *const*)pTab->azModuleArg;
67419   int nArg = pTab->nModuleArg;
67420   char *zErr = 0;
67421   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
67422
67423   if( !zModuleName ){
67424     return SQLITE_NOMEM;
67425   }
67426
67427   assert( !db->pVTab );
67428   assert( xConstruct );
67429
67430   db->pVTab = pTab;
67431   rc = sqlite3SafetyOff(db);
67432   assert( rc==SQLITE_OK );
67433   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
67434   rc2 = sqlite3SafetyOn(db);
67435   if( rc==SQLITE_OK && pVtab ){
67436     pVtab->pModule = pMod->pModule;
67437     pVtab->nRef = 1;
67438     pTab->pVtab = pVtab;
67439   }
67440
67441   if( SQLITE_OK!=rc ){
67442     if( zErr==0 ){
67443       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
67444     }else {
67445       *pzErr = sqlite3MPrintf(db, "%s", zErr);
67446       sqlite3_free(zErr);
67447     }
67448   }else if( db->pVTab ){
67449     const char *zFormat = "vtable constructor did not declare schema: %s";
67450     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
67451     rc = SQLITE_ERROR;
67452   } 
67453   if( rc==SQLITE_OK ){
67454     rc = rc2;
67455   }
67456   db->pVTab = 0;
67457   sqlite3_free(zModuleName);
67458
67459   /* If everything went according to plan, loop through the columns
67460   ** of the table to see if any of them contain the token "hidden".
67461   ** If so, set the Column.isHidden flag and remove the token from
67462   ** the type string.
67463   */
67464   if( rc==SQLITE_OK ){
67465     int iCol;
67466     for(iCol=0; iCol<pTab->nCol; iCol++){
67467       char *zType = pTab->aCol[iCol].zType;
67468       int nType;
67469       int i = 0;
67470       if( !zType ) continue;
67471       nType = strlen(zType);
67472       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
67473         for(i=0; i<nType; i++){
67474           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
67475            && (zType[i+7]=='\0' || zType[i+7]==' ')
67476           ){
67477             i++;
67478             break;
67479           }
67480         }
67481       }
67482       if( i<nType ){
67483         int j;
67484         int nDel = 6 + (zType[i+6] ? 1 : 0);
67485         for(j=i; (j+nDel)<=nType; j++){
67486           zType[j] = zType[j+nDel];
67487         }
67488         if( zType[i]=='\0' && i>0 ){
67489           assert(zType[i-1]==' ');
67490           zType[i-1] = '\0';
67491         }
67492         pTab->aCol[iCol].isHidden = 1;
67493       }
67494     }
67495   }
67496   return rc;
67497 }
67498
67499 /*
67500 ** This function is invoked by the parser to call the xConnect() method
67501 ** of the virtual table pTab. If an error occurs, an error code is returned 
67502 ** and an error left in pParse.
67503 **
67504 ** This call is a no-op if table pTab is not a virtual table.
67505 */
67506 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
67507   Module *pMod;
67508   int rc = SQLITE_OK;
67509
67510   if( !pTab || !pTab->isVirtual || pTab->pVtab ){
67511     return SQLITE_OK;
67512   }
67513
67514   pMod = pTab->pMod;
67515   if( !pMod ){
67516     const char *zModule = pTab->azModuleArg[0];
67517     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
67518     rc = SQLITE_ERROR;
67519   } else {
67520     char *zErr = 0;
67521     sqlite3 *db = pParse->db;
67522     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
67523     if( rc!=SQLITE_OK ){
67524       sqlite3ErrorMsg(pParse, "%s", zErr);
67525     }
67526     sqlite3_free(zErr);
67527   }
67528
67529   return rc;
67530 }
67531
67532 /*
67533 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
67534 */
67535 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
67536   const int ARRAY_INCR = 5;
67537
67538   /* Grow the sqlite3.aVTrans array if required */
67539   if( (db->nVTrans%ARRAY_INCR)==0 ){
67540     sqlite3_vtab **aVTrans;
67541     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
67542     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
67543     if( !aVTrans ){
67544       return SQLITE_NOMEM;
67545     }
67546     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
67547     db->aVTrans = aVTrans;
67548   }
67549
67550   /* Add pVtab to the end of sqlite3.aVTrans */
67551   db->aVTrans[db->nVTrans++] = pVtab;
67552   sqlite3VtabLock(pVtab);
67553   return SQLITE_OK;
67554 }
67555
67556 /*
67557 ** This function is invoked by the vdbe to call the xCreate method
67558 ** of the virtual table named zTab in database iDb. 
67559 **
67560 ** If an error occurs, *pzErr is set to point an an English language
67561 ** description of the error and an SQLITE_XXX error code is returned.
67562 ** In this case the caller must call sqlite3_free() on *pzErr.
67563 */
67564 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
67565   int rc = SQLITE_OK;
67566   Table *pTab;
67567   Module *pMod;
67568   const char *zModule;
67569
67570   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
67571   assert(pTab && pTab->isVirtual && !pTab->pVtab);
67572   pMod = pTab->pMod;
67573   zModule = pTab->azModuleArg[0];
67574
67575   /* If the module has been registered and includes a Create method, 
67576   ** invoke it now. If the module has not been registered, return an 
67577   ** error. Otherwise, do nothing.
67578   */
67579   if( !pMod ){
67580     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
67581     rc = SQLITE_ERROR;
67582   }else{
67583     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
67584   }
67585
67586   if( rc==SQLITE_OK && pTab->pVtab ){
67587       rc = addToVTrans(db, pTab->pVtab);
67588   }
67589
67590   return rc;
67591 }
67592
67593 /*
67594 ** This function is used to set the schema of a virtual table.  It is only
67595 ** valid to call this function from within the xCreate() or xConnect() of a
67596 ** virtual table module.
67597 */
67598 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
67599   Parse sParse;
67600
67601   int rc = SQLITE_OK;
67602   Table *pTab;
67603   char *zErr = 0;
67604
67605   sqlite3_mutex_enter(db->mutex);
67606   pTab = db->pVTab;
67607   if( !pTab ){
67608     sqlite3Error(db, SQLITE_MISUSE, 0);
67609     sqlite3_mutex_leave(db->mutex);
67610     return SQLITE_MISUSE;
67611   }
67612   assert(pTab->isVirtual && pTab->nCol==0 && pTab->aCol==0);
67613
67614   memset(&sParse, 0, sizeof(Parse));
67615   sParse.declareVtab = 1;
67616   sParse.db = db;
67617
67618   if( 
67619       SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) && 
67620       sParse.pNewTable && 
67621       !sParse.pNewTable->pSelect && 
67622       !sParse.pNewTable->isVirtual 
67623   ){
67624     pTab->aCol = sParse.pNewTable->aCol;
67625     pTab->nCol = sParse.pNewTable->nCol;
67626     sParse.pNewTable->nCol = 0;
67627     sParse.pNewTable->aCol = 0;
67628     db->pVTab = 0;
67629   } else {
67630     sqlite3Error(db, SQLITE_ERROR, zErr);
67631     sqlite3_free(zErr);
67632     rc = SQLITE_ERROR;
67633   }
67634   sParse.declareVtab = 0;
67635
67636   sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
67637   sqlite3DeleteTable(sParse.pNewTable);
67638   sParse.pNewTable = 0;
67639
67640   assert( (rc&0xff)==rc );
67641   rc = sqlite3ApiExit(db, rc);
67642   sqlite3_mutex_leave(db->mutex);
67643   return rc;
67644 }
67645
67646 /*
67647 ** This function is invoked by the vdbe to call the xDestroy method
67648 ** of the virtual table named zTab in database iDb. This occurs
67649 ** when a DROP TABLE is mentioned.
67650 **
67651 ** This call is a no-op if zTab is not a virtual table.
67652 */
67653 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
67654 {
67655   int rc = SQLITE_OK;
67656   Table *pTab;
67657
67658   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
67659   assert(pTab);
67660   if( pTab->pVtab ){
67661     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
67662     rc = sqlite3SafetyOff(db);
67663     assert( rc==SQLITE_OK );
67664     if( xDestroy ){
67665       rc = xDestroy(pTab->pVtab);
67666     }
67667     (void)sqlite3SafetyOn(db);
67668     if( rc==SQLITE_OK ){
67669       pTab->pVtab = 0;
67670     }
67671   }
67672
67673   return rc;
67674 }
67675
67676 /*
67677 ** This function invokes either the xRollback or xCommit method
67678 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
67679 ** called is identified by the second argument, "offset", which is
67680 ** the offset of the method to call in the sqlite3_module structure.
67681 **
67682 ** The array is cleared after invoking the callbacks. 
67683 */
67684 static void callFinaliser(sqlite3 *db, sqlite3_intptr_t offset){
67685   int i;
67686   if( db->aVTrans ){
67687     for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
67688       sqlite3_vtab *pVtab = db->aVTrans[i];
67689       int (*x)(sqlite3_vtab *);
67690       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
67691       if( x ) x(pVtab);
67692       sqlite3VtabUnlock(db, pVtab);
67693     }
67694     sqlite3_free(db->aVTrans);
67695     db->nVTrans = 0;
67696     db->aVTrans = 0;
67697   }
67698 }
67699
67700 /*
67701 ** If argument rc2 is not SQLITE_OK, then return it and do nothing. 
67702 ** Otherwise, invoke the xSync method of all virtual tables in the 
67703 ** sqlite3.aVTrans array. Return the error code for the first error 
67704 ** that occurs, or SQLITE_OK if all xSync operations are successful.
67705 */
67706 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, int rc2){
67707   int i;
67708   int rc = SQLITE_OK;
67709   int rcsafety;
67710   sqlite3_vtab **aVTrans = db->aVTrans;
67711   if( rc2!=SQLITE_OK ) return rc2;
67712
67713   rc = sqlite3SafetyOff(db);
67714   db->aVTrans = 0;
67715   for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
67716     sqlite3_vtab *pVtab = aVTrans[i];
67717     int (*x)(sqlite3_vtab *);
67718     x = pVtab->pModule->xSync;
67719     if( x ){
67720       rc = x(pVtab);
67721     }
67722   }
67723   db->aVTrans = aVTrans;
67724   rcsafety = sqlite3SafetyOn(db);
67725
67726   if( rc==SQLITE_OK ){
67727     rc = rcsafety;
67728   }
67729   return rc;
67730 }
67731
67732 /*
67733 ** Invoke the xRollback method of all virtual tables in the 
67734 ** sqlite3.aVTrans array. Then clear the array itself.
67735 */
67736 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
67737   callFinaliser(db, (sqlite3_intptr_t)(&((sqlite3_module *)0)->xRollback));
67738   return SQLITE_OK;
67739 }
67740
67741 /*
67742 ** Invoke the xCommit method of all virtual tables in the 
67743 ** sqlite3.aVTrans array. Then clear the array itself.
67744 */
67745 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
67746   callFinaliser(db, (sqlite3_intptr_t)(&((sqlite3_module *)0)->xCommit));
67747   return SQLITE_OK;
67748 }
67749
67750 /*
67751 ** If the virtual table pVtab supports the transaction interface
67752 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
67753 ** not currently open, invoke the xBegin method now.
67754 **
67755 ** If the xBegin call is successful, place the sqlite3_vtab pointer
67756 ** in the sqlite3.aVTrans array.
67757 */
67758 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
67759   int rc = SQLITE_OK;
67760   const sqlite3_module *pModule;
67761
67762   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
67763   ** than zero, then this function is being called from within a
67764   ** virtual module xSync() callback. It is illegal to write to 
67765   ** virtual module tables in this case, so return SQLITE_LOCKED.
67766   */
67767   if( 0==db->aVTrans && db->nVTrans>0 ){
67768     return SQLITE_LOCKED;
67769   }
67770   if( !pVtab ){
67771     return SQLITE_OK;
67772   } 
67773   pModule = pVtab->pModule;
67774
67775   if( pModule->xBegin ){
67776     int i;
67777
67778
67779     /* If pVtab is already in the aVTrans array, return early */
67780     for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
67781       if( db->aVTrans[i]==pVtab ){
67782         return SQLITE_OK;
67783       }
67784     }
67785
67786     /* Invoke the xBegin method */
67787     rc = pModule->xBegin(pVtab);
67788     if( rc!=SQLITE_OK ){
67789       return rc;
67790     }
67791
67792     rc = addToVTrans(db, pVtab);
67793   }
67794   return rc;
67795 }
67796
67797 /*
67798 ** The first parameter (pDef) is a function implementation.  The
67799 ** second parameter (pExpr) is the first argument to this function.
67800 ** If pExpr is a column in a virtual table, then let the virtual
67801 ** table implementation have an opportunity to overload the function.
67802 **
67803 ** This routine is used to allow virtual table implementations to
67804 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
67805 **
67806 ** Return either the pDef argument (indicating no change) or a 
67807 ** new FuncDef structure that is marked as ephemeral using the
67808 ** SQLITE_FUNC_EPHEM flag.
67809 */
67810 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
67811   sqlite3 *db,    /* Database connection for reporting malloc problems */
67812   FuncDef *pDef,  /* Function to possibly overload */
67813   int nArg,       /* Number of arguments to the function */
67814   Expr *pExpr     /* First argument to the function */
67815 ){
67816   Table *pTab;
67817   sqlite3_vtab *pVtab;
67818   sqlite3_module *pMod;
67819   void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
67820   void *pArg;
67821   FuncDef *pNew;
67822   int rc = 0;
67823   char *zLowerName;
67824   unsigned char *z;
67825
67826
67827   /* Check to see the left operand is a column in a virtual table */
67828   if( pExpr==0 ) return pDef;
67829   if( pExpr->op!=TK_COLUMN ) return pDef;
67830   pTab = pExpr->pTab;
67831   if( pTab==0 ) return pDef;
67832   if( !pTab->isVirtual ) return pDef;
67833   pVtab = pTab->pVtab;
67834   assert( pVtab!=0 );
67835   assert( pVtab->pModule!=0 );
67836   pMod = (sqlite3_module *)pVtab->pModule;
67837   if( pMod->xFindFunction==0 ) return pDef;
67838  
67839   /* Call the xFindFunction method on the virtual table implementation
67840   ** to see if the implementation wants to overload this function 
67841   */
67842   zLowerName = sqlite3DbStrDup(db, pDef->zName);
67843   if( zLowerName ){
67844     for(z=(unsigned char*)zLowerName; *z; z++){
67845       *z = sqlite3UpperToLower[*z];
67846     }
67847     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
67848     sqlite3_free(zLowerName);
67849   }
67850   if( rc==0 ){
67851     return pDef;
67852   }
67853
67854   /* Create a new ephemeral function definition for the overloaded
67855   ** function */
67856   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + strlen(pDef->zName) );
67857   if( pNew==0 ){
67858     return pDef;
67859   }
67860   *pNew = *pDef;
67861   memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
67862   pNew->xFunc = xFunc;
67863   pNew->pUserData = pArg;
67864   pNew->flags |= SQLITE_FUNC_EPHEM;
67865   return pNew;
67866 }
67867
67868 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67869
67870 /************** End of vtab.c ************************************************/
67871 /************** Begin file where.c *******************************************/
67872 /*
67873 ** 2001 September 15
67874 **
67875 ** The author disclaims copyright to this source code.  In place of
67876 ** a legal notice, here is a blessing:
67877 **
67878 **    May you do good and not evil.
67879 **    May you find forgiveness for yourself and forgive others.
67880 **    May you share freely, never taking more than you give.
67881 **
67882 *************************************************************************
67883 ** This module contains C code that generates VDBE code used to process
67884 ** the WHERE clause of SQL statements.  This module is reponsible for
67885 ** generating the code that loops through a table looking for applicable
67886 ** rows.  Indices are selected and used to speed the search when doing
67887 ** so is applicable.  Because this module is responsible for selecting
67888 ** indices, you might also think of this module as the "query optimizer".
67889 **
67890 ** $Id: where.c,v 1.290 2008/03/17 17:08:33 drh Exp $
67891 */
67892
67893 /*
67894 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
67895 */
67896 #define BMS  (sizeof(Bitmask)*8)
67897
67898 /*
67899 ** Trace output macros
67900 */
67901 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
67902 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
67903 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
67904 #else
67905 # define WHERETRACE(X)
67906 #endif
67907
67908 /* Forward reference
67909 */
67910 typedef struct WhereClause WhereClause;
67911 typedef struct ExprMaskSet ExprMaskSet;
67912
67913 /*
67914 ** The query generator uses an array of instances of this structure to
67915 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
67916 ** clause subexpression is separated from the others by an AND operator.
67917 **
67918 ** All WhereTerms are collected into a single WhereClause structure.  
67919 ** The following identity holds:
67920 **
67921 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
67922 **
67923 ** When a term is of the form:
67924 **
67925 **              X <op> <expr>
67926 **
67927 ** where X is a column name and <op> is one of certain operators,
67928 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
67929 ** cursor number and column number for X.  WhereTerm.operator records
67930 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
67931 ** use of a bitmask encoding for the operator allows us to search
67932 ** quickly for terms that match any of several different operators.
67933 **
67934 ** prereqRight and prereqAll record sets of cursor numbers,
67935 ** but they do so indirectly.  A single ExprMaskSet structure translates
67936 ** cursor number into bits and the translated bit is stored in the prereq
67937 ** fields.  The translation is used in order to maximize the number of
67938 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
67939 ** spread out over the non-negative integers.  For example, the cursor
67940 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
67941 ** translates these sparse cursor numbers into consecutive integers
67942 ** beginning with 0 in order to make the best possible use of the available
67943 ** bits in the Bitmask.  So, in the example above, the cursor numbers
67944 ** would be mapped into integers 0 through 7.
67945 */
67946 typedef struct WhereTerm WhereTerm;
67947 struct WhereTerm {
67948   Expr *pExpr;            /* Pointer to the subexpression */
67949   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
67950   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
67951   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
67952   u16 eOperator;          /* A WO_xx value describing <op> */
67953   u8 flags;               /* Bit flags.  See below */
67954   u8 nChild;              /* Number of children that must disable us */
67955   WhereClause *pWC;       /* The clause this term is part of */
67956   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
67957   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
67958 };
67959
67960 /*
67961 ** Allowed values of WhereTerm.flags
67962 */
67963 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(pExpr) */
67964 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
67965 #define TERM_CODED      0x04   /* This term is already coded */
67966 #define TERM_COPIED     0x08   /* Has a child */
67967 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
67968
67969 /*
67970 ** An instance of the following structure holds all information about a
67971 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
67972 */
67973 struct WhereClause {
67974   Parse *pParse;           /* The parser context */
67975   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
67976   int nTerm;               /* Number of terms */
67977   int nSlot;               /* Number of entries in a[] */
67978   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
67979   WhereTerm aStatic[10];   /* Initial static space for a[] */
67980 };
67981
67982 /*
67983 ** An instance of the following structure keeps track of a mapping
67984 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
67985 **
67986 ** The VDBE cursor numbers are small integers contained in 
67987 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
67988 ** clause, the cursor numbers might not begin with 0 and they might
67989 ** contain gaps in the numbering sequence.  But we want to make maximum
67990 ** use of the bits in our bitmasks.  This structure provides a mapping
67991 ** from the sparse cursor numbers into consecutive integers beginning
67992 ** with 0.
67993 **
67994 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
67995 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
67996 **
67997 ** For example, if the WHERE clause expression used these VDBE
67998 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
67999 ** would map those cursor numbers into bits 0 through 5.
68000 **
68001 ** Note that the mapping is not necessarily ordered.  In the example
68002 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
68003 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
68004 ** does not really matter.  What is important is that sparse cursor
68005 ** numbers all get mapped into bit numbers that begin with 0 and contain
68006 ** no gaps.
68007 */
68008 struct ExprMaskSet {
68009   int n;                        /* Number of assigned cursor values */
68010   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
68011 };
68012
68013
68014 /*
68015 ** Bitmasks for the operators that indices are able to exploit.  An
68016 ** OR-ed combination of these values can be used when searching for
68017 ** terms in the where clause.
68018 */
68019 #define WO_IN     1
68020 #define WO_EQ     2
68021 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
68022 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
68023 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
68024 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
68025 #define WO_MATCH  64
68026 #define WO_ISNULL 128
68027
68028 /*
68029 ** Value for flags returned by bestIndex().  
68030 **
68031 ** The least significant byte is reserved as a mask for WO_ values above.
68032 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
68033 ** But if the table is the right table of a left join, WhereLevel.flags
68034 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
68035 ** the "op" parameter to findTerm when we are resolving equality constraints.
68036 ** ISNULL constraints will then not be used on the right table of a left
68037 ** join.  Tickets #2177 and #2189.
68038 */
68039 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
68040 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
68041 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
68042 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
68043 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
68044 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
68045 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
68046 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
68047 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
68048 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
68049 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
68050 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
68051
68052 /*
68053 ** Initialize a preallocated WhereClause structure.
68054 */
68055 static void whereClauseInit(
68056   WhereClause *pWC,        /* The WhereClause to be initialized */
68057   Parse *pParse,           /* The parsing context */
68058   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
68059 ){
68060   pWC->pParse = pParse;
68061   pWC->pMaskSet = pMaskSet;
68062   pWC->nTerm = 0;
68063   pWC->nSlot = ArraySize(pWC->aStatic);
68064   pWC->a = pWC->aStatic;
68065 }
68066
68067 /*
68068 ** Deallocate a WhereClause structure.  The WhereClause structure
68069 ** itself is not freed.  This routine is the inverse of whereClauseInit().
68070 */
68071 static void whereClauseClear(WhereClause *pWC){
68072   int i;
68073   WhereTerm *a;
68074   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
68075     if( a->flags & TERM_DYNAMIC ){
68076       sqlite3ExprDelete(a->pExpr);
68077     }
68078   }
68079   if( pWC->a!=pWC->aStatic ){
68080     sqlite3_free(pWC->a);
68081   }
68082 }
68083
68084 /*
68085 ** Add a new entries to the WhereClause structure.  Increase the allocated
68086 ** space as necessary.
68087 **
68088 ** If the flags argument includes TERM_DYNAMIC, then responsibility
68089 ** for freeing the expression p is assumed by the WhereClause object.
68090 **
68091 ** WARNING:  This routine might reallocate the space used to store
68092 ** WhereTerms.  All pointers to WhereTerms should be invalided after
68093 ** calling this routine.  Such pointers may be reinitialized by referencing
68094 ** the pWC->a[] array.
68095 */
68096 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
68097   WhereTerm *pTerm;
68098   int idx;
68099   if( pWC->nTerm>=pWC->nSlot ){
68100     WhereTerm *pOld = pWC->a;
68101     pWC->a = sqlite3_malloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
68102     if( pWC->a==0 ){
68103       pWC->pParse->db->mallocFailed = 1;
68104       if( flags & TERM_DYNAMIC ){
68105         sqlite3ExprDelete(p);
68106       }
68107       pWC->a = pOld;
68108       return 0;
68109     }
68110     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
68111     if( pOld!=pWC->aStatic ){
68112       sqlite3_free(pOld);
68113     }
68114     pWC->nSlot *= 2;
68115   }
68116   pTerm = &pWC->a[idx = pWC->nTerm];
68117   pWC->nTerm++;
68118   pTerm->pExpr = p;
68119   pTerm->flags = flags;
68120   pTerm->pWC = pWC;
68121   pTerm->iParent = -1;
68122   return idx;
68123 }
68124
68125 /*
68126 ** This routine identifies subexpressions in the WHERE clause where
68127 ** each subexpression is separated by the AND operator or some other
68128 ** operator specified in the op parameter.  The WhereClause structure
68129 ** is filled with pointers to subexpressions.  For example:
68130 **
68131 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
68132 **           \________/     \_______________/     \________________/
68133 **            slot[0]            slot[1]               slot[2]
68134 **
68135 ** The original WHERE clause in pExpr is unaltered.  All this routine
68136 ** does is make slot[] entries point to substructure within pExpr.
68137 **
68138 ** In the previous sentence and in the diagram, "slot[]" refers to
68139 ** the WhereClause.a[] array.  This array grows as needed to contain
68140 ** all terms of the WHERE clause.
68141 */
68142 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
68143   if( pExpr==0 ) return;
68144   if( pExpr->op!=op ){
68145     whereClauseInsert(pWC, pExpr, 0);
68146   }else{
68147     whereSplit(pWC, pExpr->pLeft, op);
68148     whereSplit(pWC, pExpr->pRight, op);
68149   }
68150 }
68151
68152 /*
68153 ** Initialize an expression mask set
68154 */
68155 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
68156
68157 /*
68158 ** Return the bitmask for the given cursor number.  Return 0 if
68159 ** iCursor is not in the set.
68160 */
68161 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
68162   int i;
68163   for(i=0; i<pMaskSet->n; i++){
68164     if( pMaskSet->ix[i]==iCursor ){
68165       return ((Bitmask)1)<<i;
68166     }
68167   }
68168   return 0;
68169 }
68170
68171 /*
68172 ** Create a new mask for cursor iCursor.
68173 **
68174 ** There is one cursor per table in the FROM clause.  The number of
68175 ** tables in the FROM clause is limited by a test early in the
68176 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
68177 ** array will never overflow.
68178 */
68179 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
68180   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
68181   pMaskSet->ix[pMaskSet->n++] = iCursor;
68182 }
68183
68184 /*
68185 ** This routine walks (recursively) an expression tree and generates
68186 ** a bitmask indicating which tables are used in that expression
68187 ** tree.
68188 **
68189 ** In order for this routine to work, the calling function must have
68190 ** previously invoked sqlite3ExprResolveNames() on the expression.  See
68191 ** the header comment on that routine for additional information.
68192 ** The sqlite3ExprResolveNames() routines looks for column names and
68193 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
68194 ** the VDBE cursor number of the table.  This routine just has to
68195 ** translate the cursor numbers into bitmask values and OR all
68196 ** the bitmasks together.
68197 */
68198 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
68199 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
68200 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
68201   Bitmask mask = 0;
68202   if( p==0 ) return 0;
68203   if( p->op==TK_COLUMN ){
68204     mask = getMask(pMaskSet, p->iTable);
68205     return mask;
68206   }
68207   mask = exprTableUsage(pMaskSet, p->pRight);
68208   mask |= exprTableUsage(pMaskSet, p->pLeft);
68209   mask |= exprListTableUsage(pMaskSet, p->pList);
68210   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
68211   return mask;
68212 }
68213 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
68214   int i;
68215   Bitmask mask = 0;
68216   if( pList ){
68217     for(i=0; i<pList->nExpr; i++){
68218       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
68219     }
68220   }
68221   return mask;
68222 }
68223 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
68224   Bitmask mask = 0;
68225   while( pS ){
68226     mask |= exprListTableUsage(pMaskSet, pS->pEList);
68227     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
68228     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
68229     mask |= exprTableUsage(pMaskSet, pS->pWhere);
68230     mask |= exprTableUsage(pMaskSet, pS->pHaving);
68231     pS = pS->pPrior;
68232   }
68233   return mask;
68234 }
68235
68236 /*
68237 ** Return TRUE if the given operator is one of the operators that is
68238 ** allowed for an indexable WHERE clause term.  The allowed operators are
68239 ** "=", "<", ">", "<=", ">=", and "IN".
68240 */
68241 static int allowedOp(int op){
68242   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
68243   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
68244   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
68245   assert( TK_GE==TK_EQ+4 );
68246   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
68247 }
68248
68249 /*
68250 ** Swap two objects of type T.
68251 */
68252 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
68253
68254 /*
68255 ** Commute a comparision operator.  Expressions of the form "X op Y"
68256 ** are converted into "Y op X".
68257 **
68258 ** If a collation sequence is associated with either the left or right
68259 ** side of the comparison, it remains associated with the same side after
68260 ** the commutation. So "Y collate NOCASE op X" becomes 
68261 ** "X collate NOCASE op Y". This is because any collation sequence on
68262 ** the left hand side of a comparison overrides any collation sequence 
68263 ** attached to the right. For the same reason the EP_ExpCollate flag
68264 ** is not commuted.
68265 */
68266 static void exprCommute(Expr *pExpr){
68267   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
68268   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
68269   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
68270   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
68271   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
68272   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
68273   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
68274   if( pExpr->op>=TK_GT ){
68275     assert( TK_LT==TK_GT+2 );
68276     assert( TK_GE==TK_LE+2 );
68277     assert( TK_GT>TK_EQ );
68278     assert( TK_GT<TK_LE );
68279     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
68280     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
68281   }
68282 }
68283
68284 /*
68285 ** Translate from TK_xx operator to WO_xx bitmask.
68286 */
68287 static int operatorMask(int op){
68288   int c;
68289   assert( allowedOp(op) );
68290   if( op==TK_IN ){
68291     c = WO_IN;
68292   }else if( op==TK_ISNULL ){
68293     c = WO_ISNULL;
68294   }else{
68295     c = WO_EQ<<(op-TK_EQ);
68296   }
68297   assert( op!=TK_ISNULL || c==WO_ISNULL );
68298   assert( op!=TK_IN || c==WO_IN );
68299   assert( op!=TK_EQ || c==WO_EQ );
68300   assert( op!=TK_LT || c==WO_LT );
68301   assert( op!=TK_LE || c==WO_LE );
68302   assert( op!=TK_GT || c==WO_GT );
68303   assert( op!=TK_GE || c==WO_GE );
68304   return c;
68305 }
68306
68307 /*
68308 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
68309 ** where X is a reference to the iColumn of table iCur and <op> is one of
68310 ** the WO_xx operator codes specified by the op parameter.
68311 ** Return a pointer to the term.  Return 0 if not found.
68312 */
68313 static WhereTerm *findTerm(
68314   WhereClause *pWC,     /* The WHERE clause to be searched */
68315   int iCur,             /* Cursor number of LHS */
68316   int iColumn,          /* Column number of LHS */
68317   Bitmask notReady,     /* RHS must not overlap with this mask */
68318   u16 op,               /* Mask of WO_xx values describing operator */
68319   Index *pIdx           /* Must be compatible with this index, if not NULL */
68320 ){
68321   WhereTerm *pTerm;
68322   int k;
68323   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
68324     if( pTerm->leftCursor==iCur
68325        && (pTerm->prereqRight & notReady)==0
68326        && pTerm->leftColumn==iColumn
68327        && (pTerm->eOperator & op)!=0
68328     ){
68329       if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
68330         Expr *pX = pTerm->pExpr;
68331         CollSeq *pColl;
68332         char idxaff;
68333         int j;
68334         Parse *pParse = pWC->pParse;
68335
68336         idxaff = pIdx->pTable->aCol[iColumn].affinity;
68337         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
68338
68339         /* Figure out the collation sequence required from an index for
68340         ** it to be useful for optimising expression pX. Store this
68341         ** value in variable pColl.
68342         */
68343         assert(pX->pLeft);
68344         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
68345         if( !pColl ){
68346           pColl = pParse->db->pDfltColl;
68347         }
68348
68349         for(j=0; j<pIdx->nColumn && pIdx->aiColumn[j]!=iColumn; j++){}
68350         assert( j<pIdx->nColumn );
68351         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
68352       }
68353       return pTerm;
68354     }
68355   }
68356   return 0;
68357 }
68358
68359 /* Forward reference */
68360 static void exprAnalyze(SrcList*, WhereClause*, int);
68361
68362 /*
68363 ** Call exprAnalyze on all terms in a WHERE clause.  
68364 **
68365 **
68366 */
68367 static void exprAnalyzeAll(
68368   SrcList *pTabList,       /* the FROM clause */
68369   WhereClause *pWC         /* the WHERE clause to be analyzed */
68370 ){
68371   int i;
68372   for(i=pWC->nTerm-1; i>=0; i--){
68373     exprAnalyze(pTabList, pWC, i);
68374   }
68375 }
68376
68377 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
68378 /*
68379 ** Check to see if the given expression is a LIKE or GLOB operator that
68380 ** can be optimized using inequality constraints.  Return TRUE if it is
68381 ** so and false if not.
68382 **
68383 ** In order for the operator to be optimizible, the RHS must be a string
68384 ** literal that does not begin with a wildcard.  
68385 */
68386 static int isLikeOrGlob(
68387   sqlite3 *db,      /* The database */
68388   Expr *pExpr,      /* Test this expression */
68389   int *pnPattern,   /* Number of non-wildcard prefix characters */
68390   int *pisComplete, /* True if the only wildcard is % in the last character */
68391   int *pnoCase      /* True if uppercase is equivalent to lowercase */
68392 ){
68393   const char *z;
68394   Expr *pRight, *pLeft;
68395   ExprList *pList;
68396   int c, cnt;
68397   char wc[3];
68398   CollSeq *pColl;
68399
68400   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
68401     return 0;
68402   }
68403 #ifdef SQLITE_EBCDIC
68404   if( *pnoCase ) return 0;
68405 #endif
68406   pList = pExpr->pList;
68407   pRight = pList->a[0].pExpr;
68408   if( pRight->op!=TK_STRING ){
68409     return 0;
68410   }
68411   pLeft = pList->a[1].pExpr;
68412   if( pLeft->op!=TK_COLUMN ){
68413     return 0;
68414   }
68415   pColl = pLeft->pColl;
68416   assert( pColl!=0 || pLeft->iColumn==-1 );
68417   if( pColl==0 ){
68418     /* No collation is defined for the ROWID.  Use the default. */
68419     pColl = db->pDfltColl;
68420   }
68421   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
68422       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
68423     return 0;
68424   }
68425   sqlite3DequoteExpr(db, pRight);
68426   z = (char *)pRight->token.z;
68427   cnt = 0;
68428   if( z ){
68429     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
68430   }
68431   if( cnt==0 || 255==(u8)z[cnt] ){
68432     return 0;
68433   }
68434   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
68435   *pnPattern = cnt;
68436   return 1;
68437 }
68438 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
68439
68440
68441 #ifndef SQLITE_OMIT_VIRTUALTABLE
68442 /*
68443 ** Check to see if the given expression is of the form
68444 **
68445 **         column MATCH expr
68446 **
68447 ** If it is then return TRUE.  If not, return FALSE.
68448 */
68449 static int isMatchOfColumn(
68450   Expr *pExpr      /* Test this expression */
68451 ){
68452   ExprList *pList;
68453
68454   if( pExpr->op!=TK_FUNCTION ){
68455     return 0;
68456   }
68457   if( pExpr->token.n!=5 ||
68458        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
68459     return 0;
68460   }
68461   pList = pExpr->pList;
68462   if( pList->nExpr!=2 ){
68463     return 0;
68464   }
68465   if( pList->a[1].pExpr->op != TK_COLUMN ){
68466     return 0;
68467   }
68468   return 1;
68469 }
68470 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68471
68472 /*
68473 ** If the pBase expression originated in the ON or USING clause of
68474 ** a join, then transfer the appropriate markings over to derived.
68475 */
68476 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
68477   pDerived->flags |= pBase->flags & EP_FromJoin;
68478   pDerived->iRightJoinTable = pBase->iRightJoinTable;
68479 }
68480
68481 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
68482 /*
68483 ** Return TRUE if the given term of an OR clause can be converted
68484 ** into an IN clause.  The iCursor and iColumn define the left-hand
68485 ** side of the IN clause.
68486 **
68487 ** The context is that we have multiple OR-connected equality terms
68488 ** like this:
68489 **
68490 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
68491 **
68492 ** The pOrTerm input to this routine corresponds to a single term of
68493 ** this OR clause.  In order for the term to be a condidate for
68494 ** conversion to an IN operator, the following must be true:
68495 **
68496 **     *  The left-hand side of the term must be the column which
68497 **        is identified by iCursor and iColumn.
68498 **
68499 **     *  If the right-hand side is also a column, then the affinities
68500 **        of both right and left sides must be such that no type
68501 **        conversions are required on the right.  (Ticket #2249)
68502 **
68503 ** If both of these conditions are true, then return true.  Otherwise
68504 ** return false.
68505 */
68506 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
68507   int affLeft, affRight;
68508   assert( pOrTerm->eOperator==WO_EQ );
68509   if( pOrTerm->leftCursor!=iCursor ){
68510     return 0;
68511   }
68512   if( pOrTerm->leftColumn!=iColumn ){
68513     return 0;
68514   }
68515   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
68516   if( affRight==0 ){
68517     return 1;
68518   }
68519   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
68520   if( affRight!=affLeft ){
68521     return 0;
68522   }
68523   return 1;
68524 }
68525
68526 /*
68527 ** Return true if the given term of an OR clause can be ignored during
68528 ** a check to make sure all OR terms are candidates for optimization.
68529 ** In other words, return true if a call to the orTermIsOptCandidate()
68530 ** above returned false but it is not necessary to disqualify the
68531 ** optimization.
68532 **
68533 ** Suppose the original OR phrase was this:
68534 **
68535 **           a=4  OR  a=11  OR  a=b
68536 **
68537 ** During analysis, the third term gets flipped around and duplicate
68538 ** so that we are left with this:
68539 **
68540 **           a=4  OR  a=11  OR  a=b  OR  b=a
68541 **
68542 ** Since the last two terms are duplicates, only one of them
68543 ** has to qualify in order for the whole phrase to qualify.  When
68544 ** this routine is called, we know that pOrTerm did not qualify.
68545 ** This routine merely checks to see if pOrTerm has a duplicate that
68546 ** might qualify.  If there is a duplicate that has not yet been
68547 ** disqualified, then return true.  If there are no duplicates, or
68548 ** the duplicate has also been disqualifed, return false.
68549 */
68550 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
68551   if( pOrTerm->flags & TERM_COPIED ){
68552     /* This is the original term.  The duplicate is to the left had
68553     ** has not yet been analyzed and thus has not yet been disqualified. */
68554     return 1;
68555   }
68556   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
68557      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
68558     /* This is a duplicate term.  The original qualified so this one
68559     ** does not have to. */
68560     return 1;
68561   }
68562   /* This is either a singleton term or else it is a duplicate for
68563   ** which the original did not qualify.  Either way we are done for. */
68564   return 0;
68565 }
68566 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
68567
68568 /*
68569 ** The input to this routine is an WhereTerm structure with only the
68570 ** "pExpr" field filled in.  The job of this routine is to analyze the
68571 ** subexpression and populate all the other fields of the WhereTerm
68572 ** structure.
68573 **
68574 ** If the expression is of the form "<expr> <op> X" it gets commuted
68575 ** to the standard form of "X <op> <expr>".  If the expression is of
68576 ** the form "X <op> Y" where both X and Y are columns, then the original
68577 ** expression is unchanged and a new virtual expression of the form
68578 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
68579 */
68580 static void exprAnalyze(
68581   SrcList *pSrc,            /* the FROM clause */
68582   WhereClause *pWC,         /* the WHERE clause */
68583   int idxTerm               /* Index of the term to be analyzed */
68584 ){
68585   WhereTerm *pTerm;
68586   ExprMaskSet *pMaskSet;
68587   Expr *pExpr;
68588   Bitmask prereqLeft;
68589   Bitmask prereqAll;
68590   int nPattern;
68591   int isComplete;
68592   int noCase;
68593   int op;
68594   Parse *pParse = pWC->pParse;
68595   sqlite3 *db = pParse->db;
68596
68597   if( db->mallocFailed ){
68598     return;
68599   }
68600   pTerm = &pWC->a[idxTerm];
68601   pMaskSet = pWC->pMaskSet;
68602   pExpr = pTerm->pExpr;
68603   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
68604   op = pExpr->op;
68605   if( op==TK_IN ){
68606     assert( pExpr->pRight==0 );
68607     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
68608                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
68609   }else if( op==TK_ISNULL ){
68610     pTerm->prereqRight = 0;
68611   }else{
68612     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
68613   }
68614   prereqAll = exprTableUsage(pMaskSet, pExpr);
68615   if( ExprHasProperty(pExpr, EP_FromJoin) ){
68616     prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable);
68617   }
68618   pTerm->prereqAll = prereqAll;
68619   pTerm->leftCursor = -1;
68620   pTerm->iParent = -1;
68621   pTerm->eOperator = 0;
68622   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
68623     Expr *pLeft = pExpr->pLeft;
68624     Expr *pRight = pExpr->pRight;
68625     if( pLeft->op==TK_COLUMN ){
68626       pTerm->leftCursor = pLeft->iTable;
68627       pTerm->leftColumn = pLeft->iColumn;
68628       pTerm->eOperator = operatorMask(op);
68629     }
68630     if( pRight && pRight->op==TK_COLUMN ){
68631       WhereTerm *pNew;
68632       Expr *pDup;
68633       if( pTerm->leftCursor>=0 ){
68634         int idxNew;
68635         pDup = sqlite3ExprDup(db, pExpr);
68636         if( db->mallocFailed ){
68637           sqlite3ExprDelete(pDup);
68638           return;
68639         }
68640         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
68641         if( idxNew==0 ) return;
68642         pNew = &pWC->a[idxNew];
68643         pNew->iParent = idxTerm;
68644         pTerm = &pWC->a[idxTerm];
68645         pTerm->nChild = 1;
68646         pTerm->flags |= TERM_COPIED;
68647       }else{
68648         pDup = pExpr;
68649         pNew = pTerm;
68650       }
68651       exprCommute(pDup);
68652       pLeft = pDup->pLeft;
68653       pNew->leftCursor = pLeft->iTable;
68654       pNew->leftColumn = pLeft->iColumn;
68655       pNew->prereqRight = prereqLeft;
68656       pNew->prereqAll = prereqAll;
68657       pNew->eOperator = operatorMask(pDup->op);
68658     }
68659   }
68660
68661 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
68662   /* If a term is the BETWEEN operator, create two new virtual terms
68663   ** that define the range that the BETWEEN implements.
68664   */
68665   else if( pExpr->op==TK_BETWEEN ){
68666     ExprList *pList = pExpr->pList;
68667     int i;
68668     static const u8 ops[] = {TK_GE, TK_LE};
68669     assert( pList!=0 );
68670     assert( pList->nExpr==2 );
68671     for(i=0; i<2; i++){
68672       Expr *pNewExpr;
68673       int idxNew;
68674       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
68675                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
68676       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
68677       exprAnalyze(pSrc, pWC, idxNew);
68678       pTerm = &pWC->a[idxTerm];
68679       pWC->a[idxNew].iParent = idxTerm;
68680     }
68681     pTerm->nChild = 2;
68682   }
68683 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
68684
68685 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
68686   /* Attempt to convert OR-connected terms into an IN operator so that
68687   ** they can make use of indices.  Example:
68688   **
68689   **      x = expr1  OR  expr2 = x  OR  x = expr3
68690   **
68691   ** is converted into
68692   **
68693   **      x IN (expr1,expr2,expr3)
68694   **
68695   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
68696   ** the compiler for the the IN operator is part of sub-queries.
68697   */
68698   else if( pExpr->op==TK_OR ){
68699     int ok;
68700     int i, j;
68701     int iColumn, iCursor;
68702     WhereClause sOr;
68703     WhereTerm *pOrTerm;
68704
68705     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
68706     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
68707     whereSplit(&sOr, pExpr, TK_OR);
68708     exprAnalyzeAll(pSrc, &sOr);
68709     assert( sOr.nTerm>=2 );
68710     j = 0;
68711     if( db->mallocFailed ) goto or_not_possible;
68712     do{
68713       assert( j<sOr.nTerm );
68714       iColumn = sOr.a[j].leftColumn;
68715       iCursor = sOr.a[j].leftCursor;
68716       ok = iCursor>=0;
68717       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
68718         if( pOrTerm->eOperator!=WO_EQ ){
68719           goto or_not_possible;
68720         }
68721         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
68722           pOrTerm->flags |= TERM_OR_OK;
68723         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
68724           pOrTerm->flags &= ~TERM_OR_OK;
68725         }else{
68726           ok = 0;
68727         }
68728       }
68729     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
68730     if( ok ){
68731       ExprList *pList = 0;
68732       Expr *pNew, *pDup;
68733       Expr *pLeft = 0;
68734       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
68735         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
68736         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
68737         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
68738         pLeft = pOrTerm->pExpr->pLeft;
68739       }
68740       assert( pLeft!=0 );
68741       pDup = sqlite3ExprDup(db, pLeft);
68742       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
68743       if( pNew ){
68744         int idxNew;
68745         transferJoinMarkings(pNew, pExpr);
68746         pNew->pList = pList;
68747         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
68748         exprAnalyze(pSrc, pWC, idxNew);
68749         pTerm = &pWC->a[idxTerm];
68750         pWC->a[idxNew].iParent = idxTerm;
68751         pTerm->nChild = 1;
68752       }else{
68753         sqlite3ExprListDelete(pList);
68754       }
68755     }
68756 or_not_possible:
68757     whereClauseClear(&sOr);
68758   }
68759 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
68760
68761 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
68762   /* Add constraints to reduce the search space on a LIKE or GLOB
68763   ** operator.
68764   **
68765   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
68766   **
68767   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
68768   **
68769   ** The last character of the prefix "abc" is incremented to form the
68770   ** termination condidtion "abd".  This trick of incrementing the last
68771   ** is not 255 and if the character set is not EBCDIC.  
68772   */
68773   if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete, &noCase) ){
68774     Expr *pLeft, *pRight;
68775     Expr *pStr1, *pStr2;
68776     Expr *pNewExpr1, *pNewExpr2;
68777     int idxNew1, idxNew2;
68778
68779     pLeft = pExpr->pList->a[1].pExpr;
68780     pRight = pExpr->pList->a[0].pExpr;
68781     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
68782     if( pStr1 ){
68783       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
68784       pStr1->token.n = nPattern;
68785       pStr1->flags = EP_Dequoted;
68786     }
68787     pStr2 = sqlite3ExprDup(db, pStr1);
68788     if( !db->mallocFailed ){
68789       u8 c, *pC;
68790       assert( pStr2->token.dyn );
68791       pC = (u8*)&pStr2->token.z[nPattern-1];
68792       c = *pC;
68793       if( noCase ) c = sqlite3UpperToLower[c];
68794       *pC = c + 1;
68795     }
68796     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
68797     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
68798     exprAnalyze(pSrc, pWC, idxNew1);
68799     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
68800     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
68801     exprAnalyze(pSrc, pWC, idxNew2);
68802     pTerm = &pWC->a[idxTerm];
68803     if( isComplete ){
68804       pWC->a[idxNew1].iParent = idxTerm;
68805       pWC->a[idxNew2].iParent = idxTerm;
68806       pTerm->nChild = 2;
68807     }
68808   }
68809 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
68810
68811 #ifndef SQLITE_OMIT_VIRTUALTABLE
68812   /* Add a WO_MATCH auxiliary term to the constraint set if the
68813   ** current expression is of the form:  column MATCH expr.
68814   ** This information is used by the xBestIndex methods of
68815   ** virtual tables.  The native query optimizer does not attempt
68816   ** to do anything with MATCH functions.
68817   */
68818   if( isMatchOfColumn(pExpr) ){
68819     int idxNew;
68820     Expr *pRight, *pLeft;
68821     WhereTerm *pNewTerm;
68822     Bitmask prereqColumn, prereqExpr;
68823
68824     pRight = pExpr->pList->a[0].pExpr;
68825     pLeft = pExpr->pList->a[1].pExpr;
68826     prereqExpr = exprTableUsage(pMaskSet, pRight);
68827     prereqColumn = exprTableUsage(pMaskSet, pLeft);
68828     if( (prereqExpr & prereqColumn)==0 ){
68829       Expr *pNewExpr;
68830       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
68831       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
68832       pNewTerm = &pWC->a[idxNew];
68833       pNewTerm->prereqRight = prereqExpr;
68834       pNewTerm->leftCursor = pLeft->iTable;
68835       pNewTerm->leftColumn = pLeft->iColumn;
68836       pNewTerm->eOperator = WO_MATCH;
68837       pNewTerm->iParent = idxTerm;
68838       pTerm = &pWC->a[idxTerm];
68839       pTerm->nChild = 1;
68840       pTerm->flags |= TERM_COPIED;
68841       pNewTerm->prereqAll = pTerm->prereqAll;
68842     }
68843   }
68844 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68845 }
68846
68847 /*
68848 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
68849 ** a reference to any table other than the iBase table.
68850 */
68851 static int referencesOtherTables(
68852   ExprList *pList,          /* Search expressions in ths list */
68853   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
68854   int iFirst,               /* Be searching with the iFirst-th expression */
68855   int iBase                 /* Ignore references to this table */
68856 ){
68857   Bitmask allowed = ~getMask(pMaskSet, iBase);
68858   while( iFirst<pList->nExpr ){
68859     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
68860       return 1;
68861     }
68862   }
68863   return 0;
68864 }
68865
68866
68867 /*
68868 ** This routine decides if pIdx can be used to satisfy the ORDER BY
68869 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
68870 ** ORDER BY clause, this routine returns 0.
68871 **
68872 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
68873 ** left-most table in the FROM clause of that same SELECT statement and
68874 ** the table has a cursor number of "base".  pIdx is an index on pTab.
68875 **
68876 ** nEqCol is the number of columns of pIdx that are used as equality
68877 ** constraints.  Any of these columns may be missing from the ORDER BY
68878 ** clause and the match can still be a success.
68879 **
68880 ** All terms of the ORDER BY that match against the index must be either
68881 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
68882 ** index do not need to satisfy this constraint.)  The *pbRev value is
68883 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
68884 ** the ORDER BY clause is all ASC.
68885 */
68886 static int isSortingIndex(
68887   Parse *pParse,          /* Parsing context */
68888   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
68889   Index *pIdx,            /* The index we are testing */
68890   int base,               /* Cursor number for the table to be sorted */
68891   ExprList *pOrderBy,     /* The ORDER BY clause */
68892   int nEqCol,             /* Number of index columns with == constraints */
68893   int *pbRev              /* Set to 1 if ORDER BY is DESC */
68894 ){
68895   int i, j;                       /* Loop counters */
68896   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
68897   int nTerm;                      /* Number of ORDER BY terms */
68898   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
68899   sqlite3 *db = pParse->db;
68900
68901   assert( pOrderBy!=0 );
68902   nTerm = pOrderBy->nExpr;
68903   assert( nTerm>0 );
68904
68905   /* Match terms of the ORDER BY clause against columns of
68906   ** the index.
68907   **
68908   ** Note that indices have pIdx->nColumn regular columns plus
68909   ** one additional column containing the rowid.  The rowid column
68910   ** of the index is also allowed to match against the ORDER BY
68911   ** clause.
68912   */
68913   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
68914     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
68915     CollSeq *pColl;    /* The collating sequence of pExpr */
68916     int termSortOrder; /* Sort order for this term */
68917     int iColumn;       /* The i-th column of the index.  -1 for rowid */
68918     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
68919     const char *zColl; /* Name of the collating sequence for i-th index term */
68920
68921     pExpr = pTerm->pExpr;
68922     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
68923       /* Can not use an index sort on anything that is not a column in the
68924       ** left-most table of the FROM clause */
68925       break;
68926     }
68927     pColl = sqlite3ExprCollSeq(pParse, pExpr);
68928     if( !pColl ){
68929       pColl = db->pDfltColl;
68930     }
68931     if( i<pIdx->nColumn ){
68932       iColumn = pIdx->aiColumn[i];
68933       if( iColumn==pIdx->pTable->iPKey ){
68934         iColumn = -1;
68935       }
68936       iSortOrder = pIdx->aSortOrder[i];
68937       zColl = pIdx->azColl[i];
68938     }else{
68939       iColumn = -1;
68940       iSortOrder = 0;
68941       zColl = pColl->zName;
68942     }
68943     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
68944       /* Term j of the ORDER BY clause does not match column i of the index */
68945       if( i<nEqCol ){
68946         /* If an index column that is constrained by == fails to match an
68947         ** ORDER BY term, that is OK.  Just ignore that column of the index
68948         */
68949         continue;
68950       }else{
68951         /* If an index column fails to match and is not constrained by ==
68952         ** then the index cannot satisfy the ORDER BY constraint.
68953         */
68954         return 0;
68955       }
68956     }
68957     assert( pIdx->aSortOrder!=0 );
68958     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
68959     assert( iSortOrder==0 || iSortOrder==1 );
68960     termSortOrder = iSortOrder ^ pTerm->sortOrder;
68961     if( i>nEqCol ){
68962       if( termSortOrder!=sortOrder ){
68963         /* Indices can only be used if all ORDER BY terms past the
68964         ** equality constraints are all either DESC or ASC. */
68965         return 0;
68966       }
68967     }else{
68968       sortOrder = termSortOrder;
68969     }
68970     j++;
68971     pTerm++;
68972     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
68973       /* If the indexed column is the primary key and everything matches
68974       ** so far and none of the ORDER BY terms to the right reference other
68975       ** tables in the join, then we are assured that the index can be used 
68976       ** to sort because the primary key is unique and so none of the other
68977       ** columns will make any difference
68978       */
68979       j = nTerm;
68980     }
68981   }
68982
68983   *pbRev = sortOrder!=0;
68984   if( j>=nTerm ){
68985     /* All terms of the ORDER BY clause are covered by this index so
68986     ** this index can be used for sorting. */
68987     return 1;
68988   }
68989   if( pIdx->onError!=OE_None && i==pIdx->nColumn
68990       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
68991     /* All terms of this index match some prefix of the ORDER BY clause
68992     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
68993     ** clause reference other tables in a join.  If this is all true then
68994     ** the order by clause is superfluous. */
68995     return 1;
68996   }
68997   return 0;
68998 }
68999
69000 /*
69001 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
69002 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
69003 ** true for reverse ROWID and false for forward ROWID order.
69004 */
69005 static int sortableByRowid(
69006   int base,               /* Cursor number for table to be sorted */
69007   ExprList *pOrderBy,     /* The ORDER BY clause */
69008   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
69009   int *pbRev              /* Set to 1 if ORDER BY is DESC */
69010 ){
69011   Expr *p;
69012
69013   assert( pOrderBy!=0 );
69014   assert( pOrderBy->nExpr>0 );
69015   p = pOrderBy->a[0].pExpr;
69016   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
69017     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
69018     *pbRev = pOrderBy->a[0].sortOrder;
69019     return 1;
69020   }
69021   return 0;
69022 }
69023
69024 /*
69025 ** Prepare a crude estimate of the logarithm of the input value.
69026 ** The results need not be exact.  This is only used for estimating
69027 ** the total cost of performing operatings with O(logN) or O(NlogN)
69028 ** complexity.  Because N is just a guess, it is no great tragedy if
69029 ** logN is a little off.
69030 */
69031 static double estLog(double N){
69032   double logN = 1;
69033   double x = 10;
69034   while( N>x ){
69035     logN += 1;
69036     x *= 10;
69037   }
69038   return logN;
69039 }
69040
69041 /*
69042 ** Two routines for printing the content of an sqlite3_index_info
69043 ** structure.  Used for testing and debugging only.  If neither
69044 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
69045 ** are no-ops.
69046 */
69047 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
69048 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
69049   int i;
69050   if( !sqlite3WhereTrace ) return;
69051   for(i=0; i<p->nConstraint; i++){
69052     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
69053        i,
69054        p->aConstraint[i].iColumn,
69055        p->aConstraint[i].iTermOffset,
69056        p->aConstraint[i].op,
69057        p->aConstraint[i].usable);
69058   }
69059   for(i=0; i<p->nOrderBy; i++){
69060     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
69061        i,
69062        p->aOrderBy[i].iColumn,
69063        p->aOrderBy[i].desc);
69064   }
69065 }
69066 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
69067   int i;
69068   if( !sqlite3WhereTrace ) return;
69069   for(i=0; i<p->nConstraint; i++){
69070     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
69071        i,
69072        p->aConstraintUsage[i].argvIndex,
69073        p->aConstraintUsage[i].omit);
69074   }
69075   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
69076   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
69077   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
69078   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
69079 }
69080 #else
69081 #define TRACE_IDX_INPUTS(A)
69082 #define TRACE_IDX_OUTPUTS(A)
69083 #endif
69084
69085 #ifndef SQLITE_OMIT_VIRTUALTABLE
69086 /*
69087 ** Compute the best index for a virtual table.
69088 **
69089 ** The best index is computed by the xBestIndex method of the virtual
69090 ** table module.  This routine is really just a wrapper that sets up
69091 ** the sqlite3_index_info structure that is used to communicate with
69092 ** xBestIndex.
69093 **
69094 ** In a join, this routine might be called multiple times for the
69095 ** same virtual table.  The sqlite3_index_info structure is created
69096 ** and initialized on the first invocation and reused on all subsequent
69097 ** invocations.  The sqlite3_index_info structure is also used when
69098 ** code is generated to access the virtual table.  The whereInfoDelete() 
69099 ** routine takes care of freeing the sqlite3_index_info structure after
69100 ** everybody has finished with it.
69101 */
69102 static double bestVirtualIndex(
69103   Parse *pParse,                 /* The parsing context */
69104   WhereClause *pWC,              /* The WHERE clause */
69105   struct SrcList_item *pSrc,     /* The FROM clause term to search */
69106   Bitmask notReady,              /* Mask of cursors that are not available */
69107   ExprList *pOrderBy,            /* The order by clause */
69108   int orderByUsable,             /* True if we can potential sort */
69109   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
69110 ){
69111   Table *pTab = pSrc->pTab;
69112   sqlite3_index_info *pIdxInfo;
69113   struct sqlite3_index_constraint *pIdxCons;
69114   struct sqlite3_index_orderby *pIdxOrderBy;
69115   struct sqlite3_index_constraint_usage *pUsage;
69116   WhereTerm *pTerm;
69117   int i, j;
69118   int nOrderBy;
69119   int rc;
69120
69121   /* If the sqlite3_index_info structure has not been previously
69122   ** allocated and initialized for this virtual table, then allocate
69123   ** and initialize it now
69124   */
69125   pIdxInfo = *ppIdxInfo;
69126   if( pIdxInfo==0 ){
69127     WhereTerm *pTerm;
69128     int nTerm;
69129     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
69130
69131     /* Count the number of possible WHERE clause constraints referring
69132     ** to this virtual table */
69133     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
69134       if( pTerm->leftCursor != pSrc->iCursor ) continue;
69135       if( pTerm->eOperator==WO_IN ) continue;
69136       if( pTerm->eOperator==WO_ISNULL ) continue;
69137       nTerm++;
69138     }
69139
69140     /* If the ORDER BY clause contains only columns in the current 
69141     ** virtual table then allocate space for the aOrderBy part of
69142     ** the sqlite3_index_info structure.
69143     */
69144     nOrderBy = 0;
69145     if( pOrderBy ){
69146       for(i=0; i<pOrderBy->nExpr; i++){
69147         Expr *pExpr = pOrderBy->a[i].pExpr;
69148         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
69149       }
69150       if( i==pOrderBy->nExpr ){
69151         nOrderBy = pOrderBy->nExpr;
69152       }
69153     }
69154
69155     /* Allocate the sqlite3_index_info structure
69156     */
69157     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
69158                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
69159                              + sizeof(*pIdxOrderBy)*nOrderBy );
69160     if( pIdxInfo==0 ){
69161       sqlite3ErrorMsg(pParse, "out of memory");
69162       return 0.0;
69163     }
69164     *ppIdxInfo = pIdxInfo;
69165
69166     /* Initialize the structure.  The sqlite3_index_info structure contains
69167     ** many fields that are declared "const" to prevent xBestIndex from
69168     ** changing them.  We have to do some funky casting in order to
69169     ** initialize those fields.
69170     */
69171     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
69172     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
69173     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
69174     *(int*)&pIdxInfo->nConstraint = nTerm;
69175     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
69176     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
69177     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
69178     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
69179                                                                      pUsage;
69180
69181     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
69182       if( pTerm->leftCursor != pSrc->iCursor ) continue;
69183       if( pTerm->eOperator==WO_IN ) continue;
69184       if( pTerm->eOperator==WO_ISNULL ) continue;
69185       pIdxCons[j].iColumn = pTerm->leftColumn;
69186       pIdxCons[j].iTermOffset = i;
69187       pIdxCons[j].op = pTerm->eOperator;
69188       /* The direct assignment in the previous line is possible only because
69189       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
69190       ** following asserts verify this fact. */
69191       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
69192       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
69193       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
69194       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
69195       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
69196       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
69197       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
69198       j++;
69199     }
69200     for(i=0; i<nOrderBy; i++){
69201       Expr *pExpr = pOrderBy->a[i].pExpr;
69202       pIdxOrderBy[i].iColumn = pExpr->iColumn;
69203       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
69204     }
69205   }
69206
69207   /* At this point, the sqlite3_index_info structure that pIdxInfo points
69208   ** to will have been initialized, either during the current invocation or
69209   ** during some prior invocation.  Now we just have to customize the
69210   ** details of pIdxInfo for the current invocation and pass it to
69211   ** xBestIndex.
69212   */
69213
69214   /* The module name must be defined. Also, by this point there must
69215   ** be a pointer to an sqlite3_vtab structure. Otherwise
69216   ** sqlite3ViewGetColumnNames() would have picked up the error. 
69217   */
69218   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
69219   assert( pTab->pVtab );
69220 #if 0
69221   if( pTab->pVtab==0 ){
69222     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
69223         pTab->azModuleArg[0], pTab->zName);
69224     return 0.0;
69225   }
69226 #endif
69227
69228   /* Set the aConstraint[].usable fields and initialize all 
69229   ** output variables to zero.
69230   **
69231   ** aConstraint[].usable is true for constraints where the right-hand
69232   ** side contains only references to tables to the left of the current
69233   ** table.  In other words, if the constraint is of the form:
69234   **
69235   **           column = expr
69236   **
69237   ** and we are evaluating a join, then the constraint on column is 
69238   ** only valid if all tables referenced in expr occur to the left
69239   ** of the table containing column.
69240   **
69241   ** The aConstraints[] array contains entries for all constraints
69242   ** on the current table.  That way we only have to compute it once
69243   ** even though we might try to pick the best index multiple times.
69244   ** For each attempt at picking an index, the order of tables in the
69245   ** join might be different so we have to recompute the usable flag
69246   ** each time.
69247   */
69248   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
69249   pUsage = pIdxInfo->aConstraintUsage;
69250   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
69251     j = pIdxCons->iTermOffset;
69252     pTerm = &pWC->a[j];
69253     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
69254   }
69255   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
69256   if( pIdxInfo->needToFreeIdxStr ){
69257     sqlite3_free(pIdxInfo->idxStr);
69258   }
69259   pIdxInfo->idxStr = 0;
69260   pIdxInfo->idxNum = 0;
69261   pIdxInfo->needToFreeIdxStr = 0;
69262   pIdxInfo->orderByConsumed = 0;
69263   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
69264   nOrderBy = pIdxInfo->nOrderBy;
69265   if( pIdxInfo->nOrderBy && !orderByUsable ){
69266     *(int*)&pIdxInfo->nOrderBy = 0;
69267   }
69268
69269   (void)sqlite3SafetyOff(pParse->db);
69270   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
69271   TRACE_IDX_INPUTS(pIdxInfo);
69272   rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo);
69273   TRACE_IDX_OUTPUTS(pIdxInfo);
69274   (void)sqlite3SafetyOn(pParse->db);
69275
69276   for(i=0; i<pIdxInfo->nConstraint; i++){
69277     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
69278       sqlite3ErrorMsg(pParse, 
69279           "table %s: xBestIndex returned an invalid plan", pTab->zName);
69280       return 0.0;
69281     }
69282   }
69283
69284   if( rc!=SQLITE_OK ){
69285     if( rc==SQLITE_NOMEM ){
69286       pParse->db->mallocFailed = 1;
69287     }else {
69288       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
69289     }
69290   }
69291   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
69292
69293   return pIdxInfo->estimatedCost;
69294 }
69295 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69296
69297 /*
69298 ** Find the best index for accessing a particular table.  Return a pointer
69299 ** to the index, flags that describe how the index should be used, the
69300 ** number of equality constraints, and the "cost" for this index.
69301 **
69302 ** The lowest cost index wins.  The cost is an estimate of the amount of
69303 ** CPU and disk I/O need to process the request using the selected index.
69304 ** Factors that influence cost include:
69305 **
69306 **    *  The estimated number of rows that will be retrieved.  (The
69307 **       fewer the better.)
69308 **
69309 **    *  Whether or not sorting must occur.
69310 **
69311 **    *  Whether or not there must be separate lookups in the
69312 **       index and in the main table.
69313 **
69314 */
69315 static double bestIndex(
69316   Parse *pParse,              /* The parsing context */
69317   WhereClause *pWC,           /* The WHERE clause */
69318   struct SrcList_item *pSrc,  /* The FROM clause term to search */
69319   Bitmask notReady,           /* Mask of cursors that are not available */
69320   ExprList *pOrderBy,         /* The order by clause */
69321   Index **ppIndex,            /* Make *ppIndex point to the best index */
69322   int *pFlags,                /* Put flags describing this choice in *pFlags */
69323   int *pnEq                   /* Put the number of == or IN constraints here */
69324 ){
69325   WhereTerm *pTerm;
69326   Index *bestIdx = 0;         /* Index that gives the lowest cost */
69327   double lowestCost;          /* The cost of using bestIdx */
69328   int bestFlags = 0;          /* Flags associated with bestIdx */
69329   int bestNEq = 0;            /* Best value for nEq */
69330   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
69331   Index *pProbe;              /* An index we are evaluating */
69332   int rev;                    /* True to scan in reverse order */
69333   int flags;                  /* Flags associated with pProbe */
69334   int nEq;                    /* Number of == or IN constraints */
69335   int eqTermMask;             /* Mask of valid equality operators */
69336   double cost;                /* Cost of using pProbe */
69337
69338   WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
69339   lowestCost = SQLITE_BIG_DBL;
69340   pProbe = pSrc->pTab->pIndex;
69341
69342   /* If the table has no indices and there are no terms in the where
69343   ** clause that refer to the ROWID, then we will never be able to do
69344   ** anything other than a full table scan on this table.  We might as
69345   ** well put it first in the join order.  That way, perhaps it can be
69346   ** referenced by other tables in the join.
69347   */
69348   if( pProbe==0 &&
69349      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
69350      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
69351     *pFlags = 0;
69352     *ppIndex = 0;
69353     *pnEq = 0;
69354     return 0.0;
69355   }
69356
69357   /* Check for a rowid=EXPR or rowid IN (...) constraints
69358   */
69359   pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
69360   if( pTerm ){
69361     Expr *pExpr;
69362     *ppIndex = 0;
69363     bestFlags = WHERE_ROWID_EQ;
69364     if( pTerm->eOperator & WO_EQ ){
69365       /* Rowid== is always the best pick.  Look no further.  Because only
69366       ** a single row is generated, output is always in sorted order */
69367       *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
69368       *pnEq = 1;
69369       WHERETRACE(("... best is rowid\n"));
69370       return 0.0;
69371     }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
69372       /* Rowid IN (LIST): cost is NlogN where N is the number of list
69373       ** elements.  */
69374       lowestCost = pExpr->pList->nExpr;
69375       lowestCost *= estLog(lowestCost);
69376     }else{
69377       /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
69378       ** in the result of the inner select.  We have no way to estimate
69379       ** that value so make a wild guess. */
69380       lowestCost = 200;
69381     }
69382     WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
69383   }
69384
69385   /* Estimate the cost of a table scan.  If we do not know how many
69386   ** entries are in the table, use 1 million as a guess.
69387   */
69388   cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
69389   WHERETRACE(("... table scan base cost: %.9g\n", cost));
69390   flags = WHERE_ROWID_RANGE;
69391
69392   /* Check for constraints on a range of rowids in a table scan.
69393   */
69394   pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
69395   if( pTerm ){
69396     if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
69397       flags |= WHERE_TOP_LIMIT;
69398       cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
69399     }
69400     if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
69401       flags |= WHERE_BTM_LIMIT;
69402       cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
69403     }
69404     WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
69405   }else{
69406     flags = 0;
69407   }
69408
69409   /* If the table scan does not satisfy the ORDER BY clause, increase
69410   ** the cost by NlogN to cover the expense of sorting. */
69411   if( pOrderBy ){
69412     if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
69413       flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
69414       if( rev ){
69415         flags |= WHERE_REVERSE;
69416       }
69417     }else{
69418       cost += cost*estLog(cost);
69419       WHERETRACE(("... sorting increases cost to %.9g\n", cost));
69420     }
69421   }
69422   if( cost<lowestCost ){
69423     lowestCost = cost;
69424     bestFlags = flags;
69425   }
69426
69427   /* If the pSrc table is the right table of a LEFT JOIN then we may not
69428   ** use an index to satisfy IS NULL constraints on that table.  This is
69429   ** because columns might end up being NULL if the table does not match -
69430   ** a circumstance which the index cannot help us discover.  Ticket #2177.
69431   */
69432   if( (pSrc->jointype & JT_LEFT)!=0 ){
69433     eqTermMask = WO_EQ|WO_IN;
69434   }else{
69435     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
69436   }
69437
69438   /* Look at each index.
69439   */
69440   for(; pProbe; pProbe=pProbe->pNext){
69441     int i;                       /* Loop counter */
69442     double inMultiplier = 1;
69443
69444     WHERETRACE(("... index %s:\n", pProbe->zName));
69445
69446     /* Count the number of columns in the index that are satisfied
69447     ** by x=EXPR constraints or x IN (...) constraints.
69448     */
69449     flags = 0;
69450     for(i=0; i<pProbe->nColumn; i++){
69451       int j = pProbe->aiColumn[i];
69452       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
69453       if( pTerm==0 ) break;
69454       flags |= WHERE_COLUMN_EQ;
69455       if( pTerm->eOperator & WO_IN ){
69456         Expr *pExpr = pTerm->pExpr;
69457         flags |= WHERE_COLUMN_IN;
69458         if( pExpr->pSelect!=0 ){
69459           inMultiplier *= 25;
69460         }else if( pExpr->pList!=0 ){
69461           inMultiplier *= pExpr->pList->nExpr + 1;
69462         }
69463       }
69464     }
69465     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
69466     nEq = i;
69467     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
69468          && nEq==pProbe->nColumn ){
69469       flags |= WHERE_UNIQUE;
69470     }
69471     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
69472
69473     /* Look for range constraints
69474     */
69475     if( nEq<pProbe->nColumn ){
69476       int j = pProbe->aiColumn[nEq];
69477       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
69478       if( pTerm ){
69479         flags |= WHERE_COLUMN_RANGE;
69480         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
69481           flags |= WHERE_TOP_LIMIT;
69482           cost /= 3;
69483         }
69484         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
69485           flags |= WHERE_BTM_LIMIT;
69486           cost /= 3;
69487         }
69488         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
69489       }
69490     }
69491
69492     /* Add the additional cost of sorting if that is a factor.
69493     */
69494     if( pOrderBy ){
69495       if( (flags & WHERE_COLUMN_IN)==0 &&
69496            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
69497         if( flags==0 ){
69498           flags = WHERE_COLUMN_RANGE;
69499         }
69500         flags |= WHERE_ORDERBY;
69501         if( rev ){
69502           flags |= WHERE_REVERSE;
69503         }
69504       }else{
69505         cost += cost*estLog(cost);
69506         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
69507       }
69508     }
69509
69510     /* Check to see if we can get away with using just the index without
69511     ** ever reading the table.  If that is the case, then halve the
69512     ** cost of this index.
69513     */
69514     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
69515       Bitmask m = pSrc->colUsed;
69516       int j;
69517       for(j=0; j<pProbe->nColumn; j++){
69518         int x = pProbe->aiColumn[j];
69519         if( x<BMS-1 ){
69520           m &= ~(((Bitmask)1)<<x);
69521         }
69522       }
69523       if( m==0 ){
69524         flags |= WHERE_IDX_ONLY;
69525         cost /= 2;
69526         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
69527       }
69528     }
69529
69530     /* If this index has achieved the lowest cost so far, then use it.
69531     */
69532     if( flags && cost < lowestCost ){
69533       bestIdx = pProbe;
69534       lowestCost = cost;
69535       bestFlags = flags;
69536       bestNEq = nEq;
69537     }
69538   }
69539
69540   /* Report the best result
69541   */
69542   *ppIndex = bestIdx;
69543   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
69544         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
69545   *pFlags = bestFlags | eqTermMask;
69546   *pnEq = bestNEq;
69547   return lowestCost;
69548 }
69549
69550
69551 /*
69552 ** Disable a term in the WHERE clause.  Except, do not disable the term
69553 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
69554 ** or USING clause of that join.
69555 **
69556 ** Consider the term t2.z='ok' in the following queries:
69557 **
69558 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
69559 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
69560 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
69561 **
69562 ** The t2.z='ok' is disabled in the in (2) because it originates
69563 ** in the ON clause.  The term is disabled in (3) because it is not part
69564 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
69565 **
69566 ** Disabling a term causes that term to not be tested in the inner loop
69567 ** of the join.  Disabling is an optimization.  When terms are satisfied
69568 ** by indices, we disable them to prevent redundant tests in the inner
69569 ** loop.  We would get the correct results if nothing were ever disabled,
69570 ** but joins might run a little slower.  The trick is to disable as much
69571 ** as we can without disabling too much.  If we disabled in (1), we'd get
69572 ** the wrong answer.  See ticket #813.
69573 */
69574 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
69575   if( pTerm
69576       && (pTerm->flags & TERM_CODED)==0
69577       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
69578   ){
69579     pTerm->flags |= TERM_CODED;
69580     if( pTerm->iParent>=0 ){
69581       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
69582       if( (--pOther->nChild)==0 ){
69583         disableTerm(pLevel, pOther);
69584       }
69585     }
69586   }
69587 }
69588
69589 /*
69590 ** Generate code that builds a probe for an index.
69591 **
69592 ** There should be nColumn values on the stack.  The index
69593 ** to be probed is pIdx.  Pop the values from the stack and
69594 ** replace them all with a single record that is the index
69595 ** problem.
69596 */
69597 static void buildIndexProbe(
69598   Vdbe *v,        /* Generate code into this VM */
69599   int nColumn,    /* The number of columns to check for NULL */
69600   Index *pIdx,    /* Index that we will be searching */
69601   int regSrc,     /* Take values from this register */
69602   int regDest     /* Write the result into this register */
69603 ){
69604   assert( regSrc>0 );
69605   assert( regDest>0 );
69606   sqlite3VdbeAddOp3(v, OP_MakeRecord, regSrc, nColumn, regDest);
69607   sqlite3IndexAffinityStr(v, pIdx);
69608 }
69609
69610
69611 /*
69612 ** Generate code for a single equality term of the WHERE clause.  An equality
69613 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
69614 ** coded.
69615 **
69616 ** The current value for the constraint is left in register iReg.
69617 **
69618 ** For a constraint of the form X=expr, the expression is evaluated and its
69619 ** result is left on the stack.  For constraints of the form X IN (...)
69620 ** this routine sets up a loop that will iterate over all values of X.
69621 */
69622 static void codeEqualityTerm(
69623   Parse *pParse,      /* The parsing context */
69624   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
69625   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
69626   int iReg            /* Leave results in this register */
69627 ){
69628   Expr *pX = pTerm->pExpr;
69629   Vdbe *v = pParse->pVdbe;
69630
69631   assert( iReg>0 && iReg<=pParse->nMem );
69632   if( pX->op==TK_EQ ){
69633     sqlite3ExprCode(pParse, pX->pRight, iReg);
69634   }else if( pX->op==TK_ISNULL ){
69635     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
69636 #ifndef SQLITE_OMIT_SUBQUERY
69637   }else{
69638     int eType;
69639     int iTab;
69640     struct InLoop *pIn;
69641
69642     assert( pX->op==TK_IN );
69643     eType = sqlite3FindInIndex(pParse, pX, 1);
69644     iTab = pX->iTable;
69645     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
69646     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
69647     if( pLevel->nIn==0 ){
69648       pLevel->nxt = sqlite3VdbeMakeLabel(v);
69649     }
69650     pLevel->nIn++;
69651     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
69652                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
69653     pIn = pLevel->aInLoop;
69654     if( pIn ){
69655       pIn += pLevel->nIn - 1;
69656       pIn->iCur = iTab;
69657       if( eType==IN_INDEX_ROWID ){
69658         pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
69659       }else{
69660         pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
69661       }
69662       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
69663     }else{
69664       pLevel->nIn = 0;
69665     }
69666 #endif
69667   }
69668   disableTerm(pLevel, pTerm);
69669 }
69670
69671 /*
69672 ** Generate code that will evaluate all == and IN constraints for an
69673 ** index.  The values for all constraints are left on the stack.
69674 **
69675 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
69676 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
69677 ** The index has as many as three equality constraints, but in this
69678 ** example, the third "c" value is an inequality.  So only two 
69679 ** constraints are coded.  This routine will generate code to evaluate
69680 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
69681 ** on the stack - a is the deepest and b the shallowest.
69682 **
69683 ** In the example above nEq==2.  But this subroutine works for any value
69684 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
69685 ** The only thing it does is allocate the pLevel->iMem memory cell.
69686 **
69687 ** This routine always allocates at least one memory cell and puts
69688 ** the address of that memory cell in pLevel->iMem.  The code that
69689 ** calls this routine will use pLevel->iMem to store the termination
69690 ** key value of the loop.  If one or more IN operators appear, then
69691 ** this routine allocates an additional nEq memory cells for internal
69692 ** use.
69693 */
69694 static int codeAllEqualityTerms(
69695   Parse *pParse,        /* Parsing context */
69696   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
69697   WhereClause *pWC,     /* The WHERE clause */
69698   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
69699   int nExtraReg         /* Number of extra registers to allocate */
69700 ){
69701   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
69702   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
69703   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
69704   int iCur = pLevel->iTabCur;   /* The cursor of the table */
69705   WhereTerm *pTerm;             /* A single constraint term */
69706   int j;                        /* Loop counter */
69707   int regBase;                  /* Base register */
69708
69709   /* Figure out how many memory cells we will need then allocate them.
69710   ** We always need at least one used to store the loop terminator
69711   ** value.  If there are IN operators we'll need one for each == or
69712   ** IN constraint.
69713   */
69714   pLevel->iMem = pParse->nMem + 1;
69715   regBase = pParse->nMem + 2;
69716   pParse->nMem += pLevel->nEq + 2 + nExtraReg;
69717
69718   /* Evaluate the equality constraints
69719   */
69720   assert( pIdx->nColumn>=nEq );
69721   for(j=0; j<nEq; j++){
69722     int k = pIdx->aiColumn[j];
69723     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
69724     if( pTerm==0 ) break;
69725     assert( (pTerm->flags & TERM_CODED)==0 );
69726     codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
69727     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
69728       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
69729     }
69730   }
69731   return regBase;
69732 }
69733
69734 #if defined(SQLITE_TEST)
69735 /*
69736 ** The following variable holds a text description of query plan generated
69737 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
69738 ** overwrites the previous.  This information is used for testing and
69739 ** analysis only.
69740 */
69741 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
69742 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
69743
69744 #endif /* SQLITE_TEST */
69745
69746
69747 /*
69748 ** Free a WhereInfo structure
69749 */
69750 static void whereInfoFree(WhereInfo *pWInfo){
69751   if( pWInfo ){
69752     int i;
69753     for(i=0; i<pWInfo->nLevel; i++){
69754       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
69755       if( pInfo ){
69756         assert( pInfo->needToFreeIdxStr==0 );
69757         sqlite3_free(pInfo);
69758       }
69759     }
69760     sqlite3_free(pWInfo);
69761   }
69762 }
69763
69764
69765 /*
69766 ** Generate the beginning of the loop used for WHERE clause processing.
69767 ** The return value is a pointer to an opaque structure that contains
69768 ** information needed to terminate the loop.  Later, the calling routine
69769 ** should invoke sqlite3WhereEnd() with the return value of this function
69770 ** in order to complete the WHERE clause processing.
69771 **
69772 ** If an error occurs, this routine returns NULL.
69773 **
69774 ** The basic idea is to do a nested loop, one loop for each table in
69775 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
69776 ** same as a SELECT with only a single table in the FROM clause.)  For
69777 ** example, if the SQL is this:
69778 **
69779 **       SELECT * FROM t1, t2, t3 WHERE ...;
69780 **
69781 ** Then the code generated is conceptually like the following:
69782 **
69783 **      foreach row1 in t1 do       \    Code generated
69784 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
69785 **          foreach row3 in t3 do   /
69786 **            ...
69787 **          end                     \    Code generated
69788 **        end                        |-- by sqlite3WhereEnd()
69789 **      end                         /
69790 **
69791 ** Note that the loops might not be nested in the order in which they
69792 ** appear in the FROM clause if a different order is better able to make
69793 ** use of indices.  Note also that when the IN operator appears in
69794 ** the WHERE clause, it might result in additional nested loops for
69795 ** scanning through all values on the right-hand side of the IN.
69796 **
69797 ** There are Btree cursors associated with each table.  t1 uses cursor
69798 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
69799 ** And so forth.  This routine generates code to open those VDBE cursors
69800 ** and sqlite3WhereEnd() generates the code to close them.
69801 **
69802 ** The code that sqlite3WhereBegin() generates leaves the cursors named
69803 ** in pTabList pointing at their appropriate entries.  The [...] code
69804 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
69805 ** data from the various tables of the loop.
69806 **
69807 ** If the WHERE clause is empty, the foreach loops must each scan their
69808 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
69809 ** the tables have indices and there are terms in the WHERE clause that
69810 ** refer to those indices, a complete table scan can be avoided and the
69811 ** code will run much faster.  Most of the work of this routine is checking
69812 ** to see if there are indices that can be used to speed up the loop.
69813 **
69814 ** Terms of the WHERE clause are also used to limit which rows actually
69815 ** make it to the "..." in the middle of the loop.  After each "foreach",
69816 ** terms of the WHERE clause that use only terms in that loop and outer
69817 ** loops are evaluated and if false a jump is made around all subsequent
69818 ** inner loops (or around the "..." if the test occurs within the inner-
69819 ** most loop)
69820 **
69821 ** OUTER JOINS
69822 **
69823 ** An outer join of tables t1 and t2 is conceptally coded as follows:
69824 **
69825 **    foreach row1 in t1 do
69826 **      flag = 0
69827 **      foreach row2 in t2 do
69828 **        start:
69829 **          ...
69830 **          flag = 1
69831 **      end
69832 **      if flag==0 then
69833 **        move the row2 cursor to a null row
69834 **        goto start
69835 **      fi
69836 **    end
69837 **
69838 ** ORDER BY CLAUSE PROCESSING
69839 **
69840 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
69841 ** if there is one.  If there is no ORDER BY clause or if this routine
69842 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
69843 **
69844 ** If an index can be used so that the natural output order of the table
69845 ** scan is correct for the ORDER BY clause, then that index is used and
69846 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
69847 ** unnecessary sort of the result set if an index appropriate for the
69848 ** ORDER BY clause already exists.
69849 **
69850 ** If the where clause loops cannot be arranged to provide the correct
69851 ** output order, then the *ppOrderBy is unchanged.
69852 */
69853 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
69854   Parse *pParse,        /* The parser context */
69855   SrcList *pTabList,    /* A list of all tables to be scanned */
69856   Expr *pWhere,         /* The WHERE clause */
69857   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
69858   u8 obflag             /* One of ORDERBY_MIN, ORDERBY_MAX or ORDERBY_NORMAL */
69859 ){
69860   int i;                     /* Loop counter */
69861   WhereInfo *pWInfo;         /* Will become the return value of this function */
69862   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
69863   int brk, cont = 0;         /* Addresses used during code generation */
69864   Bitmask notReady;          /* Cursors that are not yet positioned */
69865   WhereTerm *pTerm;          /* A single term in the WHERE clause */
69866   ExprMaskSet maskSet;       /* The expression mask set */
69867   WhereClause wc;            /* The WHERE clause is divided into these terms */
69868   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
69869   WhereLevel *pLevel;             /* A single level in the pWInfo list */
69870   int iFrom;                      /* First unused FROM clause element */
69871   int andFlags;              /* AND-ed combination of all wc.a[].flags */
69872   sqlite3 *db;               /* Database connection */
69873   ExprList *pOrderBy = 0;
69874
69875   /* The number of tables in the FROM clause is limited by the number of
69876   ** bits in a Bitmask 
69877   */
69878   if( pTabList->nSrc>BMS ){
69879     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
69880     return 0;
69881   }
69882
69883   if( ppOrderBy ){
69884     pOrderBy = *ppOrderBy;
69885   }
69886
69887   /* Split the WHERE clause into separate subexpressions where each
69888   ** subexpression is separated by an AND operator.
69889   */
69890   initMaskSet(&maskSet);
69891   whereClauseInit(&wc, pParse, &maskSet);
69892   whereSplit(&wc, pWhere, TK_AND);
69893     
69894   /* Allocate and initialize the WhereInfo structure that will become the
69895   ** return value.
69896   */
69897   db = pParse->db;
69898   pWInfo = sqlite3DbMallocZero(db,  
69899                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
69900   if( db->mallocFailed ){
69901     goto whereBeginNoMem;
69902   }
69903   pWInfo->nLevel = pTabList->nSrc;
69904   pWInfo->pParse = pParse;
69905   pWInfo->pTabList = pTabList;
69906   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
69907
69908   /* Special case: a WHERE clause that is constant.  Evaluate the
69909   ** expression and either jump over all of the code or fall thru.
69910   */
69911   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
69912     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
69913     pWhere = 0;
69914   }
69915
69916   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
69917   ** add new virtual terms onto the end of the WHERE clause.  We do not
69918   ** want to analyze these virtual terms, so start analyzing at the end
69919   ** and work forward so that the added virtual terms are never processed.
69920   */
69921   for(i=0; i<pTabList->nSrc; i++){
69922     createMask(&maskSet, pTabList->a[i].iCursor);
69923   }
69924   exprAnalyzeAll(pTabList, &wc);
69925   if( db->mallocFailed ){
69926     goto whereBeginNoMem;
69927   }
69928
69929   /* Chose the best index to use for each table in the FROM clause.
69930   **
69931   ** This loop fills in the following fields:
69932   **
69933   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
69934   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
69935   **   pWInfo->a[].nEq       The number of == and IN constraints
69936   **   pWInfo->a[].iFrom     When term of the FROM clause is being coded
69937   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
69938   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
69939   **
69940   ** This loop also figures out the nesting order of tables in the FROM
69941   ** clause.
69942   */
69943   notReady = ~(Bitmask)0;
69944   pTabItem = pTabList->a;
69945   pLevel = pWInfo->a;
69946   andFlags = ~0;
69947   WHERETRACE(("*** Optimizer Start ***\n"));
69948   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
69949     Index *pIdx;                /* Index for FROM table at pTabItem */
69950     int flags;                  /* Flags asssociated with pIdx */
69951     int nEq;                    /* Number of == or IN constraints */
69952     double cost;                /* The cost for pIdx */
69953     int j;                      /* For looping over FROM tables */
69954     Index *pBest = 0;           /* The best index seen so far */
69955     int bestFlags = 0;          /* Flags associated with pBest */
69956     int bestNEq = 0;            /* nEq associated with pBest */
69957     double lowestCost;          /* Cost of the pBest */
69958     int bestJ = 0;              /* The value of j */
69959     Bitmask m;                  /* Bitmask value for j or bestJ */
69960     int once = 0;               /* True when first table is seen */
69961     sqlite3_index_info *pIndex; /* Current virtual index */
69962
69963     lowestCost = SQLITE_BIG_DBL;
69964     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
69965       int doNotReorder;  /* True if this table should not be reordered */
69966
69967       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
69968       if( once && doNotReorder ) break;
69969       m = getMask(&maskSet, pTabItem->iCursor);
69970       if( (m & notReady)==0 ){
69971         if( j==iFrom ) iFrom++;
69972         continue;
69973       }
69974       assert( pTabItem->pTab );
69975 #ifndef SQLITE_OMIT_VIRTUALTABLE
69976       if( IsVirtual(pTabItem->pTab) ){
69977         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
69978         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
69979                                 ppOrderBy ? *ppOrderBy : 0, i==0,
69980                                 ppIdxInfo);
69981         flags = WHERE_VIRTUALTABLE;
69982         pIndex = *ppIdxInfo;
69983         if( pIndex && pIndex->orderByConsumed ){
69984           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
69985         }
69986         pIdx = 0;
69987         nEq = 0;
69988         if( (SQLITE_BIG_DBL/2.0)<cost ){
69989           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
69990           ** inital value of lowestCost in this loop. If it is, then
69991           ** the (cost<lowestCost) test below will never be true and
69992           ** pLevel->pBestIdx never set.
69993           */ 
69994           cost = (SQLITE_BIG_DBL/2.0);
69995         }
69996       }else 
69997 #endif
69998       {
69999         cost = bestIndex(pParse, &wc, pTabItem, notReady,
70000                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
70001                          &pIdx, &flags, &nEq);
70002         pIndex = 0;
70003       }
70004       if( cost<lowestCost ){
70005         once = 1;
70006         lowestCost = cost;
70007         pBest = pIdx;
70008         bestFlags = flags;
70009         bestNEq = nEq;
70010         bestJ = j;
70011         pLevel->pBestIdx = pIndex;
70012       }
70013       if( doNotReorder ) break;
70014     }
70015     WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ,
70016            pLevel-pWInfo->a));
70017     if( (bestFlags & WHERE_ORDERBY)!=0 ){
70018       *ppOrderBy = 0;
70019     }
70020     andFlags &= bestFlags;
70021     pLevel->flags = bestFlags;
70022     pLevel->pIdx = pBest;
70023     pLevel->nEq = bestNEq;
70024     pLevel->aInLoop = 0;
70025     pLevel->nIn = 0;
70026     if( pBest ){
70027       pLevel->iIdxCur = pParse->nTab++;
70028     }else{
70029       pLevel->iIdxCur = -1;
70030     }
70031     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
70032     pLevel->iFrom = bestJ;
70033   }
70034   WHERETRACE(("*** Optimizer Finished ***\n"));
70035
70036   /* If the total query only selects a single row, then the ORDER BY
70037   ** clause is irrelevant.
70038   */
70039   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
70040     *ppOrderBy = 0;
70041   }
70042
70043   /* Open all tables in the pTabList and any indices selected for
70044   ** searching those tables.
70045   */
70046   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
70047   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
70048     Table *pTab;     /* Table to open */
70049     Index *pIx;      /* Index used to access pTab (if any) */
70050     int iDb;         /* Index of database containing table/index */
70051     int iIdxCur = pLevel->iIdxCur;
70052
70053 #ifndef SQLITE_OMIT_EXPLAIN
70054     if( pParse->explain==2 ){
70055       char *zMsg;
70056       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
70057       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
70058       if( pItem->zAlias ){
70059         zMsg = sqlite3MPrintf(db, "%z AS %s", zMsg, pItem->zAlias);
70060       }
70061       if( (pIx = pLevel->pIdx)!=0 ){
70062         zMsg = sqlite3MPrintf(db, "%z WITH INDEX %s", zMsg, pIx->zName);
70063       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
70064         zMsg = sqlite3MPrintf(db, "%z USING PRIMARY KEY", zMsg);
70065       }
70066 #ifndef SQLITE_OMIT_VIRTUALTABLE
70067       else if( pLevel->pBestIdx ){
70068         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
70069         zMsg = sqlite3MPrintf(db, "%z VIRTUAL TABLE INDEX %d:%s", zMsg,
70070                     pBestIdx->idxNum, pBestIdx->idxStr);
70071       }
70072 #endif
70073       if( pLevel->flags & WHERE_ORDERBY ){
70074         zMsg = sqlite3MPrintf(db, "%z ORDER BY", zMsg);
70075       }
70076       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
70077     }
70078 #endif /* SQLITE_OMIT_EXPLAIN */
70079     pTabItem = &pTabList->a[pLevel->iFrom];
70080     pTab = pTabItem->pTab;
70081     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70082     if( pTab->isEphem || pTab->pSelect ) continue;
70083 #ifndef SQLITE_OMIT_VIRTUALTABLE
70084     if( pLevel->pBestIdx ){
70085       int iCur = pTabItem->iCursor;
70086       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
70087                         (const char*)pTab->pVtab, P4_VTAB);
70088     }else
70089 #endif
70090     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
70091       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead);
70092       if( pTab->nCol<(sizeof(Bitmask)*8) ){
70093         Bitmask b = pTabItem->colUsed;
70094         int n = 0;
70095         for(; b; b=b>>1, n++){}
70096         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n);
70097         assert( n<=pTab->nCol );
70098       }
70099     }else{
70100       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
70101     }
70102     pLevel->iTabCur = pTabItem->iCursor;
70103     if( (pIx = pLevel->pIdx)!=0 ){
70104       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
70105       assert( pIx->pSchema==pTab->pSchema );
70106       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
70107                         (char*)pKey, P4_KEYINFO_HANDOFF);
70108       VdbeComment((v, "%s", pIx->zName));
70109       sqlite3VdbeAddOp2(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
70110     }
70111     sqlite3CodeVerifySchema(pParse, iDb);
70112   }
70113   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
70114
70115   /* Generate the code to do the search.  Each iteration of the for
70116   ** loop below generates code for a single nested loop of the VM
70117   ** program.
70118   */
70119   notReady = ~(Bitmask)0;
70120   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
70121     int j;
70122     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
70123     Index *pIdx;       /* The index we will be using */
70124     int nxt;           /* Where to jump to continue with the next IN case */
70125     int iIdxCur;       /* The VDBE cursor for the index */
70126     int omitTable;     /* True if we use the index only */
70127     int bRev;          /* True if we need to scan in reverse order */
70128
70129     pTabItem = &pTabList->a[pLevel->iFrom];
70130     iCur = pTabItem->iCursor;
70131     pIdx = pLevel->pIdx;
70132     iIdxCur = pLevel->iIdxCur;
70133     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
70134     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
70135
70136     /* Create labels for the "break" and "continue" instructions
70137     ** for the current loop.  Jump to brk to break out of a loop.
70138     ** Jump to cont to go immediately to the next iteration of the
70139     ** loop.
70140     **
70141     ** When there is an IN operator, we also have a "nxt" label that
70142     ** means to continue with the next IN value combination.  When
70143     ** there are no IN operators in the constraints, the "nxt" label
70144     ** is the same as "brk".
70145     */
70146     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
70147     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
70148
70149     /* If this is the right table of a LEFT OUTER JOIN, allocate and
70150     ** initialize a memory cell that records if this table matches any
70151     ** row of the left table of the join.
70152     */
70153     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
70154       pLevel->iLeftJoin = ++pParse->nMem;
70155       sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
70156       VdbeComment((v, "init LEFT JOIN no-match flag"));
70157     }
70158
70159 #ifndef SQLITE_OMIT_VIRTUALTABLE
70160     if( pLevel->pBestIdx ){
70161       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
70162       **          to access the data.
70163       */
70164       int j;
70165       int iReg;   /* P3 Value for OP_VFilter */
70166       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
70167       int nConstraint = pBestIdx->nConstraint;
70168       struct sqlite3_index_constraint_usage *aUsage =
70169                                                   pBestIdx->aConstraintUsage;
70170       const struct sqlite3_index_constraint *aConstraint =
70171                                                   pBestIdx->aConstraint;
70172
70173       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
70174       for(j=1; j<=nConstraint; j++){
70175         int k;
70176         for(k=0; k<nConstraint; k++){
70177           if( aUsage[k].argvIndex==j ){
70178             int iTerm = aConstraint[k].iTermOffset;
70179             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
70180             break;
70181           }
70182         }
70183         if( k==nConstraint ) break;
70184       }
70185       sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
70186       sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
70187       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
70188                         pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
70189       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
70190       pBestIdx->needToFreeIdxStr = 0;
70191       for(j=0; j<pBestIdx->nConstraint; j++){
70192         if( aUsage[j].omit ){
70193           int iTerm = aConstraint[j].iTermOffset;
70194           disableTerm(pLevel, &wc.a[iTerm]);
70195         }
70196       }
70197       pLevel->op = OP_VNext;
70198       pLevel->p1 = iCur;
70199       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
70200     }else
70201 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70202
70203     if( pLevel->flags & WHERE_ROWID_EQ ){
70204       /* Case 1:  We can directly reference a single row using an
70205       **          equality comparison against the ROWID field.  Or
70206       **          we reference multiple rows using a "rowid IN (...)"
70207       **          construct.
70208       */
70209       int r1;
70210       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
70211       assert( pTerm!=0 );
70212       assert( pTerm->pExpr!=0 );
70213       assert( pTerm->leftCursor==iCur );
70214       assert( omitTable==0 );
70215       r1 = sqlite3GetTempReg(pParse);
70216       codeEqualityTerm(pParse, pTerm, pLevel, r1);
70217       nxt = pLevel->nxt;
70218       sqlite3VdbeAddOp3(v, OP_MustBeInt, r1, nxt, 1);
70219       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
70220       VdbeComment((v, "pk"));
70221       sqlite3ReleaseTempReg(pParse, r1);
70222       pLevel->op = OP_Noop;
70223     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
70224       /* Case 2:  We have an inequality comparison against the ROWID field.
70225       */
70226       int testOp = OP_Noop;
70227       int start;
70228       WhereTerm *pStart, *pEnd;
70229
70230       assert( omitTable==0 );
70231       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
70232       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
70233       if( bRev ){
70234         pTerm = pStart;
70235         pStart = pEnd;
70236         pEnd = pTerm;
70237       }
70238       if( pStart ){
70239         Expr *pX;
70240         int r1, regFree1;
70241         pX = pStart->pExpr;
70242         assert( pX!=0 );
70243         assert( pStart->leftCursor==iCur );
70244         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &regFree1);
70245         sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, 
70246                              pX->op==TK_LE || pX->op==TK_GT);
70247         sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
70248         VdbeComment((v, "pk"));
70249         sqlite3ReleaseTempReg(pParse, regFree1);
70250         disableTerm(pLevel, pStart);
70251       }else{
70252         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
70253       }
70254       if( pEnd ){
70255         Expr *pX;
70256         pX = pEnd->pExpr;
70257         assert( pX!=0 );
70258         assert( pEnd->leftCursor==iCur );
70259         pLevel->iMem = ++pParse->nMem;
70260         sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
70261         if( pX->op==TK_LT || pX->op==TK_GT ){
70262           testOp = bRev ? OP_Le : OP_Ge;
70263         }else{
70264           testOp = bRev ? OP_Lt : OP_Gt;
70265         }
70266         disableTerm(pLevel, pEnd);
70267       }
70268       start = sqlite3VdbeCurrentAddr(v);
70269       pLevel->op = bRev ? OP_Prev : OP_Next;
70270       pLevel->p1 = iCur;
70271       pLevel->p2 = start;
70272       if( testOp!=OP_Noop ){
70273         int r1 = sqlite3GetTempReg(pParse);
70274         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
70275         /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
70276         sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
70277         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
70278         sqlite3ReleaseTempReg(pParse, r1);
70279       }
70280     }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
70281       /* Case 3: The WHERE clause term that refers to the right-most
70282       **         column of the index is an inequality.  For example, if
70283       **         the index is on (x,y,z) and the WHERE clause is of the
70284       **         form "x=5 AND y<10" then this case is used.  Only the
70285       **         right-most column can be an inequality - the rest must
70286       **         use the "==" and "IN" operators.
70287       **
70288       **         This case is also used when there are no WHERE clause
70289       **         constraints but an index is selected anyway, in order
70290       **         to force the output order to conform to an ORDER BY.
70291       */
70292       int start;
70293       int nEq = pLevel->nEq;
70294       int topEq=0;        /* True if top limit uses ==. False is strictly < */
70295       int btmEq=0;        /* True if btm limit uses ==. False if strictly > */
70296       int topOp, btmOp;   /* Operators for the top and bottom search bounds */
70297       int testOp;
70298       int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
70299       int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
70300       int isMinQuery = 0;      /* If this is an optimized SELECT min(x) ... */
70301       int regBase;        /* Base register holding constraint values */
70302       int r1;             /* Temp register */
70303
70304       /* Generate code to evaluate all constraint terms using == or IN
70305       ** and level the values of those terms on the stack.
70306       */
70307       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
70308
70309       /* Figure out what comparison operators to use for top and bottom 
70310       ** search bounds. For an ascending index, the bottom bound is a > or >=
70311       ** operator and the top bound is a < or <= operator.  For a descending
70312       ** index the operators are reversed.
70313       */
70314       if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){
70315         topOp = WO_LT|WO_LE;
70316         btmOp = WO_GT|WO_GE;
70317       }else{
70318         topOp = WO_GT|WO_GE;
70319         btmOp = WO_LT|WO_LE;
70320         SWAP(int, topLimit, btmLimit);
70321       }
70322
70323       /* If this loop satisfies a sort order (pOrderBy) request that 
70324       ** was passed to this function to implement a "SELECT min(x) ..." 
70325       ** query, then the caller will only allow the loop to run for
70326       ** a single iteration. This means that the first row returned
70327       ** should not have a NULL value stored in 'x'. If column 'x' is
70328       ** the first one after the nEq equality constraints in the index,
70329       ** this requires some special handling.
70330       */
70331       if( (obflag==ORDERBY_MIN)
70332        && (pLevel->flags&WHERE_ORDERBY)
70333        && (pIdx->nColumn>nEq)
70334        && (pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq])
70335       ){
70336         isMinQuery = 1;
70337       }
70338
70339       /* Generate the termination key.  This is the key value that
70340       ** will end the search.  There is no termination key if there
70341       ** are no equality terms and no "X<..." term.
70342       **
70343       ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
70344       ** key computed here really ends up being the start key.
70345       */
70346       nxt = pLevel->nxt;
70347       if( topLimit ){
70348         Expr *pX;
70349         int k = pIdx->aiColumn[nEq];
70350         pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx);
70351         assert( pTerm!=0 );
70352         pX = pTerm->pExpr;
70353         assert( (pTerm->flags & TERM_CODED)==0 );
70354         sqlite3ExprCode(pParse, pX->pRight, regBase+nEq);
70355         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
70356         topEq = pTerm->eOperator & (WO_LE|WO_GE);
70357         disableTerm(pLevel, pTerm);
70358         testOp = OP_IdxGE;
70359       }else{
70360         testOp = nEq>0 ? OP_IdxGE : OP_Noop;
70361         topEq = 1;
70362       }
70363       if( testOp!=OP_Noop || (isMinQuery&&bRev) ){
70364         int nCol = nEq + topLimit;
70365         if( isMinQuery && !topLimit ){
70366           sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nCol);
70367           nCol++;
70368           topEq = 0;
70369         }
70370         buildIndexProbe(v, nCol, pIdx, regBase, pLevel->iMem);
70371         if( bRev ){
70372           int op = topEq ? OP_MoveLe : OP_MoveLt;
70373           sqlite3VdbeAddOp3(v, op, iIdxCur, nxt, pLevel->iMem);
70374         }
70375       }else if( bRev ){
70376         sqlite3VdbeAddOp2(v, OP_Last, iIdxCur, brk);
70377       }
70378    
70379       /* Generate the start key.  This is the key that defines the lower
70380       ** bound on the search.  There is no start key if there are no
70381       ** equality terms and if there is no "X>..." term.  In
70382       ** that case, generate a "Rewind" instruction in place of the
70383       ** start key search.
70384       **
70385       ** 2002-Dec-04: In the case of a reverse-order search, the so-called
70386       ** "start" key really ends up being used as the termination key.
70387       */
70388       if( btmLimit ){
70389         Expr *pX;
70390         int k = pIdx->aiColumn[nEq];
70391         pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx);
70392         assert( pTerm!=0 );
70393         pX = pTerm->pExpr;
70394         assert( (pTerm->flags & TERM_CODED)==0 );
70395         sqlite3ExprCode(pParse, pX->pRight, regBase+nEq);
70396         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
70397         btmEq = pTerm->eOperator & (WO_LE|WO_GE);
70398         disableTerm(pLevel, pTerm);
70399       }else{
70400         btmEq = 1;
70401       }
70402       if( nEq>0 || btmLimit || (isMinQuery&&!bRev) ){
70403         int nCol = nEq + btmLimit;
70404         if( isMinQuery && !btmLimit ){
70405           sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nCol);
70406           nCol++;
70407           btmEq = 0;
70408         }
70409         if( bRev ){
70410           r1 = pLevel->iMem;
70411           testOp = OP_IdxLT;
70412         }else{
70413           r1 = sqlite3GetTempReg(pParse);
70414         }
70415         buildIndexProbe(v, nCol, pIdx, regBase, r1);
70416         if( !bRev ){
70417           int op = btmEq ? OP_MoveGe : OP_MoveGt;
70418           sqlite3VdbeAddOp3(v, op, iIdxCur, nxt, r1);
70419           sqlite3ReleaseTempReg(pParse, r1);
70420         }
70421       }else if( bRev ){
70422         testOp = OP_Noop;
70423       }else{
70424         sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, brk);
70425       }
70426
70427       /* Generate the the top of the loop.  If there is a termination
70428       ** key we have to test for that key and abort at the top of the
70429       ** loop.
70430       */
70431       start = sqlite3VdbeCurrentAddr(v);
70432       if( testOp!=OP_Noop ){
70433         sqlite3VdbeAddOp3(v, testOp, iIdxCur, nxt, pLevel->iMem);
70434         if( (topEq && !bRev) || (!btmEq && bRev) ){
70435           sqlite3VdbeChangeP5(v, 1);
70436         }
70437       }
70438       r1 = sqlite3GetTempReg(pParse);
70439       if( topLimit | btmLimit ){
70440         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
70441         sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
70442       }
70443       if( !omitTable ){
70444         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
70445         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
70446       }
70447       sqlite3ReleaseTempReg(pParse, r1);
70448
70449       /* Record the instruction used to terminate the loop.
70450       */
70451       pLevel->op = bRev ? OP_Prev : OP_Next;
70452       pLevel->p1 = iIdxCur;
70453       pLevel->p2 = start;
70454     }else if( pLevel->flags & WHERE_COLUMN_EQ ){
70455       /* Case 4:  There is an index and all terms of the WHERE clause that
70456       **          refer to the index using the "==" or "IN" operators.
70457       */
70458       int start;
70459       int nEq = pLevel->nEq;
70460       int isMinQuery = 0;      /* If this is an optimized SELECT min(x) ... */
70461       int regBase;             /* Base register of array holding constraints */
70462       int r1;
70463
70464       /* Generate code to evaluate all constraint terms using == or IN
70465       ** and leave the values of those terms on the stack.
70466       */
70467       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 1);
70468       nxt = pLevel->nxt;
70469
70470       if( (obflag==ORDERBY_MIN)
70471        && (pLevel->flags&WHERE_ORDERBY) 
70472        && (pIdx->nColumn>nEq)
70473        && (pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq])
70474       ){
70475         isMinQuery = 1;
70476         buildIndexProbe(v, nEq, pIdx, regBase, pLevel->iMem);
70477         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
70478         r1 = ++pParse->nMem;
70479         buildIndexProbe(v, nEq+1, pIdx, regBase, r1);
70480       }else{
70481         /* Generate a single key that will be used to both start and 
70482         ** terminate the search
70483         */
70484         r1 = pLevel->iMem;
70485         buildIndexProbe(v, nEq, pIdx, regBase, r1);
70486       }
70487
70488       /* Generate code (1) to move to the first matching element of the table.
70489       ** Then generate code (2) that jumps to "nxt" after the cursor is past
70490       ** the last matching element of the table.  The code (1) is executed
70491       ** once to initialize the search, the code (2) is executed before each
70492       ** iteration of the scan to see if the scan has finished. */
70493       if( bRev ){
70494         /* Scan in reverse order */
70495         int op;
70496         if( isMinQuery ){
70497           op = OP_MoveLt;
70498         }else{
70499           op = OP_MoveLe;
70500         }
70501         sqlite3VdbeAddOp3(v, op, iIdxCur, nxt, r1);
70502         start = sqlite3VdbeAddOp3(v, OP_IdxLT, iIdxCur, nxt, pLevel->iMem);
70503         pLevel->op = OP_Prev;
70504       }else{
70505         /* Scan in the forward order */
70506         int op;
70507         if( isMinQuery ){
70508           op = OP_MoveGt;
70509         }else{
70510           op = OP_MoveGe;
70511         }
70512         sqlite3VdbeAddOp3(v, op, iIdxCur, nxt, r1);
70513         start = sqlite3VdbeAddOp3(v, OP_IdxGE, iIdxCur, nxt, pLevel->iMem);
70514         sqlite3VdbeChangeP5(v, 1);
70515         pLevel->op = OP_Next;
70516       }
70517       if( !omitTable ){
70518         r1 = sqlite3GetTempReg(pParse);
70519         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
70520         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
70521         sqlite3ReleaseTempReg(pParse, r1);
70522       }
70523       pLevel->p1 = iIdxCur;
70524       pLevel->p2 = start;
70525     }else{
70526       /* Case 5:  There is no usable index.  We must do a complete
70527       **          scan of the entire table.
70528       */
70529       assert( omitTable==0 );
70530       assert( bRev==0 );
70531       pLevel->op = OP_Next;
70532       pLevel->p1 = iCur;
70533       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
70534     }
70535     notReady &= ~getMask(&maskSet, iCur);
70536
70537     /* Insert code to test every subexpression that can be completely
70538     ** computed using the current set of tables.
70539     */
70540     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
70541       Expr *pE;
70542       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
70543       if( (pTerm->prereqAll & notReady)!=0 ) continue;
70544       pE = pTerm->pExpr;
70545       assert( pE!=0 );
70546       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
70547         continue;
70548       }
70549       sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
70550       pTerm->flags |= TERM_CODED;
70551     }
70552
70553     /* For a LEFT OUTER JOIN, generate code that will record the fact that
70554     ** at least one row of the right table has matched the left table.  
70555     */
70556     if( pLevel->iLeftJoin ){
70557       pLevel->top = sqlite3VdbeCurrentAddr(v);
70558       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
70559       VdbeComment((v, "record LEFT JOIN hit"));
70560       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
70561         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
70562         if( (pTerm->prereqAll & notReady)!=0 ) continue;
70563         assert( pTerm->pExpr );
70564         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
70565         pTerm->flags |= TERM_CODED;
70566       }
70567     }
70568   }
70569
70570 #ifdef SQLITE_TEST  /* For testing and debugging use only */
70571   /* Record in the query plan information about the current table
70572   ** and the index used to access it (if any).  If the table itself
70573   ** is not used, its name is just '{}'.  If no index is used
70574   ** the index is listed as "{}".  If the primary key is used the
70575   ** index name is '*'.
70576   */
70577   for(i=0; i<pTabList->nSrc; i++){
70578     char *z;
70579     int n;
70580     pLevel = &pWInfo->a[i];
70581     pTabItem = &pTabList->a[pLevel->iFrom];
70582     z = pTabItem->zAlias;
70583     if( z==0 ) z = pTabItem->pTab->zName;
70584     n = strlen(z);
70585     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
70586       if( pLevel->flags & WHERE_IDX_ONLY ){
70587         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
70588         nQPlan += 2;
70589       }else{
70590         memcpy(&sqlite3_query_plan[nQPlan], z, n);
70591         nQPlan += n;
70592       }
70593       sqlite3_query_plan[nQPlan++] = ' ';
70594     }
70595     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
70596       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
70597       nQPlan += 2;
70598     }else if( pLevel->pIdx==0 ){
70599       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
70600       nQPlan += 3;
70601     }else{
70602       n = strlen(pLevel->pIdx->zName);
70603       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
70604         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
70605         nQPlan += n;
70606         sqlite3_query_plan[nQPlan++] = ' ';
70607       }
70608     }
70609   }
70610   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
70611     sqlite3_query_plan[--nQPlan] = 0;
70612   }
70613   sqlite3_query_plan[nQPlan] = 0;
70614   nQPlan = 0;
70615 #endif /* SQLITE_TEST // Testing and debugging use only */
70616
70617   /* Record the continuation address in the WhereInfo structure.  Then
70618   ** clean up and return.
70619   */
70620   pWInfo->iContinue = cont;
70621   whereClauseClear(&wc);
70622   return pWInfo;
70623
70624   /* Jump here if malloc fails */
70625 whereBeginNoMem:
70626   whereClauseClear(&wc);
70627   whereInfoFree(pWInfo);
70628   return 0;
70629 }
70630
70631 /*
70632 ** Generate the end of the WHERE loop.  See comments on 
70633 ** sqlite3WhereBegin() for additional information.
70634 */
70635 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
70636   Vdbe *v = pWInfo->pParse->pVdbe;
70637   int i;
70638   WhereLevel *pLevel;
70639   SrcList *pTabList = pWInfo->pTabList;
70640
70641   /* Generate loop termination code.
70642   */
70643   for(i=pTabList->nSrc-1; i>=0; i--){
70644     pLevel = &pWInfo->a[i];
70645     sqlite3VdbeResolveLabel(v, pLevel->cont);
70646     if( pLevel->op!=OP_Noop ){
70647       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
70648     }
70649     if( pLevel->nIn ){
70650       struct InLoop *pIn;
70651       int j;
70652       sqlite3VdbeResolveLabel(v, pLevel->nxt);
70653       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
70654         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
70655         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
70656         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
70657       }
70658       sqlite3_free(pLevel->aInLoop);
70659     }
70660     sqlite3VdbeResolveLabel(v, pLevel->brk);
70661     if( pLevel->iLeftJoin ){
70662       int addr;
70663       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
70664       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
70665       if( pLevel->iIdxCur>=0 ){
70666         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
70667       }
70668       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
70669       sqlite3VdbeJumpHere(v, addr);
70670     }
70671   }
70672
70673   /* The "break" point is here, just past the end of the outer loop.
70674   ** Set it.
70675   */
70676   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
70677
70678   /* Close all of the cursors that were opened by sqlite3WhereBegin.
70679   */
70680   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
70681     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
70682     Table *pTab = pTabItem->pTab;
70683     assert( pTab!=0 );
70684     if( pTab->isEphem || pTab->pSelect ) continue;
70685     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
70686       sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
70687     }
70688     if( pLevel->pIdx!=0 ){
70689       sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
70690     }
70691
70692     /* If this scan uses an index, make code substitutions to read data
70693     ** from the index in preference to the table. Sometimes, this means
70694     ** the table need never be read from. This is a performance boost,
70695     ** as the vdbe level waits until the table is read before actually
70696     ** seeking the table cursor to the record corresponding to the current
70697     ** position in the index.
70698     ** 
70699     ** Calls to the code generator in between sqlite3WhereBegin and
70700     ** sqlite3WhereEnd will have created code that references the table
70701     ** directly.  This loop scans all that code looking for opcodes
70702     ** that reference the table and converts them into opcodes that
70703     ** reference the index.
70704     */
70705     if( pLevel->pIdx ){
70706       int k, j, last;
70707       VdbeOp *pOp;
70708       Index *pIdx = pLevel->pIdx;
70709       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
70710
70711       assert( pIdx!=0 );
70712       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
70713       last = sqlite3VdbeCurrentAddr(v);
70714       for(k=pWInfo->iTop; k<last; k++, pOp++){
70715         if( pOp->p1!=pLevel->iTabCur ) continue;
70716         if( pOp->opcode==OP_Column ){
70717           for(j=0; j<pIdx->nColumn; j++){
70718             if( pOp->p2==pIdx->aiColumn[j] ){
70719               pOp->p2 = j;
70720               pOp->p1 = pLevel->iIdxCur;
70721               break;
70722             }
70723           }
70724           assert(!useIndexOnly || j<pIdx->nColumn);
70725         }else if( pOp->opcode==OP_Rowid ){
70726           pOp->p1 = pLevel->iIdxCur;
70727           pOp->opcode = OP_IdxRowid;
70728         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
70729           pOp->opcode = OP_Noop;
70730         }
70731       }
70732     }
70733   }
70734
70735   /* Final cleanup
70736   */
70737   whereInfoFree(pWInfo);
70738   return;
70739 }
70740
70741 /************** End of where.c ***********************************************/
70742 /************** Begin file parse.c *******************************************/
70743 /* Driver template for the LEMON parser generator.
70744 ** The author disclaims copyright to this source code.
70745 */
70746 /* First off, code is include which follows the "include" declaration
70747 ** in the input file. */
70748
70749
70750 /*
70751 ** An instance of this structure holds information about the
70752 ** LIMIT clause of a SELECT statement.
70753 */
70754 struct LimitVal {
70755   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
70756   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
70757 };
70758
70759 /*
70760 ** An instance of this structure is used to store the LIKE,
70761 ** GLOB, NOT LIKE, and NOT GLOB operators.
70762 */
70763 struct LikeOp {
70764   Token eOperator;  /* "like" or "glob" or "regexp" */
70765   int not;         /* True if the NOT keyword is present */
70766 };
70767
70768 /*
70769 ** An instance of the following structure describes the event of a
70770 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
70771 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
70772 **
70773 **      UPDATE ON (a,b,c)
70774 **
70775 ** Then the "b" IdList records the list "a,b,c".
70776 */
70777 struct TrigEvent { int a; IdList * b; };
70778
70779 /*
70780 ** An instance of this structure holds the ATTACH key and the key type.
70781 */
70782 struct AttachKey { int type;  Token key; };
70783
70784 /* Next is all token values, in a form suitable for use by makeheaders.
70785 ** This section will be null unless lemon is run with the -m switch.
70786 */
70787 /* 
70788 ** These constants (all generated automatically by the parser generator)
70789 ** specify the various kinds of tokens (terminals) that the parser
70790 ** understands. 
70791 **
70792 ** Each symbol here is a terminal symbol in the grammar.
70793 */
70794 /* Make sure the INTERFACE macro is defined.
70795 */
70796 #ifndef INTERFACE
70797 # define INTERFACE 1
70798 #endif
70799 /* The next thing included is series of defines which control
70800 ** various aspects of the generated parser.
70801 **    YYCODETYPE         is the data type used for storing terminal
70802 **                       and nonterminal numbers.  "unsigned char" is
70803 **                       used if there are fewer than 250 terminals
70804 **                       and nonterminals.  "int" is used otherwise.
70805 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
70806 **                       to no legal terminal or nonterminal number.  This
70807 **                       number is used to fill in empty slots of the hash 
70808 **                       table.
70809 **    YYFALLBACK         If defined, this indicates that one or more tokens
70810 **                       have fall-back values which should be used if the
70811 **                       original value of the token will not parse.
70812 **    YYACTIONTYPE       is the data type used for storing terminal
70813 **                       and nonterminal numbers.  "unsigned char" is
70814 **                       used if there are fewer than 250 rules and
70815 **                       states combined.  "int" is used otherwise.
70816 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
70817 **                       directly to the parser from the tokenizer.
70818 **    YYMINORTYPE        is the data type used for all minor tokens.
70819 **                       This is typically a union of many types, one of
70820 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
70821 **                       for base tokens is called "yy0".
70822 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
70823 **                       zero the stack is dynamically sized using realloc()
70824 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
70825 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
70826 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
70827 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
70828 **    YYNSTATE           the combined number of states.
70829 **    YYNRULE            the number of rules in the grammar
70830 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
70831 **                       defined, then do no error processing.
70832 */
70833 #define YYCODETYPE unsigned char
70834 #define YYNOCODE 248
70835 #define YYACTIONTYPE unsigned short int
70836 #define YYWILDCARD 59
70837 #define sqlite3ParserTOKENTYPE Token
70838 typedef union {
70839   sqlite3ParserTOKENTYPE yy0;
70840   int yy46;
70841   struct LikeOp yy72;
70842   Expr* yy172;
70843   ExprList* yy174;
70844   Select* yy219;
70845   struct LimitVal yy234;
70846   TriggerStep* yy243;
70847   struct TrigEvent yy370;
70848   SrcList* yy373;
70849   struct {int value; int mask;} yy405;
70850   Token yy410;
70851   IdList* yy432;
70852 } YYMINORTYPE;
70853 #ifndef YYSTACKDEPTH
70854 #define YYSTACKDEPTH 100
70855 #endif
70856 #define sqlite3ParserARG_SDECL Parse *pParse;
70857 #define sqlite3ParserARG_PDECL ,Parse *pParse
70858 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
70859 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
70860 #define YYNSTATE 588
70861 #define YYNRULE 312
70862 #define YYFALLBACK 1
70863 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
70864 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
70865 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
70866
70867 /* Next are that tables used to determine what action to take based on the
70868 ** current state and lookahead token.  These tables are used to implement
70869 ** functions that take a state number and lookahead value and return an
70870 ** action integer.  
70871 **
70872 ** Suppose the action integer is N.  Then the action is determined as
70873 ** follows
70874 **
70875 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
70876 **                                      token onto the stack and goto state N.
70877 **
70878 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
70879 **
70880 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
70881 **
70882 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
70883 **
70884 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
70885 **                                      slots in the yy_action[] table.
70886 **
70887 ** The action table is constructed as a single large table named yy_action[].
70888 ** Given state S and lookahead X, the action is computed as
70889 **
70890 **      yy_action[ yy_shift_ofst[S] + X ]
70891 **
70892 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
70893 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
70894 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
70895 ** and that yy_default[S] should be used instead.  
70896 **
70897 ** The formula above is for computing the action when the lookahead is
70898 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
70899 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
70900 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
70901 ** YY_SHIFT_USE_DFLT.
70902 **
70903 ** The following are the tables generated in this section:
70904 **
70905 **  yy_action[]        A single table containing all actions.
70906 **  yy_lookahead[]     A table containing the lookahead for each entry in
70907 **                     yy_action.  Used to detect hash collisions.
70908 **  yy_shift_ofst[]    For each state, the offset into yy_action for
70909 **                     shifting terminals.
70910 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
70911 **                     shifting non-terminals after a reduce.
70912 **  yy_default[]       Default action for each state.
70913 */
70914 static const YYACTIONTYPE yy_action[] = {
70915  /*     0 */   292,  901,  124,  587,  409,  172,    2,  418,   61,   61,
70916  /*    10 */    61,   61,  519,   63,   63,   63,   63,   64,   64,   65,
70917  /*    20 */    65,   65,   66,  210,  447,  212,  425,  431,   68,   63,
70918  /*    30 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  210,
70919  /*    40 */   391,  388,  396,  451,   60,   59,  297,  435,  436,  432,
70920  /*    50 */   432,   62,   62,   61,   61,   61,   61,  263,   63,   63,
70921  /*    60 */    63,   63,   64,   64,   65,   65,   65,   66,  210,  292,
70922  /*    70 */   493,  494,  418,  489,  208,   82,   67,  420,   69,  154,
70923  /*    80 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
70924  /*    90 */   210,   67,  462,   69,  154,  425,  431,  573,  264,   58,
70925  /*   100 */    64,   64,   65,   65,   65,   66,  210,  397,  398,  422,
70926  /*   110 */   422,  422,  292,   60,   59,  297,  435,  436,  432,  432,
70927  /*   120 */    62,   62,   61,   61,   61,   61,  317,   63,   63,   63,
70928  /*   130 */    63,   64,   64,   65,   65,   65,   66,  210,  425,  431,
70929  /*   140 */    94,   65,   65,   65,   66,  210,  396,  210,  414,   34,
70930  /*   150 */    56,  298,  442,  443,  410,  488,   60,   59,  297,  435,
70931  /*   160 */   436,  432,  432,   62,   62,   61,   61,   61,   61,  490,
70932  /*   170 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
70933  /*   180 */   210,  292,  257,  524,  295,  571,  113,  408,  522,  451,
70934  /*   190 */   331,  317,  407,   20,  418,  340,  519,  396,  532,  531,
70935  /*   200 */   505,  447,  212,  570,  569,  208,  530,  425,  431,  149,
70936  /*   210 */   150,  397,  398,  414,   41,  211,  151,  533,  372,  489,
70937  /*   220 */   261,  568,  259,  420,  292,   60,   59,  297,  435,  436,
70938  /*   230 */   432,  432,   62,   62,   61,   61,   61,   61,  317,   63,
70939  /*   240 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  210,
70940  /*   250 */   425,  431,  447,  333,  215,  422,  422,  422,  363,  418,
70941  /*   260 */   414,   41,  397,  398,  366,  567,  211,  292,   60,   59,
70942  /*   270 */   297,  435,  436,  432,  432,   62,   62,   61,   61,   61,
70943  /*   280 */    61,  396,   63,   63,   63,   63,   64,   64,   65,   65,
70944  /*   290 */    65,   66,  210,  425,  431,  491,  300,  524,  474,   66,
70945  /*   300 */   210,  214,  474,  229,  411,  286,  534,   20,  449,  523,
70946  /*   310 */   168,   60,   59,  297,  435,  436,  432,  432,   62,   62,
70947  /*   320 */    61,   61,   61,   61,  474,   63,   63,   63,   63,   64,
70948  /*   330 */    64,   65,   65,   65,   66,  210,  209,  480,  317,   77,
70949  /*   340 */   292,  239,  300,   55,  484,  230,  397,  398,  181,  547,
70950  /*   350 */   494,  345,  348,  349,   67,  152,   69,  154,  339,  524,
70951  /*   360 */   414,   35,  350,  241,  221,  370,  425,  431,  578,   20,
70952  /*   370 */   164,  118,  243,  343,  248,  344,  176,  322,  442,  443,
70953  /*   380 */   414,    3,   80,  252,   60,   59,  297,  435,  436,  432,
70954  /*   390 */   432,   62,   62,   61,   61,   61,   61,  174,   63,   63,
70955  /*   400 */    63,   63,   64,   64,   65,   65,   65,   66,  210,  292,
70956  /*   410 */   221,  550,  236,  487,  510,  353,  317,  118,  243,  343,
70957  /*   420 */   248,  344,  176,  181,  317,  525,  345,  348,  349,  252,
70958  /*   430 */   223,  415,  155,  464,  511,  425,  431,  350,  414,   34,
70959  /*   440 */   465,  211,  177,  175,  160,  237,  414,   34,  338,  549,
70960  /*   450 */   449,  323,  168,   60,   59,  297,  435,  436,  432,  432,
70961  /*   460 */    62,   62,   61,   61,   61,   61,  415,   63,   63,   63,
70962  /*   470 */    63,   64,   64,   65,   65,   65,   66,  210,  292,  542,
70963  /*   480 */   335,  517,  504,  541,  456,  571,  302,   19,  331,  144,
70964  /*   490 */   317,  390,  317,  330,    2,  362,  457,  294,  483,  373,
70965  /*   500 */   269,  268,  252,  570,  425,  431,  588,  391,  388,  458,
70966  /*   510 */   208,  495,  414,   49,  414,   49,  303,  585,  892,  159,
70967  /*   520 */   892,  496,   60,   59,  297,  435,  436,  432,  432,   62,
70968  /*   530 */    62,   61,   61,   61,   61,  201,   63,   63,   63,   63,
70969  /*   540 */    64,   64,   65,   65,   65,   66,  210,  292,  317,  181,
70970  /*   550 */   439,  255,  345,  348,  349,  370,  153,  582,  308,  251,
70971  /*   560 */   309,  452,   76,  350,   78,  382,  211,  426,  427,  415,
70972  /*   570 */   414,   27,  319,  425,  431,  440,    1,   22,  585,  891,
70973  /*   580 */   396,  891,  544,  478,  320,  263,  438,  438,  429,  430,
70974  /*   590 */   415,   60,   59,  297,  435,  436,  432,  432,   62,   62,
70975  /*   600 */    61,   61,   61,   61,  328,   63,   63,   63,   63,   64,
70976  /*   610 */    64,   65,   65,   65,   66,  210,  292,  428,  582,  374,
70977  /*   620 */   224,   93,  517,    9,  336,  396,  557,  396,  456,   67,
70978  /*   630 */   396,   69,  154,  399,  400,  401,  320,  238,  438,  438,
70979  /*   640 */   457,  318,  425,  431,  299,  397,  398,  320,  433,  438,
70980  /*   650 */   438,  581,  291,  458,  225,  327,    5,  222,  546,  292,
70981  /*   660 */    60,   59,  297,  435,  436,  432,  432,   62,   62,   61,
70982  /*   670 */    61,   61,   61,  395,   63,   63,   63,   63,   64,   64,
70983  /*   680 */    65,   65,   65,   66,  210,  425,  431,  482,  313,  392,
70984  /*   690 */   397,  398,  397,  398,  207,  397,  398,  824,  273,  517,
70985  /*   700 */   251,  200,  292,   60,   59,  297,  435,  436,  432,  432,
70986  /*   710 */    62,   62,   61,   61,   61,   61,  470,   63,   63,   63,
70987  /*   720 */    63,   64,   64,   65,   65,   65,   66,  210,  425,  431,
70988  /*   730 */   171,  160,  263,  263,  304,  415,  276,  119,  274,  263,
70989  /*   740 */   517,  517,  263,  517,  192,  292,   60,   70,  297,  435,
70990  /*   750 */   436,  432,  432,   62,   62,   61,   61,   61,   61,  379,
70991  /*   760 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
70992  /*   770 */   210,  425,  431,  384,  559,  305,  306,  251,  415,  320,
70993  /*   780 */   560,  438,  438,  561,  540,  360,  540,  387,  292,  196,
70994  /*   790 */    59,  297,  435,  436,  432,  432,   62,   62,   61,   61,
70995  /*   800 */    61,   61,  371,   63,   63,   63,   63,   64,   64,   65,
70996  /*   810 */    65,   65,   66,  210,  425,  431,  396,  275,  251,  251,
70997  /*   820 */   172,  250,  418,  415,  386,  367,  178,  179,  180,  469,
70998  /*   830 */   311,  123,  156,  128,  297,  435,  436,  432,  432,   62,
70999  /*   840 */    62,   61,   61,   61,   61,  317,   63,   63,   63,   63,
71000  /*   850 */    64,   64,   65,   65,   65,   66,  210,   72,  324,  177,
71001  /*   860 */     4,  317,  263,  317,  296,  263,  415,  414,   28,  317,
71002  /*   870 */   263,  317,  321,   72,  324,  317,    4,  421,  445,  445,
71003  /*   880 */   296,  397,  398,  414,   23,  414,   32,  418,  321,  326,
71004  /*   890 */   329,  414,   53,  414,   52,  317,  158,  414,   98,  451,
71005  /*   900 */   317,  194,  317,  277,  317,  326,  378,  471,  502,  317,
71006  /*   910 */   478,  279,  478,  165,  294,  451,  317,  414,   96,   75,
71007  /*   920 */    74,  469,  414,  101,  414,  102,  414,  112,   73,  315,
71008  /*   930 */   316,  414,  114,  420,  448,   75,   74,  481,  414,   16,
71009  /*   940 */   381,  317,  183,  467,   73,  315,  316,   72,  324,  420,
71010  /*   950 */     4,  208,  317,  186,  296,  317,  499,  500,  476,  208,
71011  /*   960 */   173,  341,  321,  414,   99,  422,  422,  422,  423,  424,
71012  /*   970 */    11,  361,  380,  307,  414,   33,  415,  414,   97,  326,
71013  /*   980 */   460,  422,  422,  422,  423,  424,   11,  415,  413,  451,
71014  /*   990 */   413,  162,  412,  317,  412,  468,  226,  227,  228,  104,
71015  /*  1000 */    84,  473,  317,  509,  508,  317,  622,  477,  317,   75,
71016  /*  1010 */    74,  249,  205,   21,  281,  414,   24,  418,   73,  315,
71017  /*  1020 */   316,  282,  317,  420,  414,   54,  507,  414,  115,  317,
71018  /*  1030 */   414,  116,  506,  203,  147,  549,  244,  512,  526,  202,
71019  /*  1040 */   317,  513,  204,  317,  414,  117,  317,  245,  317,   18,
71020  /*  1050 */   317,  414,   25,  317,  256,  422,  422,  422,  423,  424,
71021  /*  1060 */    11,  258,  414,   36,  260,  414,   37,  317,  414,   26,
71022  /*  1070 */   414,   38,  414,   39,  262,  414,   40,  317,  514,  317,
71023  /*  1080 */   128,  317,  418,  317,  189,  377,  278,  268,  267,  414,
71024  /*  1090 */    42,  293,  317,  254,  317,  128,  208,  365,    8,  414,
71025  /*  1100 */    43,  414,   44,  414,   29,  414,   30,  352,  368,  128,
71026  /*  1110 */   317,  545,  317,  128,  414,   45,  414,   46,  317,  583,
71027  /*  1120 */   383,  553,  317,  173,  554,  317,   91,  317,  564,  369,
71028  /*  1130 */    91,  357,  414,   47,  414,   48,  580,  270,  290,  271,
71029  /*  1140 */   414,   31,  272,  556,  414,   10,  566,  414,   50,  414,
71030  /*  1150 */    51,  280,  283,  284,  577,  146,  463,  405,  584,  231,
71031  /*  1160 */   325,  419,  444,  466,  446,  246,  505,  552,  563,  515,
71032  /*  1170 */   516,  520,  163,  518,  394,  347,    7,  402,  403,  404,
71033  /*  1180 */   314,   84,  232,  334,  332,   83,   79,  416,  170,   57,
71034  /*  1190 */   213,  461,  125,   85,  337,  342,  492,  301,  233,  498,
71035  /*  1200 */   497,  105,  502,  219,  354,  247,  521,  234,  501,  235,
71036  /*  1210 */   287,  417,  503,  218,  527,  528,  529,  358,  240,  535,
71037  /*  1220 */   475,  242,  288,  479,  356,  184,  185,  121,  187,  132,
71038  /*  1230 */   188,  548,  537,   88,  190,  193,  364,  142,  375,  376,
71039  /*  1240 */   555,  133,  220,  562,  134,  310,  135,  138,  136,  574,
71040  /*  1250 */   575,  141,  576,  265,  579,  100,  538,  217,  393,   92,
71041  /*  1260 */   103,   95,  406,  623,  624,  166,  434,  167,  437,   71,
71042  /*  1270 */   453,  441,  450,   17,  143,  157,  169,    6,  111,   13,
71043  /*  1280 */   454,  455,  459,  472,  126,   81,   12,  127,  161,  485,
71044  /*  1290 */   486,  216,   86,  122,  106,  182,  253,  346,  312,  107,
71045  /*  1300 */   120,   87,  351,  108,  245,  355,  145,  536,  359,  129,
71046  /*  1310 */   173,  266,  191,  109,  289,  551,  130,  539,  195,  543,
71047  /*  1320 */   131,   14,  197,  199,  198,  558,  137,  139,  140,  110,
71048  /*  1330 */    15,  285,  572,  206,  389,  565,  385,  148,  586,  902,
71049  /*  1340 */   902,  902,  902,  902,  902,   89,   90,
71050 };
71051 static const YYCODETYPE yy_lookahead[] = {
71052  /*     0 */    16,  139,  140,  141,  168,   21,  144,   23,   69,   70,
71053  /*    10 */    71,   72,  176,   74,   75,   76,   77,   78,   79,   80,
71054  /*    20 */    81,   82,   83,   84,   78,   79,   42,   43,   73,   74,
71055  /*    30 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
71056  /*    40 */     1,    2,   23,   58,   60,   61,   62,   63,   64,   65,
71057  /*    50 */    66,   67,   68,   69,   70,   71,   72,  147,   74,   75,
71058  /*    60 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
71059  /*    70 */   185,  186,   88,   88,  110,   22,  217,   92,  219,  220,
71060  /*    80 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
71061  /*    90 */    84,  217,  218,  219,  220,   42,   43,  238,  188,   46,
71062  /*   100 */    78,   79,   80,   81,   82,   83,   84,   88,   89,  124,
71063  /*   110 */   125,  126,   16,   60,   61,   62,   63,   64,   65,   66,
71064  /*   120 */    67,   68,   69,   70,   71,   72,  147,   74,   75,   76,
71065  /*   130 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
71066  /*   140 */    44,   80,   81,   82,   83,   84,   23,   84,  169,  170,
71067  /*   150 */    19,  164,  165,  166,   23,  169,   60,   61,   62,   63,
71068  /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  169,
71069  /*   170 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
71070  /*   180 */    84,   16,   14,  147,  150,  147,   21,  167,  168,   58,
71071  /*   190 */   211,  147,  156,  157,   23,  216,  176,   23,  181,  176,
71072  /*   200 */   177,   78,   79,  165,  166,  110,  183,   42,   43,   78,
71073  /*   210 */    79,   88,   89,  169,  170,  228,  180,  181,  123,   88,
71074  /*   220 */    52,   98,   54,   92,   16,   60,   61,   62,   63,   64,
71075  /*   230 */    65,   66,   67,   68,   69,   70,   71,   72,  147,   74,
71076  /*   240 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
71077  /*   250 */    42,   43,   78,  209,  210,  124,  125,  126,  224,   88,
71078  /*   260 */   169,  170,   88,   89,  230,  227,  228,   16,   60,   61,
71079  /*   270 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
71080  /*   280 */    72,   23,   74,   75,   76,   77,   78,   79,   80,   81,
71081  /*   290 */    82,   83,   84,   42,   43,  160,   16,  147,  161,   83,
71082  /*   300 */    84,  210,  161,  153,  169,  158,  156,  157,  161,  162,
71083  /*   310 */   163,   60,   61,   62,   63,   64,   65,   66,   67,   68,
71084  /*   320 */    69,   70,   71,   72,  161,   74,   75,   76,   77,   78,
71085  /*   330 */    79,   80,   81,   82,   83,   84,  192,  200,  147,  131,
71086  /*   340 */    16,  200,   16,  199,   20,  190,   88,   89,   90,  185,
71087  /*   350 */   186,   93,   94,   95,  217,   22,  219,  220,  147,  147,
71088  /*   360 */   169,  170,  104,  200,   84,  147,   42,   43,  156,  157,
71089  /*   370 */    90,   91,   92,   93,   94,   95,   96,  164,  165,  166,
71090  /*   380 */   169,  170,  131,  103,   60,   61,   62,   63,   64,   65,
71091  /*   390 */    66,   67,   68,   69,   70,   71,   72,  155,   74,   75,
71092  /*   400 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
71093  /*   410 */    84,   11,  221,   20,   30,   16,  147,   91,   92,   93,
71094  /*   420 */    94,   95,   96,   90,  147,  181,   93,   94,   95,  103,
71095  /*   430 */   212,  189,  155,   27,   50,   42,   43,  104,  169,  170,
71096  /*   440 */    34,  228,   43,  201,  202,  147,  169,  170,  206,   49,
71097  /*   450 */   161,  162,  163,   60,   61,   62,   63,   64,   65,   66,
71098  /*   460 */    67,   68,   69,   70,   71,   72,  189,   74,   75,   76,
71099  /*   470 */    77,   78,   79,   80,   81,   82,   83,   84,   16,   25,
71100  /*   480 */   211,  147,   20,   29,   12,  147,  102,   19,  211,   21,
71101  /*   490 */   147,  141,  147,  216,  144,   41,   24,   98,   20,   99,
71102  /*   500 */   100,  101,  103,  165,   42,   43,    0,    1,    2,   37,
71103  /*   510 */   110,   39,  169,  170,  169,  170,  182,   19,   20,  147,
71104  /*   520 */    22,   49,   60,   61,   62,   63,   64,   65,   66,   67,
71105  /*   530 */    68,   69,   70,   71,   72,  155,   74,   75,   76,   77,
71106  /*   540 */    78,   79,   80,   81,   82,   83,   84,   16,  147,   90,
71107  /*   550 */    20,   20,   93,   94,   95,  147,  155,   59,  215,  225,
71108  /*   560 */   215,   20,  130,  104,  132,  227,  228,   42,   43,  189,
71109  /*   570 */   169,  170,   16,   42,   43,   20,   19,   22,   19,   20,
71110  /*   580 */    23,   22,   18,  147,  106,  147,  108,  109,   63,   64,
71111  /*   590 */   189,   60,   61,   62,   63,   64,   65,   66,   67,   68,
71112  /*   600 */    69,   70,   71,   72,  186,   74,   75,   76,   77,   78,
71113  /*   610 */    79,   80,   81,   82,   83,   84,   16,   92,   59,   55,
71114  /*   620 */   212,   21,  147,   19,  147,   23,  188,   23,   12,  217,
71115  /*   630 */    23,  219,  220,    7,    8,    9,  106,  147,  108,  109,
71116  /*   640 */    24,  147,   42,   43,  208,   88,   89,  106,   92,  108,
71117  /*   650 */   109,  244,  245,   37,  145,   39,  191,  182,   94,   16,
71118  /*   660 */    60,   61,   62,   63,   64,   65,   66,   67,   68,   69,
71119  /*   670 */    70,   71,   72,  147,   74,   75,   76,   77,   78,   79,
71120  /*   680 */    80,   81,   82,   83,   84,   42,   43,   80,  142,  143,
71121  /*   690 */    88,   89,   88,   89,  148,   88,   89,  133,   14,  147,
71122  /*   700 */   225,  155,   16,   60,   61,   62,   63,   64,   65,   66,
71123  /*   710 */    67,   68,   69,   70,   71,   72,  114,   74,   75,   76,
71124  /*   720 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
71125  /*   730 */   201,  202,  147,  147,  182,  189,   52,  147,   54,  147,
71126  /*   740 */   147,  147,  147,  147,  155,   16,   60,   61,   62,   63,
71127  /*   750 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  213,
71128  /*   760 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
71129  /*   770 */    84,   42,   43,  188,  188,  182,  182,  225,  189,  106,
71130  /*   780 */   188,  108,  109,  188,   99,  100,  101,  241,   16,  155,
71131  /*   790 */    61,   62,   63,   64,   65,   66,   67,   68,   69,   70,
71132  /*   800 */    71,   72,  213,   74,   75,   76,   77,   78,   79,   80,
71133  /*   810 */    81,   82,   83,   84,   42,   43,   23,  133,  225,  225,
71134  /*   820 */    21,  225,   23,  189,  239,  236,   99,  100,  101,   22,
71135  /*   830 */   242,  243,  155,   22,   62,   63,   64,   65,   66,   67,
71136  /*   840 */    68,   69,   70,   71,   72,  147,   74,   75,   76,   77,
71137  /*   850 */    78,   79,   80,   81,   82,   83,   84,   16,   17,   43,
71138  /*   860 */    19,  147,  147,  147,   23,  147,  189,  169,  170,  147,
71139  /*   870 */   147,  147,   31,   16,   17,  147,   19,  147,  124,  125,
71140  /*   880 */    23,   88,   89,  169,  170,  169,  170,   88,   31,   48,
71141  /*   890 */   147,  169,  170,  169,  170,  147,   89,  169,  170,   58,
71142  /*   900 */   147,   22,  147,  188,  147,   48,  188,  114,   97,  147,
71143  /*   910 */   147,  188,  147,   19,   98,   58,  147,  169,  170,   78,
71144  /*   920 */    79,  114,  169,  170,  169,  170,  169,  170,   87,   88,
71145  /*   930 */    89,  169,  170,   92,  161,   78,   79,   80,  169,  170,
71146  /*   940 */    91,  147,  155,   22,   87,   88,   89,   16,   17,   92,
71147  /*   950 */    19,  110,  147,  155,   23,  147,    7,    8,   20,  110,
71148  /*   960 */    22,   80,   31,  169,  170,  124,  125,  126,  127,  128,
71149  /*   970 */   129,  208,  123,  208,  169,  170,  189,  169,  170,   48,
71150  /*   980 */   147,  124,  125,  126,  127,  128,  129,  189,  107,   58,
71151  /*   990 */   107,    5,  111,  147,  111,  203,   10,   11,   12,   13,
71152  /*  1000 */   121,  147,  147,   91,   92,  147,  112,  147,  147,   78,
71153  /*  1010 */    79,  147,   26,   19,   28,  169,  170,   23,   87,   88,
71154  /*  1020 */    89,   35,  147,   92,  169,  170,  178,  169,  170,  147,
71155  /*  1030 */   169,  170,  147,   47,  113,   49,   92,  178,  147,   53,
71156  /*  1040 */   147,  178,   56,  147,  169,  170,  147,  103,  147,   19,
71157  /*  1050 */   147,  169,  170,  147,  147,  124,  125,  126,  127,  128,
71158  /*  1060 */   129,  147,  169,  170,  147,  169,  170,  147,  169,  170,
71159  /*  1070 */   169,  170,  169,  170,  147,  169,  170,  147,   20,  147,
71160  /*  1080 */    22,  147,   88,  147,  232,   99,  100,  101,  147,  169,
71161  /*  1090 */   170,  105,  147,   20,  147,   22,  110,  147,   68,  169,
71162  /*  1100 */   170,  169,  170,  169,  170,  169,  170,   20,  147,   22,
71163  /*  1110 */   147,   20,  147,   22,  169,  170,  169,  170,  147,   20,
71164  /*  1120 */   134,   20,  147,   22,   20,  147,   22,  147,   20,  147,
71165  /*  1130 */    22,  233,  169,  170,  169,  170,   20,  147,   22,  147,
71166  /*  1140 */   169,  170,  147,  147,  169,  170,  147,  169,  170,  169,
71167  /*  1150 */   170,  147,  147,  147,  147,  191,  172,  149,   59,  193,
71168  /*  1160 */   223,  161,  229,  172,  229,  172,  177,  194,  194,  172,
71169  /*  1170 */   161,  161,    6,  172,  146,  173,   22,  146,  146,  146,
71170  /*  1180 */   154,  121,  194,  118,  116,  119,  130,  189,  112,  120,
71171  /*  1190 */   222,  152,  152,   98,  115,   98,  171,   40,  195,  179,
71172  /*  1200 */   171,   19,   97,   84,   15,  171,  179,  196,  173,  197,
71173  /*  1210 */   174,  198,  171,  226,  171,  171,  171,   38,  204,  152,
71174  /*  1220 */   205,  204,  174,  205,  152,  151,  151,   60,  151,   19,
71175  /*  1230 */   152,  184,  152,  130,  151,  184,  152,  214,  152,   15,
71176  /*  1240 */   194,  187,  226,  194,  187,  152,  187,  184,  187,   33,
71177  /*  1250 */   152,  214,  152,  234,  137,  159,  235,  175,    1,  237,
71178  /*  1260 */   175,  237,   20,  112,  112,  112,   92,  112,  107,   19,
71179  /*  1270 */    11,   20,   20,  231,   19,   19,   22,  117,  240,  117,
71180  /*  1280 */    20,   20,   20,  114,   19,   22,   22,   20,  112,   20,
71181  /*  1290 */    20,   44,   19,  243,   19,   96,   20,   44,  246,   19,
71182  /*  1300 */    32,   19,   44,   19,  103,   16,   21,   17,   36,   98,
71183  /*  1310 */    22,  133,   98,   19,    5,    1,   45,   51,  122,   45,
71184  /*  1320 */   102,   19,  113,  115,   14,   17,  113,  102,  122,   14,
71185  /*  1330 */    19,  136,   20,  135,    3,  123,   57,   19,    4,  247,
71186  /*  1340 */   247,  247,  247,  247,  247,   68,   68,
71187 };
71188 #define YY_SHIFT_USE_DFLT (-62)
71189 #define YY_SHIFT_MAX 389
71190 static const short yy_shift_ofst[] = {
71191  /*     0 */    39,  841,  986,  -16,  841,  931,  931,  258,  123,  -36,
71192  /*    10 */    96,  931,  931,  931,  931,  931,  -45,  400,  174,   19,
71193  /*    20 */   171,  -54,  -54,   53,  165,  208,  251,  324,  393,  462,
71194  /*    30 */   531,  600,  643,  686,  643,  643,  643,  643,  643,  643,
71195  /*    40 */   643,  643,  643,  643,  643,  643,  643,  643,  643,  643,
71196  /*    50 */   643,  643,  729,  772,  772,  857,  931,  931,  931,  931,
71197  /*    60 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
71198  /*    70 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
71199  /*    80 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
71200  /*    90 */   931,  931,  931,  931,  931,  931,  -61,  -61,    6,    6,
71201  /*   100 */   280,   22,   61,  399,  564,   19,   19,   19,   19,   19,
71202  /*   110 */    19,   19,  216,  171,   63,  -62,  -62,  -62,  131,  326,
71203  /*   120 */   472,  472,  498,  559,  506,  799,   19,  799,   19,   19,
71204  /*   130 */    19,   19,   19,   19,   19,   19,   19,   19,   19,   19,
71205  /*   140 */    19,  849,   95,  -36,  -36,  -36,  -62,  -62,  -62,  -15,
71206  /*   150 */   -15,  333,  459,  478,  557,  530,  541,  616,  602,  793,
71207  /*   160 */   604,  607,  626,   19,   19,  881,   19,   19,  994,   19,
71208  /*   170 */    19,  807,   19,   19,  673,  807,   19,   19,  384,  384,
71209  /*   180 */   384,   19,   19,  673,   19,   19,  673,   19,  454,  685,
71210  /*   190 */    19,   19,  673,   19,   19,   19,  673,   19,   19,   19,
71211  /*   200 */   673,  673,   19,   19,   19,   19,   19,  468,  883,  921,
71212  /*   210 */   171,  754,  754,  432,  406,  406,  406,  816,  406,  171,
71213  /*   220 */   406,  171,  811,  879,  879, 1166, 1166, 1166, 1166, 1154,
71214  /*   230 */   -36, 1060, 1065, 1066, 1068, 1069, 1056, 1076, 1076, 1095,
71215  /*   240 */  1079, 1095, 1079, 1097, 1097, 1157, 1097, 1105, 1097, 1182,
71216  /*   250 */  1119, 1119, 1157, 1097, 1097, 1097, 1182, 1189, 1076, 1189,
71217  /*   260 */  1076, 1189, 1076, 1076, 1179, 1103, 1189, 1076, 1167, 1167,
71218  /*   270 */  1210, 1060, 1076, 1224, 1224, 1224, 1224, 1060, 1167, 1210,
71219  /*   280 */  1076, 1216, 1216, 1076, 1076, 1117,  -62,  -62,  -62,  -62,
71220  /*   290 */   -62,  -62,  525,  684,  727,  168,  894,  556,  555,  938,
71221  /*   300 */   944,  949,  912, 1058, 1073, 1087, 1091, 1101, 1104, 1108,
71222  /*   310 */  1030, 1116, 1099, 1257, 1242, 1151, 1152, 1153, 1155, 1174,
71223  /*   320 */  1161, 1250, 1251, 1252, 1255, 1259, 1256, 1260, 1254, 1261,
71224  /*   330 */  1262, 1263, 1160, 1264, 1162, 1263, 1169, 1265, 1267, 1176,
71225  /*   340 */  1269, 1270, 1268, 1247, 1273, 1253, 1275, 1276, 1280, 1282,
71226  /*   350 */  1258, 1284, 1199, 1201, 1289, 1290, 1285, 1211, 1272, 1266,
71227  /*   360 */  1271, 1288, 1274, 1178, 1214, 1294, 1309, 1314, 1218, 1277,
71228  /*   370 */  1278, 1196, 1302, 1209, 1310, 1208, 1308, 1213, 1225, 1206,
71229  /*   380 */  1311, 1212, 1312, 1315, 1279, 1198, 1195, 1318, 1331, 1334,
71230 };
71231 #define YY_REDUCE_USE_DFLT (-165)
71232 #define YY_REDUCE_MAX 291
71233 static const short yy_reduce_ofst[] = {
71234  /*     0 */  -138,  277,  546,  137,  401,  -21,   44,   36,   38,  242,
71235  /*    10 */  -141,  191,   91,  269,  343,  345, -126,  589,  338,  150,
71236  /*    20 */   147,  -13,  213,  412,  412,  412,  412,  412,  412,  412,
71237  /*    30 */   412,  412,  412,  412,  412,  412,  412,  412,  412,  412,
71238  /*    40 */   412,  412,  412,  412,  412,  412,  412,  412,  412,  412,
71239  /*    50 */   412,  412,  412,  412,  412,  211,  698,  714,  716,  722,
71240  /*    60 */   724,  728,  748,  753,  755,  757,  762,  769,  794,  805,
71241  /*    70 */   808,  846,  855,  858,  861,  875,  882,  893,  896,  899,
71242  /*    80 */   901,  903,  906,  920,  930,  932,  934,  936,  945,  947,
71243  /*    90 */   963,  965,  971,  975,  978,  980,  412,  412,  412,  412,
71244  /*   100 */    20,  412,  412,   23,   34,  334,  475,  552,  593,  594,
71245  /*   110 */   585,  212,  412,  289,  412,  412,  412,  412,  135, -164,
71246  /*   120 */  -115,  164,  407,  407,  350,  141,  436,  163,  596,  -90,
71247  /*   130 */   763,  218,  765,  438,  586,  592,  595,  715,  718,  408,
71248  /*   140 */   723,  380,  634,  677,  787,  798,  144,  529,  588,  -14,
71249  /*   150 */     0,   17,  244,  155,  298,  155,  155,  418,  372,  477,
71250  /*   160 */   490,  494,  509,  526,  590,  465,  494,  730,  773,  743,
71251  /*   170 */   833,  792,  854,  860,  155,  792,  864,  885,  848,  859,
71252  /*   180 */   863,  891,  907,  155,  914,  917,  155,  927,  852,  898,
71253  /*   190 */   941,  950,  155,  961,  982,  990,  155,  992,  995,  996,
71254  /*   200 */   155,  155,  999, 1004, 1005, 1006, 1007, 1008,  964,  966,
71255  /*   210 */  1000,  933,  935,  937,  984,  991,  993,  989,  997, 1009,
71256  /*   220 */  1001, 1010, 1002,  973,  974, 1028, 1031, 1032, 1033, 1026,
71257  /*   230 */   998,  988, 1003, 1011, 1012, 1013,  968, 1039, 1040, 1014,
71258  /*   240 */  1015, 1017, 1018, 1025, 1029, 1020, 1034, 1035, 1041, 1036,
71259  /*   250 */   987, 1016, 1027, 1043, 1044, 1045, 1048, 1074, 1067, 1075,
71260  /*   260 */  1072, 1077, 1078, 1080, 1019, 1021, 1083, 1084, 1047, 1051,
71261  /*   270 */  1023, 1046, 1086, 1054, 1057, 1059, 1061, 1049, 1063, 1037,
71262  /*   280 */  1093, 1022, 1024, 1098, 1100, 1038, 1096, 1082, 1085, 1042,
71263  /*   290 */  1050, 1052,
71264 };
71265 static const YYACTIONTYPE yy_default[] = {
71266  /*     0 */   594,  819,  900,  709,  900,  819,  900,  900,  846,  713,
71267  /*    10 */   875,  817,  900,  900,  900,  900,  791,  900,  846,  900,
71268  /*    20 */   625,  846,  846,  742,  900,  900,  900,  900,  900,  900,
71269  /*    30 */   900,  900,  743,  900,  821,  816,  812,  814,  813,  820,
71270  /*    40 */   744,  733,  740,  747,  725,  859,  749,  750,  756,  757,
71271  /*    50 */   876,  874,  779,  778,  797,  900,  900,  900,  900,  900,
71272  /*    60 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71273  /*    70 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71274  /*    80 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71275  /*    90 */   900,  900,  900,  900,  900,  900,  781,  803,  780,  790,
71276  /*   100 */   618,  782,  783,  678,  613,  900,  900,  900,  900,  900,
71277  /*   110 */   900,  900,  784,  900,  785,  798,  799,  800,  900,  900,
71278  /*   120 */   900,  900,  900,  900,  594,  709,  900,  709,  900,  900,
71279  /*   130 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71280  /*   140 */   900,  900,  900,  900,  900,  900,  703,  713,  893,  900,
71281  /*   150 */   900,  669,  900,  900,  900,  900,  900,  900,  900,  900,
71282  /*   160 */   900,  900,  601,  599,  900,  701,  900,  900,  627,  900,
71283  /*   170 */   900,  711,  900,  900,  716,  717,  900,  900,  900,  900,
71284  /*   180 */   900,  900,  900,  615,  900,  900,  690,  900,  852,  900,
71285  /*   190 */   900,  900,  866,  900,  900,  900,  864,  900,  900,  900,
71286  /*   200 */   692,  752,  833,  900,  879,  881,  900,  900,  701,  710,
71287  /*   210 */   900,  900,  900,  815,  736,  736,  736,  648,  736,  900,
71288  /*   220 */   736,  900,  651,  746,  746,  598,  598,  598,  598,  668,
71289  /*   230 */   900,  746,  737,  739,  729,  741,  900,  718,  718,  726,
71290  /*   240 */   728,  726,  728,  680,  680,  665,  680,  651,  680,  825,
71291  /*   250 */   830,  830,  665,  680,  680,  680,  825,  610,  718,  610,
71292  /*   260 */   718,  610,  718,  718,  856,  858,  610,  718,  682,  682,
71293  /*   270 */   758,  746,  718,  689,  689,  689,  689,  746,  682,  758,
71294  /*   280 */   718,  878,  878,  718,  718,  886,  635,  653,  653,  861,
71295  /*   290 */   893,  898,  900,  900,  900,  900,  765,  900,  900,  900,
71296  /*   300 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71297  /*   310 */   839,  900,  900,  900,  900,  770,  766,  900,  767,  900,
71298  /*   320 */   695,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71299  /*   330 */   900,  818,  900,  730,  900,  738,  900,  900,  900,  900,
71300  /*   340 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71301  /*   350 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71302  /*   360 */   854,  855,  900,  900,  900,  900,  900,  900,  900,  900,
71303  /*   370 */   900,  900,  900,  900,  900,  900,  900,  900,  900,  900,
71304  /*   380 */   900,  900,  900,  900,  885,  900,  900,  888,  595,  900,
71305  /*   390 */   589,  592,  591,  593,  597,  600,  622,  623,  624,  602,
71306  /*   400 */   603,  604,  605,  606,  607,  608,  614,  616,  634,  636,
71307  /*   410 */   620,  638,  699,  700,  762,  693,  694,  698,  621,  773,
71308  /*   420 */   764,  768,  769,  771,  772,  786,  787,  789,  795,  802,
71309  /*   430 */   805,  788,  793,  794,  796,  801,  804,  696,  697,  808,
71310  /*   440 */   628,  629,  632,  633,  842,  844,  843,  845,  631,  630,
71311  /*   450 */   774,  777,  810,  811,  867,  868,  869,  870,  871,  806,
71312  /*   460 */   719,  809,  792,  731,  734,  735,  732,  702,  712,  721,
71313  /*   470 */   722,  723,  724,  707,  708,  714,  727,  760,  761,  715,
71314  /*   480 */   704,  705,  706,  807,  763,  775,  776,  639,  640,  770,
71315  /*   490 */   641,  642,  643,  681,  684,  685,  686,  644,  663,  666,
71316  /*   500 */   667,  645,  652,  646,  647,  654,  655,  656,  659,  660,
71317  /*   510 */   661,  662,  657,  658,  826,  827,  831,  829,  828,  649,
71318  /*   520 */   650,  664,  637,  626,  619,  670,  673,  674,  675,  676,
71319  /*   530 */   677,  679,  671,  672,  617,  609,  611,  720,  848,  857,
71320  /*   540 */   853,  849,  850,  851,  612,  822,  823,  683,  754,  755,
71321  /*   550 */   847,  860,  862,  759,  863,  865,  890,  687,  688,  691,
71322  /*   560 */   832,  872,  745,  748,  751,  753,  834,  835,  836,  837,
71323  /*   570 */   840,  841,  838,  873,  877,  880,  882,  883,  884,  887,
71324  /*   580 */   889,  894,  895,  896,  899,  897,  596,  590,
71325 };
71326 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
71327
71328 /* The next table maps tokens into fallback tokens.  If a construct
71329 ** like the following:
71330 ** 
71331 **      %fallback ID X Y Z.
71332 **
71333 ** appears in the grammer, then ID becomes a fallback token for X, Y,
71334 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
71335 ** but it does not parse, the type of the token is changed to ID and
71336 ** the parse is retried before an error is thrown.
71337 */
71338 #ifdef YYFALLBACK
71339 static const YYCODETYPE yyFallback[] = {
71340     0,  /*          $ => nothing */
71341     0,  /*       SEMI => nothing */
71342    23,  /*    EXPLAIN => ID */
71343    23,  /*      QUERY => ID */
71344    23,  /*       PLAN => ID */
71345    23,  /*      BEGIN => ID */
71346     0,  /* TRANSACTION => nothing */
71347    23,  /*   DEFERRED => ID */
71348    23,  /*  IMMEDIATE => ID */
71349    23,  /*  EXCLUSIVE => ID */
71350     0,  /*     COMMIT => nothing */
71351    23,  /*        END => ID */
71352     0,  /*   ROLLBACK => nothing */
71353     0,  /*     CREATE => nothing */
71354     0,  /*      TABLE => nothing */
71355    23,  /*         IF => ID */
71356     0,  /*        NOT => nothing */
71357     0,  /*     EXISTS => nothing */
71358    23,  /*       TEMP => ID */
71359     0,  /*         LP => nothing */
71360     0,  /*         RP => nothing */
71361     0,  /*         AS => nothing */
71362     0,  /*      COMMA => nothing */
71363     0,  /*         ID => nothing */
71364    23,  /*      ABORT => ID */
71365    23,  /*      AFTER => ID */
71366    23,  /*    ANALYZE => ID */
71367    23,  /*        ASC => ID */
71368    23,  /*     ATTACH => ID */
71369    23,  /*     BEFORE => ID */
71370    23,  /*    CASCADE => ID */
71371    23,  /*       CAST => ID */
71372    23,  /*   CONFLICT => ID */
71373    23,  /*   DATABASE => ID */
71374    23,  /*       DESC => ID */
71375    23,  /*     DETACH => ID */
71376    23,  /*       EACH => ID */
71377    23,  /*       FAIL => ID */
71378    23,  /*        FOR => ID */
71379    23,  /*     IGNORE => ID */
71380    23,  /*  INITIALLY => ID */
71381    23,  /*    INSTEAD => ID */
71382    23,  /*    LIKE_KW => ID */
71383    23,  /*      MATCH => ID */
71384    23,  /*        KEY => ID */
71385    23,  /*         OF => ID */
71386    23,  /*     OFFSET => ID */
71387    23,  /*     PRAGMA => ID */
71388    23,  /*      RAISE => ID */
71389    23,  /*    REPLACE => ID */
71390    23,  /*   RESTRICT => ID */
71391    23,  /*        ROW => ID */
71392    23,  /*    TRIGGER => ID */
71393    23,  /*     VACUUM => ID */
71394    23,  /*       VIEW => ID */
71395    23,  /*    VIRTUAL => ID */
71396    23,  /*    REINDEX => ID */
71397    23,  /*     RENAME => ID */
71398    23,  /*   CTIME_KW => ID */
71399     0,  /*        ANY => nothing */
71400     0,  /*         OR => nothing */
71401     0,  /*        AND => nothing */
71402     0,  /*         IS => nothing */
71403     0,  /*    BETWEEN => nothing */
71404     0,  /*         IN => nothing */
71405     0,  /*     ISNULL => nothing */
71406     0,  /*    NOTNULL => nothing */
71407     0,  /*         NE => nothing */
71408     0,  /*         EQ => nothing */
71409     0,  /*         GT => nothing */
71410     0,  /*         LE => nothing */
71411     0,  /*         LT => nothing */
71412     0,  /*         GE => nothing */
71413     0,  /*     ESCAPE => nothing */
71414     0,  /*     BITAND => nothing */
71415     0,  /*      BITOR => nothing */
71416     0,  /*     LSHIFT => nothing */
71417     0,  /*     RSHIFT => nothing */
71418     0,  /*       PLUS => nothing */
71419     0,  /*      MINUS => nothing */
71420     0,  /*       STAR => nothing */
71421     0,  /*      SLASH => nothing */
71422     0,  /*        REM => nothing */
71423     0,  /*     CONCAT => nothing */
71424     0,  /*    COLLATE => nothing */
71425     0,  /*     UMINUS => nothing */
71426     0,  /*      UPLUS => nothing */
71427     0,  /*     BITNOT => nothing */
71428     0,  /*     STRING => nothing */
71429     0,  /*    JOIN_KW => nothing */
71430     0,  /* CONSTRAINT => nothing */
71431     0,  /*    DEFAULT => nothing */
71432     0,  /*       NULL => nothing */
71433     0,  /*    PRIMARY => nothing */
71434     0,  /*     UNIQUE => nothing */
71435     0,  /*      CHECK => nothing */
71436     0,  /* REFERENCES => nothing */
71437     0,  /*   AUTOINCR => nothing */
71438     0,  /*         ON => nothing */
71439     0,  /*     DELETE => nothing */
71440     0,  /*     UPDATE => nothing */
71441     0,  /*     INSERT => nothing */
71442     0,  /*        SET => nothing */
71443     0,  /* DEFERRABLE => nothing */
71444     0,  /*    FOREIGN => nothing */
71445     0,  /*       DROP => nothing */
71446     0,  /*      UNION => nothing */
71447     0,  /*        ALL => nothing */
71448     0,  /*     EXCEPT => nothing */
71449     0,  /*  INTERSECT => nothing */
71450     0,  /*     SELECT => nothing */
71451     0,  /*   DISTINCT => nothing */
71452     0,  /*        DOT => nothing */
71453     0,  /*       FROM => nothing */
71454     0,  /*       JOIN => nothing */
71455     0,  /*      USING => nothing */
71456     0,  /*      ORDER => nothing */
71457     0,  /*         BY => nothing */
71458     0,  /*      GROUP => nothing */
71459     0,  /*     HAVING => nothing */
71460     0,  /*      LIMIT => nothing */
71461     0,  /*      WHERE => nothing */
71462     0,  /*       INTO => nothing */
71463     0,  /*     VALUES => nothing */
71464     0,  /*    INTEGER => nothing */
71465     0,  /*      FLOAT => nothing */
71466     0,  /*       BLOB => nothing */
71467     0,  /*   REGISTER => nothing */
71468     0,  /*   VARIABLE => nothing */
71469     0,  /*       CASE => nothing */
71470     0,  /*       WHEN => nothing */
71471     0,  /*       THEN => nothing */
71472     0,  /*       ELSE => nothing */
71473     0,  /*      INDEX => nothing */
71474     0,  /*      ALTER => nothing */
71475     0,  /*         TO => nothing */
71476     0,  /*        ADD => nothing */
71477     0,  /*   COLUMNKW => nothing */
71478 };
71479 #endif /* YYFALLBACK */
71480
71481 /* The following structure represents a single element of the
71482 ** parser's stack.  Information stored includes:
71483 **
71484 **   +  The state number for the parser at this level of the stack.
71485 **
71486 **   +  The value of the token stored at this level of the stack.
71487 **      (In other words, the "major" token.)
71488 **
71489 **   +  The semantic value stored at this level of the stack.  This is
71490 **      the information used by the action routines in the grammar.
71491 **      It is sometimes called the "minor" token.
71492 */
71493 struct yyStackEntry {
71494   int stateno;       /* The state-number */
71495   int major;         /* The major token value.  This is the code
71496                      ** number for the token at this stack level */
71497   YYMINORTYPE minor; /* The user-supplied minor token value.  This
71498                      ** is the value of the token  */
71499 };
71500 typedef struct yyStackEntry yyStackEntry;
71501
71502 /* The state of the parser is completely contained in an instance of
71503 ** the following structure */
71504 struct yyParser {
71505   int yyidx;                    /* Index of top element in stack */
71506   int yyerrcnt;                 /* Shifts left before out of the error */
71507   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
71508 #if YYSTACKDEPTH<=0
71509   int yystksz;                  /* Current side of the stack */
71510   yyStackEntry *yystack;        /* The parser's stack */
71511 #else
71512   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
71513 #endif
71514 };
71515 typedef struct yyParser yyParser;
71516
71517 #ifndef NDEBUG
71518 static FILE *yyTraceFILE = 0;
71519 static char *yyTracePrompt = 0;
71520 #endif /* NDEBUG */
71521
71522 #ifndef NDEBUG
71523 /* 
71524 ** Turn parser tracing on by giving a stream to which to write the trace
71525 ** and a prompt to preface each trace message.  Tracing is turned off
71526 ** by making either argument NULL 
71527 **
71528 ** Inputs:
71529 ** <ul>
71530 ** <li> A FILE* to which trace output should be written.
71531 **      If NULL, then tracing is turned off.
71532 ** <li> A prefix string written at the beginning of every
71533 **      line of trace output.  If NULL, then tracing is
71534 **      turned off.
71535 ** </ul>
71536 **
71537 ** Outputs:
71538 ** None.
71539 */
71540 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
71541   yyTraceFILE = TraceFILE;
71542   yyTracePrompt = zTracePrompt;
71543   if( yyTraceFILE==0 ) yyTracePrompt = 0;
71544   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
71545 }
71546 #endif /* NDEBUG */
71547
71548 #ifndef NDEBUG
71549 /* For tracing shifts, the names of all terminals and nonterminals
71550 ** are required.  The following table supplies these names */
71551 static const char *const yyTokenName[] = { 
71552   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
71553   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
71554   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
71555   "ROLLBACK",      "CREATE",        "TABLE",         "IF",          
71556   "NOT",           "EXISTS",        "TEMP",          "LP",          
71557   "RP",            "AS",            "COMMA",         "ID",          
71558   "ABORT",         "AFTER",         "ANALYZE",       "ASC",         
71559   "ATTACH",        "BEFORE",        "CASCADE",       "CAST",        
71560   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
71561   "EACH",          "FAIL",          "FOR",           "IGNORE",      
71562   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
71563   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
71564   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
71565   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
71566   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
71567   "OR",            "AND",           "IS",            "BETWEEN",     
71568   "IN",            "ISNULL",        "NOTNULL",       "NE",          
71569   "EQ",            "GT",            "LE",            "LT",          
71570   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
71571   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
71572   "STAR",          "SLASH",         "REM",           "CONCAT",      
71573   "COLLATE",       "UMINUS",        "UPLUS",         "BITNOT",      
71574   "STRING",        "JOIN_KW",       "CONSTRAINT",    "DEFAULT",     
71575   "NULL",          "PRIMARY",       "UNIQUE",        "CHECK",       
71576   "REFERENCES",    "AUTOINCR",      "ON",            "DELETE",      
71577   "UPDATE",        "INSERT",        "SET",           "DEFERRABLE",  
71578   "FOREIGN",       "DROP",          "UNION",         "ALL",         
71579   "EXCEPT",        "INTERSECT",     "SELECT",        "DISTINCT",    
71580   "DOT",           "FROM",          "JOIN",          "USING",       
71581   "ORDER",         "BY",            "GROUP",         "HAVING",      
71582   "LIMIT",         "WHERE",         "INTO",          "VALUES",      
71583   "INTEGER",       "FLOAT",         "BLOB",          "REGISTER",    
71584   "VARIABLE",      "CASE",          "WHEN",          "THEN",        
71585   "ELSE",          "INDEX",         "ALTER",         "TO",          
71586   "ADD",           "COLUMNKW",      "error",         "input",       
71587   "cmdlist",       "ecmd",          "cmdx",          "cmd",         
71588   "explain",       "transtype",     "trans_opt",     "nm",          
71589   "create_table",  "create_table_args",  "temp",          "ifnotexists", 
71590   "dbnm",          "columnlist",    "conslist_opt",  "select",      
71591   "column",        "columnid",      "type",          "carglist",    
71592   "id",            "ids",           "typetoken",     "typename",    
71593   "signed",        "plus_num",      "minus_num",     "carg",        
71594   "ccons",         "term",          "expr",          "onconf",      
71595   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
71596   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
71597   "conslist",      "tcons",         "idxlist",       "defer_subclause_opt",
71598   "orconf",        "resolvetype",   "raisetype",     "ifexists",    
71599   "fullname",      "oneselect",     "multiselect_op",  "distinct",    
71600   "selcollist",    "from",          "where_opt",     "groupby_opt", 
71601   "having_opt",    "orderby_opt",   "limit_opt",     "sclp",        
71602   "as",            "seltablist",    "stl_prefix",    "joinop",      
71603   "on_opt",        "using_opt",     "seltablist_paren",  "joinop2",     
71604   "inscollist",    "sortlist",      "sortitem",      "nexprlist",   
71605   "setlist",       "insert_cmd",    "inscollist_opt",  "itemlist",    
71606   "exprlist",      "likeop",        "escape",        "between_op",  
71607   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
71608   "uniqueflag",    "idxitem",       "collate",       "nmnum",       
71609   "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
71610   "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
71611   "trigger_cmd",   "database_kw_opt",  "key_opt",       "add_column_fullname",
71612   "kwcolumn_opt",  "create_vtab",   "vtabarglist",   "vtabarg",     
71613   "vtabargtoken",  "lp",            "anylist",     
71614 };
71615 #endif /* NDEBUG */
71616
71617 #ifndef NDEBUG
71618 /* For tracing reduce actions, the names of all rules are required.
71619 */
71620 static const char *const yyRuleName[] = {
71621  /*   0 */ "input ::= cmdlist",
71622  /*   1 */ "cmdlist ::= cmdlist ecmd",
71623  /*   2 */ "cmdlist ::= ecmd",
71624  /*   3 */ "cmdx ::= cmd",
71625  /*   4 */ "ecmd ::= SEMI",
71626  /*   5 */ "ecmd ::= explain cmdx SEMI",
71627  /*   6 */ "explain ::=",
71628  /*   7 */ "explain ::= EXPLAIN",
71629  /*   8 */ "explain ::= EXPLAIN QUERY PLAN",
71630  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
71631  /*  10 */ "trans_opt ::=",
71632  /*  11 */ "trans_opt ::= TRANSACTION",
71633  /*  12 */ "trans_opt ::= TRANSACTION nm",
71634  /*  13 */ "transtype ::=",
71635  /*  14 */ "transtype ::= DEFERRED",
71636  /*  15 */ "transtype ::= IMMEDIATE",
71637  /*  16 */ "transtype ::= EXCLUSIVE",
71638  /*  17 */ "cmd ::= COMMIT trans_opt",
71639  /*  18 */ "cmd ::= END trans_opt",
71640  /*  19 */ "cmd ::= ROLLBACK trans_opt",
71641  /*  20 */ "cmd ::= create_table create_table_args",
71642  /*  21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
71643  /*  22 */ "ifnotexists ::=",
71644  /*  23 */ "ifnotexists ::= IF NOT EXISTS",
71645  /*  24 */ "temp ::= TEMP",
71646  /*  25 */ "temp ::=",
71647  /*  26 */ "create_table_args ::= LP columnlist conslist_opt RP",
71648  /*  27 */ "create_table_args ::= AS select",
71649  /*  28 */ "columnlist ::= columnlist COMMA column",
71650  /*  29 */ "columnlist ::= column",
71651  /*  30 */ "column ::= columnid type carglist",
71652  /*  31 */ "columnid ::= nm",
71653  /*  32 */ "id ::= ID",
71654  /*  33 */ "ids ::= ID|STRING",
71655  /*  34 */ "nm ::= ID",
71656  /*  35 */ "nm ::= STRING",
71657  /*  36 */ "nm ::= JOIN_KW",
71658  /*  37 */ "type ::=",
71659  /*  38 */ "type ::= typetoken",
71660  /*  39 */ "typetoken ::= typename",
71661  /*  40 */ "typetoken ::= typename LP signed RP",
71662  /*  41 */ "typetoken ::= typename LP signed COMMA signed RP",
71663  /*  42 */ "typename ::= ids",
71664  /*  43 */ "typename ::= typename ids",
71665  /*  44 */ "signed ::= plus_num",
71666  /*  45 */ "signed ::= minus_num",
71667  /*  46 */ "carglist ::= carglist carg",
71668  /*  47 */ "carglist ::=",
71669  /*  48 */ "carg ::= CONSTRAINT nm ccons",
71670  /*  49 */ "carg ::= ccons",
71671  /*  50 */ "ccons ::= DEFAULT term",
71672  /*  51 */ "ccons ::= DEFAULT LP expr RP",
71673  /*  52 */ "ccons ::= DEFAULT PLUS term",
71674  /*  53 */ "ccons ::= DEFAULT MINUS term",
71675  /*  54 */ "ccons ::= DEFAULT id",
71676  /*  55 */ "ccons ::= NULL onconf",
71677  /*  56 */ "ccons ::= NOT NULL onconf",
71678  /*  57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
71679  /*  58 */ "ccons ::= UNIQUE onconf",
71680  /*  59 */ "ccons ::= CHECK LP expr RP",
71681  /*  60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
71682  /*  61 */ "ccons ::= defer_subclause",
71683  /*  62 */ "ccons ::= COLLATE ids",
71684  /*  63 */ "autoinc ::=",
71685  /*  64 */ "autoinc ::= AUTOINCR",
71686  /*  65 */ "refargs ::=",
71687  /*  66 */ "refargs ::= refargs refarg",
71688  /*  67 */ "refarg ::= MATCH nm",
71689  /*  68 */ "refarg ::= ON DELETE refact",
71690  /*  69 */ "refarg ::= ON UPDATE refact",
71691  /*  70 */ "refarg ::= ON INSERT refact",
71692  /*  71 */ "refact ::= SET NULL",
71693  /*  72 */ "refact ::= SET DEFAULT",
71694  /*  73 */ "refact ::= CASCADE",
71695  /*  74 */ "refact ::= RESTRICT",
71696  /*  75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
71697  /*  76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
71698  /*  77 */ "init_deferred_pred_opt ::=",
71699  /*  78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
71700  /*  79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
71701  /*  80 */ "conslist_opt ::=",
71702  /*  81 */ "conslist_opt ::= COMMA conslist",
71703  /*  82 */ "conslist ::= conslist COMMA tcons",
71704  /*  83 */ "conslist ::= conslist tcons",
71705  /*  84 */ "conslist ::= tcons",
71706  /*  85 */ "tcons ::= CONSTRAINT nm",
71707  /*  86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
71708  /*  87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
71709  /*  88 */ "tcons ::= CHECK LP expr RP onconf",
71710  /*  89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
71711  /*  90 */ "defer_subclause_opt ::=",
71712  /*  91 */ "defer_subclause_opt ::= defer_subclause",
71713  /*  92 */ "onconf ::=",
71714  /*  93 */ "onconf ::= ON CONFLICT resolvetype",
71715  /*  94 */ "orconf ::=",
71716  /*  95 */ "orconf ::= OR resolvetype",
71717  /*  96 */ "resolvetype ::= raisetype",
71718  /*  97 */ "resolvetype ::= IGNORE",
71719  /*  98 */ "resolvetype ::= REPLACE",
71720  /*  99 */ "cmd ::= DROP TABLE ifexists fullname",
71721  /* 100 */ "ifexists ::= IF EXISTS",
71722  /* 101 */ "ifexists ::=",
71723  /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
71724  /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
71725  /* 104 */ "cmd ::= select",
71726  /* 105 */ "select ::= oneselect",
71727  /* 106 */ "select ::= select multiselect_op oneselect",
71728  /* 107 */ "multiselect_op ::= UNION",
71729  /* 108 */ "multiselect_op ::= UNION ALL",
71730  /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
71731  /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
71732  /* 111 */ "distinct ::= DISTINCT",
71733  /* 112 */ "distinct ::= ALL",
71734  /* 113 */ "distinct ::=",
71735  /* 114 */ "sclp ::= selcollist COMMA",
71736  /* 115 */ "sclp ::=",
71737  /* 116 */ "selcollist ::= sclp expr as",
71738  /* 117 */ "selcollist ::= sclp STAR",
71739  /* 118 */ "selcollist ::= sclp nm DOT STAR",
71740  /* 119 */ "as ::= AS nm",
71741  /* 120 */ "as ::= ids",
71742  /* 121 */ "as ::=",
71743  /* 122 */ "from ::=",
71744  /* 123 */ "from ::= FROM seltablist",
71745  /* 124 */ "stl_prefix ::= seltablist joinop",
71746  /* 125 */ "stl_prefix ::=",
71747  /* 126 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
71748  /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
71749  /* 128 */ "seltablist_paren ::= select",
71750  /* 129 */ "seltablist_paren ::= seltablist",
71751  /* 130 */ "dbnm ::=",
71752  /* 131 */ "dbnm ::= DOT nm",
71753  /* 132 */ "fullname ::= nm dbnm",
71754  /* 133 */ "joinop ::= COMMA|JOIN",
71755  /* 134 */ "joinop ::= JOIN_KW JOIN",
71756  /* 135 */ "joinop ::= JOIN_KW nm JOIN",
71757  /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
71758  /* 137 */ "on_opt ::= ON expr",
71759  /* 138 */ "on_opt ::=",
71760  /* 139 */ "using_opt ::= USING LP inscollist RP",
71761  /* 140 */ "using_opt ::=",
71762  /* 141 */ "orderby_opt ::=",
71763  /* 142 */ "orderby_opt ::= ORDER BY sortlist",
71764  /* 143 */ "sortlist ::= sortlist COMMA sortitem sortorder",
71765  /* 144 */ "sortlist ::= sortitem sortorder",
71766  /* 145 */ "sortitem ::= expr",
71767  /* 146 */ "sortorder ::= ASC",
71768  /* 147 */ "sortorder ::= DESC",
71769  /* 148 */ "sortorder ::=",
71770  /* 149 */ "groupby_opt ::=",
71771  /* 150 */ "groupby_opt ::= GROUP BY nexprlist",
71772  /* 151 */ "having_opt ::=",
71773  /* 152 */ "having_opt ::= HAVING expr",
71774  /* 153 */ "limit_opt ::=",
71775  /* 154 */ "limit_opt ::= LIMIT expr",
71776  /* 155 */ "limit_opt ::= LIMIT expr OFFSET expr",
71777  /* 156 */ "limit_opt ::= LIMIT expr COMMA expr",
71778  /* 157 */ "cmd ::= DELETE FROM fullname where_opt",
71779  /* 158 */ "where_opt ::=",
71780  /* 159 */ "where_opt ::= WHERE expr",
71781  /* 160 */ "cmd ::= UPDATE orconf fullname SET setlist where_opt",
71782  /* 161 */ "setlist ::= setlist COMMA nm EQ expr",
71783  /* 162 */ "setlist ::= nm EQ expr",
71784  /* 163 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
71785  /* 164 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
71786  /* 165 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
71787  /* 166 */ "insert_cmd ::= INSERT orconf",
71788  /* 167 */ "insert_cmd ::= REPLACE",
71789  /* 168 */ "itemlist ::= itemlist COMMA expr",
71790  /* 169 */ "itemlist ::= expr",
71791  /* 170 */ "inscollist_opt ::=",
71792  /* 171 */ "inscollist_opt ::= LP inscollist RP",
71793  /* 172 */ "inscollist ::= inscollist COMMA nm",
71794  /* 173 */ "inscollist ::= nm",
71795  /* 174 */ "expr ::= term",
71796  /* 175 */ "expr ::= LP expr RP",
71797  /* 176 */ "term ::= NULL",
71798  /* 177 */ "expr ::= ID",
71799  /* 178 */ "expr ::= JOIN_KW",
71800  /* 179 */ "expr ::= nm DOT nm",
71801  /* 180 */ "expr ::= nm DOT nm DOT nm",
71802  /* 181 */ "term ::= INTEGER|FLOAT|BLOB",
71803  /* 182 */ "term ::= STRING",
71804  /* 183 */ "expr ::= REGISTER",
71805  /* 184 */ "expr ::= VARIABLE",
71806  /* 185 */ "expr ::= expr COLLATE ids",
71807  /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
71808  /* 187 */ "expr ::= ID LP distinct exprlist RP",
71809  /* 188 */ "expr ::= ID LP STAR RP",
71810  /* 189 */ "term ::= CTIME_KW",
71811  /* 190 */ "expr ::= expr AND expr",
71812  /* 191 */ "expr ::= expr OR expr",
71813  /* 192 */ "expr ::= expr LT|GT|GE|LE expr",
71814  /* 193 */ "expr ::= expr EQ|NE expr",
71815  /* 194 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
71816  /* 195 */ "expr ::= expr PLUS|MINUS expr",
71817  /* 196 */ "expr ::= expr STAR|SLASH|REM expr",
71818  /* 197 */ "expr ::= expr CONCAT expr",
71819  /* 198 */ "likeop ::= LIKE_KW",
71820  /* 199 */ "likeop ::= NOT LIKE_KW",
71821  /* 200 */ "likeop ::= MATCH",
71822  /* 201 */ "likeop ::= NOT MATCH",
71823  /* 202 */ "escape ::= ESCAPE expr",
71824  /* 203 */ "escape ::=",
71825  /* 204 */ "expr ::= expr likeop expr escape",
71826  /* 205 */ "expr ::= expr ISNULL|NOTNULL",
71827  /* 206 */ "expr ::= expr IS NULL",
71828  /* 207 */ "expr ::= expr NOT NULL",
71829  /* 208 */ "expr ::= expr IS NOT NULL",
71830  /* 209 */ "expr ::= NOT expr",
71831  /* 210 */ "expr ::= BITNOT expr",
71832  /* 211 */ "expr ::= MINUS expr",
71833  /* 212 */ "expr ::= PLUS expr",
71834  /* 213 */ "between_op ::= BETWEEN",
71835  /* 214 */ "between_op ::= NOT BETWEEN",
71836  /* 215 */ "expr ::= expr between_op expr AND expr",
71837  /* 216 */ "in_op ::= IN",
71838  /* 217 */ "in_op ::= NOT IN",
71839  /* 218 */ "expr ::= expr in_op LP exprlist RP",
71840  /* 219 */ "expr ::= LP select RP",
71841  /* 220 */ "expr ::= expr in_op LP select RP",
71842  /* 221 */ "expr ::= expr in_op nm dbnm",
71843  /* 222 */ "expr ::= EXISTS LP select RP",
71844  /* 223 */ "expr ::= CASE case_operand case_exprlist case_else END",
71845  /* 224 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
71846  /* 225 */ "case_exprlist ::= WHEN expr THEN expr",
71847  /* 226 */ "case_else ::= ELSE expr",
71848  /* 227 */ "case_else ::=",
71849  /* 228 */ "case_operand ::= expr",
71850  /* 229 */ "case_operand ::=",
71851  /* 230 */ "exprlist ::= nexprlist",
71852  /* 231 */ "exprlist ::=",
71853  /* 232 */ "nexprlist ::= nexprlist COMMA expr",
71854  /* 233 */ "nexprlist ::= expr",
71855  /* 234 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
71856  /* 235 */ "uniqueflag ::= UNIQUE",
71857  /* 236 */ "uniqueflag ::=",
71858  /* 237 */ "idxlist_opt ::=",
71859  /* 238 */ "idxlist_opt ::= LP idxlist RP",
71860  /* 239 */ "idxlist ::= idxlist COMMA idxitem collate sortorder",
71861  /* 240 */ "idxlist ::= idxitem collate sortorder",
71862  /* 241 */ "idxitem ::= nm",
71863  /* 242 */ "collate ::=",
71864  /* 243 */ "collate ::= COLLATE ids",
71865  /* 244 */ "cmd ::= DROP INDEX ifexists fullname",
71866  /* 245 */ "cmd ::= VACUUM",
71867  /* 246 */ "cmd ::= VACUUM nm",
71868  /* 247 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
71869  /* 248 */ "cmd ::= PRAGMA nm dbnm EQ ON",
71870  /* 249 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
71871  /* 250 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
71872  /* 251 */ "cmd ::= PRAGMA nm dbnm",
71873  /* 252 */ "nmnum ::= plus_num",
71874  /* 253 */ "nmnum ::= nm",
71875  /* 254 */ "plus_num ::= plus_opt number",
71876  /* 255 */ "minus_num ::= MINUS number",
71877  /* 256 */ "number ::= INTEGER|FLOAT",
71878  /* 257 */ "plus_opt ::= PLUS",
71879  /* 258 */ "plus_opt ::=",
71880  /* 259 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
71881  /* 260 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
71882  /* 261 */ "trigger_time ::= BEFORE",
71883  /* 262 */ "trigger_time ::= AFTER",
71884  /* 263 */ "trigger_time ::= INSTEAD OF",
71885  /* 264 */ "trigger_time ::=",
71886  /* 265 */ "trigger_event ::= DELETE|INSERT",
71887  /* 266 */ "trigger_event ::= UPDATE",
71888  /* 267 */ "trigger_event ::= UPDATE OF inscollist",
71889  /* 268 */ "foreach_clause ::=",
71890  /* 269 */ "foreach_clause ::= FOR EACH ROW",
71891  /* 270 */ "when_clause ::=",
71892  /* 271 */ "when_clause ::= WHEN expr",
71893  /* 272 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
71894  /* 273 */ "trigger_cmd_list ::=",
71895  /* 274 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
71896  /* 275 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
71897  /* 276 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
71898  /* 277 */ "trigger_cmd ::= DELETE FROM nm where_opt",
71899  /* 278 */ "trigger_cmd ::= select",
71900  /* 279 */ "expr ::= RAISE LP IGNORE RP",
71901  /* 280 */ "expr ::= RAISE LP raisetype COMMA nm RP",
71902  /* 281 */ "raisetype ::= ROLLBACK",
71903  /* 282 */ "raisetype ::= ABORT",
71904  /* 283 */ "raisetype ::= FAIL",
71905  /* 284 */ "cmd ::= DROP TRIGGER ifexists fullname",
71906  /* 285 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
71907  /* 286 */ "cmd ::= DETACH database_kw_opt expr",
71908  /* 287 */ "key_opt ::=",
71909  /* 288 */ "key_opt ::= KEY expr",
71910  /* 289 */ "database_kw_opt ::= DATABASE",
71911  /* 290 */ "database_kw_opt ::=",
71912  /* 291 */ "cmd ::= REINDEX",
71913  /* 292 */ "cmd ::= REINDEX nm dbnm",
71914  /* 293 */ "cmd ::= ANALYZE",
71915  /* 294 */ "cmd ::= ANALYZE nm dbnm",
71916  /* 295 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
71917  /* 296 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
71918  /* 297 */ "add_column_fullname ::= fullname",
71919  /* 298 */ "kwcolumn_opt ::=",
71920  /* 299 */ "kwcolumn_opt ::= COLUMNKW",
71921  /* 300 */ "cmd ::= create_vtab",
71922  /* 301 */ "cmd ::= create_vtab LP vtabarglist RP",
71923  /* 302 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
71924  /* 303 */ "vtabarglist ::= vtabarg",
71925  /* 304 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
71926  /* 305 */ "vtabarg ::=",
71927  /* 306 */ "vtabarg ::= vtabarg vtabargtoken",
71928  /* 307 */ "vtabargtoken ::= ANY",
71929  /* 308 */ "vtabargtoken ::= lp anylist RP",
71930  /* 309 */ "lp ::= LP",
71931  /* 310 */ "anylist ::=",
71932  /* 311 */ "anylist ::= anylist ANY",
71933 };
71934 #endif /* NDEBUG */
71935
71936
71937 #if YYSTACKDEPTH<=0
71938 /*
71939 ** Try to increase the size of the parser stack.
71940 */
71941 static void yyGrowStack(yyParser *p){
71942   int newSize;
71943   yyStackEntry *pNew;
71944
71945   newSize = p->yystksz*2 + 100;
71946   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
71947   if( pNew ){
71948     p->yystack = pNew;
71949     p->yystksz = newSize;
71950 #ifndef NDEBUG
71951     if( yyTraceFILE ){
71952       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
71953               yyTracePrompt, p->yystksz);
71954     }
71955 #endif
71956   }
71957 }
71958 #endif
71959
71960 /* 
71961 ** This function allocates a new parser.
71962 ** The only argument is a pointer to a function which works like
71963 ** malloc.
71964 **
71965 ** Inputs:
71966 ** A pointer to the function used to allocate memory.
71967 **
71968 ** Outputs:
71969 ** A pointer to a parser.  This pointer is used in subsequent calls
71970 ** to sqlite3Parser and sqlite3ParserFree.
71971 */
71972 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
71973   yyParser *pParser;
71974   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
71975   if( pParser ){
71976     pParser->yyidx = -1;
71977 #if YYSTACKDEPTH<=0
71978     yyGrowStack(pParser);
71979 #endif
71980   }
71981   return pParser;
71982 }
71983
71984 /* The following function deletes the value associated with a
71985 ** symbol.  The symbol can be either a terminal or nonterminal.
71986 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
71987 ** the value.
71988 */
71989 static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){
71990   switch( yymajor ){
71991     /* Here is inserted the actions which take place when a
71992     ** terminal or non-terminal is destroyed.  This can happen
71993     ** when the symbol is popped from the stack during a
71994     ** reduce or during error processing or when a parser is 
71995     ** being destroyed before it is finished parsing.
71996     **
71997     ** Note: during a reduce, the only symbols destroyed are those
71998     ** which appear on the RHS of the rule, but which are not used
71999     ** inside the C code.
72000     */
72001     case 155: /* select */
72002     case 189: /* oneselect */
72003     case 206: /* seltablist_paren */
72004 {sqlite3SelectDelete((yypminor->yy219));}
72005       break;
72006     case 169: /* term */
72007     case 170: /* expr */
72008     case 194: /* where_opt */
72009     case 196: /* having_opt */
72010     case 204: /* on_opt */
72011     case 210: /* sortitem */
72012     case 218: /* escape */
72013     case 221: /* case_operand */
72014     case 223: /* case_else */
72015     case 235: /* when_clause */
72016     case 238: /* key_opt */
72017 {sqlite3ExprDelete((yypminor->yy172));}
72018       break;
72019     case 174: /* idxlist_opt */
72020     case 182: /* idxlist */
72021     case 192: /* selcollist */
72022     case 195: /* groupby_opt */
72023     case 197: /* orderby_opt */
72024     case 199: /* sclp */
72025     case 209: /* sortlist */
72026     case 211: /* nexprlist */
72027     case 212: /* setlist */
72028     case 215: /* itemlist */
72029     case 216: /* exprlist */
72030     case 222: /* case_exprlist */
72031 {sqlite3ExprListDelete((yypminor->yy174));}
72032       break;
72033     case 188: /* fullname */
72034     case 193: /* from */
72035     case 201: /* seltablist */
72036     case 202: /* stl_prefix */
72037 {sqlite3SrcListDelete((yypminor->yy373));}
72038       break;
72039     case 205: /* using_opt */
72040     case 208: /* inscollist */
72041     case 214: /* inscollist_opt */
72042 {sqlite3IdListDelete((yypminor->yy432));}
72043       break;
72044     case 231: /* trigger_cmd_list */
72045     case 236: /* trigger_cmd */
72046 {sqlite3DeleteTriggerStep((yypminor->yy243));}
72047       break;
72048     case 233: /* trigger_event */
72049 {sqlite3IdListDelete((yypminor->yy370).b);}
72050       break;
72051     default:  break;   /* If no destructor action specified: do nothing */
72052   }
72053 }
72054
72055 /*
72056 ** Pop the parser's stack once.
72057 **
72058 ** If there is a destructor routine associated with the token which
72059 ** is popped from the stack, then call it.
72060 **
72061 ** Return the major token number for the symbol popped.
72062 */
72063 static int yy_pop_parser_stack(yyParser *pParser){
72064   YYCODETYPE yymajor;
72065   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
72066
72067   if( pParser->yyidx<0 ) return 0;
72068 #ifndef NDEBUG
72069   if( yyTraceFILE && pParser->yyidx>=0 ){
72070     fprintf(yyTraceFILE,"%sPopping %s\n",
72071       yyTracePrompt,
72072       yyTokenName[yytos->major]);
72073   }
72074 #endif
72075   yymajor = yytos->major;
72076   yy_destructor( yymajor, &yytos->minor);
72077   pParser->yyidx--;
72078   return yymajor;
72079 }
72080
72081 /* 
72082 ** Deallocate and destroy a parser.  Destructors are all called for
72083 ** all stack elements before shutting the parser down.
72084 **
72085 ** Inputs:
72086 ** <ul>
72087 ** <li>  A pointer to the parser.  This should be a pointer
72088 **       obtained from sqlite3ParserAlloc.
72089 ** <li>  A pointer to a function used to reclaim memory obtained
72090 **       from malloc.
72091 ** </ul>
72092 */
72093 SQLITE_PRIVATE void sqlite3ParserFree(
72094   void *p,                    /* The parser to be deleted */
72095   void (*freeProc)(void*)     /* Function used to reclaim memory */
72096 ){
72097   yyParser *pParser = (yyParser*)p;
72098   if( pParser==0 ) return;
72099   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
72100 #if YYSTACKDEPTH<=0
72101   free(pParser->yystack);
72102 #endif
72103   (*freeProc)((void*)pParser);
72104 }
72105
72106 /*
72107 ** Find the appropriate action for a parser given the terminal
72108 ** look-ahead token iLookAhead.
72109 **
72110 ** If the look-ahead token is YYNOCODE, then check to see if the action is
72111 ** independent of the look-ahead.  If it is, return the action, otherwise
72112 ** return YY_NO_ACTION.
72113 */
72114 static int yy_find_shift_action(
72115   yyParser *pParser,        /* The parser */
72116   YYCODETYPE iLookAhead     /* The look-ahead token */
72117 ){
72118   int i;
72119   int stateno = pParser->yystack[pParser->yyidx].stateno;
72120  
72121   if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
72122     return yy_default[stateno];
72123   }
72124   assert( iLookAhead!=YYNOCODE );
72125   i += iLookAhead;
72126   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
72127     if( iLookAhead>0 ){
72128 #ifdef YYFALLBACK
72129       int iFallback;            /* Fallback token */
72130       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
72131              && (iFallback = yyFallback[iLookAhead])!=0 ){
72132 #ifndef NDEBUG
72133         if( yyTraceFILE ){
72134           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
72135              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
72136         }
72137 #endif
72138         return yy_find_shift_action(pParser, iFallback);
72139       }
72140 #endif
72141 #ifdef YYWILDCARD
72142       {
72143         int j = i - iLookAhead + YYWILDCARD;
72144         if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
72145 #ifndef NDEBUG
72146           if( yyTraceFILE ){
72147             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
72148                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
72149           }
72150 #endif /* NDEBUG */
72151           return yy_action[j];
72152         }
72153       }
72154 #endif /* YYWILDCARD */
72155     }
72156     return yy_default[stateno];
72157   }else{
72158     return yy_action[i];
72159   }
72160 }
72161
72162 /*
72163 ** Find the appropriate action for a parser given the non-terminal
72164 ** look-ahead token iLookAhead.
72165 **
72166 ** If the look-ahead token is YYNOCODE, then check to see if the action is
72167 ** independent of the look-ahead.  If it is, return the action, otherwise
72168 ** return YY_NO_ACTION.
72169 */
72170 static int yy_find_reduce_action(
72171   int stateno,              /* Current state number */
72172   YYCODETYPE iLookAhead     /* The look-ahead token */
72173 ){
72174   int i;
72175   assert( stateno<=YY_REDUCE_MAX );
72176   i = yy_reduce_ofst[stateno];
72177   assert( i!=YY_REDUCE_USE_DFLT );
72178   assert( iLookAhead!=YYNOCODE );
72179   i += iLookAhead;
72180   assert( i>=0 && i<YY_SZ_ACTTAB );
72181   assert( yy_lookahead[i]==iLookAhead );
72182   return yy_action[i];
72183 }
72184
72185 /*
72186 ** The following routine is called if the stack overflows.
72187 */
72188 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
72189    sqlite3ParserARG_FETCH;
72190    yypParser->yyidx--;
72191 #ifndef NDEBUG
72192    if( yyTraceFILE ){
72193      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
72194    }
72195 #endif
72196    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
72197    /* Here code is inserted which will execute if the parser
72198    ** stack every overflows */
72199
72200   sqlite3ErrorMsg(pParse, "parser stack overflow");
72201   pParse->parseError = 1;
72202    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
72203 }
72204
72205 /*
72206 ** Perform a shift action.
72207 */
72208 static void yy_shift(
72209   yyParser *yypParser,          /* The parser to be shifted */
72210   int yyNewState,               /* The new state to shift in */
72211   int yyMajor,                  /* The major token to shift in */
72212   YYMINORTYPE *yypMinor         /* Pointer ot the minor token to shift in */
72213 ){
72214   yyStackEntry *yytos;
72215   yypParser->yyidx++;
72216 #if YYSTACKDEPTH>0 
72217   if( yypParser->yyidx>=YYSTACKDEPTH ){
72218     yyStackOverflow(yypParser, yypMinor);
72219     return;
72220   }
72221 #else
72222   if( yypParser->yyidx>=yypParser->yystksz ){
72223     yyGrowStack(yypParser);
72224     if( yypParser->yyidx>=yypParser->yystksz ){
72225       yyStackOverflow(yypParser, yypMinor);
72226       return;
72227     }
72228   }
72229 #endif
72230   yytos = &yypParser->yystack[yypParser->yyidx];
72231   yytos->stateno = yyNewState;
72232   yytos->major = yyMajor;
72233   yytos->minor = *yypMinor;
72234 #ifndef NDEBUG
72235   if( yyTraceFILE && yypParser->yyidx>0 ){
72236     int i;
72237     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
72238     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
72239     for(i=1; i<=yypParser->yyidx; i++)
72240       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
72241     fprintf(yyTraceFILE,"\n");
72242   }
72243 #endif
72244 }
72245
72246 /* The following table contains information about every rule that
72247 ** is used during the reduce.
72248 */
72249 static const struct {
72250   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
72251   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
72252 } yyRuleInfo[] = {
72253   { 139, 1 },
72254   { 140, 2 },
72255   { 140, 1 },
72256   { 142, 1 },
72257   { 141, 1 },
72258   { 141, 3 },
72259   { 144, 0 },
72260   { 144, 1 },
72261   { 144, 3 },
72262   { 143, 3 },
72263   { 146, 0 },
72264   { 146, 1 },
72265   { 146, 2 },
72266   { 145, 0 },
72267   { 145, 1 },
72268   { 145, 1 },
72269   { 145, 1 },
72270   { 143, 2 },
72271   { 143, 2 },
72272   { 143, 2 },
72273   { 143, 2 },
72274   { 148, 6 },
72275   { 151, 0 },
72276   { 151, 3 },
72277   { 150, 1 },
72278   { 150, 0 },
72279   { 149, 4 },
72280   { 149, 2 },
72281   { 153, 3 },
72282   { 153, 1 },
72283   { 156, 3 },
72284   { 157, 1 },
72285   { 160, 1 },
72286   { 161, 1 },
72287   { 147, 1 },
72288   { 147, 1 },
72289   { 147, 1 },
72290   { 158, 0 },
72291   { 158, 1 },
72292   { 162, 1 },
72293   { 162, 4 },
72294   { 162, 6 },
72295   { 163, 1 },
72296   { 163, 2 },
72297   { 164, 1 },
72298   { 164, 1 },
72299   { 159, 2 },
72300   { 159, 0 },
72301   { 167, 3 },
72302   { 167, 1 },
72303   { 168, 2 },
72304   { 168, 4 },
72305   { 168, 3 },
72306   { 168, 3 },
72307   { 168, 2 },
72308   { 168, 2 },
72309   { 168, 3 },
72310   { 168, 5 },
72311   { 168, 2 },
72312   { 168, 4 },
72313   { 168, 4 },
72314   { 168, 1 },
72315   { 168, 2 },
72316   { 173, 0 },
72317   { 173, 1 },
72318   { 175, 0 },
72319   { 175, 2 },
72320   { 177, 2 },
72321   { 177, 3 },
72322   { 177, 3 },
72323   { 177, 3 },
72324   { 178, 2 },
72325   { 178, 2 },
72326   { 178, 1 },
72327   { 178, 1 },
72328   { 176, 3 },
72329   { 176, 2 },
72330   { 179, 0 },
72331   { 179, 2 },
72332   { 179, 2 },
72333   { 154, 0 },
72334   { 154, 2 },
72335   { 180, 3 },
72336   { 180, 2 },
72337   { 180, 1 },
72338   { 181, 2 },
72339   { 181, 7 },
72340   { 181, 5 },
72341   { 181, 5 },
72342   { 181, 10 },
72343   { 183, 0 },
72344   { 183, 1 },
72345   { 171, 0 },
72346   { 171, 3 },
72347   { 184, 0 },
72348   { 184, 2 },
72349   { 185, 1 },
72350   { 185, 1 },
72351   { 185, 1 },
72352   { 143, 4 },
72353   { 187, 2 },
72354   { 187, 0 },
72355   { 143, 8 },
72356   { 143, 4 },
72357   { 143, 1 },
72358   { 155, 1 },
72359   { 155, 3 },
72360   { 190, 1 },
72361   { 190, 2 },
72362   { 190, 1 },
72363   { 189, 9 },
72364   { 191, 1 },
72365   { 191, 1 },
72366   { 191, 0 },
72367   { 199, 2 },
72368   { 199, 0 },
72369   { 192, 3 },
72370   { 192, 2 },
72371   { 192, 4 },
72372   { 200, 2 },
72373   { 200, 1 },
72374   { 200, 0 },
72375   { 193, 0 },
72376   { 193, 2 },
72377   { 202, 2 },
72378   { 202, 0 },
72379   { 201, 6 },
72380   { 201, 7 },
72381   { 206, 1 },
72382   { 206, 1 },
72383   { 152, 0 },
72384   { 152, 2 },
72385   { 188, 2 },
72386   { 203, 1 },
72387   { 203, 2 },
72388   { 203, 3 },
72389   { 203, 4 },
72390   { 204, 2 },
72391   { 204, 0 },
72392   { 205, 4 },
72393   { 205, 0 },
72394   { 197, 0 },
72395   { 197, 3 },
72396   { 209, 4 },
72397   { 209, 2 },
72398   { 210, 1 },
72399   { 172, 1 },
72400   { 172, 1 },
72401   { 172, 0 },
72402   { 195, 0 },
72403   { 195, 3 },
72404   { 196, 0 },
72405   { 196, 2 },
72406   { 198, 0 },
72407   { 198, 2 },
72408   { 198, 4 },
72409   { 198, 4 },
72410   { 143, 4 },
72411   { 194, 0 },
72412   { 194, 2 },
72413   { 143, 6 },
72414   { 212, 5 },
72415   { 212, 3 },
72416   { 143, 8 },
72417   { 143, 5 },
72418   { 143, 6 },
72419   { 213, 2 },
72420   { 213, 1 },
72421   { 215, 3 },
72422   { 215, 1 },
72423   { 214, 0 },
72424   { 214, 3 },
72425   { 208, 3 },
72426   { 208, 1 },
72427   { 170, 1 },
72428   { 170, 3 },
72429   { 169, 1 },
72430   { 170, 1 },
72431   { 170, 1 },
72432   { 170, 3 },
72433   { 170, 5 },
72434   { 169, 1 },
72435   { 169, 1 },
72436   { 170, 1 },
72437   { 170, 1 },
72438   { 170, 3 },
72439   { 170, 6 },
72440   { 170, 5 },
72441   { 170, 4 },
72442   { 169, 1 },
72443   { 170, 3 },
72444   { 170, 3 },
72445   { 170, 3 },
72446   { 170, 3 },
72447   { 170, 3 },
72448   { 170, 3 },
72449   { 170, 3 },
72450   { 170, 3 },
72451   { 217, 1 },
72452   { 217, 2 },
72453   { 217, 1 },
72454   { 217, 2 },
72455   { 218, 2 },
72456   { 218, 0 },
72457   { 170, 4 },
72458   { 170, 2 },
72459   { 170, 3 },
72460   { 170, 3 },
72461   { 170, 4 },
72462   { 170, 2 },
72463   { 170, 2 },
72464   { 170, 2 },
72465   { 170, 2 },
72466   { 219, 1 },
72467   { 219, 2 },
72468   { 170, 5 },
72469   { 220, 1 },
72470   { 220, 2 },
72471   { 170, 5 },
72472   { 170, 3 },
72473   { 170, 5 },
72474   { 170, 4 },
72475   { 170, 4 },
72476   { 170, 5 },
72477   { 222, 5 },
72478   { 222, 4 },
72479   { 223, 2 },
72480   { 223, 0 },
72481   { 221, 1 },
72482   { 221, 0 },
72483   { 216, 1 },
72484   { 216, 0 },
72485   { 211, 3 },
72486   { 211, 1 },
72487   { 143, 11 },
72488   { 224, 1 },
72489   { 224, 0 },
72490   { 174, 0 },
72491   { 174, 3 },
72492   { 182, 5 },
72493   { 182, 3 },
72494   { 225, 1 },
72495   { 226, 0 },
72496   { 226, 2 },
72497   { 143, 4 },
72498   { 143, 1 },
72499   { 143, 2 },
72500   { 143, 5 },
72501   { 143, 5 },
72502   { 143, 5 },
72503   { 143, 6 },
72504   { 143, 3 },
72505   { 227, 1 },
72506   { 227, 1 },
72507   { 165, 2 },
72508   { 166, 2 },
72509   { 229, 1 },
72510   { 228, 1 },
72511   { 228, 0 },
72512   { 143, 5 },
72513   { 230, 11 },
72514   { 232, 1 },
72515   { 232, 1 },
72516   { 232, 2 },
72517   { 232, 0 },
72518   { 233, 1 },
72519   { 233, 1 },
72520   { 233, 3 },
72521   { 234, 0 },
72522   { 234, 3 },
72523   { 235, 0 },
72524   { 235, 2 },
72525   { 231, 3 },
72526   { 231, 0 },
72527   { 236, 6 },
72528   { 236, 8 },
72529   { 236, 5 },
72530   { 236, 4 },
72531   { 236, 1 },
72532   { 170, 4 },
72533   { 170, 6 },
72534   { 186, 1 },
72535   { 186, 1 },
72536   { 186, 1 },
72537   { 143, 4 },
72538   { 143, 6 },
72539   { 143, 3 },
72540   { 238, 0 },
72541   { 238, 2 },
72542   { 237, 1 },
72543   { 237, 0 },
72544   { 143, 1 },
72545   { 143, 3 },
72546   { 143, 1 },
72547   { 143, 3 },
72548   { 143, 6 },
72549   { 143, 6 },
72550   { 239, 1 },
72551   { 240, 0 },
72552   { 240, 1 },
72553   { 143, 1 },
72554   { 143, 4 },
72555   { 241, 7 },
72556   { 242, 1 },
72557   { 242, 3 },
72558   { 243, 0 },
72559   { 243, 2 },
72560   { 244, 1 },
72561   { 244, 3 },
72562   { 245, 1 },
72563   { 246, 0 },
72564   { 246, 2 },
72565 };
72566
72567 static void yy_accept(yyParser*);  /* Forward Declaration */
72568
72569 /*
72570 ** Perform a reduce action and the shift that must immediately
72571 ** follow the reduce.
72572 */
72573 static void yy_reduce(
72574   yyParser *yypParser,         /* The parser */
72575   int yyruleno                 /* Number of the rule by which to reduce */
72576 ){
72577   int yygoto;                     /* The next state */
72578   int yyact;                      /* The next action */
72579   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
72580   yyStackEntry *yymsp;            /* The top of the parser's stack */
72581   int yysize;                     /* Amount to pop the stack */
72582   sqlite3ParserARG_FETCH;
72583   yymsp = &yypParser->yystack[yypParser->yyidx];
72584 #ifndef NDEBUG
72585   if( yyTraceFILE && yyruleno>=0 
72586         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
72587     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
72588       yyRuleName[yyruleno]);
72589   }
72590 #endif /* NDEBUG */
72591
72592   /* Silence complaints from purify about yygotominor being uninitialized
72593   ** in some cases when it is copied into the stack after the following
72594   ** switch.  yygotominor is uninitialized when a rule reduces that does
72595   ** not set the value of its left-hand side nonterminal.  Leaving the
72596   ** value of the nonterminal uninitialized is utterly harmless as long
72597   ** as the value is never used.  So really the only thing this code
72598   ** accomplishes is to quieten purify.  
72599   **
72600   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
72601   ** without this code, their parser segfaults.  I'm not sure what there
72602   ** parser is doing to make this happen.  This is the second bug report
72603   ** from wireshark this week.  Clearly they are stressing Lemon in ways
72604   ** that it has not been previously stressed...  (SQLite ticket #2172)
72605   */
72606   memset(&yygotominor, 0, sizeof(yygotominor));
72607
72608
72609   switch( yyruleno ){
72610   /* Beginning here are the reduction cases.  A typical example
72611   ** follows:
72612   **   case 0:
72613   **  #line <lineno> <grammarfile>
72614   **     { ... }           // User supplied code
72615   **  #line <lineno> <thisfile>
72616   **     break;
72617   */
72618       case 0: /* input ::= cmdlist */
72619       case 1: /* cmdlist ::= cmdlist ecmd */
72620       case 2: /* cmdlist ::= ecmd */
72621       case 4: /* ecmd ::= SEMI */
72622       case 5: /* ecmd ::= explain cmdx SEMI */
72623       case 10: /* trans_opt ::= */
72624       case 11: /* trans_opt ::= TRANSACTION */
72625       case 12: /* trans_opt ::= TRANSACTION nm */
72626       case 20: /* cmd ::= create_table create_table_args */
72627       case 28: /* columnlist ::= columnlist COMMA column */
72628       case 29: /* columnlist ::= column */
72629       case 37: /* type ::= */
72630       case 44: /* signed ::= plus_num */
72631       case 45: /* signed ::= minus_num */
72632       case 46: /* carglist ::= carglist carg */
72633       case 47: /* carglist ::= */
72634       case 48: /* carg ::= CONSTRAINT nm ccons */
72635       case 49: /* carg ::= ccons */
72636       case 55: /* ccons ::= NULL onconf */
72637       case 82: /* conslist ::= conslist COMMA tcons */
72638       case 83: /* conslist ::= conslist tcons */
72639       case 84: /* conslist ::= tcons */
72640       case 85: /* tcons ::= CONSTRAINT nm */
72641       case 257: /* plus_opt ::= PLUS */
72642       case 258: /* plus_opt ::= */
72643       case 268: /* foreach_clause ::= */
72644       case 269: /* foreach_clause ::= FOR EACH ROW */
72645       case 289: /* database_kw_opt ::= DATABASE */
72646       case 290: /* database_kw_opt ::= */
72647       case 298: /* kwcolumn_opt ::= */
72648       case 299: /* kwcolumn_opt ::= COLUMNKW */
72649       case 303: /* vtabarglist ::= vtabarg */
72650       case 304: /* vtabarglist ::= vtabarglist COMMA vtabarg */
72651       case 306: /* vtabarg ::= vtabarg vtabargtoken */
72652       case 310: /* anylist ::= */
72653 {
72654 }
72655         break;
72656       case 3: /* cmdx ::= cmd */
72657 { sqlite3FinishCoding(pParse); }
72658         break;
72659       case 6: /* explain ::= */
72660 { sqlite3BeginParse(pParse, 0); }
72661         break;
72662       case 7: /* explain ::= EXPLAIN */
72663 { sqlite3BeginParse(pParse, 1); }
72664         break;
72665       case 8: /* explain ::= EXPLAIN QUERY PLAN */
72666 { sqlite3BeginParse(pParse, 2); }
72667         break;
72668       case 9: /* cmd ::= BEGIN transtype trans_opt */
72669 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy46);}
72670         break;
72671       case 13: /* transtype ::= */
72672 {yygotominor.yy46 = TK_DEFERRED;}
72673         break;
72674       case 14: /* transtype ::= DEFERRED */
72675       case 15: /* transtype ::= IMMEDIATE */
72676       case 16: /* transtype ::= EXCLUSIVE */
72677       case 107: /* multiselect_op ::= UNION */
72678       case 109: /* multiselect_op ::= EXCEPT|INTERSECT */
72679 {yygotominor.yy46 = yymsp[0].major;}
72680         break;
72681       case 17: /* cmd ::= COMMIT trans_opt */
72682       case 18: /* cmd ::= END trans_opt */
72683 {sqlite3CommitTransaction(pParse);}
72684         break;
72685       case 19: /* cmd ::= ROLLBACK trans_opt */
72686 {sqlite3RollbackTransaction(pParse);}
72687         break;
72688       case 21: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
72689 {
72690    sqlite3StartTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46);
72691 }
72692         break;
72693       case 22: /* ifnotexists ::= */
72694       case 25: /* temp ::= */
72695       case 63: /* autoinc ::= */
72696       case 77: /* init_deferred_pred_opt ::= */
72697       case 79: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
72698       case 90: /* defer_subclause_opt ::= */
72699       case 101: /* ifexists ::= */
72700       case 112: /* distinct ::= ALL */
72701       case 113: /* distinct ::= */
72702       case 213: /* between_op ::= BETWEEN */
72703       case 216: /* in_op ::= IN */
72704 {yygotominor.yy46 = 0;}
72705         break;
72706       case 23: /* ifnotexists ::= IF NOT EXISTS */
72707       case 24: /* temp ::= TEMP */
72708       case 64: /* autoinc ::= AUTOINCR */
72709       case 78: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
72710       case 100: /* ifexists ::= IF EXISTS */
72711       case 111: /* distinct ::= DISTINCT */
72712       case 214: /* between_op ::= NOT BETWEEN */
72713       case 217: /* in_op ::= NOT IN */
72714 {yygotominor.yy46 = 1;}
72715         break;
72716       case 26: /* create_table_args ::= LP columnlist conslist_opt RP */
72717 {
72718   sqlite3EndTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy0,0);
72719 }
72720         break;
72721       case 27: /* create_table_args ::= AS select */
72722 {
72723   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy219);
72724   sqlite3SelectDelete(yymsp[0].minor.yy219);
72725 }
72726         break;
72727       case 30: /* column ::= columnid type carglist */
72728 {
72729   yygotominor.yy410.z = yymsp[-2].minor.yy410.z;
72730   yygotominor.yy410.n = (pParse->sLastToken.z-yymsp[-2].minor.yy410.z) + pParse->sLastToken.n;
72731 }
72732         break;
72733       case 31: /* columnid ::= nm */
72734 {
72735   sqlite3AddColumn(pParse,&yymsp[0].minor.yy410);
72736   yygotominor.yy410 = yymsp[0].minor.yy410;
72737 }
72738         break;
72739       case 32: /* id ::= ID */
72740       case 33: /* ids ::= ID|STRING */
72741       case 34: /* nm ::= ID */
72742       case 35: /* nm ::= STRING */
72743       case 36: /* nm ::= JOIN_KW */
72744       case 256: /* number ::= INTEGER|FLOAT */
72745 {yygotominor.yy410 = yymsp[0].minor.yy0;}
72746         break;
72747       case 38: /* type ::= typetoken */
72748 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy410);}
72749         break;
72750       case 39: /* typetoken ::= typename */
72751       case 42: /* typename ::= ids */
72752       case 119: /* as ::= AS nm */
72753       case 120: /* as ::= ids */
72754       case 131: /* dbnm ::= DOT nm */
72755       case 241: /* idxitem ::= nm */
72756       case 243: /* collate ::= COLLATE ids */
72757       case 252: /* nmnum ::= plus_num */
72758       case 253: /* nmnum ::= nm */
72759       case 254: /* plus_num ::= plus_opt number */
72760       case 255: /* minus_num ::= MINUS number */
72761 {yygotominor.yy410 = yymsp[0].minor.yy410;}
72762         break;
72763       case 40: /* typetoken ::= typename LP signed RP */
72764 {
72765   yygotominor.yy410.z = yymsp[-3].minor.yy410.z;
72766   yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy410.z;
72767 }
72768         break;
72769       case 41: /* typetoken ::= typename LP signed COMMA signed RP */
72770 {
72771   yygotominor.yy410.z = yymsp[-5].minor.yy410.z;
72772   yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy410.z;
72773 }
72774         break;
72775       case 43: /* typename ::= typename ids */
72776 {yygotominor.yy410.z=yymsp[-1].minor.yy410.z; yygotominor.yy410.n=yymsp[0].minor.yy410.n+(yymsp[0].minor.yy410.z-yymsp[-1].minor.yy410.z);}
72777         break;
72778       case 50: /* ccons ::= DEFAULT term */
72779       case 52: /* ccons ::= DEFAULT PLUS term */
72780 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy172);}
72781         break;
72782       case 51: /* ccons ::= DEFAULT LP expr RP */
72783 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy172);}
72784         break;
72785       case 53: /* ccons ::= DEFAULT MINUS term */
72786 {
72787   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
72788   sqlite3AddDefaultValue(pParse,p);
72789 }
72790         break;
72791       case 54: /* ccons ::= DEFAULT id */
72792 {
72793   Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy410);
72794   sqlite3AddDefaultValue(pParse,p);
72795 }
72796         break;
72797       case 56: /* ccons ::= NOT NULL onconf */
72798 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy46);}
72799         break;
72800       case 57: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
72801 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);}
72802         break;
72803       case 58: /* ccons ::= UNIQUE onconf */
72804 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy46,0,0,0,0);}
72805         break;
72806       case 59: /* ccons ::= CHECK LP expr RP */
72807 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy172);}
72808         break;
72809       case 60: /* ccons ::= REFERENCES nm idxlist_opt refargs */
72810 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy410,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);}
72811         break;
72812       case 61: /* ccons ::= defer_subclause */
72813 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy46);}
72814         break;
72815       case 62: /* ccons ::= COLLATE ids */
72816 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy410);}
72817         break;
72818       case 65: /* refargs ::= */
72819 { yygotominor.yy46 = OE_Restrict * 0x010101; }
72820         break;
72821       case 66: /* refargs ::= refargs refarg */
72822 { yygotominor.yy46 = (yymsp[-1].minor.yy46 & yymsp[0].minor.yy405.mask) | yymsp[0].minor.yy405.value; }
72823         break;
72824       case 67: /* refarg ::= MATCH nm */
72825 { yygotominor.yy405.value = 0;     yygotominor.yy405.mask = 0x000000; }
72826         break;
72827       case 68: /* refarg ::= ON DELETE refact */
72828 { yygotominor.yy405.value = yymsp[0].minor.yy46;     yygotominor.yy405.mask = 0x0000ff; }
72829         break;
72830       case 69: /* refarg ::= ON UPDATE refact */
72831 { yygotominor.yy405.value = yymsp[0].minor.yy46<<8;  yygotominor.yy405.mask = 0x00ff00; }
72832         break;
72833       case 70: /* refarg ::= ON INSERT refact */
72834 { yygotominor.yy405.value = yymsp[0].minor.yy46<<16; yygotominor.yy405.mask = 0xff0000; }
72835         break;
72836       case 71: /* refact ::= SET NULL */
72837 { yygotominor.yy46 = OE_SetNull; }
72838         break;
72839       case 72: /* refact ::= SET DEFAULT */
72840 { yygotominor.yy46 = OE_SetDflt; }
72841         break;
72842       case 73: /* refact ::= CASCADE */
72843 { yygotominor.yy46 = OE_Cascade; }
72844         break;
72845       case 74: /* refact ::= RESTRICT */
72846 { yygotominor.yy46 = OE_Restrict; }
72847         break;
72848       case 75: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
72849       case 76: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
72850       case 91: /* defer_subclause_opt ::= defer_subclause */
72851       case 93: /* onconf ::= ON CONFLICT resolvetype */
72852       case 95: /* orconf ::= OR resolvetype */
72853       case 96: /* resolvetype ::= raisetype */
72854       case 166: /* insert_cmd ::= INSERT orconf */
72855 {yygotominor.yy46 = yymsp[0].minor.yy46;}
72856         break;
72857       case 80: /* conslist_opt ::= */
72858 {yygotominor.yy410.n = 0; yygotominor.yy410.z = 0;}
72859         break;
72860       case 81: /* conslist_opt ::= COMMA conslist */
72861 {yygotominor.yy410 = yymsp[-1].minor.yy0;}
72862         break;
72863       case 86: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
72864 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy174,yymsp[0].minor.yy46,yymsp[-2].minor.yy46,0);}
72865         break;
72866       case 87: /* tcons ::= UNIQUE LP idxlist RP onconf */
72867 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy174,yymsp[0].minor.yy46,0,0,0,0);}
72868         break;
72869       case 88: /* tcons ::= CHECK LP expr RP onconf */
72870 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy172);}
72871         break;
72872       case 89: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
72873 {
72874     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy174, &yymsp[-3].minor.yy410, yymsp[-2].minor.yy174, yymsp[-1].minor.yy46);
72875     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy46);
72876 }
72877         break;
72878       case 92: /* onconf ::= */
72879       case 94: /* orconf ::= */
72880 {yygotominor.yy46 = OE_Default;}
72881         break;
72882       case 97: /* resolvetype ::= IGNORE */
72883 {yygotominor.yy46 = OE_Ignore;}
72884         break;
72885       case 98: /* resolvetype ::= REPLACE */
72886       case 167: /* insert_cmd ::= REPLACE */
72887 {yygotominor.yy46 = OE_Replace;}
72888         break;
72889       case 99: /* cmd ::= DROP TABLE ifexists fullname */
72890 {
72891   sqlite3DropTable(pParse, yymsp[0].minor.yy373, 0, yymsp[-1].minor.yy46);
72892 }
72893         break;
72894       case 102: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
72895 {
72896   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, yymsp[0].minor.yy219, yymsp[-6].minor.yy46, yymsp[-4].minor.yy46);
72897 }
72898         break;
72899       case 103: /* cmd ::= DROP VIEW ifexists fullname */
72900 {
72901   sqlite3DropTable(pParse, yymsp[0].minor.yy373, 1, yymsp[-1].minor.yy46);
72902 }
72903         break;
72904       case 104: /* cmd ::= select */
72905 {
72906   SelectDest dest = {SRT_Callback, 0, 0};
72907   sqlite3Select(pParse, yymsp[0].minor.yy219, &dest, 0, 0, 0, 0);
72908   sqlite3SelectDelete(yymsp[0].minor.yy219);
72909 }
72910         break;
72911       case 105: /* select ::= oneselect */
72912       case 128: /* seltablist_paren ::= select */
72913 {yygotominor.yy219 = yymsp[0].minor.yy219;}
72914         break;
72915       case 106: /* select ::= select multiselect_op oneselect */
72916 {
72917   if( yymsp[0].minor.yy219 ){
72918     yymsp[0].minor.yy219->op = yymsp[-1].minor.yy46;
72919     yymsp[0].minor.yy219->pPrior = yymsp[-2].minor.yy219;
72920   }else{
72921     sqlite3SelectDelete(yymsp[-2].minor.yy219);
72922   }
72923   yygotominor.yy219 = yymsp[0].minor.yy219;
72924 }
72925         break;
72926       case 108: /* multiselect_op ::= UNION ALL */
72927 {yygotominor.yy46 = TK_ALL;}
72928         break;
72929       case 110: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
72930 {
72931   yygotominor.yy219 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy174,yymsp[-5].minor.yy373,yymsp[-4].minor.yy172,yymsp[-3].minor.yy174,yymsp[-2].minor.yy172,yymsp[-1].minor.yy174,yymsp[-7].minor.yy46,yymsp[0].minor.yy234.pLimit,yymsp[0].minor.yy234.pOffset);
72932 }
72933         break;
72934       case 114: /* sclp ::= selcollist COMMA */
72935       case 238: /* idxlist_opt ::= LP idxlist RP */
72936 {yygotominor.yy174 = yymsp[-1].minor.yy174;}
72937         break;
72938       case 115: /* sclp ::= */
72939       case 141: /* orderby_opt ::= */
72940       case 149: /* groupby_opt ::= */
72941       case 231: /* exprlist ::= */
72942       case 237: /* idxlist_opt ::= */
72943 {yygotominor.yy174 = 0;}
72944         break;
72945       case 116: /* selcollist ::= sclp expr as */
72946 {
72947    yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy410.n?&yymsp[0].minor.yy410:0);
72948 }
72949         break;
72950       case 117: /* selcollist ::= sclp STAR */
72951 {
72952   Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
72953   yygotominor.yy174 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy174, p, 0);
72954 }
72955         break;
72956       case 118: /* selcollist ::= sclp nm DOT STAR */
72957 {
72958   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
72959   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
72960   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
72961   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174, pDot, 0);
72962 }
72963         break;
72964       case 121: /* as ::= */
72965 {yygotominor.yy410.n = 0;}
72966         break;
72967       case 122: /* from ::= */
72968 {yygotominor.yy373 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy373));}
72969         break;
72970       case 123: /* from ::= FROM seltablist */
72971 {
72972   yygotominor.yy373 = yymsp[0].minor.yy373;
72973   sqlite3SrcListShiftJoinType(yygotominor.yy373);
72974 }
72975         break;
72976       case 124: /* stl_prefix ::= seltablist joinop */
72977 {
72978    yygotominor.yy373 = yymsp[-1].minor.yy373;
72979    if( yygotominor.yy373 && yygotominor.yy373->nSrc>0 ) yygotominor.yy373->a[yygotominor.yy373->nSrc-1].jointype = yymsp[0].minor.yy46;
72980 }
72981         break;
72982       case 125: /* stl_prefix ::= */
72983 {yygotominor.yy373 = 0;}
72984         break;
72985       case 126: /* seltablist ::= stl_prefix nm dbnm as on_opt using_opt */
72986 {
72987   yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy373,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,0,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
72988 }
72989         break;
72990       case 127: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */
72991 {
72992     yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy373,0,0,&yymsp[-2].minor.yy410,yymsp[-4].minor.yy219,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
72993   }
72994         break;
72995       case 129: /* seltablist_paren ::= seltablist */
72996 {
72997      sqlite3SrcListShiftJoinType(yymsp[0].minor.yy373);
72998      yygotominor.yy219 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy373,0,0,0,0,0,0,0);
72999   }
73000         break;
73001       case 130: /* dbnm ::= */
73002 {yygotominor.yy410.z=0; yygotominor.yy410.n=0;}
73003         break;
73004       case 132: /* fullname ::= nm dbnm */
73005 {yygotominor.yy373 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);}
73006         break;
73007       case 133: /* joinop ::= COMMA|JOIN */
73008 { yygotominor.yy46 = JT_INNER; }
73009         break;
73010       case 134: /* joinop ::= JOIN_KW JOIN */
73011 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
73012         break;
73013       case 135: /* joinop ::= JOIN_KW nm JOIN */
73014 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy410,0); }
73015         break;
73016       case 136: /* joinop ::= JOIN_KW nm nm JOIN */
73017 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy410,&yymsp[-1].minor.yy410); }
73018         break;
73019       case 137: /* on_opt ::= ON expr */
73020       case 145: /* sortitem ::= expr */
73021       case 152: /* having_opt ::= HAVING expr */
73022       case 159: /* where_opt ::= WHERE expr */
73023       case 174: /* expr ::= term */
73024       case 202: /* escape ::= ESCAPE expr */
73025       case 226: /* case_else ::= ELSE expr */
73026       case 228: /* case_operand ::= expr */
73027 {yygotominor.yy172 = yymsp[0].minor.yy172;}
73028         break;
73029       case 138: /* on_opt ::= */
73030       case 151: /* having_opt ::= */
73031       case 158: /* where_opt ::= */
73032       case 203: /* escape ::= */
73033       case 227: /* case_else ::= */
73034       case 229: /* case_operand ::= */
73035 {yygotominor.yy172 = 0;}
73036         break;
73037       case 139: /* using_opt ::= USING LP inscollist RP */
73038       case 171: /* inscollist_opt ::= LP inscollist RP */
73039 {yygotominor.yy432 = yymsp[-1].minor.yy432;}
73040         break;
73041       case 140: /* using_opt ::= */
73042       case 170: /* inscollist_opt ::= */
73043 {yygotominor.yy432 = 0;}
73044         break;
73045       case 142: /* orderby_opt ::= ORDER BY sortlist */
73046       case 150: /* groupby_opt ::= GROUP BY nexprlist */
73047       case 230: /* exprlist ::= nexprlist */
73048 {yygotominor.yy174 = yymsp[0].minor.yy174;}
73049         break;
73050       case 143: /* sortlist ::= sortlist COMMA sortitem sortorder */
73051 {
73052   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174,yymsp[-1].minor.yy172,0);
73053   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
73054 }
73055         break;
73056       case 144: /* sortlist ::= sortitem sortorder */
73057 {
73058   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy172,0);
73059   if( yygotominor.yy174 && yygotominor.yy174->a ) yygotominor.yy174->a[0].sortOrder = yymsp[0].minor.yy46;
73060 }
73061         break;
73062       case 146: /* sortorder ::= ASC */
73063       case 148: /* sortorder ::= */
73064 {yygotominor.yy46 = SQLITE_SO_ASC;}
73065         break;
73066       case 147: /* sortorder ::= DESC */
73067 {yygotominor.yy46 = SQLITE_SO_DESC;}
73068         break;
73069       case 153: /* limit_opt ::= */
73070 {yygotominor.yy234.pLimit = 0; yygotominor.yy234.pOffset = 0;}
73071         break;
73072       case 154: /* limit_opt ::= LIMIT expr */
73073 {yygotominor.yy234.pLimit = yymsp[0].minor.yy172; yygotominor.yy234.pOffset = 0;}
73074         break;
73075       case 155: /* limit_opt ::= LIMIT expr OFFSET expr */
73076 {yygotominor.yy234.pLimit = yymsp[-2].minor.yy172; yygotominor.yy234.pOffset = yymsp[0].minor.yy172;}
73077         break;
73078       case 156: /* limit_opt ::= LIMIT expr COMMA expr */
73079 {yygotominor.yy234.pOffset = yymsp[-2].minor.yy172; yygotominor.yy234.pLimit = yymsp[0].minor.yy172;}
73080         break;
73081       case 157: /* cmd ::= DELETE FROM fullname where_opt */
73082 {sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy373,yymsp[0].minor.yy172);}
73083         break;
73084       case 160: /* cmd ::= UPDATE orconf fullname SET setlist where_opt */
73085 {
73086   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy174,SQLITE_MAX_COLUMN,"set list"); 
73087   sqlite3Update(pParse,yymsp[-3].minor.yy373,yymsp[-1].minor.yy174,yymsp[0].minor.yy172,yymsp[-4].minor.yy46);
73088 }
73089         break;
73090       case 161: /* setlist ::= setlist COMMA nm EQ expr */
73091 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
73092         break;
73093       case 162: /* setlist ::= nm EQ expr */
73094 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
73095         break;
73096       case 163: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
73097 {sqlite3Insert(pParse, yymsp[-5].minor.yy373, yymsp[-1].minor.yy174, 0, yymsp[-4].minor.yy432, yymsp[-7].minor.yy46);}
73098         break;
73099       case 164: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
73100 {sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);}
73101         break;
73102       case 165: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
73103 {sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);}
73104         break;
73105       case 168: /* itemlist ::= itemlist COMMA expr */
73106       case 232: /* nexprlist ::= nexprlist COMMA expr */
73107 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);}
73108         break;
73109       case 169: /* itemlist ::= expr */
73110       case 233: /* nexprlist ::= expr */
73111 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,0);}
73112         break;
73113       case 172: /* inscollist ::= inscollist COMMA nm */
73114 {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy432,&yymsp[0].minor.yy410);}
73115         break;
73116       case 173: /* inscollist ::= nm */
73117 {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy410);}
73118         break;
73119       case 175: /* expr ::= LP expr RP */
73120 {yygotominor.yy172 = yymsp[-1].minor.yy172; sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
73121         break;
73122       case 176: /* term ::= NULL */
73123       case 181: /* term ::= INTEGER|FLOAT|BLOB */
73124       case 182: /* term ::= STRING */
73125 {yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
73126         break;
73127       case 177: /* expr ::= ID */
73128       case 178: /* expr ::= JOIN_KW */
73129 {yygotominor.yy172 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
73130         break;
73131       case 179: /* expr ::= nm DOT nm */
73132 {
73133   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
73134   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy410);
73135   yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
73136 }
73137         break;
73138       case 180: /* expr ::= nm DOT nm DOT nm */
73139 {
73140   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy410);
73141   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
73142   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy410);
73143   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
73144   yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
73145 }
73146         break;
73147       case 183: /* expr ::= REGISTER */
73148 {yygotominor.yy172 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
73149         break;
73150       case 184: /* expr ::= VARIABLE */
73151 {
73152   Token *pToken = &yymsp[0].minor.yy0;
73153   Expr *pExpr = yygotominor.yy172 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
73154   sqlite3ExprAssignVarNumber(pParse, pExpr);
73155 }
73156         break;
73157       case 185: /* expr ::= expr COLLATE ids */
73158 {
73159   yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy410);
73160 }
73161         break;
73162       case 186: /* expr ::= CAST LP expr AS typetoken RP */
73163 {
73164   yygotominor.yy172 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy172, 0, &yymsp[-1].minor.yy410);
73165   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
73166 }
73167         break;
73168       case 187: /* expr ::= ID LP distinct exprlist RP */
73169 {
73170   if( yymsp[-1].minor.yy174 && yymsp[-1].minor.yy174->nExpr>SQLITE_MAX_FUNCTION_ARG ){
73171     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
73172   }
73173   yygotominor.yy172 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy174, &yymsp[-4].minor.yy0);
73174   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
73175   if( yymsp[-2].minor.yy46 && yygotominor.yy172 ){
73176     yygotominor.yy172->flags |= EP_Distinct;
73177   }
73178 }
73179         break;
73180       case 188: /* expr ::= ID LP STAR RP */
73181 {
73182   yygotominor.yy172 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
73183   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
73184 }
73185         break;
73186       case 189: /* term ::= CTIME_KW */
73187 {
73188   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
73189   ** treated as functions that return constants */
73190   yygotominor.yy172 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
73191   if( yygotominor.yy172 ){
73192     yygotominor.yy172->op = TK_CONST_FUNC;  
73193     yygotominor.yy172->span = yymsp[0].minor.yy0;
73194   }
73195 }
73196         break;
73197       case 190: /* expr ::= expr AND expr */
73198       case 191: /* expr ::= expr OR expr */
73199       case 192: /* expr ::= expr LT|GT|GE|LE expr */
73200       case 193: /* expr ::= expr EQ|NE expr */
73201       case 194: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
73202       case 195: /* expr ::= expr PLUS|MINUS expr */
73203       case 196: /* expr ::= expr STAR|SLASH|REM expr */
73204       case 197: /* expr ::= expr CONCAT expr */
73205 {yygotominor.yy172 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy172,yymsp[0].minor.yy172,0);}
73206         break;
73207       case 198: /* likeop ::= LIKE_KW */
73208       case 200: /* likeop ::= MATCH */
73209 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 0;}
73210         break;
73211       case 199: /* likeop ::= NOT LIKE_KW */
73212       case 201: /* likeop ::= NOT MATCH */
73213 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 1;}
73214         break;
73215       case 204: /* expr ::= expr likeop expr escape */
73216 {
73217   ExprList *pList;
73218   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy172, 0);
73219   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy172, 0);
73220   if( yymsp[0].minor.yy172 ){
73221     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0);
73222   }
73223   yygotominor.yy172 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy72.eOperator);
73224   if( yymsp[-2].minor.yy72.not ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
73225   sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy172->span, &yymsp[-1].minor.yy172->span);
73226   if( yygotominor.yy172 ) yygotominor.yy172->flags |= EP_InfixFunc;
73227 }
73228         break;
73229       case 205: /* expr ::= expr ISNULL|NOTNULL */
73230 {
73231   yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy172, 0, 0);
73232   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy172->span,&yymsp[0].minor.yy0);
73233 }
73234         break;
73235       case 206: /* expr ::= expr IS NULL */
73236 {
73237   yygotominor.yy172 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy172, 0, 0);
73238   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
73239 }
73240         break;
73241       case 207: /* expr ::= expr NOT NULL */
73242 {
73243   yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy172, 0, 0);
73244   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
73245 }
73246         break;
73247       case 208: /* expr ::= expr IS NOT NULL */
73248 {
73249   yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy172, 0, 0);
73250   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,&yymsp[0].minor.yy0);
73251 }
73252         break;
73253       case 209: /* expr ::= NOT expr */
73254       case 210: /* expr ::= BITNOT expr */
73255 {
73256   yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy172, 0, 0);
73257   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
73258 }
73259         break;
73260       case 211: /* expr ::= MINUS expr */
73261 {
73262   yygotominor.yy172 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
73263   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
73264 }
73265         break;
73266       case 212: /* expr ::= PLUS expr */
73267 {
73268   yygotominor.yy172 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy172, 0, 0);
73269   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
73270 }
73271         break;
73272       case 215: /* expr ::= expr between_op expr AND expr */
73273 {
73274   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0);
73275   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0);
73276   yygotominor.yy172 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy172, 0, 0);
73277   if( yygotominor.yy172 ){
73278     yygotominor.yy172->pList = pList;
73279   }else{
73280     sqlite3ExprListDelete(pList);
73281   } 
73282   if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
73283   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy172->span);
73284 }
73285         break;
73286       case 218: /* expr ::= expr in_op LP exprlist RP */
73287 {
73288     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0);
73289     if( yygotominor.yy172 ){
73290       yygotominor.yy172->pList = yymsp[-1].minor.yy174;
73291       sqlite3ExprSetHeight(yygotominor.yy172);
73292     }else{
73293       sqlite3ExprListDelete(yymsp[-1].minor.yy174);
73294     }
73295     if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
73296     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
73297   }
73298         break;
73299       case 219: /* expr ::= LP select RP */
73300 {
73301     yygotominor.yy172 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
73302     if( yygotominor.yy172 ){
73303       yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
73304       sqlite3ExprSetHeight(yygotominor.yy172);
73305     }else{
73306       sqlite3SelectDelete(yymsp[-1].minor.yy219);
73307     }
73308     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
73309   }
73310         break;
73311       case 220: /* expr ::= expr in_op LP select RP */
73312 {
73313     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0);
73314     if( yygotominor.yy172 ){
73315       yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
73316       sqlite3ExprSetHeight(yygotominor.yy172);
73317     }else{
73318       sqlite3SelectDelete(yymsp[-1].minor.yy219);
73319     }
73320     if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
73321     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
73322   }
73323         break;
73324       case 221: /* expr ::= expr in_op nm dbnm */
73325 {
73326     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);
73327     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy172, 0, 0);
73328     if( yygotominor.yy172 ){
73329       yygotominor.yy172->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
73330       sqlite3ExprSetHeight(yygotominor.yy172);
73331     }else{
73332       sqlite3SrcListDelete(pSrc);
73333     }
73334     if( yymsp[-2].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
73335     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,yymsp[0].minor.yy410.z?&yymsp[0].minor.yy410:&yymsp[-1].minor.yy410);
73336   }
73337         break;
73338       case 222: /* expr ::= EXISTS LP select RP */
73339 {
73340     Expr *p = yygotominor.yy172 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
73341     if( p ){
73342       p->pSelect = yymsp[-1].minor.yy219;
73343       sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
73344       sqlite3ExprSetHeight(yygotominor.yy172);
73345     }else{
73346       sqlite3SelectDelete(yymsp[-1].minor.yy219);
73347     }
73348   }
73349         break;
73350       case 223: /* expr ::= CASE case_operand case_exprlist case_else END */
73351 {
73352   yygotominor.yy172 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, 0);
73353   if( yygotominor.yy172 ){
73354     yygotominor.yy172->pList = yymsp[-2].minor.yy174;
73355     sqlite3ExprSetHeight(yygotominor.yy172);
73356   }else{
73357     sqlite3ExprListDelete(yymsp[-2].minor.yy174);
73358   }
73359   sqlite3ExprSpan(yygotominor.yy172, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
73360 }
73361         break;
73362       case 224: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
73363 {
73364   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, yymsp[-2].minor.yy172, 0);
73365   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0);
73366 }
73367         break;
73368       case 225: /* case_exprlist ::= WHEN expr THEN expr */
73369 {
73370   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0);
73371   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0);
73372 }
73373         break;
73374       case 234: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
73375 {
73376   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy410, &yymsp[-5].minor.yy410, 
73377                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy410,0), yymsp[-1].minor.yy174, yymsp[-9].minor.yy46,
73378                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy46);
73379 }
73380         break;
73381       case 235: /* uniqueflag ::= UNIQUE */
73382       case 282: /* raisetype ::= ABORT */
73383 {yygotominor.yy46 = OE_Abort;}
73384         break;
73385       case 236: /* uniqueflag ::= */
73386 {yygotominor.yy46 = OE_None;}
73387         break;
73388       case 239: /* idxlist ::= idxlist COMMA idxitem collate sortorder */
73389 {
73390   Expr *p = 0;
73391   if( yymsp[-1].minor.yy410.n>0 ){
73392     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
73393     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410);
73394   }
73395   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, p, &yymsp[-2].minor.yy410);
73396   sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index");
73397   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
73398 }
73399         break;
73400       case 240: /* idxlist ::= idxitem collate sortorder */
73401 {
73402   Expr *p = 0;
73403   if( yymsp[-1].minor.yy410.n>0 ){
73404     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
73405     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410);
73406   }
73407   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy410);
73408   sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index");
73409   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
73410 }
73411         break;
73412       case 242: /* collate ::= */
73413 {yygotominor.yy410.z = 0; yygotominor.yy410.n = 0;}
73414         break;
73415       case 244: /* cmd ::= DROP INDEX ifexists fullname */
73416 {sqlite3DropIndex(pParse, yymsp[0].minor.yy373, yymsp[-1].minor.yy46);}
73417         break;
73418       case 245: /* cmd ::= VACUUM */
73419       case 246: /* cmd ::= VACUUM nm */
73420 {sqlite3Vacuum(pParse);}
73421         break;
73422       case 247: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
73423 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,0);}
73424         break;
73425       case 248: /* cmd ::= PRAGMA nm dbnm EQ ON */
73426 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy0,0);}
73427         break;
73428       case 249: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
73429 {
73430   sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,1);
73431 }
73432         break;
73433       case 250: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
73434 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-1].minor.yy410,0);}
73435         break;
73436       case 251: /* cmd ::= PRAGMA nm dbnm */
73437 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,0,0);}
73438         break;
73439       case 259: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
73440 {
73441   Token all;
73442   all.z = yymsp[-3].minor.yy410.z;
73443   all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy410.z) + yymsp[0].minor.yy0.n;
73444   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy243, &all);
73445 }
73446         break;
73447       case 260: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
73448 {
73449   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy410, &yymsp[-6].minor.yy410, yymsp[-5].minor.yy46, yymsp[-4].minor.yy370.a, yymsp[-4].minor.yy370.b, yymsp[-2].minor.yy373, yymsp[0].minor.yy172, yymsp[-10].minor.yy46, yymsp[-8].minor.yy46);
73450   yygotominor.yy410 = (yymsp[-6].minor.yy410.n==0?yymsp[-7].minor.yy410:yymsp[-6].minor.yy410);
73451 }
73452         break;
73453       case 261: /* trigger_time ::= BEFORE */
73454       case 264: /* trigger_time ::= */
73455 { yygotominor.yy46 = TK_BEFORE; }
73456         break;
73457       case 262: /* trigger_time ::= AFTER */
73458 { yygotominor.yy46 = TK_AFTER;  }
73459         break;
73460       case 263: /* trigger_time ::= INSTEAD OF */
73461 { yygotominor.yy46 = TK_INSTEAD;}
73462         break;
73463       case 265: /* trigger_event ::= DELETE|INSERT */
73464       case 266: /* trigger_event ::= UPDATE */
73465 {yygotominor.yy370.a = yymsp[0].major; yygotominor.yy370.b = 0;}
73466         break;
73467       case 267: /* trigger_event ::= UPDATE OF inscollist */
73468 {yygotominor.yy370.a = TK_UPDATE; yygotominor.yy370.b = yymsp[0].minor.yy432;}
73469         break;
73470       case 270: /* when_clause ::= */
73471       case 287: /* key_opt ::= */
73472 { yygotominor.yy172 = 0; }
73473         break;
73474       case 271: /* when_clause ::= WHEN expr */
73475       case 288: /* key_opt ::= KEY expr */
73476 { yygotominor.yy172 = yymsp[0].minor.yy172; }
73477         break;
73478       case 272: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
73479 {
73480   if( yymsp[-2].minor.yy243 ){
73481     yymsp[-2].minor.yy243->pLast->pNext = yymsp[-1].minor.yy243;
73482   }else{
73483     yymsp[-2].minor.yy243 = yymsp[-1].minor.yy243;
73484   }
73485   yymsp[-2].minor.yy243->pLast = yymsp[-1].minor.yy243;
73486   yygotominor.yy243 = yymsp[-2].minor.yy243;
73487 }
73488         break;
73489       case 273: /* trigger_cmd_list ::= */
73490 { yygotominor.yy243 = 0; }
73491         break;
73492       case 274: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
73493 { yygotominor.yy243 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy410, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); }
73494         break;
73495       case 275: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
73496 {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy410, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);}
73497         break;
73498       case 276: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
73499 {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy410, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);}
73500         break;
73501       case 277: /* trigger_cmd ::= DELETE FROM nm where_opt */
73502 {yygotominor.yy243 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy410, yymsp[0].minor.yy172);}
73503         break;
73504       case 278: /* trigger_cmd ::= select */
73505 {yygotominor.yy243 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy219); }
73506         break;
73507       case 279: /* expr ::= RAISE LP IGNORE RP */
73508 {
73509   yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
73510   if( yygotominor.yy172 ){
73511     yygotominor.yy172->iColumn = OE_Ignore;
73512     sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
73513   }
73514 }
73515         break;
73516       case 280: /* expr ::= RAISE LP raisetype COMMA nm RP */
73517 {
73518   yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy410); 
73519   if( yygotominor.yy172 ) {
73520     yygotominor.yy172->iColumn = yymsp[-3].minor.yy46;
73521     sqlite3ExprSpan(yygotominor.yy172, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
73522   }
73523 }
73524         break;
73525       case 281: /* raisetype ::= ROLLBACK */
73526 {yygotominor.yy46 = OE_Rollback;}
73527         break;
73528       case 283: /* raisetype ::= FAIL */
73529 {yygotominor.yy46 = OE_Fail;}
73530         break;
73531       case 284: /* cmd ::= DROP TRIGGER ifexists fullname */
73532 {
73533   sqlite3DropTrigger(pParse,yymsp[0].minor.yy373,yymsp[-1].minor.yy46);
73534 }
73535         break;
73536       case 285: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
73537 {
73538   sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy172);
73539 }
73540         break;
73541       case 286: /* cmd ::= DETACH database_kw_opt expr */
73542 {
73543   sqlite3Detach(pParse, yymsp[0].minor.yy172);
73544 }
73545         break;
73546       case 291: /* cmd ::= REINDEX */
73547 {sqlite3Reindex(pParse, 0, 0);}
73548         break;
73549       case 292: /* cmd ::= REINDEX nm dbnm */
73550 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
73551         break;
73552       case 293: /* cmd ::= ANALYZE */
73553 {sqlite3Analyze(pParse, 0, 0);}
73554         break;
73555       case 294: /* cmd ::= ANALYZE nm dbnm */
73556 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
73557         break;
73558       case 295: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
73559 {
73560   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy410);
73561 }
73562         break;
73563       case 296: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
73564 {
73565   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy410);
73566 }
73567         break;
73568       case 297: /* add_column_fullname ::= fullname */
73569 {
73570   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy373);
73571 }
73572         break;
73573       case 300: /* cmd ::= create_vtab */
73574 {sqlite3VtabFinishParse(pParse,0);}
73575         break;
73576       case 301: /* cmd ::= create_vtab LP vtabarglist RP */
73577 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
73578         break;
73579       case 302: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */
73580 {
73581     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, &yymsp[0].minor.yy410);
73582 }
73583         break;
73584       case 305: /* vtabarg ::= */
73585 {sqlite3VtabArgInit(pParse);}
73586         break;
73587       case 307: /* vtabargtoken ::= ANY */
73588       case 308: /* vtabargtoken ::= lp anylist RP */
73589       case 309: /* lp ::= LP */
73590       case 311: /* anylist ::= anylist ANY */
73591 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
73592         break;
73593   };
73594   yygoto = yyRuleInfo[yyruleno].lhs;
73595   yysize = yyRuleInfo[yyruleno].nrhs;
73596   yypParser->yyidx -= yysize;
73597   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
73598   if( yyact < YYNSTATE ){
73599 #ifdef NDEBUG
73600     /* If we are not debugging and the reduce action popped at least
73601     ** one element off the stack, then we can push the new element back
73602     ** onto the stack here, and skip the stack overflow test in yy_shift().
73603     ** That gives a significant speed improvement. */
73604     if( yysize ){
73605       yypParser->yyidx++;
73606       yymsp -= yysize-1;
73607       yymsp->stateno = yyact;
73608       yymsp->major = yygoto;
73609       yymsp->minor = yygotominor;
73610     }else
73611 #endif
73612     {
73613       yy_shift(yypParser,yyact,yygoto,&yygotominor);
73614     }
73615   }else{
73616     assert( yyact == YYNSTATE + YYNRULE + 1 );
73617     yy_accept(yypParser);
73618   }
73619 }
73620
73621 /*
73622 ** The following code executes when the parse fails
73623 */
73624 static void yy_parse_failed(
73625   yyParser *yypParser           /* The parser */
73626 ){
73627   sqlite3ParserARG_FETCH;
73628 #ifndef NDEBUG
73629   if( yyTraceFILE ){
73630     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
73631   }
73632 #endif
73633   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
73634   /* Here code is inserted which will be executed whenever the
73635   ** parser fails */
73636   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
73637 }
73638
73639 /*
73640 ** The following code executes when a syntax error first occurs.
73641 */
73642 static void yy_syntax_error(
73643   yyParser *yypParser,           /* The parser */
73644   int yymajor,                   /* The major type of the error token */
73645   YYMINORTYPE yyminor            /* The minor type of the error token */
73646 ){
73647   sqlite3ParserARG_FETCH;
73648 #define TOKEN (yyminor.yy0)
73649
73650   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
73651   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
73652   pParse->parseError = 1;
73653   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
73654 }
73655
73656 /*
73657 ** The following is executed when the parser accepts
73658 */
73659 static void yy_accept(
73660   yyParser *yypParser           /* The parser */
73661 ){
73662   sqlite3ParserARG_FETCH;
73663 #ifndef NDEBUG
73664   if( yyTraceFILE ){
73665     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
73666   }
73667 #endif
73668   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
73669   /* Here code is inserted which will be executed whenever the
73670   ** parser accepts */
73671   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
73672 }
73673
73674 /* The main parser program.
73675 ** The first argument is a pointer to a structure obtained from
73676 ** "sqlite3ParserAlloc" which describes the current state of the parser.
73677 ** The second argument is the major token number.  The third is
73678 ** the minor token.  The fourth optional argument is whatever the
73679 ** user wants (and specified in the grammar) and is available for
73680 ** use by the action routines.
73681 **
73682 ** Inputs:
73683 ** <ul>
73684 ** <li> A pointer to the parser (an opaque structure.)
73685 ** <li> The major token number.
73686 ** <li> The minor token number.
73687 ** <li> An option argument of a grammar-specified type.
73688 ** </ul>
73689 **
73690 ** Outputs:
73691 ** None.
73692 */
73693 SQLITE_PRIVATE void sqlite3Parser(
73694   void *yyp,                   /* The parser */
73695   int yymajor,                 /* The major token code number */
73696   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
73697   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
73698 ){
73699   YYMINORTYPE yyminorunion;
73700   int yyact;            /* The parser action. */
73701   int yyendofinput;     /* True if we are at the end of input */
73702 #ifdef YYERRORSYMBOL
73703   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
73704 #endif
73705   yyParser *yypParser;  /* The parser */
73706
73707   /* (re)initialize the parser, if necessary */
73708   yypParser = (yyParser*)yyp;
73709   if( yypParser->yyidx<0 ){
73710 #if YYSTACKDEPTH<=0
73711     if( yypParser->yystksz <=0 ){
73712       memset(&yyminorunion, 0, sizeof(yyminorunion));
73713       yyStackOverflow(yypParser, &yyminorunion);
73714       return;
73715     }
73716 #endif
73717     yypParser->yyidx = 0;
73718     yypParser->yyerrcnt = -1;
73719     yypParser->yystack[0].stateno = 0;
73720     yypParser->yystack[0].major = 0;
73721   }
73722   yyminorunion.yy0 = yyminor;
73723   yyendofinput = (yymajor==0);
73724   sqlite3ParserARG_STORE;
73725
73726 #ifndef NDEBUG
73727   if( yyTraceFILE ){
73728     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
73729   }
73730 #endif
73731
73732   do{
73733     yyact = yy_find_shift_action(yypParser,yymajor);
73734     if( yyact<YYNSTATE ){
73735       assert( !yyendofinput );  /* Impossible to shift the $ token */
73736       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
73737       yypParser->yyerrcnt--;
73738       yymajor = YYNOCODE;
73739     }else if( yyact < YYNSTATE + YYNRULE ){
73740       yy_reduce(yypParser,yyact-YYNSTATE);
73741     }else{
73742       assert( yyact == YY_ERROR_ACTION );
73743 #ifdef YYERRORSYMBOL
73744       int yymx;
73745 #endif
73746 #ifndef NDEBUG
73747       if( yyTraceFILE ){
73748         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
73749       }
73750 #endif
73751 #ifdef YYERRORSYMBOL
73752       /* A syntax error has occurred.
73753       ** The response to an error depends upon whether or not the
73754       ** grammar defines an error token "ERROR".  
73755       **
73756       ** This is what we do if the grammar does define ERROR:
73757       **
73758       **  * Call the %syntax_error function.
73759       **
73760       **  * Begin popping the stack until we enter a state where
73761       **    it is legal to shift the error symbol, then shift
73762       **    the error symbol.
73763       **
73764       **  * Set the error count to three.
73765       **
73766       **  * Begin accepting and shifting new tokens.  No new error
73767       **    processing will occur until three tokens have been
73768       **    shifted successfully.
73769       **
73770       */
73771       if( yypParser->yyerrcnt<0 ){
73772         yy_syntax_error(yypParser,yymajor,yyminorunion);
73773       }
73774       yymx = yypParser->yystack[yypParser->yyidx].major;
73775       if( yymx==YYERRORSYMBOL || yyerrorhit ){
73776 #ifndef NDEBUG
73777         if( yyTraceFILE ){
73778           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
73779              yyTracePrompt,yyTokenName[yymajor]);
73780         }
73781 #endif
73782         yy_destructor(yymajor,&yyminorunion);
73783         yymajor = YYNOCODE;
73784       }else{
73785          while(
73786           yypParser->yyidx >= 0 &&
73787           yymx != YYERRORSYMBOL &&
73788           (yyact = yy_find_reduce_action(
73789                         yypParser->yystack[yypParser->yyidx].stateno,
73790                         YYERRORSYMBOL)) >= YYNSTATE
73791         ){
73792           yy_pop_parser_stack(yypParser);
73793         }
73794         if( yypParser->yyidx < 0 || yymajor==0 ){
73795           yy_destructor(yymajor,&yyminorunion);
73796           yy_parse_failed(yypParser);
73797           yymajor = YYNOCODE;
73798         }else if( yymx!=YYERRORSYMBOL ){
73799           YYMINORTYPE u2;
73800           u2.YYERRSYMDT = 0;
73801           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
73802         }
73803       }
73804       yypParser->yyerrcnt = 3;
73805       yyerrorhit = 1;
73806 #else  /* YYERRORSYMBOL is not defined */
73807       /* This is what we do if the grammar does not define ERROR:
73808       **
73809       **  * Report an error message, and throw away the input token.
73810       **
73811       **  * If the input token is $, then fail the parse.
73812       **
73813       ** As before, subsequent error messages are suppressed until
73814       ** three input tokens have been successfully shifted.
73815       */
73816       if( yypParser->yyerrcnt<=0 ){
73817         yy_syntax_error(yypParser,yymajor,yyminorunion);
73818       }
73819       yypParser->yyerrcnt = 3;
73820       yy_destructor(yymajor,&yyminorunion);
73821       if( yyendofinput ){
73822         yy_parse_failed(yypParser);
73823       }
73824       yymajor = YYNOCODE;
73825 #endif
73826     }
73827   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
73828   return;
73829 }
73830
73831 /************** End of parse.c ***********************************************/
73832 /************** Begin file tokenize.c ****************************************/
73833 /*
73834 ** 2001 September 15
73835 **
73836 ** The author disclaims copyright to this source code.  In place of
73837 ** a legal notice, here is a blessing:
73838 **
73839 **    May you do good and not evil.
73840 **    May you find forgiveness for yourself and forgive others.
73841 **    May you share freely, never taking more than you give.
73842 **
73843 *************************************************************************
73844 ** An tokenizer for SQL
73845 **
73846 ** This file contains C code that splits an SQL input string up into
73847 ** individual tokens and sends those tokens one-by-one over to the
73848 ** parser for analysis.
73849 **
73850 ** $Id: tokenize.c,v 1.138 2008/01/22 23:37:10 drh Exp $
73851 */
73852
73853 /*
73854 ** The charMap() macro maps alphabetic characters into their
73855 ** lower-case ASCII equivalent.  On ASCII machines, this is just
73856 ** an upper-to-lower case map.  On EBCDIC machines we also need
73857 ** to adjust the encoding.  Only alphabetic characters and underscores
73858 ** need to be translated.
73859 */
73860 #ifdef SQLITE_ASCII
73861 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
73862 #endif
73863 #ifdef SQLITE_EBCDIC
73864 # define charMap(X) ebcdicToAscii[(unsigned char)X]
73865 const unsigned char ebcdicToAscii[] = {
73866 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
73867    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
73868    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
73869    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
73870    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
73871    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
73872    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
73873    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
73874    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
73875    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
73876    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
73877    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
73878    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
73879    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
73880    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
73881    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
73882    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
73883 };
73884 #endif
73885
73886 /*
73887 ** The sqlite3KeywordCode function looks up an identifier to determine if
73888 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
73889 ** returned.  If the input is not a keyword, TK_ID is returned.
73890 **
73891 ** The implementation of this routine was generated by a program,
73892 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
73893 ** The output of the mkkeywordhash.c program is written into a file
73894 ** named keywordhash.h and then included into this source file by
73895 ** the #include below.
73896 */
73897 /************** Include keywordhash.h in the middle of tokenize.c ************/
73898 /************** Begin file keywordhash.h *************************************/
73899 /***** This file contains automatically generated code ******
73900 **
73901 ** The code in this file has been automatically generated by
73902 **
73903 **     $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.31 2007/07/30 18:26:20 rse Exp $
73904 **
73905 ** The code in this file implements a function that determines whether
73906 ** or not a given identifier is really an SQL keyword.  The same thing
73907 ** might be implemented more directly using a hand-written hash table.
73908 ** But by using this automatically generated code, the size of the code
73909 ** is substantially reduced.  This is important for embedded applications
73910 ** on platforms with limited memory.
73911 */
73912 /* Hash score: 165 */
73913 static int keywordCode(const char *z, int n){
73914   /* zText[] encodes 775 bytes of keywords in 526 bytes */
73915   static const char zText[526] =
73916     "BEFOREIGNOREGEXPLAINSTEADDESCAPEACHECKEYCONSTRAINTERSECTABLEFT"
73917     "HENDATABASELECTRANSACTIONATURALTERAISELSEXCEPTRIGGEREFERENCES"
73918     "UNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNEREINDEXCLUSIVEXISTSBETWEEN"
73919     "OTNULLIKECASCADEFERRABLECASECOLLATECREATECURRENT_DATEDELETEDETACH"
73920     "IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN"
73921     "WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICT"
73922     "CROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOB"
73923     "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM"
73924     "VIEWINITIALLY";
73925   static const unsigned char aHash[127] = {
73926       63,  92, 109,  61,   0,  38,   0,   0,  69,   0,  64,   0,   0,
73927      102,   4,  65,   7,   0, 108,  72, 103,  99,   0,  22,   0,   0,
73928      113,   0, 111, 106,   0,  18,  80,   0,   1,   0,   0,  56,  57,
73929        0,  55,  11,   0,  33,  77,  89,   0, 110,  88,   0,   0,  45,
73930        0,  90,  54,   0,  20,   0, 114,  34,  19,   0,  10,  97,  28,
73931       83,   0,   0, 116,  93,  47, 115,  41,  12,  44,   0,  78,   0,
73932       87,  29,   0,  86,   0,   0,   0,  82,  79,  84,  75,  96,   6,
73933       14,  95,   0,  68,   0,  21,  76,  98,  27,   0, 112,  67, 104,
73934       49,  40,  71,   0,   0,  81, 100,   0, 107,   0,  15,   0,   0,
73935       24,   0,  73,  42,  50,   0,  16,  48,   0,  37,
73936   };
73937   static const unsigned char aNext[116] = {
73938        0,   0,   0,   0,   0,   0,   0,   0,   0,   9,   0,   0,   0,
73939        0,   0,   0,   0,   5,   0,   0,   0,   0,   0,   0,   0,   0,
73940        0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  32,   0,   0,
73941       17,   0,   0,   0,  36,  39,   0,   0,  25,   0,   0,  31,   0,
73942        0,   0,  43,  52,   0,   0,   0,  53,   0,   0,   0,   0,   0,
73943        0,   0,   0,   0,  51,   0,   0,   0,   0,  26,   0,   8,  46,
73944        2,   0,   0,   0,   0,   0,   0,   0,   3,  58,  66,   0,  13,
73945        0,  91,  85,   0,  94,   0,  74,   0,   0,  62,   0,  35, 101,
73946        0,   0, 105,  23,  30,  60,  70,   0,   0,  59,   0,   0,
73947   };
73948   static const unsigned char aLen[116] = {
73949        6,   7,   3,   6,   6,   7,   7,   3,   4,   6,   4,   5,   3,
73950       10,   9,   5,   4,   4,   3,   8,   2,   6,  11,   2,   7,   5,
73951        5,   4,   6,   7,  10,   6,   5,   6,   6,   5,   6,   4,   9,
73952        2,   5,   5,   7,   5,   9,   6,   7,   7,   3,   4,   4,   7,
73953        3,  10,   4,   7,   6,  12,   6,   6,   9,   4,   6,   5,   4,
73954        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
73955       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
73956        2,   4,   4,   4,   4,   4,   2,   2,   4,   6,   2,   3,   6,
73957        5,   8,   5,   5,   8,   3,   5,   5,   6,   4,   9,   3,
73958   };
73959   static const unsigned short int aOffset[116] = {
73960        0,   2,   2,   6,  10,  13,  18,  23,  25,  26,  31,  33,  37,
73961       40,  47,  55,  58,  61,  63,  65,  70,  71,  76,  85,  86,  91,
73962       95,  99, 102, 107, 113, 123, 126, 131, 136, 141, 144, 148, 148,
73963      152, 157, 160, 164, 166, 169, 177, 183, 189, 189, 192, 195, 199,
73964      200, 204, 214, 218, 225, 231, 243, 249, 255, 264, 266, 272, 277,
73965      279, 286, 291, 296, 302, 308, 313, 317, 320, 326, 330, 337, 339,
73966      346, 348, 350, 359, 363, 369, 375, 383, 388, 388, 404, 411, 418,
73967      419, 426, 430, 434, 438, 442, 445, 447, 449, 452, 452, 455, 458,
73968      464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521,
73969   };
73970   static const unsigned char aCode[116] = {
73971     TK_BEFORE,     TK_FOREIGN,    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    
73972     TK_EXPLAIN,    TK_INSTEAD,    TK_ADD,        TK_DESC,       TK_ESCAPE,     
73973     TK_EACH,       TK_CHECK,      TK_KEY,        TK_CONSTRAINT, TK_INTERSECT,  
73974     TK_TABLE,      TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DATABASE,   
73975     TK_AS,         TK_SELECT,     TK_TRANSACTION,TK_ON,         TK_JOIN_KW,    
73976     TK_ALTER,      TK_RAISE,      TK_ELSE,       TK_EXCEPT,     TK_TRIGGER,    
73977     TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
73978     TK_GROUP,      TK_UPDATE,     TK_TEMP,       TK_TEMP,       TK_OR,         
73979     TK_BEGIN,      TK_JOIN_KW,    TK_REINDEX,    TK_INDEX,      TK_EXCLUSIVE,  
73980     TK_EXISTS,     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NULL,       
73981     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DEFERRABLE, TK_CASE,       
73982     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DELETE,     TK_DETACH,     
73983     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       
73984     TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    
73985     TK_LIMIT,      TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      
73986     TK_REPLACE,    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         
73987     TK_IN,         TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   
73988     TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   
73989     TK_DISTINCT,   TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       
73990     TK_JOIN_KW,    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_INTO,       
73991     TK_OFFSET,     TK_OF,         TK_SET,        TK_ISNULL,     TK_ORDER,      
73992     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
73993     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
73994     TK_ALL,        
73995   };
73996   int h, i;
73997   if( n<2 ) return TK_ID;
73998   h = ((charMap(z[0])*4) ^
73999       (charMap(z[n-1])*3) ^
74000       n) % 127;
74001   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
74002     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
74003       return aCode[i];
74004     }
74005   }
74006   return TK_ID;
74007 }
74008 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
74009   return keywordCode((char*)z, n);
74010 }
74011
74012 /************** End of keywordhash.h *****************************************/
74013 /************** Continuing where we left off in tokenize.c *******************/
74014
74015
74016 /*
74017 ** If X is a character that can be used in an identifier then
74018 ** IdChar(X) will be true.  Otherwise it is false.
74019 **
74020 ** For ASCII, any character with the high-order bit set is
74021 ** allowed in an identifier.  For 7-bit characters, 
74022 ** sqlite3IsIdChar[X] must be 1.
74023 **
74024 ** For EBCDIC, the rules are more complex but have the same
74025 ** end result.
74026 **
74027 ** Ticket #1066.  the SQL standard does not allow '$' in the
74028 ** middle of identfiers.  But many SQL implementations do. 
74029 ** SQLite will allow '$' in identifiers for compatibility.
74030 ** But the feature is undocumented.
74031 */
74032 #ifdef SQLITE_ASCII
74033 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
74034 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
74035     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
74036     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
74037     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
74038     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
74039     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
74040     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
74041 };
74042 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
74043 #endif
74044 #ifdef SQLITE_EBCDIC
74045 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
74046 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
74047     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
74048     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
74049     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
74050     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
74051     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
74052     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
74053     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
74054     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
74055     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
74056     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
74057     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
74058     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
74059 };
74060 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
74061 #endif
74062
74063
74064 /*
74065 ** Return the length of the token that begins at z[0]. 
74066 ** Store the token type in *tokenType before returning.
74067 */
74068 static int getToken(const unsigned char *z, int *tokenType){
74069   int i, c;
74070   switch( *z ){
74071     case ' ': case '\t': case '\n': case '\f': case '\r': {
74072       for(i=1; isspace(z[i]); i++){}
74073       *tokenType = TK_SPACE;
74074       return i;
74075     }
74076     case '-': {
74077       if( z[1]=='-' ){
74078         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
74079         *tokenType = TK_COMMENT;
74080         return i;
74081       }
74082       *tokenType = TK_MINUS;
74083       return 1;
74084     }
74085     case '(': {
74086       *tokenType = TK_LP;
74087       return 1;
74088     }
74089     case ')': {
74090       *tokenType = TK_RP;
74091       return 1;
74092     }
74093     case ';': {
74094       *tokenType = TK_SEMI;
74095       return 1;
74096     }
74097     case '+': {
74098       *tokenType = TK_PLUS;
74099       return 1;
74100     }
74101     case '*': {
74102       *tokenType = TK_STAR;
74103       return 1;
74104     }
74105     case '/': {
74106       if( z[1]!='*' || z[2]==0 ){
74107         *tokenType = TK_SLASH;
74108         return 1;
74109       }
74110       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
74111       if( c ) i++;
74112       *tokenType = TK_COMMENT;
74113       return i;
74114     }
74115     case '%': {
74116       *tokenType = TK_REM;
74117       return 1;
74118     }
74119     case '=': {
74120       *tokenType = TK_EQ;
74121       return 1 + (z[1]=='=');
74122     }
74123     case '<': {
74124       if( (c=z[1])=='=' ){
74125         *tokenType = TK_LE;
74126         return 2;
74127       }else if( c=='>' ){
74128         *tokenType = TK_NE;
74129         return 2;
74130       }else if( c=='<' ){
74131         *tokenType = TK_LSHIFT;
74132         return 2;
74133       }else{
74134         *tokenType = TK_LT;
74135         return 1;
74136       }
74137     }
74138     case '>': {
74139       if( (c=z[1])=='=' ){
74140         *tokenType = TK_GE;
74141         return 2;
74142       }else if( c=='>' ){
74143         *tokenType = TK_RSHIFT;
74144         return 2;
74145       }else{
74146         *tokenType = TK_GT;
74147         return 1;
74148       }
74149     }
74150     case '!': {
74151       if( z[1]!='=' ){
74152         *tokenType = TK_ILLEGAL;
74153         return 2;
74154       }else{
74155         *tokenType = TK_NE;
74156         return 2;
74157       }
74158     }
74159     case '|': {
74160       if( z[1]!='|' ){
74161         *tokenType = TK_BITOR;
74162         return 1;
74163       }else{
74164         *tokenType = TK_CONCAT;
74165         return 2;
74166       }
74167     }
74168     case ',': {
74169       *tokenType = TK_COMMA;
74170       return 1;
74171     }
74172     case '&': {
74173       *tokenType = TK_BITAND;
74174       return 1;
74175     }
74176     case '~': {
74177       *tokenType = TK_BITNOT;
74178       return 1;
74179     }
74180     case '`':
74181     case '\'':
74182     case '"': {
74183       int delim = z[0];
74184       for(i=1; (c=z[i])!=0; i++){
74185         if( c==delim ){
74186           if( z[i+1]==delim ){
74187             i++;
74188           }else{
74189             break;
74190           }
74191         }
74192       }
74193       if( c ){
74194         *tokenType = TK_STRING;
74195         return i+1;
74196       }else{
74197         *tokenType = TK_ILLEGAL;
74198         return i;
74199       }
74200     }
74201     case '.': {
74202 #ifndef SQLITE_OMIT_FLOATING_POINT
74203       if( !isdigit(z[1]) )
74204 #endif
74205       {
74206         *tokenType = TK_DOT;
74207         return 1;
74208       }
74209       /* If the next character is a digit, this is a floating point
74210       ** number that begins with ".".  Fall thru into the next case */
74211     }
74212     case '0': case '1': case '2': case '3': case '4':
74213     case '5': case '6': case '7': case '8': case '9': {
74214       *tokenType = TK_INTEGER;
74215       for(i=0; isdigit(z[i]); i++){}
74216 #ifndef SQLITE_OMIT_FLOATING_POINT
74217       if( z[i]=='.' ){
74218         i++;
74219         while( isdigit(z[i]) ){ i++; }
74220         *tokenType = TK_FLOAT;
74221       }
74222       if( (z[i]=='e' || z[i]=='E') &&
74223            ( isdigit(z[i+1]) 
74224             || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
74225            )
74226       ){
74227         i += 2;
74228         while( isdigit(z[i]) ){ i++; }
74229         *tokenType = TK_FLOAT;
74230       }
74231 #endif
74232       while( IdChar(z[i]) ){
74233         *tokenType = TK_ILLEGAL;
74234         i++;
74235       }
74236       return i;
74237     }
74238     case '[': {
74239       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
74240       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
74241       return i;
74242     }
74243     case '?': {
74244       *tokenType = TK_VARIABLE;
74245       for(i=1; isdigit(z[i]); i++){}
74246       return i;
74247     }
74248     case '#': {
74249       for(i=1; isdigit(z[i]); i++){}
74250       if( i>1 ){
74251         /* Parameters of the form #NNN (where NNN is a number) are used
74252         ** internally by sqlite3NestedParse.  */
74253         *tokenType = TK_REGISTER;
74254         return i;
74255       }
74256       /* Fall through into the next case if the '#' is not followed by
74257       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
74258     }
74259 #ifndef SQLITE_OMIT_TCL_VARIABLE
74260     case '$':
74261 #endif
74262     case '@':  /* For compatibility with MS SQL Server */
74263     case ':': {
74264       int n = 0;
74265       *tokenType = TK_VARIABLE;
74266       for(i=1; (c=z[i])!=0; i++){
74267         if( IdChar(c) ){
74268           n++;
74269 #ifndef SQLITE_OMIT_TCL_VARIABLE
74270         }else if( c=='(' && n>0 ){
74271           do{
74272             i++;
74273           }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
74274           if( c==')' ){
74275             i++;
74276           }else{
74277             *tokenType = TK_ILLEGAL;
74278           }
74279           break;
74280         }else if( c==':' && z[i+1]==':' ){
74281           i++;
74282 #endif
74283         }else{
74284           break;
74285         }
74286       }
74287       if( n==0 ) *tokenType = TK_ILLEGAL;
74288       return i;
74289     }
74290 #ifndef SQLITE_OMIT_BLOB_LITERAL
74291     case 'x': case 'X': {
74292       if( z[1]=='\'' ){
74293         *tokenType = TK_BLOB;
74294         for(i=2; (c=z[i])!=0 && c!='\''; i++){
74295           if( !isxdigit(c) ){
74296             *tokenType = TK_ILLEGAL;
74297           }
74298         }
74299         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
74300         if( c ) i++;
74301         return i;
74302       }
74303       /* Otherwise fall through to the next case */
74304     }
74305 #endif
74306     default: {
74307       if( !IdChar(*z) ){
74308         break;
74309       }
74310       for(i=1; IdChar(z[i]); i++){}
74311       *tokenType = keywordCode((char*)z, i);
74312       return i;
74313     }
74314   }
74315   *tokenType = TK_ILLEGAL;
74316   return 1;
74317 }
74318 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
74319   return getToken(z, tokenType);
74320 }
74321
74322 /*
74323 ** Run the parser on the given SQL string.  The parser structure is
74324 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
74325 ** and pzErrMsg!=NULL then an error message might be written into 
74326 ** memory obtained from sqlite3_malloc() and *pzErrMsg made to point to that
74327 ** error message.  Or maybe not.
74328 */
74329 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
74330   int nErr = 0;
74331   int i;
74332   void *pEngine;
74333   int tokenType;
74334   int lastTokenParsed = -1;
74335   sqlite3 *db = pParse->db;
74336
74337   if( db->activeVdbeCnt==0 ){
74338     db->u1.isInterrupted = 0;
74339   }
74340   pParse->rc = SQLITE_OK;
74341   i = 0;
74342   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3_malloc);
74343   if( pEngine==0 ){
74344     db->mallocFailed = 1;
74345     return SQLITE_NOMEM;
74346   }
74347   assert( pParse->sLastToken.dyn==0 );
74348   assert( pParse->pNewTable==0 );
74349   assert( pParse->pNewTrigger==0 );
74350   assert( pParse->nVar==0 );
74351   assert( pParse->nVarExpr==0 );
74352   assert( pParse->nVarExprAlloc==0 );
74353   assert( pParse->apVarExpr==0 );
74354   pParse->zTail = pParse->zSql = zSql;
74355   while( !db->mallocFailed && zSql[i]!=0 ){
74356     assert( i>=0 );
74357     pParse->sLastToken.z = (u8*)&zSql[i];
74358     assert( pParse->sLastToken.dyn==0 );
74359     pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType);
74360     i += pParse->sLastToken.n;
74361     if( SQLITE_MAX_SQL_LENGTH>0 && i>SQLITE_MAX_SQL_LENGTH ){
74362       pParse->rc = SQLITE_TOOBIG;
74363       break;
74364     }
74365     switch( tokenType ){
74366       case TK_SPACE:
74367       case TK_COMMENT: {
74368         if( db->u1.isInterrupted ){
74369           pParse->rc = SQLITE_INTERRUPT;
74370           sqlite3SetString(pzErrMsg, "interrupt", (char*)0);
74371           goto abort_parse;
74372         }
74373         break;
74374       }
74375       case TK_ILLEGAL: {
74376         if( pzErrMsg ){
74377           sqlite3_free(*pzErrMsg);
74378           *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
74379                           &pParse->sLastToken);
74380         }
74381         nErr++;
74382         goto abort_parse;
74383       }
74384       case TK_SEMI: {
74385         pParse->zTail = &zSql[i];
74386         /* Fall thru into the default case */
74387       }
74388       default: {
74389         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
74390         lastTokenParsed = tokenType;
74391         if( pParse->rc!=SQLITE_OK ){
74392           goto abort_parse;
74393         }
74394         break;
74395       }
74396     }
74397   }
74398 abort_parse:
74399   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
74400     if( lastTokenParsed!=TK_SEMI ){
74401       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
74402       pParse->zTail = &zSql[i];
74403     }
74404     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
74405   }
74406   sqlite3ParserFree(pEngine, sqlite3_free);
74407   if( db->mallocFailed ){
74408     pParse->rc = SQLITE_NOMEM;
74409   }
74410   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
74411     sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc), (char*)0);
74412   }
74413   if( pParse->zErrMsg ){
74414     if( pzErrMsg && *pzErrMsg==0 ){
74415       *pzErrMsg = pParse->zErrMsg;
74416     }else{
74417       sqlite3_free(pParse->zErrMsg);
74418     }
74419     pParse->zErrMsg = 0;
74420     nErr++;
74421   }
74422   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
74423     sqlite3VdbeDelete(pParse->pVdbe);
74424     pParse->pVdbe = 0;
74425   }
74426 #ifndef SQLITE_OMIT_SHARED_CACHE
74427   if( pParse->nested==0 ){
74428     sqlite3_free(pParse->aTableLock);
74429     pParse->aTableLock = 0;
74430     pParse->nTableLock = 0;
74431   }
74432 #endif
74433
74434   if( !IN_DECLARE_VTAB ){
74435     /* If the pParse->declareVtab flag is set, do not delete any table 
74436     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
74437     ** will take responsibility for freeing the Table structure.
74438     */
74439     sqlite3DeleteTable(pParse->pNewTable);
74440   }
74441
74442   sqlite3DeleteTrigger(pParse->pNewTrigger);
74443   sqlite3_free(pParse->apVarExpr);
74444   if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
74445     pParse->rc = SQLITE_ERROR;
74446   }
74447   return nErr;
74448 }
74449
74450 /************** End of tokenize.c ********************************************/
74451 /************** Begin file complete.c ****************************************/
74452 /*
74453 ** 2001 September 15
74454 **
74455 ** The author disclaims copyright to this source code.  In place of
74456 ** a legal notice, here is a blessing:
74457 **
74458 **    May you do good and not evil.
74459 **    May you find forgiveness for yourself and forgive others.
74460 **    May you share freely, never taking more than you give.
74461 **
74462 *************************************************************************
74463 ** An tokenizer for SQL
74464 **
74465 ** This file contains C code that implements the sqlite3_complete() API.
74466 ** This code used to be part of the tokenizer.c source file.  But by
74467 ** separating it out, the code will be automatically omitted from
74468 ** static links that do not use it.
74469 **
74470 ** $Id: complete.c,v 1.6 2007/08/27 23:26:59 drh Exp $
74471 */
74472 #ifndef SQLITE_OMIT_COMPLETE
74473
74474 /*
74475 ** This is defined in tokenize.c.  We just have to import the definition.
74476 */
74477 #ifndef SQLITE_AMALGAMATION
74478 #ifdef SQLITE_ASCII
74479 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
74480 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
74481 #endif
74482 #ifdef SQLITE_EBCDIC
74483 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
74484 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
74485 #endif
74486 #endif /* SQLITE_AMALGAMATION */
74487
74488
74489 /*
74490 ** Token types used by the sqlite3_complete() routine.  See the header
74491 ** comments on that procedure for additional information.
74492 */
74493 #define tkSEMI    0
74494 #define tkWS      1
74495 #define tkOTHER   2
74496 #define tkEXPLAIN 3
74497 #define tkCREATE  4
74498 #define tkTEMP    5
74499 #define tkTRIGGER 6
74500 #define tkEND     7
74501
74502 /*
74503 ** Return TRUE if the given SQL string ends in a semicolon.
74504 **
74505 ** Special handling is require for CREATE TRIGGER statements.
74506 ** Whenever the CREATE TRIGGER keywords are seen, the statement
74507 ** must end with ";END;".
74508 **
74509 ** This implementation uses a state machine with 7 states:
74510 **
74511 **   (0) START     At the beginning or end of an SQL statement.  This routine
74512 **                 returns 1 if it ends in the START state and 0 if it ends
74513 **                 in any other state.
74514 **
74515 **   (1) NORMAL    We are in the middle of statement which ends with a single
74516 **                 semicolon.
74517 **
74518 **   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
74519 **                 a statement.
74520 **
74521 **   (3) CREATE    The keyword CREATE has been seen at the beginning of a
74522 **                 statement, possibly preceeded by EXPLAIN and/or followed by
74523 **                 TEMP or TEMPORARY
74524 **
74525 **   (4) TRIGGER   We are in the middle of a trigger definition that must be
74526 **                 ended by a semicolon, the keyword END, and another semicolon.
74527 **
74528 **   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
74529 **                 the end of a trigger definition.
74530 **
74531 **   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
74532 **                 of a trigger difinition.
74533 **
74534 ** Transitions between states above are determined by tokens extracted
74535 ** from the input.  The following tokens are significant:
74536 **
74537 **   (0) tkSEMI      A semicolon.
74538 **   (1) tkWS        Whitespace
74539 **   (2) tkOTHER     Any other SQL token.
74540 **   (3) tkEXPLAIN   The "explain" keyword.
74541 **   (4) tkCREATE    The "create" keyword.
74542 **   (5) tkTEMP      The "temp" or "temporary" keyword.
74543 **   (6) tkTRIGGER   The "trigger" keyword.
74544 **   (7) tkEND       The "end" keyword.
74545 **
74546 ** Whitespace never causes a state transition and is always ignored.
74547 **
74548 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
74549 ** to recognize the end of a trigger can be omitted.  All we have to do
74550 ** is look for a semicolon that is not part of an string or comment.
74551 */
74552 SQLITE_API int sqlite3_complete(const char *zSql){
74553   u8 state = 0;   /* Current state, using numbers defined in header comment */
74554   u8 token;       /* Value of the next token */
74555
74556 #ifndef SQLITE_OMIT_TRIGGER
74557   /* A complex statement machine used to detect the end of a CREATE TRIGGER
74558   ** statement.  This is the normal case.
74559   */
74560   static const u8 trans[7][8] = {
74561                      /* Token:                                                */
74562      /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
74563      /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
74564      /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
74565      /* 2 EXPLAIN: */ {    0,  2,     1,      1,      3,    1,       1,   1,  },
74566      /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
74567      /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
74568      /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
74569      /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
74570   };
74571 #else
74572   /* If triggers are not suppored by this compile then the statement machine
74573   ** used to detect the end of a statement is much simplier
74574   */
74575   static const u8 trans[2][3] = {
74576                      /* Token:           */
74577      /* State:       **  SEMI  WS  OTHER */
74578      /* 0   START: */ {    0,  0,     1, },
74579      /* 1  NORMAL: */ {    0,  1,     1, },
74580   };
74581 #endif /* SQLITE_OMIT_TRIGGER */
74582
74583   while( *zSql ){
74584     switch( *zSql ){
74585       case ';': {  /* A semicolon */
74586         token = tkSEMI;
74587         break;
74588       }
74589       case ' ':
74590       case '\r':
74591       case '\t':
74592       case '\n':
74593       case '\f': {  /* White space is ignored */
74594         token = tkWS;
74595         break;
74596       }
74597       case '/': {   /* C-style comments */
74598         if( zSql[1]!='*' ){
74599           token = tkOTHER;
74600           break;
74601         }
74602         zSql += 2;
74603         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
74604         if( zSql[0]==0 ) return 0;
74605         zSql++;
74606         token = tkWS;
74607         break;
74608       }
74609       case '-': {   /* SQL-style comments from "--" to end of line */
74610         if( zSql[1]!='-' ){
74611           token = tkOTHER;
74612           break;
74613         }
74614         while( *zSql && *zSql!='\n' ){ zSql++; }
74615         if( *zSql==0 ) return state==0;
74616         token = tkWS;
74617         break;
74618       }
74619       case '[': {   /* Microsoft-style identifiers in [...] */
74620         zSql++;
74621         while( *zSql && *zSql!=']' ){ zSql++; }
74622         if( *zSql==0 ) return 0;
74623         token = tkOTHER;
74624         break;
74625       }
74626       case '`':     /* Grave-accent quoted symbols used by MySQL */
74627       case '"':     /* single- and double-quoted strings */
74628       case '\'': {
74629         int c = *zSql;
74630         zSql++;
74631         while( *zSql && *zSql!=c ){ zSql++; }
74632         if( *zSql==0 ) return 0;
74633         token = tkOTHER;
74634         break;
74635       }
74636       default: {
74637         int c;
74638         if( IdChar((u8)*zSql) ){
74639           /* Keywords and unquoted identifiers */
74640           int nId;
74641           for(nId=1; IdChar(zSql[nId]); nId++){}
74642 #ifdef SQLITE_OMIT_TRIGGER
74643           token = tkOTHER;
74644 #else
74645           switch( *zSql ){
74646             case 'c': case 'C': {
74647               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
74648                 token = tkCREATE;
74649               }else{
74650                 token = tkOTHER;
74651               }
74652               break;
74653             }
74654             case 't': case 'T': {
74655               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
74656                 token = tkTRIGGER;
74657               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
74658                 token = tkTEMP;
74659               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
74660                 token = tkTEMP;
74661               }else{
74662                 token = tkOTHER;
74663               }
74664               break;
74665             }
74666             case 'e':  case 'E': {
74667               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
74668                 token = tkEND;
74669               }else
74670 #ifndef SQLITE_OMIT_EXPLAIN
74671               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
74672                 token = tkEXPLAIN;
74673               }else
74674 #endif
74675               {
74676                 token = tkOTHER;
74677               }
74678               break;
74679             }
74680             default: {
74681               token = tkOTHER;
74682               break;
74683             }
74684           }
74685 #endif /* SQLITE_OMIT_TRIGGER */
74686           zSql += nId-1;
74687         }else{
74688           /* Operators and special symbols */
74689           token = tkOTHER;
74690         }
74691         break;
74692       }
74693     }
74694     state = trans[state][token];
74695     zSql++;
74696   }
74697   return state==0;
74698 }
74699
74700 #ifndef SQLITE_OMIT_UTF16
74701 /*
74702 ** This routine is the same as the sqlite3_complete() routine described
74703 ** above, except that the parameter is required to be UTF-16 encoded, not
74704 ** UTF-8.
74705 */
74706 SQLITE_API int sqlite3_complete16(const void *zSql){
74707   sqlite3_value *pVal;
74708   char const *zSql8;
74709   int rc = SQLITE_NOMEM;
74710
74711   pVal = sqlite3ValueNew(0);
74712   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
74713   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
74714   if( zSql8 ){
74715     rc = sqlite3_complete(zSql8);
74716   }
74717   sqlite3ValueFree(pVal);
74718   return sqlite3ApiExit(0, rc);
74719 }
74720 #endif /* SQLITE_OMIT_UTF16 */
74721 #endif /* SQLITE_OMIT_COMPLETE */
74722
74723 /************** End of complete.c ********************************************/
74724 /************** Begin file main.c ********************************************/
74725 /*
74726 ** 2001 September 15
74727 **
74728 ** The author disclaims copyright to this source code.  In place of
74729 ** a legal notice, here is a blessing:
74730 **
74731 **    May you do good and not evil.
74732 **    May you find forgiveness for yourself and forgive others.
74733 **    May you share freely, never taking more than you give.
74734 **
74735 *************************************************************************
74736 ** Main file for the SQLite library.  The routines in this file
74737 ** implement the programmer interface to the library.  Routines in
74738 ** other files are for internal use by SQLite and should not be
74739 ** accessed by users of the library.
74740 **
74741 ** $Id: main.c,v 1.421 2008/03/07 21:37:19 drh Exp $
74742 */
74743 #ifdef SQLITE_ENABLE_FTS3
74744 /************** Include fts3.h in the middle of main.c ***********************/
74745 /************** Begin file fts3.h ********************************************/
74746 /*
74747 ** 2006 Oct 10
74748 **
74749 ** The author disclaims copyright to this source code.  In place of
74750 ** a legal notice, here is a blessing:
74751 **
74752 **    May you do good and not evil.
74753 **    May you find forgiveness for yourself and forgive others.
74754 **    May you share freely, never taking more than you give.
74755 **
74756 ******************************************************************************
74757 **
74758 ** This header file is used by programs that want to link against the
74759 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
74760 */
74761
74762 #if 0
74763 extern "C" {
74764 #endif  /* __cplusplus */
74765
74766 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
74767
74768 #if 0
74769 }  /* extern "C" */
74770 #endif  /* __cplusplus */
74771
74772 /************** End of fts3.h ************************************************/
74773 /************** Continuing where we left off in main.c ***********************/
74774 #endif
74775
74776 /*
74777 ** The version of the library
74778 */
74779 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
74780 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
74781 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
74782 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
74783
74784 /*
74785 ** If the following function pointer is not NULL and if
74786 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
74787 ** I/O active are written using this function.  These messages
74788 ** are intended for debugging activity only.
74789 */
74790 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
74791
74792 /*
74793 ** If the following global variable points to a string which is the
74794 ** name of a directory, then that directory will be used to store
74795 ** temporary files.
74796 **
74797 ** See also the "PRAGMA temp_store_directory" SQL command.
74798 */
74799 SQLITE_API char *sqlite3_temp_directory = 0;
74800
74801
74802 /*
74803 ** Return true if the buffer z[0..n-1] contains all spaces.
74804 */
74805 static int allSpaces(const char *z, int n){
74806   while( n>0 && z[--n]==' ' ){}
74807   return n==0;
74808 }
74809
74810 /*
74811 ** This is the default collating function named "BINARY" which is always
74812 ** available.
74813 **
74814 ** If the padFlag argument is not NULL then space padding at the end
74815 ** of strings is ignored.  This implements the RTRIM collation.
74816 */
74817 static int binCollFunc(
74818   void *padFlag,
74819   int nKey1, const void *pKey1,
74820   int nKey2, const void *pKey2
74821 ){
74822   int rc, n;
74823   n = nKey1<nKey2 ? nKey1 : nKey2;
74824   rc = memcmp(pKey1, pKey2, n);
74825   if( rc==0 ){
74826     if( padFlag
74827      && allSpaces(((char*)pKey1)+n, nKey1-n)
74828      && allSpaces(((char*)pKey2)+n, nKey2-n)
74829     ){
74830       /* Leave rc unchanged at 0 */
74831     }else{
74832       rc = nKey1 - nKey2;
74833     }
74834   }
74835   return rc;
74836 }
74837
74838 /*
74839 ** Another built-in collating sequence: NOCASE. 
74840 **
74841 ** This collating sequence is intended to be used for "case independant
74842 ** comparison". SQLite's knowledge of upper and lower case equivalents
74843 ** extends only to the 26 characters used in the English language.
74844 **
74845 ** At the moment there is only a UTF-8 implementation.
74846 */
74847 static int nocaseCollatingFunc(
74848   void *NotUsed,
74849   int nKey1, const void *pKey1,
74850   int nKey2, const void *pKey2
74851 ){
74852   int r = sqlite3StrNICmp(
74853       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
74854   if( 0==r ){
74855     r = nKey1-nKey2;
74856   }
74857   return r;
74858 }
74859
74860 /*
74861 ** Return the ROWID of the most recent insert
74862 */
74863 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
74864   return db->lastRowid;
74865 }
74866
74867 /*
74868 ** Return the number of changes in the most recent call to sqlite3_exec().
74869 */
74870 SQLITE_API int sqlite3_changes(sqlite3 *db){
74871   return db->nChange;
74872 }
74873
74874 /*
74875 ** Return the number of changes since the database handle was opened.
74876 */
74877 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
74878   return db->nTotalChange;
74879 }
74880
74881 /*
74882 ** Close an existing SQLite database
74883 */
74884 SQLITE_API int sqlite3_close(sqlite3 *db){
74885   HashElem *i;
74886   int j;
74887
74888   if( !db ){
74889     return SQLITE_OK;
74890   }
74891   if( !sqlite3SafetyCheckSickOrOk(db) ){
74892     return SQLITE_MISUSE;
74893   }
74894   sqlite3_mutex_enter(db->mutex);
74895
74896 #ifdef SQLITE_SSE
74897   {
74898     extern void sqlite3SseCleanup(sqlite3*);
74899     sqlite3SseCleanup(db);
74900   }
74901 #endif 
74902
74903   sqlite3ResetInternalSchema(db, 0);
74904
74905   /* If a transaction is open, the ResetInternalSchema() call above
74906   ** will not have called the xDisconnect() method on any virtual
74907   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
74908   ** call will do so. We need to do this before the check for active
74909   ** SQL statements below, as the v-table implementation may be storing
74910   ** some prepared statements internally.
74911   */
74912   sqlite3VtabRollback(db);
74913
74914   /* If there are any outstanding VMs, return SQLITE_BUSY. */
74915   if( db->pVdbe ){
74916     sqlite3Error(db, SQLITE_BUSY, 
74917         "Unable to close due to unfinalised statements");
74918     sqlite3_mutex_leave(db->mutex);
74919     return SQLITE_BUSY;
74920   }
74921   assert( sqlite3SafetyCheckSickOrOk(db) );
74922
74923   for(j=0; j<db->nDb; j++){
74924     struct Db *pDb = &db->aDb[j];
74925     if( pDb->pBt ){
74926       sqlite3BtreeClose(pDb->pBt);
74927       pDb->pBt = 0;
74928       if( j!=1 ){
74929         pDb->pSchema = 0;
74930       }
74931     }
74932   }
74933   sqlite3ResetInternalSchema(db, 0);
74934   assert( db->nDb<=2 );
74935   assert( db->aDb==db->aDbStatic );
74936   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
74937     FuncDef *pFunc, *pNext;
74938     for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
74939       pNext = pFunc->pNext;
74940       sqlite3_free(pFunc);
74941     }
74942   }
74943
74944   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
74945     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
74946     /* Invoke any destructors registered for collation sequence user data. */
74947     for(j=0; j<3; j++){
74948       if( pColl[j].xDel ){
74949         pColl[j].xDel(pColl[j].pUser);
74950       }
74951     }
74952     sqlite3_free(pColl);
74953   }
74954   sqlite3HashClear(&db->aCollSeq);
74955 #ifndef SQLITE_OMIT_VIRTUALTABLE
74956   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
74957     Module *pMod = (Module *)sqliteHashData(i);
74958     if( pMod->xDestroy ){
74959       pMod->xDestroy(pMod->pAux);
74960     }
74961     sqlite3_free(pMod);
74962   }
74963   sqlite3HashClear(&db->aModule);
74964 #endif
74965
74966   sqlite3HashClear(&db->aFunc);
74967   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
74968   if( db->pErr ){
74969     sqlite3ValueFree(db->pErr);
74970   }
74971   sqlite3CloseExtensions(db);
74972
74973   db->magic = SQLITE_MAGIC_ERROR;
74974
74975   /* The temp-database schema is allocated differently from the other schema
74976   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
74977   ** So it needs to be freed here. Todo: Why not roll the temp schema into
74978   ** the same sqliteMalloc() as the one that allocates the database 
74979   ** structure?
74980   */
74981   sqlite3_free(db->aDb[1].pSchema);
74982   sqlite3_mutex_leave(db->mutex);
74983   db->magic = SQLITE_MAGIC_CLOSED;
74984   sqlite3_mutex_free(db->mutex);
74985   sqlite3_free(db);
74986   return SQLITE_OK;
74987 }
74988
74989 /*
74990 ** Rollback all database files.
74991 */
74992 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
74993   int i;
74994   int inTrans = 0;
74995   assert( sqlite3_mutex_held(db->mutex) );
74996   sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 1);
74997   for(i=0; i<db->nDb; i++){
74998     if( db->aDb[i].pBt ){
74999       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
75000         inTrans = 1;
75001       }
75002       sqlite3BtreeRollback(db->aDb[i].pBt);
75003       db->aDb[i].inTrans = 0;
75004     }
75005   }
75006   sqlite3VtabRollback(db);
75007   sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 0);
75008
75009   if( db->flags&SQLITE_InternChanges ){
75010     sqlite3ExpirePreparedStatements(db);
75011     sqlite3ResetInternalSchema(db, 0);
75012   }
75013
75014   /* If one has been configured, invoke the rollback-hook callback */
75015   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
75016     db->xRollbackCallback(db->pRollbackArg);
75017   }
75018 }
75019
75020 /*
75021 ** Return a static string that describes the kind of error specified in the
75022 ** argument.
75023 */
75024 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
75025   const char *z;
75026   switch( rc & 0xff ){
75027     case SQLITE_ROW:
75028     case SQLITE_DONE:
75029     case SQLITE_OK:         z = "not an error";                          break;
75030     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
75031     case SQLITE_PERM:       z = "access permission denied";              break;
75032     case SQLITE_ABORT:      z = "callback requested query abort";        break;
75033     case SQLITE_BUSY:       z = "database is locked";                    break;
75034     case SQLITE_LOCKED:     z = "database table is locked";              break;
75035     case SQLITE_NOMEM:      z = "out of memory";                         break;
75036     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
75037     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
75038     case SQLITE_IOERR:      z = "disk I/O error";                        break;
75039     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
75040     case SQLITE_FULL:       z = "database or disk is full";              break;
75041     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
75042     case SQLITE_EMPTY:      z = "table contains no data";                break;
75043     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
75044     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
75045     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
75046     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
75047     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
75048     case SQLITE_NOLFS:      z = "kernel lacks large file support";       break;
75049     case SQLITE_AUTH:       z = "authorization denied";                  break;
75050     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
75051     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
75052     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
75053     default:                z = "unknown error";                         break;
75054   }
75055   return z;
75056 }
75057
75058 /*
75059 ** This routine implements a busy callback that sleeps and tries
75060 ** again until a timeout value is reached.  The timeout value is
75061 ** an integer number of milliseconds passed in as the first
75062 ** argument.
75063 */
75064 static int sqliteDefaultBusyCallback(
75065  void *ptr,               /* Database connection */
75066  int count                /* Number of times table has been busy */
75067 ){
75068 #if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
75069   static const u8 delays[] =
75070      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
75071   static const u8 totals[] =
75072      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
75073 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
75074   sqlite3 *db = (sqlite3 *)ptr;
75075   int timeout = db->busyTimeout;
75076   int delay, prior;
75077
75078   assert( count>=0 );
75079   if( count < NDELAY ){
75080     delay = delays[count];
75081     prior = totals[count];
75082   }else{
75083     delay = delays[NDELAY-1];
75084     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
75085   }
75086   if( prior + delay > timeout ){
75087     delay = timeout - prior;
75088     if( delay<=0 ) return 0;
75089   }
75090   sqlite3OsSleep(db->pVfs, delay*1000);
75091   return 1;
75092 #else
75093   sqlite3 *db = (sqlite3 *)ptr;
75094   int timeout = ((sqlite3 *)ptr)->busyTimeout;
75095   if( (count+1)*1000 > timeout ){
75096     return 0;
75097   }
75098   sqlite3OsSleep(db->pVfs, 1000000);
75099   return 1;
75100 #endif
75101 }
75102
75103 /*
75104 ** Invoke the given busy handler.
75105 **
75106 ** This routine is called when an operation failed with a lock.
75107 ** If this routine returns non-zero, the lock is retried.  If it
75108 ** returns 0, the operation aborts with an SQLITE_BUSY error.
75109 */
75110 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
75111   int rc;
75112   if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
75113   rc = p->xFunc(p->pArg, p->nBusy);
75114   if( rc==0 ){
75115     p->nBusy = -1;
75116   }else{
75117     p->nBusy++;
75118   }
75119   return rc; 
75120 }
75121
75122 /*
75123 ** This routine sets the busy callback for an Sqlite database to the
75124 ** given callback function with the given argument.
75125 */
75126 SQLITE_API int sqlite3_busy_handler(
75127   sqlite3 *db,
75128   int (*xBusy)(void*,int),
75129   void *pArg
75130 ){
75131   sqlite3_mutex_enter(db->mutex);
75132   db->busyHandler.xFunc = xBusy;
75133   db->busyHandler.pArg = pArg;
75134   db->busyHandler.nBusy = 0;
75135   sqlite3_mutex_leave(db->mutex);
75136   return SQLITE_OK;
75137 }
75138
75139 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
75140 /*
75141 ** This routine sets the progress callback for an Sqlite database to the
75142 ** given callback function with the given argument. The progress callback will
75143 ** be invoked every nOps opcodes.
75144 */
75145 SQLITE_API void sqlite3_progress_handler(
75146   sqlite3 *db, 
75147   int nOps,
75148   int (*xProgress)(void*), 
75149   void *pArg
75150 ){
75151   if( sqlite3SafetyCheckOk(db) ){
75152     sqlite3_mutex_enter(db->mutex);
75153     if( nOps>0 ){
75154       db->xProgress = xProgress;
75155       db->nProgressOps = nOps;
75156       db->pProgressArg = pArg;
75157     }else{
75158       db->xProgress = 0;
75159       db->nProgressOps = 0;
75160       db->pProgressArg = 0;
75161     }
75162     sqlite3_mutex_leave(db->mutex);
75163   }
75164 }
75165 #endif
75166
75167
75168 /*
75169 ** This routine installs a default busy handler that waits for the
75170 ** specified number of milliseconds before returning 0.
75171 */
75172 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
75173   if( ms>0 ){
75174     db->busyTimeout = ms;
75175     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
75176   }else{
75177     sqlite3_busy_handler(db, 0, 0);
75178   }
75179   return SQLITE_OK;
75180 }
75181
75182 /*
75183 ** Cause any pending operation to stop at its earliest opportunity.
75184 */
75185 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
75186   if( sqlite3SafetyCheckOk(db) ){
75187     db->u1.isInterrupted = 1;
75188   }
75189 }
75190
75191
75192 /*
75193 ** This function is exactly the same as sqlite3_create_function(), except
75194 ** that it is designed to be called by internal code. The difference is
75195 ** that if a malloc() fails in sqlite3_create_function(), an error code
75196 ** is returned and the mallocFailed flag cleared. 
75197 */
75198 SQLITE_PRIVATE int sqlite3CreateFunc(
75199   sqlite3 *db,
75200   const char *zFunctionName,
75201   int nArg,
75202   int enc,
75203   void *pUserData,
75204   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
75205   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
75206   void (*xFinal)(sqlite3_context*)
75207 ){
75208   FuncDef *p;
75209   int nName;
75210
75211   assert( sqlite3_mutex_held(db->mutex) );
75212   if( zFunctionName==0 ||
75213       (xFunc && (xFinal || xStep)) || 
75214       (!xFunc && (xFinal && !xStep)) ||
75215       (!xFunc && (!xFinal && xStep)) ||
75216       (nArg<-1 || nArg>127) ||
75217       (255<(nName = strlen(zFunctionName))) ){
75218     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
75219     return SQLITE_ERROR;
75220   }
75221   
75222 #ifndef SQLITE_OMIT_UTF16
75223   /* If SQLITE_UTF16 is specified as the encoding type, transform this
75224   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
75225   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
75226   **
75227   ** If SQLITE_ANY is specified, add three versions of the function
75228   ** to the hash table.
75229   */
75230   if( enc==SQLITE_UTF16 ){
75231     enc = SQLITE_UTF16NATIVE;
75232   }else if( enc==SQLITE_ANY ){
75233     int rc;
75234     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
75235          pUserData, xFunc, xStep, xFinal);
75236     if( rc==SQLITE_OK ){
75237       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
75238           pUserData, xFunc, xStep, xFinal);
75239     }
75240     if( rc!=SQLITE_OK ){
75241       return rc;
75242     }
75243     enc = SQLITE_UTF16BE;
75244   }
75245 #else
75246   enc = SQLITE_UTF8;
75247 #endif
75248   
75249   /* Check if an existing function is being overridden or deleted. If so,
75250   ** and there are active VMs, then return SQLITE_BUSY. If a function
75251   ** is being overridden/deleted but there are no active VMs, allow the
75252   ** operation to continue but invalidate all precompiled statements.
75253   */
75254   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
75255   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
75256     if( db->activeVdbeCnt ){
75257       sqlite3Error(db, SQLITE_BUSY, 
75258         "Unable to delete/modify user-function due to active statements");
75259       assert( !db->mallocFailed );
75260       return SQLITE_BUSY;
75261     }else{
75262       sqlite3ExpirePreparedStatements(db);
75263     }
75264   }
75265
75266   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
75267   assert(p || db->mallocFailed);
75268   if( !p ){
75269     return SQLITE_NOMEM;
75270   }
75271   p->flags = 0;
75272   p->xFunc = xFunc;
75273   p->xStep = xStep;
75274   p->xFinalize = xFinal;
75275   p->pUserData = pUserData;
75276   p->nArg = nArg;
75277   return SQLITE_OK;
75278 }
75279
75280 /*
75281 ** Create new user functions.
75282 */
75283 SQLITE_API int sqlite3_create_function(
75284   sqlite3 *db,
75285   const char *zFunctionName,
75286   int nArg,
75287   int enc,
75288   void *p,
75289   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
75290   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
75291   void (*xFinal)(sqlite3_context*)
75292 ){
75293   int rc;
75294   sqlite3_mutex_enter(db->mutex);
75295   assert( !db->mallocFailed );
75296   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
75297   rc = sqlite3ApiExit(db, rc);
75298   sqlite3_mutex_leave(db->mutex);
75299   return rc;
75300 }
75301
75302 #ifndef SQLITE_OMIT_UTF16
75303 SQLITE_API int sqlite3_create_function16(
75304   sqlite3 *db,
75305   const void *zFunctionName,
75306   int nArg,
75307   int eTextRep,
75308   void *p,
75309   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
75310   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
75311   void (*xFinal)(sqlite3_context*)
75312 ){
75313   int rc;
75314   char *zFunc8;
75315   sqlite3_mutex_enter(db->mutex);
75316   assert( !db->mallocFailed );
75317   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
75318   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
75319   sqlite3_free(zFunc8);
75320   rc = sqlite3ApiExit(db, rc);
75321   sqlite3_mutex_leave(db->mutex);
75322   return rc;
75323 }
75324 #endif
75325
75326
75327 /*
75328 ** Declare that a function has been overloaded by a virtual table.
75329 **
75330 ** If the function already exists as a regular global function, then
75331 ** this routine is a no-op.  If the function does not exist, then create
75332 ** a new one that always throws a run-time error.  
75333 **
75334 ** When virtual tables intend to provide an overloaded function, they
75335 ** should call this routine to make sure the global function exists.
75336 ** A global function must exist in order for name resolution to work
75337 ** properly.
75338 */
75339 SQLITE_API int sqlite3_overload_function(
75340   sqlite3 *db,
75341   const char *zName,
75342   int nArg
75343 ){
75344   int nName = strlen(zName);
75345   int rc;
75346   sqlite3_mutex_enter(db->mutex);
75347   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
75348     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
75349                       0, sqlite3InvalidFunction, 0, 0);
75350   }
75351   rc = sqlite3ApiExit(db, SQLITE_OK);
75352   sqlite3_mutex_leave(db->mutex);
75353   return rc;
75354 }
75355
75356 #ifndef SQLITE_OMIT_TRACE
75357 /*
75358 ** Register a trace function.  The pArg from the previously registered trace
75359 ** is returned.  
75360 **
75361 ** A NULL trace function means that no tracing is executes.  A non-NULL
75362 ** trace is a pointer to a function that is invoked at the start of each
75363 ** SQL statement.
75364 */
75365 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
75366   void *pOld;
75367   sqlite3_mutex_enter(db->mutex);
75368   pOld = db->pTraceArg;
75369   db->xTrace = xTrace;
75370   db->pTraceArg = pArg;
75371   sqlite3_mutex_leave(db->mutex);
75372   return pOld;
75373 }
75374 /*
75375 ** Register a profile function.  The pArg from the previously registered 
75376 ** profile function is returned.  
75377 **
75378 ** A NULL profile function means that no profiling is executes.  A non-NULL
75379 ** profile is a pointer to a function that is invoked at the conclusion of
75380 ** each SQL statement that is run.
75381 */
75382 SQLITE_API void *sqlite3_profile(
75383   sqlite3 *db,
75384   void (*xProfile)(void*,const char*,sqlite_uint64),
75385   void *pArg
75386 ){
75387   void *pOld;
75388   sqlite3_mutex_enter(db->mutex);
75389   pOld = db->pProfileArg;
75390   db->xProfile = xProfile;
75391   db->pProfileArg = pArg;
75392   sqlite3_mutex_leave(db->mutex);
75393   return pOld;
75394 }
75395 #endif /* SQLITE_OMIT_TRACE */
75396
75397 /*** EXPERIMENTAL ***
75398 **
75399 ** Register a function to be invoked when a transaction comments.
75400 ** If the invoked function returns non-zero, then the commit becomes a
75401 ** rollback.
75402 */
75403 SQLITE_API void *sqlite3_commit_hook(
75404   sqlite3 *db,              /* Attach the hook to this database */
75405   int (*xCallback)(void*),  /* Function to invoke on each commit */
75406   void *pArg                /* Argument to the function */
75407 ){
75408   void *pOld;
75409   sqlite3_mutex_enter(db->mutex);
75410   pOld = db->pCommitArg;
75411   db->xCommitCallback = xCallback;
75412   db->pCommitArg = pArg;
75413   sqlite3_mutex_leave(db->mutex);
75414   return pOld;
75415 }
75416
75417 /*
75418 ** Register a callback to be invoked each time a row is updated,
75419 ** inserted or deleted using this database connection.
75420 */
75421 SQLITE_API void *sqlite3_update_hook(
75422   sqlite3 *db,              /* Attach the hook to this database */
75423   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
75424   void *pArg                /* Argument to the function */
75425 ){
75426   void *pRet;
75427   sqlite3_mutex_enter(db->mutex);
75428   pRet = db->pUpdateArg;
75429   db->xUpdateCallback = xCallback;
75430   db->pUpdateArg = pArg;
75431   sqlite3_mutex_leave(db->mutex);
75432   return pRet;
75433 }
75434
75435 /*
75436 ** Register a callback to be invoked each time a transaction is rolled
75437 ** back by this database connection.
75438 */
75439 SQLITE_API void *sqlite3_rollback_hook(
75440   sqlite3 *db,              /* Attach the hook to this database */
75441   void (*xCallback)(void*), /* Callback function */
75442   void *pArg                /* Argument to the function */
75443 ){
75444   void *pRet;
75445   sqlite3_mutex_enter(db->mutex);
75446   pRet = db->pRollbackArg;
75447   db->xRollbackCallback = xCallback;
75448   db->pRollbackArg = pArg;
75449   sqlite3_mutex_leave(db->mutex);
75450   return pRet;
75451 }
75452
75453 /*
75454 ** This routine is called to create a connection to a database BTree
75455 ** driver.  If zFilename is the name of a file, then that file is
75456 ** opened and used.  If zFilename is the magic name ":memory:" then
75457 ** the database is stored in memory (and is thus forgotten as soon as
75458 ** the connection is closed.)  If zFilename is NULL then the database
75459 ** is a "virtual" database for transient use only and is deleted as
75460 ** soon as the connection is closed.
75461 **
75462 ** A virtual database can be either a disk file (that is automatically
75463 ** deleted when the file is closed) or it an be held entirely in memory,
75464 ** depending on the values of the TEMP_STORE compile-time macro and the
75465 ** db->temp_store variable, according to the following chart:
75466 **
75467 **       TEMP_STORE     db->temp_store     Location of temporary database
75468 **       ----------     --------------     ------------------------------
75469 **           0               any             file
75470 **           1                1              file
75471 **           1                2              memory
75472 **           1                0              file
75473 **           2                1              file
75474 **           2                2              memory
75475 **           2                0              memory
75476 **           3               any             memory
75477 */
75478 SQLITE_PRIVATE int sqlite3BtreeFactory(
75479   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
75480   const char *zFilename,    /* Name of the file containing the BTree database */
75481   int omitJournal,          /* if TRUE then do not journal this file */
75482   int nCache,               /* How many pages in the page cache */
75483   int vfsFlags,             /* Flags passed through to vfsOpen */
75484   Btree **ppBtree           /* Pointer to new Btree object written here */
75485 ){
75486   int btFlags = 0;
75487   int rc;
75488   
75489   assert( sqlite3_mutex_held(db->mutex) );
75490   assert( ppBtree != 0);
75491   if( omitJournal ){
75492     btFlags |= BTREE_OMIT_JOURNAL;
75493   }
75494   if( db->flags & SQLITE_NoReadlock ){
75495     btFlags |= BTREE_NO_READLOCK;
75496   }
75497   if( zFilename==0 ){
75498 #if TEMP_STORE==0
75499     /* Do nothing */
75500 #endif
75501 #ifndef SQLITE_OMIT_MEMORYDB
75502 #if TEMP_STORE==1
75503     if( db->temp_store==2 ) zFilename = ":memory:";
75504 #endif
75505 #if TEMP_STORE==2
75506     if( db->temp_store!=1 ) zFilename = ":memory:";
75507 #endif
75508 #if TEMP_STORE==3
75509     zFilename = ":memory:";
75510 #endif
75511 #endif /* SQLITE_OMIT_MEMORYDB */
75512   }
75513
75514   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
75515     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
75516   }
75517   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
75518   if( rc==SQLITE_OK ){
75519     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
75520   }
75521   return rc;
75522 }
75523
75524 /*
75525 ** Return UTF-8 encoded English language explanation of the most recent
75526 ** error.
75527 */
75528 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
75529   const char *z;
75530   if( !db ){
75531     return sqlite3ErrStr(SQLITE_NOMEM);
75532   }
75533   if( !sqlite3SafetyCheckSickOrOk(db) || db->errCode==SQLITE_MISUSE ){
75534     return sqlite3ErrStr(SQLITE_MISUSE);
75535   }
75536   sqlite3_mutex_enter(db->mutex);
75537   assert( !db->mallocFailed );
75538   z = (char*)sqlite3_value_text(db->pErr);
75539   if( z==0 ){
75540     z = sqlite3ErrStr(db->errCode);
75541   }
75542   sqlite3_mutex_leave(db->mutex);
75543   return z;
75544 }
75545
75546 #ifndef SQLITE_OMIT_UTF16
75547 /*
75548 ** Return UTF-16 encoded English language explanation of the most recent
75549 ** error.
75550 */
75551 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
75552   /* Because all the characters in the string are in the unicode
75553   ** range 0x00-0xFF, if we pad the big-endian string with a 
75554   ** zero byte, we can obtain the little-endian string with
75555   ** &big_endian[1].
75556   */
75557   static const char outOfMemBe[] = {
75558     0, 'o', 0, 'u', 0, 't', 0, ' ', 
75559     0, 'o', 0, 'f', 0, ' ', 
75560     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
75561   };
75562   static const char misuseBe [] = {
75563     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
75564     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
75565     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
75566     0, 'o', 0, 'u', 0, 't', 0, ' ', 
75567     0, 'o', 0, 'f', 0, ' ', 
75568     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
75569   };
75570
75571   const void *z;
75572   if( !db ){
75573     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
75574   }
75575   if( !sqlite3SafetyCheckSickOrOk(db) || db->errCode==SQLITE_MISUSE ){
75576     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
75577   }
75578   sqlite3_mutex_enter(db->mutex);
75579   assert( !db->mallocFailed );
75580   z = sqlite3_value_text16(db->pErr);
75581   if( z==0 ){
75582     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
75583          SQLITE_UTF8, SQLITE_STATIC);
75584     z = sqlite3_value_text16(db->pErr);
75585   }
75586   sqlite3ApiExit(0, 0);
75587   sqlite3_mutex_leave(db->mutex);
75588   return z;
75589 }
75590 #endif /* SQLITE_OMIT_UTF16 */
75591
75592 /*
75593 ** Return the most recent error code generated by an SQLite routine. If NULL is
75594 ** passed to this function, we assume a malloc() failed during sqlite3_open().
75595 */
75596 SQLITE_API int sqlite3_errcode(sqlite3 *db){
75597   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
75598     return SQLITE_MISUSE;
75599   }
75600   if( !db || db->mallocFailed ){
75601     return SQLITE_NOMEM;
75602   }
75603   return db->errCode & db->errMask;
75604 }
75605
75606 /*
75607 ** Create a new collating function for database "db".  The name is zName
75608 ** and the encoding is enc.
75609 */
75610 static int createCollation(
75611   sqlite3* db, 
75612   const char *zName, 
75613   int enc, 
75614   void* pCtx,
75615   int(*xCompare)(void*,int,const void*,int,const void*),
75616   void(*xDel)(void*)
75617 ){
75618   CollSeq *pColl;
75619   int enc2;
75620   
75621   assert( sqlite3_mutex_held(db->mutex) );
75622
75623   /* If SQLITE_UTF16 is specified as the encoding type, transform this
75624   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
75625   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
75626   */
75627   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
75628   if( enc2==SQLITE_UTF16 ){
75629     enc2 = SQLITE_UTF16NATIVE;
75630   }
75631
75632   if( (enc2&~3)!=0 ){
75633     sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
75634     return SQLITE_ERROR;
75635   }
75636
75637   /* Check if this call is removing or replacing an existing collation 
75638   ** sequence. If so, and there are active VMs, return busy. If there
75639   ** are no active VMs, invalidate any pre-compiled statements.
75640   */
75641   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
75642   if( pColl && pColl->xCmp ){
75643     if( db->activeVdbeCnt ){
75644       sqlite3Error(db, SQLITE_BUSY, 
75645         "Unable to delete/modify collation sequence due to active statements");
75646       return SQLITE_BUSY;
75647     }
75648     sqlite3ExpirePreparedStatements(db);
75649
75650     /* If collation sequence pColl was created directly by a call to
75651     ** sqlite3_create_collation, and not generated by synthCollSeq(),
75652     ** then any copies made by synthCollSeq() need to be invalidated.
75653     ** Also, collation destructor - CollSeq.xDel() - function may need
75654     ** to be called.
75655     */ 
75656     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
75657       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, strlen(zName));
75658       int j;
75659       for(j=0; j<3; j++){
75660         CollSeq *p = &aColl[j];
75661         if( p->enc==pColl->enc ){
75662           if( p->xDel ){
75663             p->xDel(p->pUser);
75664           }
75665           p->xCmp = 0;
75666         }
75667       }
75668     }
75669   }
75670
75671   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
75672   if( pColl ){
75673     pColl->xCmp = xCompare;
75674     pColl->pUser = pCtx;
75675     pColl->xDel = xDel;
75676     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
75677   }
75678   sqlite3Error(db, SQLITE_OK, 0);
75679   return SQLITE_OK;
75680 }
75681
75682
75683 /*
75684 ** This routine does the work of opening a database on behalf of
75685 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
75686 ** is UTF-8 encoded.
75687 */
75688 static int openDatabase(
75689   const char *zFilename, /* Database filename UTF-8 encoded */
75690   sqlite3 **ppDb,        /* OUT: Returned database handle */
75691   unsigned flags,        /* Operational flags */
75692   const char *zVfs       /* Name of the VFS to use */
75693 ){
75694   sqlite3 *db;
75695   int rc;
75696   CollSeq *pColl;
75697
75698   /* Remove harmful bits from the flags parameter */
75699   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
75700                SQLITE_OPEN_MAIN_DB |
75701                SQLITE_OPEN_TEMP_DB | 
75702                SQLITE_OPEN_TRANSIENT_DB | 
75703                SQLITE_OPEN_MAIN_JOURNAL | 
75704                SQLITE_OPEN_TEMP_JOURNAL | 
75705                SQLITE_OPEN_SUBJOURNAL | 
75706                SQLITE_OPEN_MASTER_JOURNAL
75707              );
75708
75709   /* Allocate the sqlite data structure */
75710   db = sqlite3MallocZero( sizeof(sqlite3) );
75711   if( db==0 ) goto opendb_out;
75712   db->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
75713   if( db->mutex==0 ){
75714     sqlite3_free(db);
75715     db = 0;
75716     goto opendb_out;
75717   }
75718   sqlite3_mutex_enter(db->mutex);
75719   db->errMask = 0xff;
75720   db->priorNewRowid = 0;
75721   db->nDb = 2;
75722   db->magic = SQLITE_MAGIC_BUSY;
75723   db->aDb = db->aDbStatic;
75724   db->autoCommit = 1;
75725   db->nextAutovac = -1;
75726   db->flags |= SQLITE_ShortColNames
75727 #if SQLITE_DEFAULT_FILE_FORMAT<4
75728                  | SQLITE_LegacyFileFmt
75729 #endif
75730 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
75731                  | SQLITE_LoadExtension
75732 #endif
75733       ;
75734   sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
75735   sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
75736 #ifndef SQLITE_OMIT_VIRTUALTABLE
75737   sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
75738 #endif
75739
75740   db->pVfs = sqlite3_vfs_find(zVfs);
75741   if( !db->pVfs ){
75742     rc = SQLITE_ERROR;
75743     db->magic = SQLITE_MAGIC_SICK;
75744     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
75745     goto opendb_out;
75746   }
75747
75748   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
75749   ** and UTF-16, so add a version for each to avoid any unnecessary
75750   ** conversions. The only error that can occur here is a malloc() failure.
75751   */
75752   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
75753   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
75754   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
75755   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
75756   if( db->mallocFailed ||
75757       (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0 
75758   ){
75759     assert( db->mallocFailed );
75760     db->magic = SQLITE_MAGIC_SICK;
75761     goto opendb_out;
75762   }
75763
75764   /* Also add a UTF-8 case-insensitive collation sequence. */
75765   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
75766
75767   /* Set flags on the built-in collating sequences */
75768   db->pDfltColl->type = SQLITE_COLL_BINARY;
75769   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
75770   if( pColl ){
75771     pColl->type = SQLITE_COLL_NOCASE;
75772   }
75773
75774   /* Open the backend database driver */
75775   db->openFlags = flags;
75776   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
75777                            flags | SQLITE_OPEN_MAIN_DB,
75778                            &db->aDb[0].pBt);
75779   if( rc!=SQLITE_OK ){
75780     sqlite3Error(db, rc, 0);
75781     db->magic = SQLITE_MAGIC_SICK;
75782     goto opendb_out;
75783   }
75784   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
75785   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
75786
75787
75788   /* The default safety_level for the main database is 'full'; for the temp
75789   ** database it is 'NONE'. This matches the pager layer defaults.  
75790   */
75791   db->aDb[0].zName = "main";
75792   db->aDb[0].safety_level = 3;
75793 #ifndef SQLITE_OMIT_TEMPDB
75794   db->aDb[1].zName = "temp";
75795   db->aDb[1].safety_level = 1;
75796 #endif
75797
75798   db->magic = SQLITE_MAGIC_OPEN;
75799   if( db->mallocFailed ){
75800     goto opendb_out;
75801   }
75802
75803   /* Register all built-in functions, but do not attempt to read the
75804   ** database schema yet. This is delayed until the first time the database
75805   ** is accessed.
75806   */
75807   sqlite3Error(db, SQLITE_OK, 0);
75808   sqlite3RegisterBuiltinFunctions(db);
75809
75810   /* Load automatic extensions - extensions that have been registered
75811   ** using the sqlite3_automatic_extension() API.
75812   */
75813   (void)sqlite3AutoLoadExtensions(db);
75814   if( sqlite3_errcode(db)!=SQLITE_OK ){
75815     goto opendb_out;
75816   }
75817
75818 #ifdef SQLITE_ENABLE_FTS1
75819   if( !db->mallocFailed ){
75820     extern int sqlite3Fts1Init(sqlite3*);
75821     rc = sqlite3Fts1Init(db);
75822   }
75823 #endif
75824
75825 #ifdef SQLITE_ENABLE_FTS2
75826   if( !db->mallocFailed && rc==SQLITE_OK ){
75827     extern int sqlite3Fts2Init(sqlite3*);
75828     rc = sqlite3Fts2Init(db);
75829   }
75830 #endif
75831
75832 #ifdef SQLITE_ENABLE_FTS3
75833   if( !db->mallocFailed && rc==SQLITE_OK ){
75834     rc = sqlite3Fts3Init(db);
75835   }
75836 #endif
75837
75838 #ifdef SQLITE_ENABLE_ICU
75839   if( !db->mallocFailed && rc==SQLITE_OK ){
75840     extern int sqlite3IcuInit(sqlite3*);
75841     rc = sqlite3IcuInit(db);
75842   }
75843 #endif
75844   sqlite3Error(db, rc, 0);
75845
75846   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
75847   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
75848   ** mode.  Doing nothing at all also makes NORMAL the default.
75849   */
75850 #ifdef SQLITE_DEFAULT_LOCKING_MODE
75851   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
75852   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
75853                           SQLITE_DEFAULT_LOCKING_MODE);
75854 #endif
75855
75856 opendb_out:
75857   if( db ){
75858     assert( db->mutex!=0 );
75859     sqlite3_mutex_leave(db->mutex);
75860   }
75861   if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
75862     sqlite3_close(db);
75863     db = 0;
75864   }
75865   *ppDb = db;
75866   return sqlite3ApiExit(0, rc);
75867 }
75868
75869 /*
75870 ** Open a new database handle.
75871 */
75872 SQLITE_API int sqlite3_open(
75873   const char *zFilename, 
75874   sqlite3 **ppDb 
75875 ){
75876   return openDatabase(zFilename, ppDb,
75877                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
75878 }
75879 SQLITE_API int sqlite3_open_v2(
75880   const char *filename,   /* Database filename (UTF-8) */
75881   sqlite3 **ppDb,         /* OUT: SQLite db handle */
75882   int flags,              /* Flags */
75883   const char *zVfs        /* Name of VFS module to use */
75884 ){
75885   return openDatabase(filename, ppDb, flags, zVfs);
75886 }
75887
75888 #ifndef SQLITE_OMIT_UTF16
75889 /*
75890 ** Open a new database handle.
75891 */
75892 SQLITE_API int sqlite3_open16(
75893   const void *zFilename, 
75894   sqlite3 **ppDb
75895 ){
75896   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
75897   sqlite3_value *pVal;
75898   int rc = SQLITE_NOMEM;
75899
75900   assert( zFilename );
75901   assert( ppDb );
75902   *ppDb = 0;
75903   pVal = sqlite3ValueNew(0);
75904   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
75905   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
75906   if( zFilename8 ){
75907     rc = openDatabase(zFilename8, ppDb,
75908                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
75909     assert( *ppDb || rc==SQLITE_NOMEM );
75910     if( rc==SQLITE_OK ){
75911       rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
75912       if( rc!=SQLITE_OK ){
75913         sqlite3_close(*ppDb);
75914         *ppDb = 0;
75915       }
75916     }
75917   }
75918   sqlite3ValueFree(pVal);
75919
75920   return sqlite3ApiExit(0, rc);
75921 }
75922 #endif /* SQLITE_OMIT_UTF16 */
75923
75924 /*
75925 ** Register a new collation sequence with the database handle db.
75926 */
75927 SQLITE_API int sqlite3_create_collation(
75928   sqlite3* db, 
75929   const char *zName, 
75930   int enc, 
75931   void* pCtx,
75932   int(*xCompare)(void*,int,const void*,int,const void*)
75933 ){
75934   int rc;
75935   sqlite3_mutex_enter(db->mutex);
75936   assert( !db->mallocFailed );
75937   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
75938   rc = sqlite3ApiExit(db, rc);
75939   sqlite3_mutex_leave(db->mutex);
75940   return rc;
75941 }
75942
75943 /*
75944 ** Register a new collation sequence with the database handle db.
75945 */
75946 SQLITE_API int sqlite3_create_collation_v2(
75947   sqlite3* db, 
75948   const char *zName, 
75949   int enc, 
75950   void* pCtx,
75951   int(*xCompare)(void*,int,const void*,int,const void*),
75952   void(*xDel)(void*)
75953 ){
75954   int rc;
75955   sqlite3_mutex_enter(db->mutex);
75956   assert( !db->mallocFailed );
75957   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
75958   rc = sqlite3ApiExit(db, rc);
75959   sqlite3_mutex_leave(db->mutex);
75960   return rc;
75961 }
75962
75963 #ifndef SQLITE_OMIT_UTF16
75964 /*
75965 ** Register a new collation sequence with the database handle db.
75966 */
75967 SQLITE_API int sqlite3_create_collation16(
75968   sqlite3* db, 
75969   const char *zName, 
75970   int enc, 
75971   void* pCtx,
75972   int(*xCompare)(void*,int,const void*,int,const void*)
75973 ){
75974   int rc = SQLITE_OK;
75975   char *zName8;
75976   sqlite3_mutex_enter(db->mutex);
75977   assert( !db->mallocFailed );
75978   zName8 = sqlite3Utf16to8(db, zName, -1);
75979   if( zName8 ){
75980     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
75981     sqlite3_free(zName8);
75982   }
75983   rc = sqlite3ApiExit(db, rc);
75984   sqlite3_mutex_leave(db->mutex);
75985   return rc;
75986 }
75987 #endif /* SQLITE_OMIT_UTF16 */
75988
75989 /*
75990 ** Register a collation sequence factory callback with the database handle
75991 ** db. Replace any previously installed collation sequence factory.
75992 */
75993 SQLITE_API int sqlite3_collation_needed(
75994   sqlite3 *db, 
75995   void *pCollNeededArg, 
75996   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
75997 ){
75998   sqlite3_mutex_enter(db->mutex);
75999   db->xCollNeeded = xCollNeeded;
76000   db->xCollNeeded16 = 0;
76001   db->pCollNeededArg = pCollNeededArg;
76002   sqlite3_mutex_leave(db->mutex);
76003   return SQLITE_OK;
76004 }
76005
76006 #ifndef SQLITE_OMIT_UTF16
76007 /*
76008 ** Register a collation sequence factory callback with the database handle
76009 ** db. Replace any previously installed collation sequence factory.
76010 */
76011 SQLITE_API int sqlite3_collation_needed16(
76012   sqlite3 *db, 
76013   void *pCollNeededArg, 
76014   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
76015 ){
76016   sqlite3_mutex_enter(db->mutex);
76017   db->xCollNeeded = 0;
76018   db->xCollNeeded16 = xCollNeeded16;
76019   db->pCollNeededArg = pCollNeededArg;
76020   sqlite3_mutex_leave(db->mutex);
76021   return SQLITE_OK;
76022 }
76023 #endif /* SQLITE_OMIT_UTF16 */
76024
76025 #ifndef SQLITE_OMIT_GLOBALRECOVER
76026 /*
76027 ** This function is now an anachronism. It used to be used to recover from a
76028 ** malloc() failure, but SQLite now does this automatically.
76029 */
76030 SQLITE_API int sqlite3_global_recover(void){
76031   return SQLITE_OK;
76032 }
76033 #endif
76034
76035 /*
76036 ** Test to see whether or not the database connection is in autocommit
76037 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
76038 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
76039 ** by the next COMMIT or ROLLBACK.
76040 **
76041 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
76042 */
76043 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
76044   return db->autoCommit;
76045 }
76046
76047 #ifdef SQLITE_DEBUG
76048 /*
76049 ** The following routine is subtituted for constant SQLITE_CORRUPT in
76050 ** debugging builds.  This provides a way to set a breakpoint for when
76051 ** corruption is first detected.
76052 */
76053 SQLITE_PRIVATE int sqlite3Corrupt(void){
76054   return SQLITE_CORRUPT;
76055 }
76056 #endif
76057
76058 /*
76059 ** This is a convenience routine that makes sure that all thread-specific
76060 ** data for this thread has been deallocated.
76061 **
76062 ** SQLite no longer uses thread-specific data so this routine is now a
76063 ** no-op.  It is retained for historical compatibility.
76064 */
76065 SQLITE_API void sqlite3_thread_cleanup(void){
76066 }
76067
76068 /*
76069 ** Return meta information about a specific column of a database table.
76070 ** See comment in sqlite3.h (sqlite.h.in) for details.
76071 */
76072 #ifdef SQLITE_ENABLE_COLUMN_METADATA
76073 SQLITE_API int sqlite3_table_column_metadata(
76074   sqlite3 *db,                /* Connection handle */
76075   const char *zDbName,        /* Database name or NULL */
76076   const char *zTableName,     /* Table name */
76077   const char *zColumnName,    /* Column name */
76078   char const **pzDataType,    /* OUTPUT: Declared data type */
76079   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
76080   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
76081   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
76082   int *pAutoinc               /* OUTPUT: True if colums is auto-increment */
76083 ){
76084   int rc;
76085   char *zErrMsg = 0;
76086   Table *pTab = 0;
76087   Column *pCol = 0;
76088   int iCol;
76089
76090   char const *zDataType = 0;
76091   char const *zCollSeq = 0;
76092   int notnull = 0;
76093   int primarykey = 0;
76094   int autoinc = 0;
76095
76096   /* Ensure the database schema has been loaded */
76097   (void)sqlite3SafetyOn(db);
76098   sqlite3_mutex_enter(db->mutex);
76099   sqlite3BtreeEnterAll(db);
76100   rc = sqlite3Init(db, &zErrMsg);
76101   sqlite3BtreeLeaveAll(db);
76102   if( SQLITE_OK!=rc ){
76103     goto error_out;
76104   }
76105
76106   /* Locate the table in question */
76107   pTab = sqlite3FindTable(db, zTableName, zDbName);
76108   if( !pTab || pTab->pSelect ){
76109     pTab = 0;
76110     goto error_out;
76111   }
76112
76113   /* Find the column for which info is requested */
76114   if( sqlite3IsRowid(zColumnName) ){
76115     iCol = pTab->iPKey;
76116     if( iCol>=0 ){
76117       pCol = &pTab->aCol[iCol];
76118     }
76119   }else{
76120     for(iCol=0; iCol<pTab->nCol; iCol++){
76121       pCol = &pTab->aCol[iCol];
76122       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
76123         break;
76124       }
76125     }
76126     if( iCol==pTab->nCol ){
76127       pTab = 0;
76128       goto error_out;
76129     }
76130   }
76131
76132   /* The following block stores the meta information that will be returned
76133   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
76134   ** and autoinc. At this point there are two possibilities:
76135   ** 
76136   **     1. The specified column name was rowid", "oid" or "_rowid_" 
76137   **        and there is no explicitly declared IPK column. 
76138   **
76139   **     2. The table is not a view and the column name identified an 
76140   **        explicitly declared column. Copy meta information from *pCol.
76141   */ 
76142   if( pCol ){
76143     zDataType = pCol->zType;
76144     zCollSeq = pCol->zColl;
76145     notnull = (pCol->notNull?1:0);
76146     primarykey  = (pCol->isPrimKey?1:0);
76147     autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
76148   }else{
76149     zDataType = "INTEGER";
76150     primarykey = 1;
76151   }
76152   if( !zCollSeq ){
76153     zCollSeq = "BINARY";
76154   }
76155
76156 error_out:
76157   (void)sqlite3SafetyOff(db);
76158
76159   /* Whether the function call succeeded or failed, set the output parameters
76160   ** to whatever their local counterparts contain. If an error did occur,
76161   ** this has the effect of zeroing all output parameters.
76162   */
76163   if( pzDataType ) *pzDataType = zDataType;
76164   if( pzCollSeq ) *pzCollSeq = zCollSeq;
76165   if( pNotNull ) *pNotNull = notnull;
76166   if( pPrimaryKey ) *pPrimaryKey = primarykey;
76167   if( pAutoinc ) *pAutoinc = autoinc;
76168
76169   if( SQLITE_OK==rc && !pTab ){
76170     sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".", 
76171         zColumnName, 0);
76172     rc = SQLITE_ERROR;
76173   }
76174   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
76175   sqlite3_free(zErrMsg);
76176   rc = sqlite3ApiExit(db, rc);
76177   sqlite3_mutex_leave(db->mutex);
76178   return rc;
76179 }
76180 #endif
76181
76182 /*
76183 ** Sleep for a little while.  Return the amount of time slept.
76184 */
76185 SQLITE_API int sqlite3_sleep(int ms){
76186   sqlite3_vfs *pVfs;
76187   int rc;
76188   pVfs = sqlite3_vfs_find(0);
76189
76190   /* This function works in milliseconds, but the underlying OsSleep() 
76191   ** API uses microseconds. Hence the 1000's.
76192   */
76193   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
76194   return rc;
76195 }
76196
76197 /*
76198 ** Enable or disable the extended result codes.
76199 */
76200 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
76201   sqlite3_mutex_enter(db->mutex);
76202   db->errMask = onoff ? 0xffffffff : 0xff;
76203   sqlite3_mutex_leave(db->mutex);
76204   return SQLITE_OK;
76205 }
76206
76207 /*
76208 ** Invoke the xFileControl method on a particular database.
76209 */
76210 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
76211   int rc = SQLITE_ERROR;
76212   int iDb;
76213   sqlite3_mutex_enter(db->mutex);
76214   if( zDbName==0 ){
76215     iDb = 0;
76216   }else{
76217     for(iDb=0; iDb<db->nDb; iDb++){
76218       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
76219     }
76220   }
76221   if( iDb<db->nDb ){
76222     Btree *pBtree = db->aDb[iDb].pBt;
76223     if( pBtree ){
76224       Pager *pPager;
76225       sqlite3_file *fd;
76226       sqlite3BtreeEnter(pBtree);
76227       pPager = sqlite3BtreePager(pBtree);
76228       assert( pPager!=0 );
76229       fd = sqlite3PagerFile(pPager);
76230       assert( fd!=0 );
76231       if( fd->pMethods ){
76232         rc = sqlite3OsFileControl(fd, op, pArg);
76233       }
76234       sqlite3BtreeLeave(pBtree);
76235     }
76236   }
76237   sqlite3_mutex_leave(db->mutex);
76238   return rc;   
76239 }
76240
76241 /*
76242 ** Interface to the testing logic.
76243 */
76244 SQLITE_API int sqlite3_test_control(int op, ...){
76245   va_list ap;
76246   int rc = 0;
76247   va_start(ap, op);
76248   switch( op ){
76249 #ifndef SQLITE_OMIT_FAULTINJECTOR
76250     case SQLITE_TESTCTRL_FAULT_CONFIG: {
76251       int id = va_arg(ap, int);
76252       int nDelay = va_arg(ap, int);
76253       int nRepeat = va_arg(ap, int);
76254       sqlite3FaultConfig(id, nDelay, nRepeat);
76255       break;
76256     }
76257     case SQLITE_TESTCTRL_FAULT_FAILURES: {
76258       int id = va_arg(ap, int);
76259       rc = sqlite3FaultFailures(id);
76260       break;
76261     }
76262     case SQLITE_TESTCTRL_FAULT_BENIGN_FAILURES: {
76263       int id = va_arg(ap, int);
76264       rc = sqlite3FaultBenignFailures(id);
76265       break;
76266     }
76267     case SQLITE_TESTCTRL_FAULT_PENDING: {
76268       int id = va_arg(ap, int);
76269       rc = sqlite3FaultPending(id);
76270       break;
76271     }
76272 #endif /* SQLITE_OMIT_FAULTINJECTOR */
76273   }
76274   va_end(ap);
76275   return rc;
76276 }
76277
76278 /************** End of main.c ************************************************/
76279 /************** Begin file fts3.c ********************************************/
76280 /*
76281 ** 2006 Oct 10
76282 **
76283 ** The author disclaims copyright to this source code.  In place of
76284 ** a legal notice, here is a blessing:
76285 **
76286 **    May you do good and not evil.
76287 **    May you find forgiveness for yourself and forgive others.
76288 **    May you share freely, never taking more than you give.
76289 **
76290 ******************************************************************************
76291 **
76292 ** This is an SQLite module implementing full-text search.
76293 */
76294
76295 /*
76296 ** The code in this file is only compiled if:
76297 **
76298 **     * The FTS3 module is being built as an extension
76299 **       (in which case SQLITE_CORE is not defined), or
76300 **
76301 **     * The FTS3 module is being built into the core of
76302 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
76303 */
76304
76305 /* TODO(shess) Consider exporting this comment to an HTML file or the
76306 ** wiki.
76307 */
76308 /* The full-text index is stored in a series of b+tree (-like)
76309 ** structures called segments which map terms to doclists.  The
76310 ** structures are like b+trees in layout, but are constructed from the
76311 ** bottom up in optimal fashion and are not updatable.  Since trees
76312 ** are built from the bottom up, things will be described from the
76313 ** bottom up.
76314 **
76315 **
76316 **** Varints ****
76317 ** The basic unit of encoding is a variable-length integer called a
76318 ** varint.  We encode variable-length integers in little-endian order
76319 ** using seven bits * per byte as follows:
76320 **
76321 ** KEY:
76322 **         A = 0xxxxxxx    7 bits of data and one flag bit
76323 **         B = 1xxxxxxx    7 bits of data and one flag bit
76324 **
76325 **  7 bits - A
76326 ** 14 bits - BA
76327 ** 21 bits - BBA
76328 ** and so on.
76329 **
76330 ** This is identical to how sqlite encodes varints (see util.c).
76331 **
76332 **
76333 **** Document lists ****
76334 ** A doclist (document list) holds a docid-sorted list of hits for a
76335 ** given term.  Doclists hold docids, and can optionally associate
76336 ** token positions and offsets with docids.
76337 **
76338 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
76339 **
76340 ** array {
76341 **   varint docid;
76342 **   array {                (position list for column 0)
76343 **     varint position;     (delta from previous position plus POS_BASE)
76344 **     varint startOffset;  (delta from previous startOffset)
76345 **     varint endOffset;    (delta from startOffset)
76346 **   }
76347 **   array {
76348 **     varint POS_COLUMN;   (marks start of position list for new column)
76349 **     varint column;       (index of new column)
76350 **     array {
76351 **       varint position;   (delta from previous position plus POS_BASE)
76352 **       varint startOffset;(delta from previous startOffset)
76353 **       varint endOffset;  (delta from startOffset)
76354 **     }
76355 **   }
76356 **   varint POS_END;        (marks end of positions for this document.
76357 ** }
76358 **
76359 ** Here, array { X } means zero or more occurrences of X, adjacent in
76360 ** memory.  A "position" is an index of a token in the token stream
76361 ** generated by the tokenizer, while an "offset" is a byte offset,
76362 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
76363 ** same logical place as the position element, and act as sentinals
76364 ** ending a position list array.
76365 **
76366 ** A DL_POSITIONS doclist omits the startOffset and endOffset
76367 ** information.  A DL_DOCIDS doclist omits both the position and
76368 ** offset information, becoming an array of varint-encoded docids.
76369 **
76370 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
76371 ** the type.  Due to how deletion is implemented in the segmentation
76372 ** system, on-disk doclists MUST store at least positions.
76373 **
76374 **
76375 **** Segment leaf nodes ****
76376 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
76377 ** nodes are written using LeafWriter, and read using LeafReader (to
76378 ** iterate through a single leaf node's data) and LeavesReader (to
76379 ** iterate through a segment's entire leaf layer).  Leaf nodes have
76380 ** the format:
76381 **
76382 ** varint iHeight;             (height from leaf level, always 0)
76383 ** varint nTerm;               (length of first term)
76384 ** char pTerm[nTerm];          (content of first term)
76385 ** varint nDoclist;            (length of term's associated doclist)
76386 ** char pDoclist[nDoclist];    (content of doclist)
76387 ** array {
76388 **                             (further terms are delta-encoded)
76389 **   varint nPrefix;           (length of prefix shared with previous term)
76390 **   varint nSuffix;           (length of unshared suffix)
76391 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
76392 **   varint nDoclist;          (length of term's associated doclist)
76393 **   char pDoclist[nDoclist];  (content of doclist)
76394 ** }
76395 **
76396 ** Here, array { X } means zero or more occurrences of X, adjacent in
76397 ** memory.
76398 **
76399 ** Leaf nodes are broken into blocks which are stored contiguously in
76400 ** the %_segments table in sorted order.  This means that when the end
76401 ** of a node is reached, the next term is in the node with the next
76402 ** greater node id.
76403 **
76404 ** New data is spilled to a new leaf node when the current node
76405 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
76406 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
76407 ** node (a leaf node with a single term and doclist).  The goal of
76408 ** these settings is to pack together groups of small doclists while
76409 ** making it efficient to directly access large doclists.  The
76410 ** assumption is that large doclists represent terms which are more
76411 ** likely to be query targets.
76412 **
76413 ** TODO(shess) It may be useful for blocking decisions to be more
76414 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
76415 ** node rather than splitting into 2k and .5k nodes.  My intuition is
76416 ** that this might extend through 2x or 4x the pagesize.
76417 **
76418 **
76419 **** Segment interior nodes ****
76420 ** Segment interior nodes store blockids for subtree nodes and terms
76421 ** to describe what data is stored by the each subtree.  Interior
76422 ** nodes are written using InteriorWriter, and read using
76423 ** InteriorReader.  InteriorWriters are created as needed when
76424 ** SegmentWriter creates new leaf nodes, or when an interior node
76425 ** itself grows too big and must be split.  The format of interior
76426 ** nodes:
76427 **
76428 ** varint iHeight;           (height from leaf level, always >0)
76429 ** varint iBlockid;          (block id of node's leftmost subtree)
76430 ** optional {
76431 **   varint nTerm;           (length of first term)
76432 **   char pTerm[nTerm];      (content of first term)
76433 **   array {
76434 **                                (further terms are delta-encoded)
76435 **     varint nPrefix;            (length of shared prefix with previous term)
76436 **     varint nSuffix;            (length of unshared suffix)
76437 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
76438 **   }
76439 ** }
76440 **
76441 ** Here, optional { X } means an optional element, while array { X }
76442 ** means zero or more occurrences of X, adjacent in memory.
76443 **
76444 ** An interior node encodes n terms separating n+1 subtrees.  The
76445 ** subtree blocks are contiguous, so only the first subtree's blockid
76446 ** is encoded.  The subtree at iBlockid will contain all terms less
76447 ** than the first term encoded (or all terms if no term is encoded).
76448 ** Otherwise, for terms greater than or equal to pTerm[i] but less
76449 ** than pTerm[i+1], the subtree for that term will be rooted at
76450 ** iBlockid+i.  Interior nodes only store enough term data to
76451 ** distinguish adjacent children (if the rightmost term of the left
76452 ** child is "something", and the leftmost term of the right child is
76453 ** "wicked", only "w" is stored).
76454 **
76455 ** New data is spilled to a new interior node at the same height when
76456 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
76457 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
76458 ** interior nodes and making the tree too skinny.  The interior nodes
76459 ** at a given height are naturally tracked by interior nodes at
76460 ** height+1, and so on.
76461 **
76462 **
76463 **** Segment directory ****
76464 ** The segment directory in table %_segdir stores meta-information for
76465 ** merging and deleting segments, and also the root node of the
76466 ** segment's tree.
76467 **
76468 ** The root node is the top node of the segment's tree after encoding
76469 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
76470 ** This could be either a leaf node or an interior node.  If the top
76471 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
76472 ** and a new root interior node is generated (which should always fit
76473 ** within ROOT_MAX because it only needs space for 2 varints, the
76474 ** height and the blockid of the previous root).
76475 **
76476 ** The meta-information in the segment directory is:
76477 **   level               - segment level (see below)
76478 **   idx                 - index within level
76479 **                       - (level,idx uniquely identify a segment)
76480 **   start_block         - first leaf node
76481 **   leaves_end_block    - last leaf node
76482 **   end_block           - last block (including interior nodes)
76483 **   root                - contents of root node
76484 **
76485 ** If the root node is a leaf node, then start_block,
76486 ** leaves_end_block, and end_block are all 0.
76487 **
76488 **
76489 **** Segment merging ****
76490 ** To amortize update costs, segments are groups into levels and
76491 ** merged in matches.  Each increase in level represents exponentially
76492 ** more documents.
76493 **
76494 ** New documents (actually, document updates) are tokenized and
76495 ** written individually (using LeafWriter) to a level 0 segment, with
76496 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
76497 ** level 0 segments are merged into a single level 1 segment.  Level 1
76498 ** is populated like level 0, and eventually MERGE_COUNT level 1
76499 ** segments are merged to a single level 2 segment (representing
76500 ** MERGE_COUNT^2 updates), and so on.
76501 **
76502 ** A segment merge traverses all segments at a given level in
76503 ** parallel, performing a straightforward sorted merge.  Since segment
76504 ** leaf nodes are written in to the %_segments table in order, this
76505 ** merge traverses the underlying sqlite disk structures efficiently.
76506 ** After the merge, all segment blocks from the merged level are
76507 ** deleted.
76508 **
76509 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
76510 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
76511 ** very similar performance numbers to 16 on insertion, though they're
76512 ** a tiny bit slower (perhaps due to more overhead in merge-time
76513 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
76514 ** 16, 2 about 66% slower than 16.
76515 **
76516 ** At query time, high MERGE_COUNT increases the number of segments
76517 ** which need to be scanned and merged.  For instance, with 100k docs
76518 ** inserted:
76519 **
76520 **    MERGE_COUNT   segments
76521 **       16           25
76522 **        8           12
76523 **        4           10
76524 **        2            6
76525 **
76526 ** This appears to have only a moderate impact on queries for very
76527 ** frequent terms (which are somewhat dominated by segment merge
76528 ** costs), and infrequent and non-existent terms still seem to be fast
76529 ** even with many segments.
76530 **
76531 ** TODO(shess) That said, it would be nice to have a better query-side
76532 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
76533 ** optimizations to things like doclist merging will swing the sweet
76534 ** spot around.
76535 **
76536 **
76537 **
76538 **** Handling of deletions and updates ****
76539 ** Since we're using a segmented structure, with no docid-oriented
76540 ** index into the term index, we clearly cannot simply update the term
76541 ** index when a document is deleted or updated.  For deletions, we
76542 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
76543 ** we simply write the new doclist.  Segment merges overwrite older
76544 ** data for a particular docid with newer data, so deletes or updates
76545 ** will eventually overtake the earlier data and knock it out.  The
76546 ** query logic likewise merges doclists so that newer data knocks out
76547 ** older data.
76548 **
76549 ** TODO(shess) Provide a VACUUM type operation to clear out all
76550 ** deletions and duplications.  This would basically be a forced merge
76551 ** into a single segment.
76552 */
76553
76554 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
76555
76556 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
76557 # define SQLITE_CORE 1
76558 #endif
76559
76560
76561 /************** Include fts3_hash.h in the middle of fts3.c ******************/
76562 /************** Begin file fts3_hash.h ***************************************/
76563 /*
76564 ** 2001 September 22
76565 **
76566 ** The author disclaims copyright to this source code.  In place of
76567 ** a legal notice, here is a blessing:
76568 **
76569 **    May you do good and not evil.
76570 **    May you find forgiveness for yourself and forgive others.
76571 **    May you share freely, never taking more than you give.
76572 **
76573 *************************************************************************
76574 ** This is the header file for the generic hash-table implemenation
76575 ** used in SQLite.  We've modified it slightly to serve as a standalone
76576 ** hash table implementation for the full-text indexing module.
76577 **
76578 */
76579 #ifndef _FTS3_HASH_H_
76580 #define _FTS3_HASH_H_
76581
76582 /* Forward declarations of structures. */
76583 typedef struct fts3Hash fts3Hash;
76584 typedef struct fts3HashElem fts3HashElem;
76585
76586 /* A complete hash table is an instance of the following structure.
76587 ** The internals of this structure are intended to be opaque -- client
76588 ** code should not attempt to access or modify the fields of this structure
76589 ** directly.  Change this structure only by using the routines below.
76590 ** However, many of the "procedures" and "functions" for modifying and
76591 ** accessing this structure are really macros, so we can't really make
76592 ** this structure opaque.
76593 */
76594 struct fts3Hash {
76595   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
76596   char copyKey;           /* True if copy of key made on insert */
76597   int count;              /* Number of entries in this table */
76598   fts3HashElem *first;    /* The first element of the array */
76599   int htsize;             /* Number of buckets in the hash table */
76600   struct _fts3ht {        /* the hash table */
76601     int count;               /* Number of entries with this hash */
76602     fts3HashElem *chain;     /* Pointer to first entry with this hash */
76603   } *ht;
76604 };
76605
76606 /* Each element in the hash table is an instance of the following 
76607 ** structure.  All elements are stored on a single doubly-linked list.
76608 **
76609 ** Again, this structure is intended to be opaque, but it can't really
76610 ** be opaque because it is used by macros.
76611 */
76612 struct fts3HashElem {
76613   fts3HashElem *next, *prev; /* Next and previous elements in the table */
76614   void *data;                /* Data associated with this element */
76615   void *pKey; int nKey;      /* Key associated with this element */
76616 };
76617
76618 /*
76619 ** There are 2 different modes of operation for a hash table:
76620 **
76621 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
76622 **                           (including the null-terminator, if any).  Case
76623 **                           is respected in comparisons.
76624 **
76625 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
76626 **                           memcmp() is used to compare keys.
76627 **
76628 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
76629 */
76630 #define FTS3_HASH_STRING    1
76631 #define FTS3_HASH_BINARY    2
76632
76633 /*
76634 ** Access routines.  To delete, insert a NULL pointer.
76635 */
76636 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
76637 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
76638 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
76639 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
76640
76641 /*
76642 ** Shorthand for the functions above
76643 */
76644 #define fts3HashInit   sqlite3Fts3HashInit
76645 #define fts3HashInsert sqlite3Fts3HashInsert
76646 #define fts3HashFind   sqlite3Fts3HashFind
76647 #define fts3HashClear  sqlite3Fts3HashClear
76648
76649 /*
76650 ** Macros for looping over all elements of a hash table.  The idiom is
76651 ** like this:
76652 **
76653 **   fts3Hash h;
76654 **   fts3HashElem *p;
76655 **   ...
76656 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
76657 **     SomeStructure *pData = fts3HashData(p);
76658 **     // do something with pData
76659 **   }
76660 */
76661 #define fts3HashFirst(H)  ((H)->first)
76662 #define fts3HashNext(E)   ((E)->next)
76663 #define fts3HashData(E)   ((E)->data)
76664 #define fts3HashKey(E)    ((E)->pKey)
76665 #define fts3HashKeysize(E) ((E)->nKey)
76666
76667 /*
76668 ** Number of entries in a hash table
76669 */
76670 #define fts3HashCount(H)  ((H)->count)
76671
76672 #endif /* _FTS3_HASH_H_ */
76673
76674 /************** End of fts3_hash.h *******************************************/
76675 /************** Continuing where we left off in fts3.c ***********************/
76676 /************** Include fts3_tokenizer.h in the middle of fts3.c *************/
76677 /************** Begin file fts3_tokenizer.h **********************************/
76678 /*
76679 ** 2006 July 10
76680 **
76681 ** The author disclaims copyright to this source code.
76682 **
76683 *************************************************************************
76684 ** Defines the interface to tokenizers used by fulltext-search.  There
76685 ** are three basic components:
76686 **
76687 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
76688 ** interface functions.  This is essentially the class structure for
76689 ** tokenizers.
76690 **
76691 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
76692 ** including customization information defined at creation time.
76693 **
76694 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
76695 ** tokens from a particular input.
76696 */
76697 #ifndef _FTS3_TOKENIZER_H_
76698 #define _FTS3_TOKENIZER_H_
76699
76700 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
76701 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
76702 ** we will need a way to register the API consistently.
76703 */
76704
76705 /*
76706 ** Structures used by the tokenizer interface. When a new tokenizer
76707 ** implementation is registered, the caller provides a pointer to
76708 ** an sqlite3_tokenizer_module containing pointers to the callback
76709 ** functions that make up an implementation.
76710 **
76711 ** When an fts3 table is created, it passes any arguments passed to
76712 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
76713 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
76714 ** implementation. The xCreate() function in turn returns an 
76715 ** sqlite3_tokenizer structure representing the specific tokenizer to
76716 ** be used for the fts3 table (customized by the tokenizer clause arguments).
76717 **
76718 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
76719 ** method is called. It returns an sqlite3_tokenizer_cursor object
76720 ** that may be used to tokenize a specific input buffer based on
76721 ** the tokenization rules supplied by a specific sqlite3_tokenizer
76722 ** object.
76723 */
76724 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
76725 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
76726 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
76727
76728 struct sqlite3_tokenizer_module {
76729
76730   /*
76731   ** Structure version. Should always be set to 0.
76732   */
76733   int iVersion;
76734
76735   /*
76736   ** Create a new tokenizer. The values in the argv[] array are the
76737   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
76738   ** TABLE statement that created the fts3 table. For example, if
76739   ** the following SQL is executed:
76740   **
76741   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
76742   **
76743   ** then argc is set to 2, and the argv[] array contains pointers
76744   ** to the strings "arg1" and "arg2".
76745   **
76746   ** This method should return either SQLITE_OK (0), or an SQLite error 
76747   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
76748   ** to point at the newly created tokenizer structure. The generic
76749   ** sqlite3_tokenizer.pModule variable should not be initialised by
76750   ** this callback. The caller will do so.
76751   */
76752   int (*xCreate)(
76753     int argc,                           /* Size of argv array */
76754     const char *const*argv,             /* Tokenizer argument strings */
76755     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
76756   );
76757
76758   /*
76759   ** Destroy an existing tokenizer. The fts3 module calls this method
76760   ** exactly once for each successful call to xCreate().
76761   */
76762   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
76763
76764   /*
76765   ** Create a tokenizer cursor to tokenize an input buffer. The caller
76766   ** is responsible for ensuring that the input buffer remains valid
76767   ** until the cursor is closed (using the xClose() method). 
76768   */
76769   int (*xOpen)(
76770     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
76771     const char *pInput, int nBytes,      /* Input buffer */
76772     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
76773   );
76774
76775   /*
76776   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
76777   ** method exactly once for each successful call to xOpen().
76778   */
76779   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
76780
76781   /*
76782   ** Retrieve the next token from the tokenizer cursor pCursor. This
76783   ** method should either return SQLITE_OK and set the values of the
76784   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
76785   ** the end of the buffer has been reached, or an SQLite error code.
76786   **
76787   ** *ppToken should be set to point at a buffer containing the 
76788   ** normalized version of the token (i.e. after any case-folding and/or
76789   ** stemming has been performed). *pnBytes should be set to the length
76790   ** of this buffer in bytes. The input text that generated the token is
76791   ** identified by the byte offsets returned in *piStartOffset and
76792   ** *piEndOffset.
76793   **
76794   ** The buffer *ppToken is set to point at is managed by the tokenizer
76795   ** implementation. It is only required to be valid until the next call
76796   ** to xNext() or xClose(). 
76797   */
76798   /* TODO(shess) current implementation requires pInput to be
76799   ** nul-terminated.  This should either be fixed, or pInput/nBytes
76800   ** should be converted to zInput.
76801   */
76802   int (*xNext)(
76803     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
76804     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
76805     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
76806     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
76807     int *piPosition      /* OUT: Number of tokens returned before this one */
76808   );
76809 };
76810
76811 struct sqlite3_tokenizer {
76812   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
76813   /* Tokenizer implementations will typically add additional fields */
76814 };
76815
76816 struct sqlite3_tokenizer_cursor {
76817   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
76818   /* Tokenizer implementations will typically add additional fields */
76819 };
76820
76821 #endif /* _FTS3_TOKENIZER_H_ */
76822
76823 /************** End of fts3_tokenizer.h **************************************/
76824 /************** Continuing where we left off in fts3.c ***********************/
76825 #ifndef SQLITE_CORE 
76826   SQLITE_EXTENSION_INIT1
76827 #endif
76828
76829
76830 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
76831 ** would be nice to order the file better, perhaps something along the
76832 ** lines of:
76833 **
76834 **  - utility functions
76835 **  - table setup functions
76836 **  - table update functions
76837 **  - table query functions
76838 **
76839 ** Put the query functions last because they're likely to reference
76840 ** typedefs or functions from the table update section.
76841 */
76842
76843 #if 0
76844 # define FTSTRACE(A)  printf A; fflush(stdout)
76845 #else
76846 # define FTSTRACE(A)
76847 #endif
76848
76849 /*
76850 ** Default span for NEAR operators.
76851 */
76852 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
76853
76854 /* It is not safe to call isspace(), tolower(), or isalnum() on
76855 ** hi-bit-set characters.  This is the same solution used in the
76856 ** tokenizer.
76857 */
76858 /* TODO(shess) The snippet-generation code should be using the
76859 ** tokenizer-generated tokens rather than doing its own local
76860 ** tokenization.
76861 */
76862 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
76863 static int safe_isspace(char c){
76864   return (c&0x80)==0 ? isspace(c) : 0;
76865 }
76866 static int safe_tolower(char c){
76867   return (c&0x80)==0 ? tolower(c) : c;
76868 }
76869 static int safe_isalnum(char c){
76870   return (c&0x80)==0 ? isalnum(c) : 0;
76871 }
76872
76873 typedef enum DocListType {
76874   DL_DOCIDS,              /* docids only */
76875   DL_POSITIONS,           /* docids + positions */
76876   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
76877 } DocListType;
76878
76879 /*
76880 ** By default, only positions and not offsets are stored in the doclists.
76881 ** To change this so that offsets are stored too, compile with
76882 **
76883 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
76884 **
76885 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
76886 ** into (no deletes or updates).
76887 */
76888 #ifndef DL_DEFAULT
76889 # define DL_DEFAULT DL_POSITIONS
76890 #endif
76891
76892 enum {
76893   POS_END = 0,        /* end of this position list */
76894   POS_COLUMN,         /* followed by new column number */
76895   POS_BASE
76896 };
76897
76898 /* MERGE_COUNT controls how often we merge segments (see comment at
76899 ** top of file).
76900 */
76901 #define MERGE_COUNT 16
76902
76903 /* utility functions */
76904
76905 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
76906 ** record to prevent errors of the form:
76907 **
76908 ** my_function(SomeType *b){
76909 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
76910 ** }
76911 */
76912 /* TODO(shess) Obvious candidates for a header file. */
76913 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
76914
76915 #ifndef NDEBUG
76916 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
76917 #else
76918 #  define SCRAMBLE(b)
76919 #endif
76920
76921 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
76922 #define VARINT_MAX 10
76923
76924 /* Write a 64-bit variable-length integer to memory starting at p[0].
76925  * The length of data written will be between 1 and VARINT_MAX bytes.
76926  * The number of bytes written is returned. */
76927 static int fts3PutVarint(char *p, sqlite_int64 v){
76928   unsigned char *q = (unsigned char *) p;
76929   sqlite_uint64 vu = v;
76930   do{
76931     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
76932     vu >>= 7;
76933   }while( vu!=0 );
76934   q[-1] &= 0x7f;  /* turn off high bit in final byte */
76935   assert( q - (unsigned char *)p <= VARINT_MAX );
76936   return (int) (q - (unsigned char *)p);
76937 }
76938
76939 /* Read a 64-bit variable-length integer from memory starting at p[0].
76940  * Return the number of bytes read, or 0 on error.
76941  * The value is stored in *v. */
76942 static int fts3GetVarint(const char *p, sqlite_int64 *v){
76943   const unsigned char *q = (const unsigned char *) p;
76944   sqlite_uint64 x = 0, y = 1;
76945   while( (*q & 0x80) == 0x80 ){
76946     x += y * (*q++ & 0x7f);
76947     y <<= 7;
76948     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
76949       assert( 0 );
76950       return 0;
76951     }
76952   }
76953   x += y * (*q++);
76954   *v = (sqlite_int64) x;
76955   return (int) (q - (unsigned char *)p);
76956 }
76957
76958 static int fts3GetVarint32(const char *p, int *pi){
76959  sqlite_int64 i;
76960  int ret = fts3GetVarint(p, &i);
76961  *pi = (int) i;
76962  assert( *pi==i );
76963  return ret;
76964 }
76965
76966 /*******************************************************************/
76967 /* DataBuffer is used to collect data into a buffer in piecemeal
76968 ** fashion.  It implements the usual distinction between amount of
76969 ** data currently stored (nData) and buffer capacity (nCapacity).
76970 **
76971 ** dataBufferInit - create a buffer with given initial capacity.
76972 ** dataBufferReset - forget buffer's data, retaining capacity.
76973 ** dataBufferDestroy - free buffer's data.
76974 ** dataBufferSwap - swap contents of two buffers.
76975 ** dataBufferExpand - expand capacity without adding data.
76976 ** dataBufferAppend - append data.
76977 ** dataBufferAppend2 - append two pieces of data at once.
76978 ** dataBufferReplace - replace buffer's data.
76979 */
76980 typedef struct DataBuffer {
76981   char *pData;          /* Pointer to malloc'ed buffer. */
76982   int nCapacity;        /* Size of pData buffer. */
76983   int nData;            /* End of data loaded into pData. */
76984 } DataBuffer;
76985
76986 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
76987   assert( nCapacity>=0 );
76988   pBuffer->nData = 0;
76989   pBuffer->nCapacity = nCapacity;
76990   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
76991 }
76992 static void dataBufferReset(DataBuffer *pBuffer){
76993   pBuffer->nData = 0;
76994 }
76995 static void dataBufferDestroy(DataBuffer *pBuffer){
76996   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
76997   SCRAMBLE(pBuffer);
76998 }
76999 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
77000   DataBuffer tmp = *pBuffer1;
77001   *pBuffer1 = *pBuffer2;
77002   *pBuffer2 = tmp;
77003 }
77004 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
77005   assert( nAddCapacity>0 );
77006   /* TODO(shess) Consider expanding more aggressively.  Note that the
77007   ** underlying malloc implementation may take care of such things for
77008   ** us already.
77009   */
77010   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
77011     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
77012     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
77013   }
77014 }
77015 static void dataBufferAppend(DataBuffer *pBuffer,
77016                              const char *pSource, int nSource){
77017   assert( nSource>0 && pSource!=NULL );
77018   dataBufferExpand(pBuffer, nSource);
77019   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
77020   pBuffer->nData += nSource;
77021 }
77022 static void dataBufferAppend2(DataBuffer *pBuffer,
77023                               const char *pSource1, int nSource1,
77024                               const char *pSource2, int nSource2){
77025   assert( nSource1>0 && pSource1!=NULL );
77026   assert( nSource2>0 && pSource2!=NULL );
77027   dataBufferExpand(pBuffer, nSource1+nSource2);
77028   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
77029   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
77030   pBuffer->nData += nSource1+nSource2;
77031 }
77032 static void dataBufferReplace(DataBuffer *pBuffer,
77033                               const char *pSource, int nSource){
77034   dataBufferReset(pBuffer);
77035   dataBufferAppend(pBuffer, pSource, nSource);
77036 }
77037
77038 /* StringBuffer is a null-terminated version of DataBuffer. */
77039 typedef struct StringBuffer {
77040   DataBuffer b;            /* Includes null terminator. */
77041 } StringBuffer;
77042
77043 static void initStringBuffer(StringBuffer *sb){
77044   dataBufferInit(&sb->b, 100);
77045   dataBufferReplace(&sb->b, "", 1);
77046 }
77047 static int stringBufferLength(StringBuffer *sb){
77048   return sb->b.nData-1;
77049 }
77050 static char *stringBufferData(StringBuffer *sb){
77051   return sb->b.pData;
77052 }
77053 static void stringBufferDestroy(StringBuffer *sb){
77054   dataBufferDestroy(&sb->b);
77055 }
77056
77057 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
77058   assert( sb->b.nData>0 );
77059   if( nFrom>0 ){
77060     sb->b.nData--;
77061     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
77062   }
77063 }
77064 static void append(StringBuffer *sb, const char *zFrom){
77065   nappend(sb, zFrom, strlen(zFrom));
77066 }
77067
77068 /* Append a list of strings separated by commas. */
77069 static void appendList(StringBuffer *sb, int nString, char **azString){
77070   int i;
77071   for(i=0; i<nString; ++i){
77072     if( i>0 ) append(sb, ", ");
77073     append(sb, azString[i]);
77074   }
77075 }
77076
77077 static int endsInWhiteSpace(StringBuffer *p){
77078   return stringBufferLength(p)>0 &&
77079     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
77080 }
77081
77082 /* If the StringBuffer ends in something other than white space, add a
77083 ** single space character to the end.
77084 */
77085 static void appendWhiteSpace(StringBuffer *p){
77086   if( stringBufferLength(p)==0 ) return;
77087   if( !endsInWhiteSpace(p) ) append(p, " ");
77088 }
77089
77090 /* Remove white space from the end of the StringBuffer */
77091 static void trimWhiteSpace(StringBuffer *p){
77092   while( endsInWhiteSpace(p) ){
77093     p->b.pData[--p->b.nData-1] = '\0';
77094   }
77095 }
77096
77097 /*******************************************************************/
77098 /* DLReader is used to read document elements from a doclist.  The
77099 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
77100 ** own the doclist buffer.
77101 **
77102 ** dlrAtEnd - true if there's no more data to read.
77103 ** dlrDocid - docid of current document.
77104 ** dlrDocData - doclist data for current document (including docid).
77105 ** dlrDocDataBytes - length of same.
77106 ** dlrAllDataBytes - length of all remaining data.
77107 ** dlrPosData - position data for current document.
77108 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
77109 ** dlrStep - step to current document.
77110 ** dlrInit - initial for doclist of given type against given data.
77111 ** dlrDestroy - clean up.
77112 **
77113 ** Expected usage is something like:
77114 **
77115 **   DLReader reader;
77116 **   dlrInit(&reader, pData, nData);
77117 **   while( !dlrAtEnd(&reader) ){
77118 **     // calls to dlrDocid() and kin.
77119 **     dlrStep(&reader);
77120 **   }
77121 **   dlrDestroy(&reader);
77122 */
77123 typedef struct DLReader {
77124   DocListType iType;
77125   const char *pData;
77126   int nData;
77127
77128   sqlite_int64 iDocid;
77129   int nElement;
77130 } DLReader;
77131
77132 static int dlrAtEnd(DLReader *pReader){
77133   assert( pReader->nData>=0 );
77134   return pReader->nData==0;
77135 }
77136 static sqlite_int64 dlrDocid(DLReader *pReader){
77137   assert( !dlrAtEnd(pReader) );
77138   return pReader->iDocid;
77139 }
77140 static const char *dlrDocData(DLReader *pReader){
77141   assert( !dlrAtEnd(pReader) );
77142   return pReader->pData;
77143 }
77144 static int dlrDocDataBytes(DLReader *pReader){
77145   assert( !dlrAtEnd(pReader) );
77146   return pReader->nElement;
77147 }
77148 static int dlrAllDataBytes(DLReader *pReader){
77149   assert( !dlrAtEnd(pReader) );
77150   return pReader->nData;
77151 }
77152 /* TODO(shess) Consider adding a field to track iDocid varint length
77153 ** to make these two functions faster.  This might matter (a tiny bit)
77154 ** for queries.
77155 */
77156 static const char *dlrPosData(DLReader *pReader){
77157   sqlite_int64 iDummy;
77158   int n = fts3GetVarint(pReader->pData, &iDummy);
77159   assert( !dlrAtEnd(pReader) );
77160   return pReader->pData+n;
77161 }
77162 static int dlrPosDataLen(DLReader *pReader){
77163   sqlite_int64 iDummy;
77164   int n = fts3GetVarint(pReader->pData, &iDummy);
77165   assert( !dlrAtEnd(pReader) );
77166   return pReader->nElement-n;
77167 }
77168 static void dlrStep(DLReader *pReader){
77169   assert( !dlrAtEnd(pReader) );
77170
77171   /* Skip past current doclist element. */
77172   assert( pReader->nElement<=pReader->nData );
77173   pReader->pData += pReader->nElement;
77174   pReader->nData -= pReader->nElement;
77175
77176   /* If there is more data, read the next doclist element. */
77177   if( pReader->nData!=0 ){
77178     sqlite_int64 iDocidDelta;
77179     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
77180     pReader->iDocid += iDocidDelta;
77181     if( pReader->iType>=DL_POSITIONS ){
77182       assert( n<pReader->nData );
77183       while( 1 ){
77184         n += fts3GetVarint32(pReader->pData+n, &iDummy);
77185         assert( n<=pReader->nData );
77186         if( iDummy==POS_END ) break;
77187         if( iDummy==POS_COLUMN ){
77188           n += fts3GetVarint32(pReader->pData+n, &iDummy);
77189           assert( n<pReader->nData );
77190         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
77191           n += fts3GetVarint32(pReader->pData+n, &iDummy);
77192           n += fts3GetVarint32(pReader->pData+n, &iDummy);
77193           assert( n<pReader->nData );
77194         }
77195       }
77196     }
77197     pReader->nElement = n;
77198     assert( pReader->nElement<=pReader->nData );
77199   }
77200 }
77201 static void dlrInit(DLReader *pReader, DocListType iType,
77202                     const char *pData, int nData){
77203   assert( pData!=NULL && nData!=0 );
77204   pReader->iType = iType;
77205   pReader->pData = pData;
77206   pReader->nData = nData;
77207   pReader->nElement = 0;
77208   pReader->iDocid = 0;
77209
77210   /* Load the first element's data.  There must be a first element. */
77211   dlrStep(pReader);
77212 }
77213 static void dlrDestroy(DLReader *pReader){
77214   SCRAMBLE(pReader);
77215 }
77216
77217 #ifndef NDEBUG
77218 /* Verify that the doclist can be validly decoded.  Also returns the
77219 ** last docid found because it is convenient in other assertions for
77220 ** DLWriter.
77221 */
77222 static void docListValidate(DocListType iType, const char *pData, int nData,
77223                             sqlite_int64 *pLastDocid){
77224   sqlite_int64 iPrevDocid = 0;
77225   assert( nData>0 );
77226   assert( pData!=0 );
77227   assert( pData+nData>pData );
77228   while( nData!=0 ){
77229     sqlite_int64 iDocidDelta;
77230     int n = fts3GetVarint(pData, &iDocidDelta);
77231     iPrevDocid += iDocidDelta;
77232     if( iType>DL_DOCIDS ){
77233       int iDummy;
77234       while( 1 ){
77235         n += fts3GetVarint32(pData+n, &iDummy);
77236         if( iDummy==POS_END ) break;
77237         if( iDummy==POS_COLUMN ){
77238           n += fts3GetVarint32(pData+n, &iDummy);
77239         }else if( iType>DL_POSITIONS ){
77240           n += fts3GetVarint32(pData+n, &iDummy);
77241           n += fts3GetVarint32(pData+n, &iDummy);
77242         }
77243         assert( n<=nData );
77244       }
77245     }
77246     assert( n<=nData );
77247     pData += n;
77248     nData -= n;
77249   }
77250   if( pLastDocid ) *pLastDocid = iPrevDocid;
77251 }
77252 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
77253 #else
77254 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
77255 #endif
77256
77257 /*******************************************************************/
77258 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
77259 ** always appends to the buffer and does not own it.
77260 **
77261 ** dlwInit - initialize to write a given type doclistto a buffer.
77262 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
77263 ** dlwAppend - append raw doclist data to buffer.
77264 ** dlwCopy - copy next doclist from reader to writer.
77265 ** dlwAdd - construct doclist element and append to buffer.
77266 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
77267 */
77268 typedef struct DLWriter {
77269   DocListType iType;
77270   DataBuffer *b;
77271   sqlite_int64 iPrevDocid;
77272 #ifndef NDEBUG
77273   int has_iPrevDocid;
77274 #endif
77275 } DLWriter;
77276
77277 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
77278   pWriter->b = b;
77279   pWriter->iType = iType;
77280   pWriter->iPrevDocid = 0;
77281 #ifndef NDEBUG
77282   pWriter->has_iPrevDocid = 0;
77283 #endif
77284 }
77285 static void dlwDestroy(DLWriter *pWriter){
77286   SCRAMBLE(pWriter);
77287 }
77288 /* iFirstDocid is the first docid in the doclist in pData.  It is
77289 ** needed because pData may point within a larger doclist, in which
77290 ** case the first item would be delta-encoded.
77291 **
77292 ** iLastDocid is the final docid in the doclist in pData.  It is
77293 ** needed to create the new iPrevDocid for future delta-encoding.  The
77294 ** code could decode the passed doclist to recreate iLastDocid, but
77295 ** the only current user (docListMerge) already has decoded this
77296 ** information.
77297 */
77298 /* TODO(shess) This has become just a helper for docListMerge.
77299 ** Consider a refactor to make this cleaner.
77300 */
77301 static void dlwAppend(DLWriter *pWriter,
77302                       const char *pData, int nData,
77303                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
77304   sqlite_int64 iDocid = 0;
77305   char c[VARINT_MAX];
77306   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
77307 #ifndef NDEBUG
77308   sqlite_int64 iLastDocidDelta;
77309 #endif
77310
77311   /* Recode the initial docid as delta from iPrevDocid. */
77312   nFirstOld = fts3GetVarint(pData, &iDocid);
77313   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
77314   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
77315
77316   /* Verify that the incoming doclist is valid AND that it ends with
77317   ** the expected docid.  This is essential because we'll trust this
77318   ** docid in future delta-encoding.
77319   */
77320   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
77321   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
77322
77323   /* Append recoded initial docid and everything else.  Rest of docids
77324   ** should have been delta-encoded from previous initial docid.
77325   */
77326   if( nFirstOld<nData ){
77327     dataBufferAppend2(pWriter->b, c, nFirstNew,
77328                       pData+nFirstOld, nData-nFirstOld);
77329   }else{
77330     dataBufferAppend(pWriter->b, c, nFirstNew);
77331   }
77332   pWriter->iPrevDocid = iLastDocid;
77333 }
77334 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
77335   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
77336             dlrDocid(pReader), dlrDocid(pReader));
77337 }
77338 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
77339   char c[VARINT_MAX];
77340   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
77341
77342   /* Docids must ascend. */
77343   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
77344   assert( pWriter->iType==DL_DOCIDS );
77345
77346   dataBufferAppend(pWriter->b, c, n);
77347   pWriter->iPrevDocid = iDocid;
77348 #ifndef NDEBUG
77349   pWriter->has_iPrevDocid = 1;
77350 #endif
77351 }
77352
77353 /*******************************************************************/
77354 /* PLReader is used to read data from a document's position list.  As
77355 ** the caller steps through the list, data is cached so that varints
77356 ** only need to be decoded once.
77357 **
77358 ** plrInit, plrDestroy - create/destroy a reader.
77359 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
77360 ** plrAtEnd - at end of stream, only call plrDestroy once true.
77361 ** plrStep - step to the next element.
77362 */
77363 typedef struct PLReader {
77364   /* These refer to the next position's data.  nData will reach 0 when
77365   ** reading the last position, so plrStep() signals EOF by setting
77366   ** pData to NULL.
77367   */
77368   const char *pData;
77369   int nData;
77370
77371   DocListType iType;
77372   int iColumn;         /* the last column read */
77373   int iPosition;       /* the last position read */
77374   int iStartOffset;    /* the last start offset read */
77375   int iEndOffset;      /* the last end offset read */
77376 } PLReader;
77377
77378 static int plrAtEnd(PLReader *pReader){
77379   return pReader->pData==NULL;
77380 }
77381 static int plrColumn(PLReader *pReader){
77382   assert( !plrAtEnd(pReader) );
77383   return pReader->iColumn;
77384 }
77385 static int plrPosition(PLReader *pReader){
77386   assert( !plrAtEnd(pReader) );
77387   return pReader->iPosition;
77388 }
77389 static int plrStartOffset(PLReader *pReader){
77390   assert( !plrAtEnd(pReader) );
77391   return pReader->iStartOffset;
77392 }
77393 static int plrEndOffset(PLReader *pReader){
77394   assert( !plrAtEnd(pReader) );
77395   return pReader->iEndOffset;
77396 }
77397 static void plrStep(PLReader *pReader){
77398   int i, n;
77399
77400   assert( !plrAtEnd(pReader) );
77401
77402   if( pReader->nData==0 ){
77403     pReader->pData = NULL;
77404     return;
77405   }
77406
77407   n = fts3GetVarint32(pReader->pData, &i);
77408   if( i==POS_COLUMN ){
77409     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
77410     pReader->iPosition = 0;
77411     pReader->iStartOffset = 0;
77412     n += fts3GetVarint32(pReader->pData+n, &i);
77413   }
77414   /* Should never see adjacent column changes. */
77415   assert( i!=POS_COLUMN );
77416
77417   if( i==POS_END ){
77418     pReader->nData = 0;
77419     pReader->pData = NULL;
77420     return;
77421   }
77422
77423   pReader->iPosition += i-POS_BASE;
77424   if( pReader->iType==DL_POSITIONS_OFFSETS ){
77425     n += fts3GetVarint32(pReader->pData+n, &i);
77426     pReader->iStartOffset += i;
77427     n += fts3GetVarint32(pReader->pData+n, &i);
77428     pReader->iEndOffset = pReader->iStartOffset+i;
77429   }
77430   assert( n<=pReader->nData );
77431   pReader->pData += n;
77432   pReader->nData -= n;
77433 }
77434
77435 static void plrInit(PLReader *pReader, DLReader *pDLReader){
77436   pReader->pData = dlrPosData(pDLReader);
77437   pReader->nData = dlrPosDataLen(pDLReader);
77438   pReader->iType = pDLReader->iType;
77439   pReader->iColumn = 0;
77440   pReader->iPosition = 0;
77441   pReader->iStartOffset = 0;
77442   pReader->iEndOffset = 0;
77443   plrStep(pReader);
77444 }
77445 static void plrDestroy(PLReader *pReader){
77446   SCRAMBLE(pReader);
77447 }
77448
77449 /*******************************************************************/
77450 /* PLWriter is used in constructing a document's position list.  As a
77451 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
77452 ** PLWriter writes to the associated DLWriter's buffer.
77453 **
77454 ** plwInit - init for writing a document's poslist.
77455 ** plwDestroy - clear a writer.
77456 ** plwAdd - append position and offset information.
77457 ** plwCopy - copy next position's data from reader to writer.
77458 ** plwTerminate - add any necessary doclist terminator.
77459 **
77460 ** Calling plwAdd() after plwTerminate() may result in a corrupt
77461 ** doclist.
77462 */
77463 /* TODO(shess) Until we've written the second item, we can cache the
77464 ** first item's information.  Then we'd have three states:
77465 **
77466 ** - initialized with docid, no positions.
77467 ** - docid and one position.
77468 ** - docid and multiple positions.
77469 **
77470 ** Only the last state needs to actually write to dlw->b, which would
77471 ** be an improvement in the DLCollector case.
77472 */
77473 typedef struct PLWriter {
77474   DLWriter *dlw;
77475
77476   int iColumn;    /* the last column written */
77477   int iPos;       /* the last position written */
77478   int iOffset;    /* the last start offset written */
77479 } PLWriter;
77480
77481 /* TODO(shess) In the case where the parent is reading these values
77482 ** from a PLReader, we could optimize to a copy if that PLReader has
77483 ** the same type as pWriter.
77484 */
77485 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
77486                    int iStartOffset, int iEndOffset){
77487   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
77488   ** iStartOffsetDelta, and iEndOffsetDelta.
77489   */
77490   char c[5*VARINT_MAX];
77491   int n = 0;
77492
77493   /* Ban plwAdd() after plwTerminate(). */
77494   assert( pWriter->iPos!=-1 );
77495
77496   if( pWriter->dlw->iType==DL_DOCIDS ) return;
77497
77498   if( iColumn!=pWriter->iColumn ){
77499     n += fts3PutVarint(c+n, POS_COLUMN);
77500     n += fts3PutVarint(c+n, iColumn);
77501     pWriter->iColumn = iColumn;
77502     pWriter->iPos = 0;
77503     pWriter->iOffset = 0;
77504   }
77505   assert( iPos>=pWriter->iPos );
77506   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
77507   pWriter->iPos = iPos;
77508   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
77509     assert( iStartOffset>=pWriter->iOffset );
77510     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
77511     pWriter->iOffset = iStartOffset;
77512     assert( iEndOffset>=iStartOffset );
77513     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
77514   }
77515   dataBufferAppend(pWriter->dlw->b, c, n);
77516 }
77517 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
77518   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
77519          plrStartOffset(pReader), plrEndOffset(pReader));
77520 }
77521 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
77522   char c[VARINT_MAX];
77523   int n;
77524
77525   pWriter->dlw = dlw;
77526
77527   /* Docids must ascend. */
77528   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
77529   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
77530   dataBufferAppend(pWriter->dlw->b, c, n);
77531   pWriter->dlw->iPrevDocid = iDocid;
77532 #ifndef NDEBUG
77533   pWriter->dlw->has_iPrevDocid = 1;
77534 #endif
77535
77536   pWriter->iColumn = 0;
77537   pWriter->iPos = 0;
77538   pWriter->iOffset = 0;
77539 }
77540 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
77541 ** then plwDestroy() would no longer be just a destructor, it would
77542 ** also be doing work, which isn't consistent with the overall idiom.
77543 ** Another option would be for plwAdd() to always append any necessary
77544 ** terminator, so that the output is always correct.  But that would
77545 ** add incremental work to the common case with the only benefit being
77546 ** API elegance.  Punt for now.
77547 */
77548 static void plwTerminate(PLWriter *pWriter){
77549   if( pWriter->dlw->iType>DL_DOCIDS ){
77550     char c[VARINT_MAX];
77551     int n = fts3PutVarint(c, POS_END);
77552     dataBufferAppend(pWriter->dlw->b, c, n);
77553   }
77554 #ifndef NDEBUG
77555   /* Mark as terminated for assert in plwAdd(). */
77556   pWriter->iPos = -1;
77557 #endif
77558 }
77559 static void plwDestroy(PLWriter *pWriter){
77560   SCRAMBLE(pWriter);
77561 }
77562
77563 /*******************************************************************/
77564 /* DLCollector wraps PLWriter and DLWriter to provide a
77565 ** dynamically-allocated doclist area to use during tokenization.
77566 **
77567 ** dlcNew - malloc up and initialize a collector.
77568 ** dlcDelete - destroy a collector and all contained items.
77569 ** dlcAddPos - append position and offset information.
77570 ** dlcAddDoclist - add the collected doclist to the given buffer.
77571 ** dlcNext - terminate the current document and open another.
77572 */
77573 typedef struct DLCollector {
77574   DataBuffer b;
77575   DLWriter dlw;
77576   PLWriter plw;
77577 } DLCollector;
77578
77579 /* TODO(shess) This could also be done by calling plwTerminate() and
77580 ** dataBufferAppend().  I tried that, expecting nominal performance
77581 ** differences, but it seemed to pretty reliably be worth 1% to code
77582 ** it this way.  I suspect it is the incremental malloc overhead (some
77583 ** percentage of the plwTerminate() calls will cause a realloc), so
77584 ** this might be worth revisiting if the DataBuffer implementation
77585 ** changes.
77586 */
77587 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
77588   if( pCollector->dlw.iType>DL_DOCIDS ){
77589     char c[VARINT_MAX];
77590     int n = fts3PutVarint(c, POS_END);
77591     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
77592   }else{
77593     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
77594   }
77595 }
77596 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
77597   plwTerminate(&pCollector->plw);
77598   plwDestroy(&pCollector->plw);
77599   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
77600 }
77601 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
77602                       int iStartOffset, int iEndOffset){
77603   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
77604 }
77605
77606 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
77607   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
77608   dataBufferInit(&pCollector->b, 0);
77609   dlwInit(&pCollector->dlw, iType, &pCollector->b);
77610   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
77611   return pCollector;
77612 }
77613 static void dlcDelete(DLCollector *pCollector){
77614   plwDestroy(&pCollector->plw);
77615   dlwDestroy(&pCollector->dlw);
77616   dataBufferDestroy(&pCollector->b);
77617   SCRAMBLE(pCollector);
77618   sqlite3_free(pCollector);
77619 }
77620
77621
77622 /* Copy the doclist data of iType in pData/nData into *out, trimming
77623 ** unnecessary data as we go.  Only columns matching iColumn are
77624 ** copied, all columns copied if iColumn is -1.  Elements with no
77625 ** matching columns are dropped.  The output is an iOutType doclist.
77626 */
77627 /* NOTE(shess) This code is only valid after all doclists are merged.
77628 ** If this is run before merges, then doclist items which represent
77629 ** deletion will be trimmed, and will thus not effect a deletion
77630 ** during the merge.
77631 */
77632 static void docListTrim(DocListType iType, const char *pData, int nData,
77633                         int iColumn, DocListType iOutType, DataBuffer *out){
77634   DLReader dlReader;
77635   DLWriter dlWriter;
77636
77637   assert( iOutType<=iType );
77638
77639   dlrInit(&dlReader, iType, pData, nData);
77640   dlwInit(&dlWriter, iOutType, out);
77641
77642   while( !dlrAtEnd(&dlReader) ){
77643     PLReader plReader;
77644     PLWriter plWriter;
77645     int match = 0;
77646
77647     plrInit(&plReader, &dlReader);
77648
77649     while( !plrAtEnd(&plReader) ){
77650       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
77651         if( !match ){
77652           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
77653           match = 1;
77654         }
77655         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
77656                plrStartOffset(&plReader), plrEndOffset(&plReader));
77657       }
77658       plrStep(&plReader);
77659     }
77660     if( match ){
77661       plwTerminate(&plWriter);
77662       plwDestroy(&plWriter);
77663     }
77664
77665     plrDestroy(&plReader);
77666     dlrStep(&dlReader);
77667   }
77668   dlwDestroy(&dlWriter);
77669   dlrDestroy(&dlReader);
77670 }
77671
77672 /* Used by docListMerge() to keep doclists in the ascending order by
77673 ** docid, then ascending order by age (so the newest comes first).
77674 */
77675 typedef struct OrderedDLReader {
77676   DLReader *pReader;
77677
77678   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
77679   ** age (which we do), then we could use pReader comparisons to break
77680   ** ties.
77681   */
77682   int idx;
77683 } OrderedDLReader;
77684
77685 /* Order eof to end, then by docid asc, idx desc. */
77686 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
77687   if( dlrAtEnd(r1->pReader) ){
77688     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
77689     return 1;                              /* Only r1 atEnd(). */
77690   }
77691   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
77692
77693   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
77694   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
77695
77696   /* Descending on idx. */
77697   return r2->idx-r1->idx;
77698 }
77699
77700 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
77701 ** p[1..n-1] is already sorted.
77702 */
77703 /* TODO(shess) Is this frequent enough to warrant a binary search?
77704 ** Before implementing that, instrument the code to check.  In most
77705 ** current usage, I expect that p[0] will be less than p[1] a very
77706 ** high proportion of the time.
77707 */
77708 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
77709   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
77710     OrderedDLReader tmp = p[0];
77711     p[0] = p[1];
77712     p[1] = tmp;
77713     n--;
77714     p++;
77715   }
77716 }
77717
77718 /* Given an array of doclist readers, merge their doclist elements
77719 ** into out in sorted order (by docid), dropping elements from older
77720 ** readers when there is a duplicate docid.  pReaders is assumed to be
77721 ** ordered by age, oldest first.
77722 */
77723 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
77724 ** be fixed.
77725 */
77726 static void docListMerge(DataBuffer *out,
77727                          DLReader *pReaders, int nReaders){
77728   OrderedDLReader readers[MERGE_COUNT];
77729   DLWriter writer;
77730   int i, n;
77731   const char *pStart = 0;
77732   int nStart = 0;
77733   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
77734
77735   assert( nReaders>0 );
77736   if( nReaders==1 ){
77737     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
77738     return;
77739   }
77740
77741   assert( nReaders<=MERGE_COUNT );
77742   n = 0;
77743   for(i=0; i<nReaders; i++){
77744     assert( pReaders[i].iType==pReaders[0].iType );
77745     readers[i].pReader = pReaders+i;
77746     readers[i].idx = i;
77747     n += dlrAllDataBytes(&pReaders[i]);
77748   }
77749   /* Conservatively size output to sum of inputs.  Output should end
77750   ** up strictly smaller than input.
77751   */
77752   dataBufferExpand(out, n);
77753
77754   /* Get the readers into sorted order. */
77755   while( i-->0 ){
77756     orderedDLReaderReorder(readers+i, nReaders-i);
77757   }
77758
77759   dlwInit(&writer, pReaders[0].iType, out);
77760   while( !dlrAtEnd(readers[0].pReader) ){
77761     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
77762
77763     /* If this is a continuation of the current buffer to copy, extend
77764     ** that buffer.  memcpy() seems to be more efficient if it has a
77765     ** lots of data to copy.
77766     */
77767     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
77768       nStart += dlrDocDataBytes(readers[0].pReader);
77769     }else{
77770       if( pStart!=0 ){
77771         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
77772       }
77773       pStart = dlrDocData(readers[0].pReader);
77774       nStart = dlrDocDataBytes(readers[0].pReader);
77775       iFirstDocid = iDocid;
77776     }
77777     iLastDocid = iDocid;
77778     dlrStep(readers[0].pReader);
77779
77780     /* Drop all of the older elements with the same docid. */
77781     for(i=1; i<nReaders &&
77782              !dlrAtEnd(readers[i].pReader) &&
77783              dlrDocid(readers[i].pReader)==iDocid; i++){
77784       dlrStep(readers[i].pReader);
77785     }
77786
77787     /* Get the readers back into order. */
77788     while( i-->0 ){
77789       orderedDLReaderReorder(readers+i, nReaders-i);
77790     }
77791   }
77792
77793   /* Copy over any remaining elements. */
77794   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
77795   dlwDestroy(&writer);
77796 }
77797
77798 /* Helper function for posListUnion().  Compares the current position
77799 ** between left and right, returning as standard C idiom of <0 if
77800 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
77801 ** compares greater.
77802 */
77803 static int posListCmp(PLReader *pLeft, PLReader *pRight){
77804   assert( pLeft->iType==pRight->iType );
77805   if( pLeft->iType==DL_DOCIDS ) return 0;
77806
77807   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
77808   if( plrAtEnd(pRight) ) return -1;
77809
77810   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
77811   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
77812
77813   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
77814   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
77815   if( pLeft->iType==DL_POSITIONS ) return 0;
77816
77817   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
77818   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
77819
77820   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
77821   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
77822
77823   return 0;
77824 }
77825
77826 /* Write the union of position lists in pLeft and pRight to pOut.
77827 ** "Union" in this case meaning "All unique position tuples".  Should
77828 ** work with any doclist type, though both inputs and the output
77829 ** should be the same type.
77830 */
77831 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
77832   PLReader left, right;
77833   PLWriter writer;
77834
77835   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
77836   assert( pLeft->iType==pRight->iType );
77837   assert( pLeft->iType==pOut->iType );
77838
77839   plrInit(&left, pLeft);
77840   plrInit(&right, pRight);
77841   plwInit(&writer, pOut, dlrDocid(pLeft));
77842
77843   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
77844     int c = posListCmp(&left, &right);
77845     if( c<0 ){
77846       plwCopy(&writer, &left);
77847       plrStep(&left);
77848     }else if( c>0 ){
77849       plwCopy(&writer, &right);
77850       plrStep(&right);
77851     }else{
77852       plwCopy(&writer, &left);
77853       plrStep(&left);
77854       plrStep(&right);
77855     }
77856   }
77857
77858   plwTerminate(&writer);
77859   plwDestroy(&writer);
77860   plrDestroy(&left);
77861   plrDestroy(&right);
77862 }
77863
77864 /* Write the union of doclists in pLeft and pRight to pOut.  For
77865 ** docids in common between the inputs, the union of the position
77866 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
77867 */
77868 static void docListUnion(
77869   const char *pLeft, int nLeft,
77870   const char *pRight, int nRight,
77871   DataBuffer *pOut      /* Write the combined doclist here */
77872 ){
77873   DLReader left, right;
77874   DLWriter writer;
77875
77876   if( nLeft==0 ){
77877     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
77878     return;
77879   }
77880   if( nRight==0 ){
77881     dataBufferAppend(pOut, pLeft, nLeft);
77882     return;
77883   }
77884
77885   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
77886   dlrInit(&right, DL_DEFAULT, pRight, nRight);
77887   dlwInit(&writer, DL_DEFAULT, pOut);
77888
77889   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
77890     if( dlrAtEnd(&right) ){
77891       dlwCopy(&writer, &left);
77892       dlrStep(&left);
77893     }else if( dlrAtEnd(&left) ){
77894       dlwCopy(&writer, &right);
77895       dlrStep(&right);
77896     }else if( dlrDocid(&left)<dlrDocid(&right) ){
77897       dlwCopy(&writer, &left);
77898       dlrStep(&left);
77899     }else if( dlrDocid(&left)>dlrDocid(&right) ){
77900       dlwCopy(&writer, &right);
77901       dlrStep(&right);
77902     }else{
77903       posListUnion(&left, &right, &writer);
77904       dlrStep(&left);
77905       dlrStep(&right);
77906     }
77907   }
77908
77909   dlrDestroy(&left);
77910   dlrDestroy(&right);
77911   dlwDestroy(&writer);
77912 }
77913
77914 /* 
77915 ** This function is used as part of the implementation of phrase and
77916 ** NEAR matching.
77917 **
77918 ** pLeft and pRight are DLReaders positioned to the same docid in
77919 ** lists of type DL_POSITION. This function writes an entry to the
77920 ** DLWriter pOut for each position in pRight that is less than
77921 ** (nNear+1) greater (but not equal to or smaller) than a position 
77922 ** in pLeft. For example, if nNear is 0, and the positions contained
77923 ** by pLeft and pRight are:
77924 **
77925 **    pLeft:  5 10 15 20
77926 **    pRight: 6  9 17 21
77927 **
77928 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
77929 ** then a positionids "6" and "21" are also added to pOut.
77930 **
77931 ** If boolean argument isSaveLeft is true, then positionids are copied
77932 ** from pLeft instead of pRight. In the example above, the positions "5"
77933 ** and "20" would be added instead of "6" and "21".
77934 */
77935 static void posListPhraseMerge(
77936   DLReader *pLeft, 
77937   DLReader *pRight,
77938   int nNear,
77939   int isSaveLeft,
77940   DLWriter *pOut
77941 ){
77942   PLReader left, right;
77943   PLWriter writer;
77944   int match = 0;
77945
77946   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
77947   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
77948
77949   plrInit(&left, pLeft);
77950   plrInit(&right, pRight);
77951
77952   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
77953     if( plrColumn(&left)<plrColumn(&right) ){
77954       plrStep(&left);
77955     }else if( plrColumn(&left)>plrColumn(&right) ){
77956       plrStep(&right);
77957     }else if( plrPosition(&left)>=plrPosition(&right) ){
77958       plrStep(&right);
77959     }else{
77960       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
77961         if( !match ){
77962           plwInit(&writer, pOut, dlrDocid(pLeft));
77963           match = 1;
77964         }
77965         if( !isSaveLeft ){
77966           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
77967         }else{
77968           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
77969         }
77970         plrStep(&right);
77971       }else{
77972         plrStep(&left);
77973       }
77974     }
77975   }
77976
77977   if( match ){
77978     plwTerminate(&writer);
77979     plwDestroy(&writer);
77980   }
77981
77982   plrDestroy(&left);
77983   plrDestroy(&right);
77984 }
77985
77986 /*
77987 ** Compare the values pointed to by the PLReaders passed as arguments. 
77988 ** Return -1 if the value pointed to by pLeft is considered less than
77989 ** the value pointed to by pRight, +1 if it is considered greater
77990 ** than it, or 0 if it is equal. i.e.
77991 **
77992 **     (*pLeft - *pRight)
77993 **
77994 ** A PLReader that is in the EOF condition is considered greater than
77995 ** any other. If neither argument is in EOF state, the return value of
77996 ** plrColumn() is used. If the plrColumn() values are equal, the
77997 ** comparison is on the basis of plrPosition().
77998 */
77999 static int plrCompare(PLReader *pLeft, PLReader *pRight){
78000   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
78001
78002   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
78003     return (plrAtEnd(pRight) ? -1 : 1);
78004   }
78005   if( plrColumn(pLeft)!=plrColumn(pRight) ){
78006     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
78007   }
78008   if( plrPosition(pLeft)!=plrPosition(pRight) ){
78009     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
78010   }
78011   return 0;
78012 }
78013
78014 /* We have two doclists with positions:  pLeft and pRight. Depending
78015 ** on the value of the nNear parameter, perform either a phrase
78016 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
78017 ** and write the results into pOut.
78018 **
78019 ** A phrase intersection means that two documents only match
78020 ** if pLeft.iPos+1==pRight.iPos.
78021 **
78022 ** A NEAR intersection means that two documents only match if 
78023 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
78024 **
78025 ** If a NEAR intersection is requested, then the nPhrase argument should
78026 ** be passed the number of tokens in the two operands to the NEAR operator
78027 ** combined. For example:
78028 **
78029 **       Query syntax               nPhrase
78030 **      ------------------------------------
78031 **       "A B C" NEAR "D E"         5
78032 **       A NEAR B                   2
78033 **
78034 ** iType controls the type of data written to pOut.  If iType is
78035 ** DL_POSITIONS, the positions are those from pRight.
78036 */
78037 static void docListPhraseMerge(
78038   const char *pLeft, int nLeft,
78039   const char *pRight, int nRight,
78040   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
78041   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
78042   DocListType iType,    /* Type of doclist to write to pOut */
78043   DataBuffer *pOut      /* Write the combined doclist here */
78044 ){
78045   DLReader left, right;
78046   DLWriter writer;
78047
78048   if( nLeft==0 || nRight==0 ) return;
78049
78050   assert( iType!=DL_POSITIONS_OFFSETS );
78051
78052   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
78053   dlrInit(&right, DL_POSITIONS, pRight, nRight);
78054   dlwInit(&writer, iType, pOut);
78055
78056   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
78057     if( dlrDocid(&left)<dlrDocid(&right) ){
78058       dlrStep(&left);
78059     }else if( dlrDocid(&right)<dlrDocid(&left) ){
78060       dlrStep(&right);
78061     }else{
78062       if( nNear==0 ){
78063         posListPhraseMerge(&left, &right, 0, 0, &writer);
78064       }else{
78065         /* This case occurs when two terms (simple terms or phrases) are
78066          * connected by a NEAR operator, span (nNear+1). i.e.
78067          *
78068          *     '"terrible company" NEAR widget'
78069          */
78070         DataBuffer one = {0, 0, 0};
78071         DataBuffer two = {0, 0, 0};
78072
78073         DLWriter dlwriter2;
78074         DLReader dr1 = {0, 0, 0, 0, 0}; 
78075         DLReader dr2 = {0, 0, 0, 0, 0};
78076
78077         dlwInit(&dlwriter2, iType, &one);
78078         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
78079         dlwInit(&dlwriter2, iType, &two);
78080         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
78081
78082         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
78083         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
78084
78085         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
78086           PLReader pr1 = {0};
78087           PLReader pr2 = {0};
78088
78089           PLWriter plwriter;
78090           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
78091
78092           if( one.nData ) plrInit(&pr1, &dr1);
78093           if( two.nData ) plrInit(&pr2, &dr2);
78094           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
78095             int iCompare = plrCompare(&pr1, &pr2);
78096             switch( iCompare ){
78097               case -1:
78098                 plwCopy(&plwriter, &pr1);
78099                 plrStep(&pr1);
78100                 break;
78101               case 1:
78102                 plwCopy(&plwriter, &pr2);
78103                 plrStep(&pr2);
78104                 break;
78105               case 0:
78106                 plwCopy(&plwriter, &pr1);
78107                 plrStep(&pr1);
78108                 plrStep(&pr2);
78109                 break;
78110             }
78111           }
78112           plwTerminate(&plwriter);
78113         }
78114         dataBufferDestroy(&one);
78115         dataBufferDestroy(&two);
78116       }
78117       dlrStep(&left);
78118       dlrStep(&right);
78119     }
78120   }
78121
78122   dlrDestroy(&left);
78123   dlrDestroy(&right);
78124   dlwDestroy(&writer);
78125 }
78126
78127 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
78128 ** Write the intersection of these two doclists into pOut as a
78129 ** DL_DOCIDS doclist.
78130 */
78131 static void docListAndMerge(
78132   const char *pLeft, int nLeft,
78133   const char *pRight, int nRight,
78134   DataBuffer *pOut      /* Write the combined doclist here */
78135 ){
78136   DLReader left, right;
78137   DLWriter writer;
78138
78139   if( nLeft==0 || nRight==0 ) return;
78140
78141   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
78142   dlrInit(&right, DL_DOCIDS, pRight, nRight);
78143   dlwInit(&writer, DL_DOCIDS, pOut);
78144
78145   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
78146     if( dlrDocid(&left)<dlrDocid(&right) ){
78147       dlrStep(&left);
78148     }else if( dlrDocid(&right)<dlrDocid(&left) ){
78149       dlrStep(&right);
78150     }else{
78151       dlwAdd(&writer, dlrDocid(&left));
78152       dlrStep(&left);
78153       dlrStep(&right);
78154     }
78155   }
78156
78157   dlrDestroy(&left);
78158   dlrDestroy(&right);
78159   dlwDestroy(&writer);
78160 }
78161
78162 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
78163 ** Write the union of these two doclists into pOut as a
78164 ** DL_DOCIDS doclist.
78165 */
78166 static void docListOrMerge(
78167   const char *pLeft, int nLeft,
78168   const char *pRight, int nRight,
78169   DataBuffer *pOut      /* Write the combined doclist here */
78170 ){
78171   DLReader left, right;
78172   DLWriter writer;
78173
78174   if( nLeft==0 ){
78175     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
78176     return;
78177   }
78178   if( nRight==0 ){
78179     dataBufferAppend(pOut, pLeft, nLeft);
78180     return;
78181   }
78182
78183   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
78184   dlrInit(&right, DL_DOCIDS, pRight, nRight);
78185   dlwInit(&writer, DL_DOCIDS, pOut);
78186
78187   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
78188     if( dlrAtEnd(&right) ){
78189       dlwAdd(&writer, dlrDocid(&left));
78190       dlrStep(&left);
78191     }else if( dlrAtEnd(&left) ){
78192       dlwAdd(&writer, dlrDocid(&right));
78193       dlrStep(&right);
78194     }else if( dlrDocid(&left)<dlrDocid(&right) ){
78195       dlwAdd(&writer, dlrDocid(&left));
78196       dlrStep(&left);
78197     }else if( dlrDocid(&right)<dlrDocid(&left) ){
78198       dlwAdd(&writer, dlrDocid(&right));
78199       dlrStep(&right);
78200     }else{
78201       dlwAdd(&writer, dlrDocid(&left));
78202       dlrStep(&left);
78203       dlrStep(&right);
78204     }
78205   }
78206
78207   dlrDestroy(&left);
78208   dlrDestroy(&right);
78209   dlwDestroy(&writer);
78210 }
78211
78212 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
78213 ** Write into pOut as DL_DOCIDS doclist containing all documents that
78214 ** occur in pLeft but not in pRight.
78215 */
78216 static void docListExceptMerge(
78217   const char *pLeft, int nLeft,
78218   const char *pRight, int nRight,
78219   DataBuffer *pOut      /* Write the combined doclist here */
78220 ){
78221   DLReader left, right;
78222   DLWriter writer;
78223
78224   if( nLeft==0 ) return;
78225   if( nRight==0 ){
78226     dataBufferAppend(pOut, pLeft, nLeft);
78227     return;
78228   }
78229
78230   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
78231   dlrInit(&right, DL_DOCIDS, pRight, nRight);
78232   dlwInit(&writer, DL_DOCIDS, pOut);
78233
78234   while( !dlrAtEnd(&left) ){
78235     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
78236       dlrStep(&right);
78237     }
78238     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
78239       dlwAdd(&writer, dlrDocid(&left));
78240     }
78241     dlrStep(&left);
78242   }
78243
78244   dlrDestroy(&left);
78245   dlrDestroy(&right);
78246   dlwDestroy(&writer);
78247 }
78248
78249 static char *string_dup_n(const char *s, int n){
78250   char *str = sqlite3_malloc(n + 1);
78251   memcpy(str, s, n);
78252   str[n] = '\0';
78253   return str;
78254 }
78255
78256 /* Duplicate a string; the caller must free() the returned string.
78257  * (We don't use strdup() since it is not part of the standard C library and
78258  * may not be available everywhere.) */
78259 static char *string_dup(const char *s){
78260   return string_dup_n(s, strlen(s));
78261 }
78262
78263 /* Format a string, replacing each occurrence of the % character with
78264  * zDb.zName.  This may be more convenient than sqlite_mprintf()
78265  * when one string is used repeatedly in a format string.
78266  * The caller must free() the returned string. */
78267 static char *string_format(const char *zFormat,
78268                            const char *zDb, const char *zName){
78269   const char *p;
78270   size_t len = 0;
78271   size_t nDb = strlen(zDb);
78272   size_t nName = strlen(zName);
78273   size_t nFullTableName = nDb+1+nName;
78274   char *result;
78275   char *r;
78276
78277   /* first compute length needed */
78278   for(p = zFormat ; *p ; ++p){
78279     len += (*p=='%' ? nFullTableName : 1);
78280   }
78281   len += 1;  /* for null terminator */
78282
78283   r = result = sqlite3_malloc(len);
78284   for(p = zFormat; *p; ++p){
78285     if( *p=='%' ){
78286       memcpy(r, zDb, nDb);
78287       r += nDb;
78288       *r++ = '.';
78289       memcpy(r, zName, nName);
78290       r += nName;
78291     } else {
78292       *r++ = *p;
78293     }
78294   }
78295   *r++ = '\0';
78296   assert( r == result + len );
78297   return result;
78298 }
78299
78300 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
78301                     const char *zFormat){
78302   char *zCommand = string_format(zFormat, zDb, zName);
78303   int rc;
78304   FTSTRACE(("FTS3 sql: %s\n", zCommand));
78305   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
78306   sqlite3_free(zCommand);
78307   return rc;
78308 }
78309
78310 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
78311                        sqlite3_stmt **ppStmt, const char *zFormat){
78312   char *zCommand = string_format(zFormat, zDb, zName);
78313   int rc;
78314   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
78315   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
78316   sqlite3_free(zCommand);
78317   return rc;
78318 }
78319
78320 /* end utility functions */
78321
78322 /* Forward reference */
78323 typedef struct fulltext_vtab fulltext_vtab;
78324
78325 /* A single term in a query is represented by an instances of
78326 ** the following structure. Each word which may match against
78327 ** document content is a term. Operators, like NEAR or OR, are
78328 ** not terms. Query terms are organized as a flat list stored
78329 ** in the Query.pTerms array.
78330 **
78331 ** If the QueryTerm.nPhrase variable is non-zero, then the QueryTerm
78332 ** is the first in a contiguous string of terms that are either part
78333 ** of the same phrase, or connected by the NEAR operator.
78334 **
78335 ** If the QueryTerm.nNear variable is non-zero, then the token is followed 
78336 ** by a NEAR operator with span set to (nNear-1). For example, the 
78337 ** following query:
78338 **
78339 ** The QueryTerm.iPhrase variable stores the index of the token within
78340 ** its phrase, indexed starting at 1, or 1 if the token is not part 
78341 ** of any phrase.
78342 **
78343 ** For example, the data structure used to represent the following query:
78344 **
78345 **     ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"'
78346 **
78347 ** is:
78348 **
78349 **     {nPhrase=4, iPhrase=1, nNear=6, pTerm="sqlite"},
78350 **     {nPhrase=0, iPhrase=1, nNear=3, pTerm="google"},
78351 **     {nPhrase=0, iPhrase=1, nNear=0, pTerm="search"},
78352 **     {nPhrase=0, iPhrase=2, nNear=0, pTerm="engine"},
78353 **
78354 ** compiling the FTS3 syntax to Query structures is done by the parseQuery()
78355 ** function.
78356 */
78357 typedef struct QueryTerm {
78358   short int nPhrase; /* How many following terms are part of the same phrase */
78359   short int iPhrase; /* This is the i-th term of a phrase. */
78360   short int iColumn; /* Column of the index that must match this term */
78361   signed char nNear; /* term followed by a NEAR operator with span=(nNear-1) */
78362   signed char isOr;  /* this term is preceded by "OR" */
78363   signed char isNot; /* this term is preceded by "-" */
78364   signed char isPrefix; /* this term is followed by "*" */
78365   char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
78366   int nTerm;         /* Number of bytes in pTerm[] */
78367 } QueryTerm;
78368
78369
78370 /* A query string is parsed into a Query structure.
78371  *
78372  * We could, in theory, allow query strings to be complicated
78373  * nested expressions with precedence determined by parentheses.
78374  * But none of the major search engines do this.  (Perhaps the
78375  * feeling is that an parenthesized expression is two complex of
78376  * an idea for the average user to grasp.)  Taking our lead from
78377  * the major search engines, we will allow queries to be a list
78378  * of terms (with an implied AND operator) or phrases in double-quotes,
78379  * with a single optional "-" before each non-phrase term to designate
78380  * negation and an optional OR connector.
78381  *
78382  * OR binds more tightly than the implied AND, which is what the
78383  * major search engines seem to do.  So, for example:
78384  * 
78385  *    [one two OR three]     ==>    one AND (two OR three)
78386  *    [one OR two three]     ==>    (one OR two) AND three
78387  *
78388  * A "-" before a term matches all entries that lack that term.
78389  * The "-" must occur immediately before the term with in intervening
78390  * space.  This is how the search engines do it.
78391  *
78392  * A NOT term cannot be the right-hand operand of an OR.  If this
78393  * occurs in the query string, the NOT is ignored:
78394  *
78395  *    [one OR -two]          ==>    one OR two
78396  *
78397  */
78398 typedef struct Query {
78399   fulltext_vtab *pFts;  /* The full text index */
78400   int nTerms;           /* Number of terms in the query */
78401   QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
78402   int nextIsOr;         /* Set the isOr flag on the next inserted term */
78403   int nextIsNear;       /* Set the isOr flag on the next inserted term */
78404   int nextColumn;       /* Next word parsed must be in this column */
78405   int dfltColumn;       /* The default column */
78406 } Query;
78407
78408
78409 /*
78410 ** An instance of the following structure keeps track of generated
78411 ** matching-word offset information and snippets.
78412 */
78413 typedef struct Snippet {
78414   int nMatch;     /* Total number of matches */
78415   int nAlloc;     /* Space allocated for aMatch[] */
78416   struct snippetMatch { /* One entry for each matching term */
78417     char snStatus;       /* Status flag for use while constructing snippets */
78418     short int iCol;      /* The column that contains the match */
78419     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
78420     int iToken;          /* The index of the matching document token */
78421     short int nByte;     /* Number of bytes in the term */
78422     int iStart;          /* The offset to the first character of the term */
78423   } *aMatch;      /* Points to space obtained from malloc */
78424   char *zOffset;  /* Text rendering of aMatch[] */
78425   int nOffset;    /* strlen(zOffset) */
78426   char *zSnippet; /* Snippet text */
78427   int nSnippet;   /* strlen(zSnippet) */
78428 } Snippet;
78429
78430
78431 typedef enum QueryType {
78432   QUERY_GENERIC,   /* table scan */
78433   QUERY_DOCID,     /* lookup by docid */
78434   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
78435 } QueryType;
78436
78437 typedef enum fulltext_statement {
78438   CONTENT_INSERT_STMT,
78439   CONTENT_SELECT_STMT,
78440   CONTENT_UPDATE_STMT,
78441   CONTENT_DELETE_STMT,
78442
78443   BLOCK_INSERT_STMT,
78444   BLOCK_SELECT_STMT,
78445   BLOCK_DELETE_STMT,
78446
78447   SEGDIR_MAX_INDEX_STMT,
78448   SEGDIR_SET_STMT,
78449   SEGDIR_SELECT_STMT,
78450   SEGDIR_SPAN_STMT,
78451   SEGDIR_DELETE_STMT,
78452   SEGDIR_SELECT_ALL_STMT,
78453
78454   MAX_STMT                     /* Always at end! */
78455 } fulltext_statement;
78456
78457 /* These must exactly match the enum above. */
78458 /* TODO(shess): Is there some risk that a statement will be used in two
78459 ** cursors at once, e.g.  if a query joins a virtual table to itself?
78460 ** If so perhaps we should move some of these to the cursor object.
78461 */
78462 static const char *const fulltext_zStatement[MAX_STMT] = {
78463   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
78464   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
78465   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
78466   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
78467
78468   /* BLOCK_INSERT */
78469   "insert into %_segments (blockid, block) values (null, ?)",
78470   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
78471   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
78472
78473   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
78474   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
78475   /* SEGDIR_SELECT */
78476   "select start_block, leaves_end_block, root from %_segdir "
78477   " where level = ? order by idx",
78478   /* SEGDIR_SPAN */
78479   "select min(start_block), max(end_block) from %_segdir "
78480   " where level = ? and start_block <> 0",
78481   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
78482   /* SEGDIR_SELECT_ALL */
78483   "select root, leaves_end_block from %_segdir order by level desc, idx",
78484 };
78485
78486 /*
78487 ** A connection to a fulltext index is an instance of the following
78488 ** structure.  The xCreate and xConnect methods create an instance
78489 ** of this structure and xDestroy and xDisconnect free that instance.
78490 ** All other methods receive a pointer to the structure as one of their
78491 ** arguments.
78492 */
78493 struct fulltext_vtab {
78494   sqlite3_vtab base;               /* Base class used by SQLite core */
78495   sqlite3 *db;                     /* The database connection */
78496   const char *zDb;                 /* logical database name */
78497   const char *zName;               /* virtual table name */
78498   int nColumn;                     /* number of columns in virtual table */
78499   char **azColumn;                 /* column names.  malloced */
78500   char **azContentColumn;          /* column names in content table; malloced */
78501   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
78502
78503   /* Precompiled statements which we keep as long as the table is
78504   ** open.
78505   */
78506   sqlite3_stmt *pFulltextStatements[MAX_STMT];
78507
78508   /* Precompiled statements used for segment merges.  We run a
78509   ** separate select across the leaf level of each tree being merged.
78510   */
78511   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
78512   /* The statement used to prepare pLeafSelectStmts. */
78513 #define LEAF_SELECT \
78514   "select block from %_segments where blockid between ? and ? order by blockid"
78515
78516   /* These buffer pending index updates during transactions.
78517   ** nPendingData estimates the memory size of the pending data.  It
78518   ** doesn't include the hash-bucket overhead, nor any malloc
78519   ** overhead.  When nPendingData exceeds kPendingThreshold, the
78520   ** buffer is flushed even before the transaction closes.
78521   ** pendingTerms stores the data, and is only valid when nPendingData
78522   ** is >=0 (nPendingData<0 means pendingTerms has not been
78523   ** initialized).  iPrevDocid is the last docid written, used to make
78524   ** certain we're inserting in sorted order.
78525   */
78526   int nPendingData;
78527 #define kPendingThreshold (1*1024*1024)
78528   sqlite_int64 iPrevDocid;
78529   fts3Hash pendingTerms;
78530 };
78531
78532 /*
78533 ** When the core wants to do a query, it create a cursor using a
78534 ** call to xOpen.  This structure is an instance of a cursor.  It
78535 ** is destroyed by xClose.
78536 */
78537 typedef struct fulltext_cursor {
78538   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
78539   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
78540   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
78541   int eof;                         /* True if at End Of Results */
78542   Query q;                         /* Parsed query string */
78543   Snippet snippet;                 /* Cached snippet for the current row */
78544   int iColumn;                     /* Column being searched */
78545   DataBuffer result;               /* Doclist results from fulltextQuery */
78546   DLReader reader;                 /* Result reader if result not empty */
78547 } fulltext_cursor;
78548
78549 static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
78550   return (fulltext_vtab *) c->base.pVtab;
78551 }
78552
78553 static const sqlite3_module fts3Module;   /* forward declaration */
78554
78555 /* Return a dynamically generated statement of the form
78556  *   insert into %_content (docid, ...) values (?, ...)
78557  */
78558 static const char *contentInsertStatement(fulltext_vtab *v){
78559   StringBuffer sb;
78560   int i;
78561
78562   initStringBuffer(&sb);
78563   append(&sb, "insert into %_content (docid, ");
78564   appendList(&sb, v->nColumn, v->azContentColumn);
78565   append(&sb, ") values (?");
78566   for(i=0; i<v->nColumn; ++i)
78567     append(&sb, ", ?");
78568   append(&sb, ")");
78569   return stringBufferData(&sb);
78570 }
78571
78572 /* Return a dynamically generated statement of the form
78573  *   select <content columns> from %_content where docid = ?
78574  */
78575 static const char *contentSelectStatement(fulltext_vtab *v){
78576   StringBuffer sb;
78577   initStringBuffer(&sb);
78578   append(&sb, "SELECT ");
78579   appendList(&sb, v->nColumn, v->azContentColumn);
78580   append(&sb, " FROM %_content WHERE docid = ?");
78581   return stringBufferData(&sb);
78582 }
78583
78584 /* Return a dynamically generated statement of the form
78585  *   update %_content set [col_0] = ?, [col_1] = ?, ...
78586  *                    where docid = ?
78587  */
78588 static const char *contentUpdateStatement(fulltext_vtab *v){
78589   StringBuffer sb;
78590   int i;
78591
78592   initStringBuffer(&sb);
78593   append(&sb, "update %_content set ");
78594   for(i=0; i<v->nColumn; ++i) {
78595     if( i>0 ){
78596       append(&sb, ", ");
78597     }
78598     append(&sb, v->azContentColumn[i]);
78599     append(&sb, " = ?");
78600   }
78601   append(&sb, " where docid = ?");
78602   return stringBufferData(&sb);
78603 }
78604
78605 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
78606 ** If the indicated statement has never been prepared, it is prepared
78607 ** and cached, otherwise the cached version is reset.
78608 */
78609 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
78610                              sqlite3_stmt **ppStmt){
78611   assert( iStmt<MAX_STMT );
78612   if( v->pFulltextStatements[iStmt]==NULL ){
78613     const char *zStmt;
78614     int rc;
78615     switch( iStmt ){
78616       case CONTENT_INSERT_STMT:
78617         zStmt = contentInsertStatement(v); break;
78618       case CONTENT_SELECT_STMT:
78619         zStmt = contentSelectStatement(v); break;
78620       case CONTENT_UPDATE_STMT:
78621         zStmt = contentUpdateStatement(v); break;
78622       default:
78623         zStmt = fulltext_zStatement[iStmt];
78624     }
78625     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
78626                          zStmt);
78627     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
78628     if( rc!=SQLITE_OK ) return rc;
78629   } else {
78630     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
78631     if( rc!=SQLITE_OK ) return rc;
78632   }
78633
78634   *ppStmt = v->pFulltextStatements[iStmt];
78635   return SQLITE_OK;
78636 }
78637
78638 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
78639 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
78640 ** where we expect no results.
78641 */
78642 static int sql_single_step(sqlite3_stmt *s){
78643   int rc = sqlite3_step(s);
78644   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
78645 }
78646
78647 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
78648 ** statements.
78649 */
78650 /* TODO(shess) Write version for generic statements and then share
78651 ** that between the cached-statement functions.
78652 */
78653 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
78654                                   sqlite3_stmt **ppStmt){
78655   assert( idx>=0 && idx<MERGE_COUNT );
78656   if( v->pLeafSelectStmts[idx]==NULL ){
78657     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
78658                          LEAF_SELECT);
78659     if( rc!=SQLITE_OK ) return rc;
78660   }else{
78661     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
78662     if( rc!=SQLITE_OK ) return rc;
78663   }
78664
78665   *ppStmt = v->pLeafSelectStmts[idx];
78666   return SQLITE_OK;
78667 }
78668
78669 /* insert into %_content (docid, ...) values ([docid], [pValues])
78670 ** If the docid contains SQL NULL, then a unique docid will be
78671 ** generated.
78672 */
78673 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
78674                           sqlite3_value **pValues){
78675   sqlite3_stmt *s;
78676   int i;
78677   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
78678   if( rc!=SQLITE_OK ) return rc;
78679
78680   rc = sqlite3_bind_value(s, 1, docid);
78681   if( rc!=SQLITE_OK ) return rc;
78682
78683   for(i=0; i<v->nColumn; ++i){
78684     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
78685     if( rc!=SQLITE_OK ) return rc;
78686   }
78687
78688   return sql_single_step(s);
78689 }
78690
78691 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
78692  *                  where docid = [iDocid] */
78693 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
78694                           sqlite_int64 iDocid){
78695   sqlite3_stmt *s;
78696   int i;
78697   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
78698   if( rc!=SQLITE_OK ) return rc;
78699
78700   for(i=0; i<v->nColumn; ++i){
78701     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
78702     if( rc!=SQLITE_OK ) return rc;
78703   }
78704
78705   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
78706   if( rc!=SQLITE_OK ) return rc;
78707
78708   return sql_single_step(s);
78709 }
78710
78711 static void freeStringArray(int nString, const char **pString){
78712   int i;
78713
78714   for (i=0 ; i < nString ; ++i) {
78715     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
78716   }
78717   sqlite3_free((void *) pString);
78718 }
78719
78720 /* select * from %_content where docid = [iDocid]
78721  * The caller must delete the returned array and all strings in it.
78722  * null fields will be NULL in the returned array.
78723  *
78724  * TODO: Perhaps we should return pointer/length strings here for consistency
78725  * with other code which uses pointer/length. */
78726 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
78727                           const char ***pValues){
78728   sqlite3_stmt *s;
78729   const char **values;
78730   int i;
78731   int rc;
78732
78733   *pValues = NULL;
78734
78735   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
78736   if( rc!=SQLITE_OK ) return rc;
78737
78738   rc = sqlite3_bind_int64(s, 1, iDocid);
78739   if( rc!=SQLITE_OK ) return rc;
78740
78741   rc = sqlite3_step(s);
78742   if( rc!=SQLITE_ROW ) return rc;
78743
78744   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
78745   for(i=0; i<v->nColumn; ++i){
78746     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
78747       values[i] = NULL;
78748     }else{
78749       values[i] = string_dup((char*)sqlite3_column_text(s, i));
78750     }
78751   }
78752
78753   /* We expect only one row.  We must execute another sqlite3_step()
78754    * to complete the iteration; otherwise the table will remain locked. */
78755   rc = sqlite3_step(s);
78756   if( rc==SQLITE_DONE ){
78757     *pValues = values;
78758     return SQLITE_OK;
78759   }
78760
78761   freeStringArray(v->nColumn, values);
78762   return rc;
78763 }
78764
78765 /* delete from %_content where docid = [iDocid ] */
78766 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
78767   sqlite3_stmt *s;
78768   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
78769   if( rc!=SQLITE_OK ) return rc;
78770
78771   rc = sqlite3_bind_int64(s, 1, iDocid);
78772   if( rc!=SQLITE_OK ) return rc;
78773
78774   return sql_single_step(s);
78775 }
78776
78777 /* insert into %_segments values ([pData])
78778 **   returns assigned blockid in *piBlockid
78779 */
78780 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
78781                         sqlite_int64 *piBlockid){
78782   sqlite3_stmt *s;
78783   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
78784   if( rc!=SQLITE_OK ) return rc;
78785
78786   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
78787   if( rc!=SQLITE_OK ) return rc;
78788
78789   rc = sqlite3_step(s);
78790   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
78791   if( rc!=SQLITE_DONE ) return rc;
78792
78793   /* blockid column is an alias for rowid. */
78794   *piBlockid = sqlite3_last_insert_rowid(v->db);
78795   return SQLITE_OK;
78796 }
78797
78798 /* delete from %_segments
78799 **   where blockid between [iStartBlockid] and [iEndBlockid]
78800 **
78801 ** Deletes the range of blocks, inclusive, used to delete the blocks
78802 ** which form a segment.
78803 */
78804 static int block_delete(fulltext_vtab *v,
78805                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
78806   sqlite3_stmt *s;
78807   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
78808   if( rc!=SQLITE_OK ) return rc;
78809
78810   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
78811   if( rc!=SQLITE_OK ) return rc;
78812
78813   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
78814   if( rc!=SQLITE_OK ) return rc;
78815
78816   return sql_single_step(s);
78817 }
78818
78819 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
78820 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
78821 ** iLevel.  Otherwise returns an error.
78822 */
78823 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
78824   sqlite3_stmt *s;
78825   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
78826   if( rc!=SQLITE_OK ) return rc;
78827
78828   rc = sqlite3_bind_int(s, 1, iLevel);
78829   if( rc!=SQLITE_OK ) return rc;
78830
78831   rc = sqlite3_step(s);
78832   /* Should always get at least one row due to how max() works. */
78833   if( rc==SQLITE_DONE ) return SQLITE_DONE;
78834   if( rc!=SQLITE_ROW ) return rc;
78835
78836   /* NULL means that there were no inputs to max(). */
78837   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
78838     rc = sqlite3_step(s);
78839     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
78840     return rc;
78841   }
78842
78843   *pidx = sqlite3_column_int(s, 0);
78844
78845   /* We expect only one row.  We must execute another sqlite3_step()
78846    * to complete the iteration; otherwise the table will remain locked. */
78847   rc = sqlite3_step(s);
78848   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
78849   if( rc!=SQLITE_DONE ) return rc;
78850   return SQLITE_ROW;
78851 }
78852
78853 /* insert into %_segdir values (
78854 **   [iLevel], [idx],
78855 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
78856 **   [pRootData]
78857 ** )
78858 */
78859 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
78860                       sqlite_int64 iStartBlockid,
78861                       sqlite_int64 iLeavesEndBlockid,
78862                       sqlite_int64 iEndBlockid,
78863                       const char *pRootData, int nRootData){
78864   sqlite3_stmt *s;
78865   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
78866   if( rc!=SQLITE_OK ) return rc;
78867
78868   rc = sqlite3_bind_int(s, 1, iLevel);
78869   if( rc!=SQLITE_OK ) return rc;
78870
78871   rc = sqlite3_bind_int(s, 2, idx);
78872   if( rc!=SQLITE_OK ) return rc;
78873
78874   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
78875   if( rc!=SQLITE_OK ) return rc;
78876
78877   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
78878   if( rc!=SQLITE_OK ) return rc;
78879
78880   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
78881   if( rc!=SQLITE_OK ) return rc;
78882
78883   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
78884   if( rc!=SQLITE_OK ) return rc;
78885
78886   return sql_single_step(s);
78887 }
78888
78889 /* Queries %_segdir for the block span of the segments in level
78890 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
78891 ** SQLITE_ROW if there are blocks, else an error.
78892 */
78893 static int segdir_span(fulltext_vtab *v, int iLevel,
78894                        sqlite_int64 *piStartBlockid,
78895                        sqlite_int64 *piEndBlockid){
78896   sqlite3_stmt *s;
78897   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
78898   if( rc!=SQLITE_OK ) return rc;
78899
78900   rc = sqlite3_bind_int(s, 1, iLevel);
78901   if( rc!=SQLITE_OK ) return rc;
78902
78903   rc = sqlite3_step(s);
78904   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
78905   if( rc!=SQLITE_ROW ) return rc;
78906
78907   /* This happens if all segments at this level are entirely inline. */
78908   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
78909     /* We expect only one row.  We must execute another sqlite3_step()
78910      * to complete the iteration; otherwise the table will remain locked. */
78911     int rc2 = sqlite3_step(s);
78912     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
78913     return rc2;
78914   }
78915
78916   *piStartBlockid = sqlite3_column_int64(s, 0);
78917   *piEndBlockid = sqlite3_column_int64(s, 1);
78918
78919   /* We expect only one row.  We must execute another sqlite3_step()
78920    * to complete the iteration; otherwise the table will remain locked. */
78921   rc = sqlite3_step(s);
78922   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
78923   if( rc!=SQLITE_DONE ) return rc;
78924   return SQLITE_ROW;
78925 }
78926
78927 /* Delete the segment blocks and segment directory records for all
78928 ** segments at iLevel.
78929 */
78930 static int segdir_delete(fulltext_vtab *v, int iLevel){
78931   sqlite3_stmt *s;
78932   sqlite_int64 iStartBlockid, iEndBlockid;
78933   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
78934   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
78935
78936   if( rc==SQLITE_ROW ){
78937     rc = block_delete(v, iStartBlockid, iEndBlockid);
78938     if( rc!=SQLITE_OK ) return rc;
78939   }
78940
78941   /* Delete the segment directory itself. */
78942   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
78943   if( rc!=SQLITE_OK ) return rc;
78944
78945   rc = sqlite3_bind_int64(s, 1, iLevel);
78946   if( rc!=SQLITE_OK ) return rc;
78947
78948   return sql_single_step(s);
78949 }
78950
78951 /* TODO(shess) clearPendingTerms() is far down the file because
78952 ** writeZeroSegment() is far down the file because LeafWriter is far
78953 ** down the file.  Consider refactoring the code to move the non-vtab
78954 ** code above the vtab code so that we don't need this forward
78955 ** reference.
78956 */
78957 static int clearPendingTerms(fulltext_vtab *v);
78958
78959 /*
78960 ** Free the memory used to contain a fulltext_vtab structure.
78961 */
78962 static void fulltext_vtab_destroy(fulltext_vtab *v){
78963   int iStmt, i;
78964
78965   FTSTRACE(("FTS3 Destroy %p\n", v));
78966   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
78967     if( v->pFulltextStatements[iStmt]!=NULL ){
78968       sqlite3_finalize(v->pFulltextStatements[iStmt]);
78969       v->pFulltextStatements[iStmt] = NULL;
78970     }
78971   }
78972
78973   for( i=0; i<MERGE_COUNT; i++ ){
78974     if( v->pLeafSelectStmts[i]!=NULL ){
78975       sqlite3_finalize(v->pLeafSelectStmts[i]);
78976       v->pLeafSelectStmts[i] = NULL;
78977     }
78978   }
78979
78980   if( v->pTokenizer!=NULL ){
78981     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
78982     v->pTokenizer = NULL;
78983   }
78984
78985   clearPendingTerms(v);
78986
78987   sqlite3_free(v->azColumn);
78988   for(i = 0; i < v->nColumn; ++i) {
78989     sqlite3_free(v->azContentColumn[i]);
78990   }
78991   sqlite3_free(v->azContentColumn);
78992   sqlite3_free(v);
78993 }
78994
78995 /*
78996 ** Token types for parsing the arguments to xConnect or xCreate.
78997 */
78998 #define TOKEN_EOF         0    /* End of file */
78999 #define TOKEN_SPACE       1    /* Any kind of whitespace */
79000 #define TOKEN_ID          2    /* An identifier */
79001 #define TOKEN_STRING      3    /* A string literal */
79002 #define TOKEN_PUNCT       4    /* A single punctuation character */
79003
79004 /*
79005 ** If X is a character that can be used in an identifier then
79006 ** ftsIdChar(X) will be true.  Otherwise it is false.
79007 **
79008 ** For ASCII, any character with the high-order bit set is
79009 ** allowed in an identifier.  For 7-bit characters, 
79010 ** isFtsIdChar[X] must be 1.
79011 **
79012 ** Ticket #1066.  the SQL standard does not allow '$' in the
79013 ** middle of identfiers.  But many SQL implementations do. 
79014 ** SQLite will allow '$' in identifiers for compatibility.
79015 ** But the feature is undocumented.
79016 */
79017 static const char isFtsIdChar[] = {
79018 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
79019     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
79020     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
79021     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
79022     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
79023     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
79024     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
79025 };
79026 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
79027
79028
79029 /*
79030 ** Return the length of the token that begins at z[0]. 
79031 ** Store the token type in *tokenType before returning.
79032 */
79033 static int ftsGetToken(const char *z, int *tokenType){
79034   int i, c;
79035   switch( *z ){
79036     case 0: {
79037       *tokenType = TOKEN_EOF;
79038       return 0;
79039     }
79040     case ' ': case '\t': case '\n': case '\f': case '\r': {
79041       for(i=1; safe_isspace(z[i]); i++){}
79042       *tokenType = TOKEN_SPACE;
79043       return i;
79044     }
79045     case '`':
79046     case '\'':
79047     case '"': {
79048       int delim = z[0];
79049       for(i=1; (c=z[i])!=0; i++){
79050         if( c==delim ){
79051           if( z[i+1]==delim ){
79052             i++;
79053           }else{
79054             break;
79055           }
79056         }
79057       }
79058       *tokenType = TOKEN_STRING;
79059       return i + (c!=0);
79060     }
79061     case '[': {
79062       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
79063       *tokenType = TOKEN_ID;
79064       return i;
79065     }
79066     default: {
79067       if( !ftsIdChar(*z) ){
79068         break;
79069       }
79070       for(i=1; ftsIdChar(z[i]); i++){}
79071       *tokenType = TOKEN_ID;
79072       return i;
79073     }
79074   }
79075   *tokenType = TOKEN_PUNCT;
79076   return 1;
79077 }
79078
79079 /*
79080 ** A token extracted from a string is an instance of the following
79081 ** structure.
79082 */
79083 typedef struct FtsToken {
79084   const char *z;       /* Pointer to token text.  Not '\000' terminated */
79085   short int n;         /* Length of the token text in bytes. */
79086 } FtsToken;
79087
79088 /*
79089 ** Given a input string (which is really one of the argv[] parameters
79090 ** passed into xConnect or xCreate) split the string up into tokens.
79091 ** Return an array of pointers to '\000' terminated strings, one string
79092 ** for each non-whitespace token.
79093 **
79094 ** The returned array is terminated by a single NULL pointer.
79095 **
79096 ** Space to hold the returned array is obtained from a single
79097 ** malloc and should be freed by passing the return value to free().
79098 ** The individual strings within the token list are all a part of
79099 ** the single memory allocation and will all be freed at once.
79100 */
79101 static char **tokenizeString(const char *z, int *pnToken){
79102   int nToken = 0;
79103   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
79104   int n = 1;
79105   int e, i;
79106   int totalSize = 0;
79107   char **azToken;
79108   char *zCopy;
79109   while( n>0 ){
79110     n = ftsGetToken(z, &e);
79111     if( e!=TOKEN_SPACE ){
79112       aToken[nToken].z = z;
79113       aToken[nToken].n = n;
79114       nToken++;
79115       totalSize += n+1;
79116     }
79117     z += n;
79118   }
79119   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
79120   zCopy = (char*)&azToken[nToken];
79121   nToken--;
79122   for(i=0; i<nToken; i++){
79123     azToken[i] = zCopy;
79124     n = aToken[i].n;
79125     memcpy(zCopy, aToken[i].z, n);
79126     zCopy[n] = 0;
79127     zCopy += n+1;
79128   }
79129   azToken[nToken] = 0;
79130   sqlite3_free(aToken);
79131   *pnToken = nToken;
79132   return azToken;
79133 }
79134
79135 /*
79136 ** Convert an SQL-style quoted string into a normal string by removing
79137 ** the quote characters.  The conversion is done in-place.  If the
79138 ** input does not begin with a quote character, then this routine
79139 ** is a no-op.
79140 **
79141 ** Examples:
79142 **
79143 **     "abc"   becomes   abc
79144 **     'xyz'   becomes   xyz
79145 **     [pqr]   becomes   pqr
79146 **     `mno`   becomes   mno
79147 */
79148 static void dequoteString(char *z){
79149   int quote;
79150   int i, j;
79151   if( z==0 ) return;
79152   quote = z[0];
79153   switch( quote ){
79154     case '\'':  break;
79155     case '"':   break;
79156     case '`':   break;                /* For MySQL compatibility */
79157     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
79158     default:    return;
79159   }
79160   for(i=1, j=0; z[i]; i++){
79161     if( z[i]==quote ){
79162       if( z[i+1]==quote ){
79163         z[j++] = quote;
79164         i++;
79165       }else{
79166         z[j++] = 0;
79167         break;
79168       }
79169     }else{
79170       z[j++] = z[i];
79171     }
79172   }
79173 }
79174
79175 /*
79176 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
79177 ** token and all punctuation tokens.  Remove the quotes from
79178 ** around string literal tokens.
79179 **
79180 ** Example:
79181 **
79182 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
79183 **     output:     chinese simplifed mixed
79184 **
79185 ** Another example:
79186 **
79187 **     input:      delimiters ( '[' , ']' , '...' )
79188 **     output:     [ ] ...
79189 */
79190 static void tokenListToIdList(char **azIn){
79191   int i, j;
79192   if( azIn ){
79193     for(i=0, j=-1; azIn[i]; i++){
79194       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
79195         dequoteString(azIn[i]);
79196         if( j>=0 ){
79197           azIn[j] = azIn[i];
79198         }
79199         j++;
79200       }
79201     }
79202     azIn[j] = 0;
79203   }
79204 }
79205
79206
79207 /*
79208 ** Find the first alphanumeric token in the string zIn.  Null-terminate
79209 ** this token.  Remove any quotation marks.  And return a pointer to
79210 ** the result.
79211 */
79212 static char *firstToken(char *zIn, char **pzTail){
79213   int n, ttype;
79214   while(1){
79215     n = ftsGetToken(zIn, &ttype);
79216     if( ttype==TOKEN_SPACE ){
79217       zIn += n;
79218     }else if( ttype==TOKEN_EOF ){
79219       *pzTail = zIn;
79220       return 0;
79221     }else{
79222       zIn[n] = 0;
79223       *pzTail = &zIn[1];
79224       dequoteString(zIn);
79225       return zIn;
79226     }
79227   }
79228   /*NOTREACHED*/
79229 }
79230
79231 /* Return true if...
79232 **
79233 **   *  s begins with the string t, ignoring case
79234 **   *  s is longer than t
79235 **   *  The first character of s beyond t is not a alphanumeric
79236 ** 
79237 ** Ignore leading space in *s.
79238 **
79239 ** To put it another way, return true if the first token of
79240 ** s[] is t[].
79241 */
79242 static int startsWith(const char *s, const char *t){
79243   while( safe_isspace(*s) ){ s++; }
79244   while( *t ){
79245     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
79246   }
79247   return *s!='_' && !safe_isalnum(*s);
79248 }
79249
79250 /*
79251 ** An instance of this structure defines the "spec" of a
79252 ** full text index.  This structure is populated by parseSpec
79253 ** and use by fulltextConnect and fulltextCreate.
79254 */
79255 typedef struct TableSpec {
79256   const char *zDb;         /* Logical database name */
79257   const char *zName;       /* Name of the full-text index */
79258   int nColumn;             /* Number of columns to be indexed */
79259   char **azColumn;         /* Original names of columns to be indexed */
79260   char **azContentColumn;  /* Column names for %_content */
79261   char **azTokenizer;      /* Name of tokenizer and its arguments */
79262 } TableSpec;
79263
79264 /*
79265 ** Reclaim all of the memory used by a TableSpec
79266 */
79267 static void clearTableSpec(TableSpec *p) {
79268   sqlite3_free(p->azColumn);
79269   sqlite3_free(p->azContentColumn);
79270   sqlite3_free(p->azTokenizer);
79271 }
79272
79273 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
79274  *
79275  * CREATE VIRTUAL TABLE email
79276  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
79277  *
79278  * We return parsed information in a TableSpec structure.
79279  * 
79280  */
79281 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
79282                      char**pzErr){
79283   int i, n;
79284   char *z, *zDummy;
79285   char **azArg;
79286   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
79287
79288   assert( argc>=3 );
79289   /* Current interface:
79290   ** argv[0] - module name
79291   ** argv[1] - database name
79292   ** argv[2] - table name
79293   ** argv[3..] - columns, optionally followed by tokenizer specification
79294   **             and snippet delimiters specification.
79295   */
79296
79297   /* Make a copy of the complete argv[][] array in a single allocation.
79298   ** The argv[][] array is read-only and transient.  We can write to the
79299   ** copy in order to modify things and the copy is persistent.
79300   */
79301   CLEAR(pSpec);
79302   for(i=n=0; i<argc; i++){
79303     n += strlen(argv[i]) + 1;
79304   }
79305   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
79306   if( azArg==0 ){
79307     return SQLITE_NOMEM;
79308   }
79309   z = (char*)&azArg[argc];
79310   for(i=0; i<argc; i++){
79311     azArg[i] = z;
79312     strcpy(z, argv[i]);
79313     z += strlen(z)+1;
79314   }
79315
79316   /* Identify the column names and the tokenizer and delimiter arguments
79317   ** in the argv[][] array.
79318   */
79319   pSpec->zDb = azArg[1];
79320   pSpec->zName = azArg[2];
79321   pSpec->nColumn = 0;
79322   pSpec->azColumn = azArg;
79323   zTokenizer = "tokenize simple";
79324   for(i=3; i<argc; ++i){
79325     if( startsWith(azArg[i],"tokenize") ){
79326       zTokenizer = azArg[i];
79327     }else{
79328       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
79329       pSpec->nColumn++;
79330     }
79331   }
79332   if( pSpec->nColumn==0 ){
79333     azArg[0] = "content";
79334     pSpec->nColumn = 1;
79335   }
79336
79337   /*
79338   ** Construct the list of content column names.
79339   **
79340   ** Each content column name will be of the form cNNAAAA
79341   ** where NN is the column number and AAAA is the sanitized
79342   ** column name.  "sanitized" means that special characters are
79343   ** converted to "_".  The cNN prefix guarantees that all column
79344   ** names are unique.
79345   **
79346   ** The AAAA suffix is not strictly necessary.  It is included
79347   ** for the convenience of people who might examine the generated
79348   ** %_content table and wonder what the columns are used for.
79349   */
79350   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
79351   if( pSpec->azContentColumn==0 ){
79352     clearTableSpec(pSpec);
79353     return SQLITE_NOMEM;
79354   }
79355   for(i=0; i<pSpec->nColumn; i++){
79356     char *p;
79357     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
79358     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
79359       if( !safe_isalnum(*p) ) *p = '_';
79360     }
79361   }
79362
79363   /*
79364   ** Parse the tokenizer specification string.
79365   */
79366   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
79367   tokenListToIdList(pSpec->azTokenizer);
79368
79369   return SQLITE_OK;
79370 }
79371
79372 /*
79373 ** Generate a CREATE TABLE statement that describes the schema of
79374 ** the virtual table.  Return a pointer to this schema string.
79375 **
79376 ** Space is obtained from sqlite3_mprintf() and should be freed
79377 ** using sqlite3_free().
79378 */
79379 static char *fulltextSchema(
79380   int nColumn,                  /* Number of columns */
79381   const char *const* azColumn,  /* List of columns */
79382   const char *zTableName        /* Name of the table */
79383 ){
79384   int i;
79385   char *zSchema, *zNext;
79386   const char *zSep = "(";
79387   zSchema = sqlite3_mprintf("CREATE TABLE x");
79388   for(i=0; i<nColumn; i++){
79389     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
79390     sqlite3_free(zSchema);
79391     zSchema = zNext;
79392     zSep = ",";
79393   }
79394   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
79395   sqlite3_free(zSchema);
79396   zSchema = zNext;
79397   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
79398   sqlite3_free(zSchema);
79399   return zNext;
79400 }
79401
79402 /*
79403 ** Build a new sqlite3_vtab structure that will describe the
79404 ** fulltext index defined by spec.
79405 */
79406 static int constructVtab(
79407   sqlite3 *db,              /* The SQLite database connection */
79408   fts3Hash *pHash,          /* Hash table containing tokenizers */
79409   TableSpec *spec,          /* Parsed spec information from parseSpec() */
79410   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
79411   char **pzErr              /* Write any error message here */
79412 ){
79413   int rc;
79414   int n;
79415   fulltext_vtab *v = 0;
79416   const sqlite3_tokenizer_module *m = NULL;
79417   char *schema;
79418
79419   char const *zTok;         /* Name of tokenizer to use for this fts table */
79420   int nTok;                 /* Length of zTok, including nul terminator */
79421
79422   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
79423   if( v==0 ) return SQLITE_NOMEM;
79424   CLEAR(v);
79425   /* sqlite will initialize v->base */
79426   v->db = db;
79427   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
79428   v->zName = spec->zName;   /* Freed when azColumn is freed */
79429   v->nColumn = spec->nColumn;
79430   v->azContentColumn = spec->azContentColumn;
79431   spec->azContentColumn = 0;
79432   v->azColumn = spec->azColumn;
79433   spec->azColumn = 0;
79434
79435   if( spec->azTokenizer==0 ){
79436     return SQLITE_NOMEM;
79437   }
79438
79439   zTok = spec->azTokenizer[0]; 
79440   if( !zTok ){
79441     zTok = "simple";
79442   }
79443   nTok = strlen(zTok)+1;
79444
79445   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
79446   if( !m ){
79447     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
79448     rc = SQLITE_ERROR;
79449     goto err;
79450   }
79451
79452   for(n=0; spec->azTokenizer[n]; n++){}
79453   if( n ){
79454     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
79455                     &v->pTokenizer);
79456   }else{
79457     rc = m->xCreate(0, 0, &v->pTokenizer);
79458   }
79459   if( rc!=SQLITE_OK ) goto err;
79460   v->pTokenizer->pModule = m;
79461
79462   /* TODO: verify the existence of backing tables foo_content, foo_term */
79463
79464   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
79465                           spec->zName);
79466   rc = sqlite3_declare_vtab(db, schema);
79467   sqlite3_free(schema);
79468   if( rc!=SQLITE_OK ) goto err;
79469
79470   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
79471
79472   /* Indicate that the buffer is not live. */
79473   v->nPendingData = -1;
79474
79475   *ppVTab = &v->base;
79476   FTSTRACE(("FTS3 Connect %p\n", v));
79477
79478   return rc;
79479
79480 err:
79481   fulltext_vtab_destroy(v);
79482   return rc;
79483 }
79484
79485 static int fulltextConnect(
79486   sqlite3 *db,
79487   void *pAux,
79488   int argc, const char *const*argv,
79489   sqlite3_vtab **ppVTab,
79490   char **pzErr
79491 ){
79492   TableSpec spec;
79493   int rc = parseSpec(&spec, argc, argv, pzErr);
79494   if( rc!=SQLITE_OK ) return rc;
79495
79496   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
79497   clearTableSpec(&spec);
79498   return rc;
79499 }
79500
79501 /* The %_content table holds the text of each document, with
79502 ** the docid column exposed as the SQLite rowid for the table.
79503 */
79504 /* TODO(shess) This comment needs elaboration to match the updated
79505 ** code.  Work it into the top-of-file comment at that time.
79506 */
79507 static int fulltextCreate(sqlite3 *db, void *pAux,
79508                           int argc, const char * const *argv,
79509                           sqlite3_vtab **ppVTab, char **pzErr){
79510   int rc;
79511   TableSpec spec;
79512   StringBuffer schema;
79513   FTSTRACE(("FTS3 Create\n"));
79514
79515   rc = parseSpec(&spec, argc, argv, pzErr);
79516   if( rc!=SQLITE_OK ) return rc;
79517
79518   initStringBuffer(&schema);
79519   append(&schema, "CREATE TABLE %_content(");
79520   append(&schema, "  docid INTEGER PRIMARY KEY,");
79521   appendList(&schema, spec.nColumn, spec.azContentColumn);
79522   append(&schema, ")");
79523   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
79524   stringBufferDestroy(&schema);
79525   if( rc!=SQLITE_OK ) goto out;
79526
79527   rc = sql_exec(db, spec.zDb, spec.zName,
79528                 "create table %_segments("
79529                 "  blockid INTEGER PRIMARY KEY,"
79530                 "  block blob"
79531                 ");"
79532                 );
79533   if( rc!=SQLITE_OK ) goto out;
79534
79535   rc = sql_exec(db, spec.zDb, spec.zName,
79536                 "create table %_segdir("
79537                 "  level integer,"
79538                 "  idx integer,"
79539                 "  start_block integer,"
79540                 "  leaves_end_block integer,"
79541                 "  end_block integer,"
79542                 "  root blob,"
79543                 "  primary key(level, idx)"
79544                 ");");
79545   if( rc!=SQLITE_OK ) goto out;
79546
79547   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
79548
79549 out:
79550   clearTableSpec(&spec);
79551   return rc;
79552 }
79553
79554 /* Decide how to handle an SQL query. */
79555 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
79556   fulltext_vtab *v = (fulltext_vtab *)pVTab;
79557   int i;
79558   FTSTRACE(("FTS3 BestIndex\n"));
79559
79560   for(i=0; i<pInfo->nConstraint; ++i){
79561     const struct sqlite3_index_constraint *pConstraint;
79562     pConstraint = &pInfo->aConstraint[i];
79563     if( pConstraint->usable ) {
79564       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
79565           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
79566         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
79567         FTSTRACE(("FTS3 QUERY_DOCID\n"));
79568       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
79569                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
79570         /* full-text search */
79571         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
79572         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
79573       } else continue;
79574
79575       pInfo->aConstraintUsage[i].argvIndex = 1;
79576       pInfo->aConstraintUsage[i].omit = 1;
79577
79578       /* An arbitrary value for now.
79579        * TODO: Perhaps docid matches should be considered cheaper than
79580        * full-text searches. */
79581       pInfo->estimatedCost = 1.0;   
79582
79583       return SQLITE_OK;
79584     }
79585   }
79586   pInfo->idxNum = QUERY_GENERIC;
79587   return SQLITE_OK;
79588 }
79589
79590 static int fulltextDisconnect(sqlite3_vtab *pVTab){
79591   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
79592   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
79593   return SQLITE_OK;
79594 }
79595
79596 static int fulltextDestroy(sqlite3_vtab *pVTab){
79597   fulltext_vtab *v = (fulltext_vtab *)pVTab;
79598   int rc;
79599
79600   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
79601   rc = sql_exec(v->db, v->zDb, v->zName,
79602                 "drop table if exists %_content;"
79603                 "drop table if exists %_segments;"
79604                 "drop table if exists %_segdir;"
79605                 );
79606   if( rc!=SQLITE_OK ) return rc;
79607
79608   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
79609   return SQLITE_OK;
79610 }
79611
79612 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
79613   fulltext_cursor *c;
79614
79615   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
79616   if( c ){
79617     memset(c, 0, sizeof(fulltext_cursor));
79618     /* sqlite will initialize c->base */
79619     *ppCursor = &c->base;
79620     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
79621     return SQLITE_OK;
79622   }else{
79623     return SQLITE_NOMEM;
79624   }
79625 }
79626
79627
79628 /* Free all of the dynamically allocated memory held by *q
79629 */
79630 static void queryClear(Query *q){
79631   int i;
79632   for(i = 0; i < q->nTerms; ++i){
79633     sqlite3_free(q->pTerms[i].pTerm);
79634   }
79635   sqlite3_free(q->pTerms);
79636   CLEAR(q);
79637 }
79638
79639 /* Free all of the dynamically allocated memory held by the
79640 ** Snippet
79641 */
79642 static void snippetClear(Snippet *p){
79643   sqlite3_free(p->aMatch);
79644   sqlite3_free(p->zOffset);
79645   sqlite3_free(p->zSnippet);
79646   CLEAR(p);
79647 }
79648 /*
79649 ** Append a single entry to the p->aMatch[] log.
79650 */
79651 static void snippetAppendMatch(
79652   Snippet *p,               /* Append the entry to this snippet */
79653   int iCol, int iTerm,      /* The column and query term */
79654   int iToken,               /* Matching token in document */
79655   int iStart, int nByte     /* Offset and size of the match */
79656 ){
79657   int i;
79658   struct snippetMatch *pMatch;
79659   if( p->nMatch+1>=p->nAlloc ){
79660     p->nAlloc = p->nAlloc*2 + 10;
79661     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
79662     if( p->aMatch==0 ){
79663       p->nMatch = 0;
79664       p->nAlloc = 0;
79665       return;
79666     }
79667   }
79668   i = p->nMatch++;
79669   pMatch = &p->aMatch[i];
79670   pMatch->iCol = iCol;
79671   pMatch->iTerm = iTerm;
79672   pMatch->iToken = iToken;
79673   pMatch->iStart = iStart;
79674   pMatch->nByte = nByte;
79675 }
79676
79677 /*
79678 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
79679 */
79680 #define FTS3_ROTOR_SZ   (32)
79681 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
79682
79683 /*
79684 ** Add entries to pSnippet->aMatch[] for every match that occurs against
79685 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
79686 */
79687 static void snippetOffsetsOfColumn(
79688   Query *pQuery,
79689   Snippet *pSnippet,
79690   int iColumn,
79691   const char *zDoc,
79692   int nDoc
79693 ){
79694   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
79695   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
79696   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
79697   fulltext_vtab *pVtab;                /* The full text index */
79698   int nColumn;                         /* Number of columns in the index */
79699   const QueryTerm *aTerm;              /* Query string terms */
79700   int nTerm;                           /* Number of query string terms */  
79701   int i, j;                            /* Loop counters */
79702   int rc;                              /* Return code */
79703   unsigned int match, prevMatch;       /* Phrase search bitmasks */
79704   const char *zToken;                  /* Next token from the tokenizer */
79705   int nToken;                          /* Size of zToken */
79706   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
79707
79708   /* The following variables keep a circular buffer of the last
79709   ** few tokens */
79710   unsigned int iRotor = 0;             /* Index of current token */
79711   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
79712   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
79713
79714   pVtab = pQuery->pFts;
79715   nColumn = pVtab->nColumn;
79716   pTokenizer = pVtab->pTokenizer;
79717   pTModule = pTokenizer->pModule;
79718   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
79719   if( rc ) return;
79720   pTCursor->pTokenizer = pTokenizer;
79721   aTerm = pQuery->pTerms;
79722   nTerm = pQuery->nTerms;
79723   if( nTerm>=FTS3_ROTOR_SZ ){
79724     nTerm = FTS3_ROTOR_SZ - 1;
79725   }
79726   prevMatch = 0;
79727   while(1){
79728     rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
79729     if( rc ) break;
79730     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
79731     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
79732     match = 0;
79733     for(i=0; i<nTerm; i++){
79734       int iCol;
79735       iCol = aTerm[i].iColumn;
79736       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
79737       if( aTerm[i].nTerm>nToken ) continue;
79738       if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
79739       assert( aTerm[i].nTerm<=nToken );
79740       if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
79741       if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
79742       match |= 1<<i;
79743       if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
79744         for(j=aTerm[i].iPhrase-1; j>=0; j--){
79745           int k = (iRotor-j) & FTS3_ROTOR_MASK;
79746           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
79747                 iRotorBegin[k], iRotorLen[k]);
79748         }
79749       }
79750     }
79751     prevMatch = match<<1;
79752     iRotor++;
79753   }
79754   pTModule->xClose(pTCursor);  
79755 }
79756
79757 /*
79758 ** Remove entries from the pSnippet structure to account for the NEAR
79759 ** operator. When this is called, pSnippet contains the list of token 
79760 ** offsets produced by treating all NEAR operators as AND operators.
79761 ** This function removes any entries that should not be present after
79762 ** accounting for the NEAR restriction. For example, if the queried
79763 ** document is:
79764 **
79765 **     "A B C D E A"
79766 **
79767 ** and the query is:
79768 ** 
79769 **     A NEAR/0 E
79770 **
79771 ** then when this function is called the Snippet contains token offsets
79772 ** 0, 4 and 5. This function removes the "0" entry (because the first A
79773 ** is not near enough to an E).
79774 */
79775 static void trimSnippetOffsetsForNear(Query *pQuery, Snippet *pSnippet){
79776   int ii;
79777   int iDir = 1;
79778
79779   while(iDir>-2) {
79780     assert( iDir==1 || iDir==-1 );
79781     for(ii=0; ii<pSnippet->nMatch; ii++){
79782       int jj;
79783       int nNear;
79784       struct snippetMatch *pMatch = &pSnippet->aMatch[ii];
79785       QueryTerm *pQueryTerm = &pQuery->pTerms[pMatch->iTerm];
79786
79787       if( (pMatch->iTerm+iDir)<0 
79788        || (pMatch->iTerm+iDir)>=pQuery->nTerms
79789       ){
79790         continue;
79791       }
79792      
79793       nNear = pQueryTerm->nNear;
79794       if( iDir<0 ){
79795         nNear = pQueryTerm[-1].nNear;
79796       }
79797   
79798       if( pMatch->iTerm>=0 && nNear ){
79799         int isOk = 0;
79800         int iNextTerm = pMatch->iTerm+iDir;
79801         int iPrevTerm = iNextTerm;
79802
79803         int iEndToken;
79804         int iStartToken;
79805
79806         if( iDir<0 ){
79807           int nPhrase = 1;
79808           iStartToken = pMatch->iToken;
79809           while( (pMatch->iTerm+nPhrase)<pQuery->nTerms 
79810               && pQuery->pTerms[pMatch->iTerm+nPhrase].iPhrase>1 
79811           ){
79812             nPhrase++;
79813           }
79814           iEndToken = iStartToken + nPhrase - 1;
79815         }else{
79816           iEndToken   = pMatch->iToken;
79817           iStartToken = pMatch->iToken+1-pQueryTerm->iPhrase;
79818         }
79819
79820         while( pQuery->pTerms[iNextTerm].iPhrase>1 ){
79821           iNextTerm--;
79822         }
79823         while( (iPrevTerm+1)<pQuery->nTerms && 
79824                pQuery->pTerms[iPrevTerm+1].iPhrase>1 
79825         ){
79826           iPrevTerm++;
79827         }
79828   
79829         for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
79830           struct snippetMatch *p = &pSnippet->aMatch[jj];
79831           if( p->iCol==pMatch->iCol && ((
79832                p->iTerm==iNextTerm && 
79833                p->iToken>iEndToken && 
79834                p->iToken<=iEndToken+nNear
79835           ) || (
79836                p->iTerm==iPrevTerm && 
79837                p->iToken<iStartToken && 
79838                p->iToken>=iStartToken-nNear
79839           ))){
79840             isOk = 1;
79841           }
79842         }
79843         if( !isOk ){
79844           for(jj=1-pQueryTerm->iPhrase; jj<=0; jj++){
79845             pMatch[jj].iTerm = -1;
79846           }
79847           ii = -1;
79848           iDir = 1;
79849         }
79850       }
79851     }
79852     iDir -= 2;
79853   }
79854 }
79855
79856 /*
79857 ** Compute all offsets for the current row of the query.  
79858 ** If the offsets have already been computed, this routine is a no-op.
79859 */
79860 static void snippetAllOffsets(fulltext_cursor *p){
79861   int nColumn;
79862   int iColumn, i;
79863   int iFirst, iLast;
79864   fulltext_vtab *pFts;
79865
79866   if( p->snippet.nMatch ) return;
79867   if( p->q.nTerms==0 ) return;
79868   pFts = p->q.pFts;
79869   nColumn = pFts->nColumn;
79870   iColumn = (p->iCursorType - QUERY_FULLTEXT);
79871   if( iColumn<0 || iColumn>=nColumn ){
79872     iFirst = 0;
79873     iLast = nColumn-1;
79874   }else{
79875     iFirst = iColumn;
79876     iLast = iColumn;
79877   }
79878   for(i=iFirst; i<=iLast; i++){
79879     const char *zDoc;
79880     int nDoc;
79881     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
79882     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
79883     snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
79884   }
79885
79886   trimSnippetOffsetsForNear(&p->q, &p->snippet);
79887 }
79888
79889 /*
79890 ** Convert the information in the aMatch[] array of the snippet
79891 ** into the string zOffset[0..nOffset-1].
79892 */
79893 static void snippetOffsetText(Snippet *p){
79894   int i;
79895   int cnt = 0;
79896   StringBuffer sb;
79897   char zBuf[200];
79898   if( p->zOffset ) return;
79899   initStringBuffer(&sb);
79900   for(i=0; i<p->nMatch; i++){
79901     struct snippetMatch *pMatch = &p->aMatch[i];
79902     if( pMatch->iTerm>=0 ){
79903       /* If snippetMatch.iTerm is less than 0, then the match was 
79904       ** discarded as part of processing the NEAR operator (see the 
79905       ** trimSnippetOffsetsForNear() function for details). Ignore 
79906       ** it in this case
79907       */
79908       zBuf[0] = ' ';
79909       sprintf(&zBuf[cnt>0], "%d %d %d %d", pMatch->iCol,
79910           pMatch->iTerm, pMatch->iStart, pMatch->nByte);
79911       append(&sb, zBuf);
79912       cnt++;
79913     }
79914   }
79915   p->zOffset = stringBufferData(&sb);
79916   p->nOffset = stringBufferLength(&sb);
79917 }
79918
79919 /*
79920 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
79921 ** of matching words some of which might be in zDoc.  zDoc is column
79922 ** number iCol.
79923 **
79924 ** iBreak is suggested spot in zDoc where we could begin or end an
79925 ** excerpt.  Return a value similar to iBreak but possibly adjusted
79926 ** to be a little left or right so that the break point is better.
79927 */
79928 static int wordBoundary(
79929   int iBreak,                   /* The suggested break point */
79930   const char *zDoc,             /* Document text */
79931   int nDoc,                     /* Number of bytes in zDoc[] */
79932   struct snippetMatch *aMatch,  /* Matching words */
79933   int nMatch,                   /* Number of entries in aMatch[] */
79934   int iCol                      /* The column number for zDoc[] */
79935 ){
79936   int i;
79937   if( iBreak<=10 ){
79938     return 0;
79939   }
79940   if( iBreak>=nDoc-10 ){
79941     return nDoc;
79942   }
79943   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
79944   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
79945   if( i<nMatch ){
79946     if( aMatch[i].iStart<iBreak+10 ){
79947       return aMatch[i].iStart;
79948     }
79949     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
79950       return aMatch[i-1].iStart;
79951     }
79952   }
79953   for(i=1; i<=10; i++){
79954     if( safe_isspace(zDoc[iBreak-i]) ){
79955       return iBreak - i + 1;
79956     }
79957     if( safe_isspace(zDoc[iBreak+i]) ){
79958       return iBreak + i + 1;
79959     }
79960   }
79961   return iBreak;
79962 }
79963
79964
79965
79966 /*
79967 ** Allowed values for Snippet.aMatch[].snStatus
79968 */
79969 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
79970 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
79971
79972 /*
79973 ** Generate the text of a snippet.
79974 */
79975 static void snippetText(
79976   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
79977   const char *zStartMark,     /* Markup to appear before each match */
79978   const char *zEndMark,       /* Markup to appear after each match */
79979   const char *zEllipsis       /* Ellipsis mark */
79980 ){
79981   int i, j;
79982   struct snippetMatch *aMatch;
79983   int nMatch;
79984   int nDesired;
79985   StringBuffer sb;
79986   int tailCol;
79987   int tailOffset;
79988   int iCol;
79989   int nDoc;
79990   const char *zDoc;
79991   int iStart, iEnd;
79992   int tailEllipsis = 0;
79993   int iMatch;
79994   
79995
79996   sqlite3_free(pCursor->snippet.zSnippet);
79997   pCursor->snippet.zSnippet = 0;
79998   aMatch = pCursor->snippet.aMatch;
79999   nMatch = pCursor->snippet.nMatch;
80000   initStringBuffer(&sb);
80001
80002   for(i=0; i<nMatch; i++){
80003     aMatch[i].snStatus = SNIPPET_IGNORE;
80004   }
80005   nDesired = 0;
80006   for(i=0; i<pCursor->q.nTerms; i++){
80007     for(j=0; j<nMatch; j++){
80008       if( aMatch[j].iTerm==i ){
80009         aMatch[j].snStatus = SNIPPET_DESIRED;
80010         nDesired++;
80011         break;
80012       }
80013     }
80014   }
80015
80016   iMatch = 0;
80017   tailCol = -1;
80018   tailOffset = 0;
80019   for(i=0; i<nMatch && nDesired>0; i++){
80020     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
80021     nDesired--;
80022     iCol = aMatch[i].iCol;
80023     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
80024     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
80025     iStart = aMatch[i].iStart - 40;
80026     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
80027     if( iStart<=10 ){
80028       iStart = 0;
80029     }
80030     if( iCol==tailCol && iStart<=tailOffset+20 ){
80031       iStart = tailOffset;
80032     }
80033     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
80034       trimWhiteSpace(&sb);
80035       appendWhiteSpace(&sb);
80036       append(&sb, zEllipsis);
80037       appendWhiteSpace(&sb);
80038     }
80039     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
80040     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
80041     if( iEnd>=nDoc-10 ){
80042       iEnd = nDoc;
80043       tailEllipsis = 0;
80044     }else{
80045       tailEllipsis = 1;
80046     }
80047     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
80048     while( iStart<iEnd ){
80049       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
80050              && aMatch[iMatch].iCol<=iCol ){
80051         iMatch++;
80052       }
80053       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
80054              && aMatch[iMatch].iCol==iCol ){
80055         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
80056         iStart = aMatch[iMatch].iStart;
80057         append(&sb, zStartMark);
80058         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
80059         append(&sb, zEndMark);
80060         iStart += aMatch[iMatch].nByte;
80061         for(j=iMatch+1; j<nMatch; j++){
80062           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
80063               && aMatch[j].snStatus==SNIPPET_DESIRED ){
80064             nDesired--;
80065             aMatch[j].snStatus = SNIPPET_IGNORE;
80066           }
80067         }
80068       }else{
80069         nappend(&sb, &zDoc[iStart], iEnd - iStart);
80070         iStart = iEnd;
80071       }
80072     }
80073     tailCol = iCol;
80074     tailOffset = iEnd;
80075   }
80076   trimWhiteSpace(&sb);
80077   if( tailEllipsis ){
80078     appendWhiteSpace(&sb);
80079     append(&sb, zEllipsis);
80080   }
80081   pCursor->snippet.zSnippet = stringBufferData(&sb);
80082   pCursor->snippet.nSnippet = stringBufferLength(&sb);
80083 }
80084
80085
80086 /*
80087 ** Close the cursor.  For additional information see the documentation
80088 ** on the xClose method of the virtual table interface.
80089 */
80090 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
80091   fulltext_cursor *c = (fulltext_cursor *) pCursor;
80092   FTSTRACE(("FTS3 Close %p\n", c));
80093   sqlite3_finalize(c->pStmt);
80094   queryClear(&c->q);
80095   snippetClear(&c->snippet);
80096   if( c->result.nData!=0 ) dlrDestroy(&c->reader);
80097   dataBufferDestroy(&c->result);
80098   sqlite3_free(c);
80099   return SQLITE_OK;
80100 }
80101
80102 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
80103   fulltext_cursor *c = (fulltext_cursor *) pCursor;
80104   int rc;
80105
80106   FTSTRACE(("FTS3 Next %p\n", pCursor));
80107   snippetClear(&c->snippet);
80108   if( c->iCursorType < QUERY_FULLTEXT ){
80109     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
80110     rc = sqlite3_step(c->pStmt);
80111     switch( rc ){
80112       case SQLITE_ROW:
80113         c->eof = 0;
80114         return SQLITE_OK;
80115       case SQLITE_DONE:
80116         c->eof = 1;
80117         return SQLITE_OK;
80118       default:
80119         c->eof = 1;
80120         return rc;
80121     }
80122   } else {  /* full-text query */
80123     rc = sqlite3_reset(c->pStmt);
80124     if( rc!=SQLITE_OK ) return rc;
80125
80126     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
80127       c->eof = 1;
80128       return SQLITE_OK;
80129     }
80130     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
80131     dlrStep(&c->reader);
80132     if( rc!=SQLITE_OK ) return rc;
80133     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
80134     rc = sqlite3_step(c->pStmt);
80135     if( rc==SQLITE_ROW ){   /* the case we expect */
80136       c->eof = 0;
80137       return SQLITE_OK;
80138     }
80139     /* an error occurred; abort */
80140     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
80141   }
80142 }
80143
80144
80145 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
80146 ** another file, term_select() could be pushed above
80147 ** docListOfTerm().
80148 */
80149 static int termSelect(fulltext_vtab *v, int iColumn,
80150                       const char *pTerm, int nTerm, int isPrefix,
80151                       DocListType iType, DataBuffer *out);
80152
80153 /* Return a DocList corresponding to the query term *pTerm.  If *pTerm
80154 ** is the first term of a phrase query, go ahead and evaluate the phrase
80155 ** query and return the doclist for the entire phrase query.
80156 **
80157 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
80158 ** overwritten.
80159 */
80160 static int docListOfTerm(
80161   fulltext_vtab *v,    /* The full text index */
80162   int iColumn,         /* column to restrict to.  No restriction if >=nColumn */
80163   QueryTerm *pQTerm,   /* Term we are looking for, or 1st term of a phrase */
80164   DataBuffer *pResult  /* Write the result here */
80165 ){
80166   DataBuffer left, right, new;
80167   int i, rc;
80168
80169   /* No phrase search if no position info. */
80170   assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
80171
80172   /* This code should never be called with buffered updates. */
80173   assert( v->nPendingData<0 );
80174
80175   dataBufferInit(&left, 0);
80176   rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
80177                   (0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS), &left);
80178   if( rc ) return rc;
80179   for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
80180     /* If this token is connected to the next by a NEAR operator, and
80181     ** the next token is the start of a phrase, then set nPhraseRight
80182     ** to the number of tokens in the phrase. Otherwise leave it at 1.
80183     */
80184     int nPhraseRight = 1;
80185     while( (i+nPhraseRight)<=pQTerm->nPhrase 
80186         && pQTerm[i+nPhraseRight].nNear==0 
80187     ){
80188       nPhraseRight++;
80189     }
80190
80191     dataBufferInit(&right, 0);
80192     rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
80193                     pQTerm[i].isPrefix, DL_POSITIONS, &right);
80194     if( rc ){
80195       dataBufferDestroy(&left);
80196       return rc;
80197     }
80198     dataBufferInit(&new, 0);
80199     docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
80200                        pQTerm[i-1].nNear, pQTerm[i-1].iPhrase + nPhraseRight,
80201                        ((i<pQTerm->nPhrase) ? DL_POSITIONS : DL_DOCIDS),
80202                        &new);
80203     dataBufferDestroy(&left);
80204     dataBufferDestroy(&right);
80205     left = new;
80206   }
80207   *pResult = left;
80208   return SQLITE_OK;
80209 }
80210
80211 /* Add a new term pTerm[0..nTerm-1] to the query *q.
80212 */
80213 static void queryAdd(Query *q, const char *pTerm, int nTerm){
80214   QueryTerm *t;
80215   ++q->nTerms;
80216   q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
80217   if( q->pTerms==0 ){
80218     q->nTerms = 0;
80219     return;
80220   }
80221   t = &q->pTerms[q->nTerms - 1];
80222   CLEAR(t);
80223   t->pTerm = sqlite3_malloc(nTerm+1);
80224   memcpy(t->pTerm, pTerm, nTerm);
80225   t->pTerm[nTerm] = 0;
80226   t->nTerm = nTerm;
80227   t->isOr = q->nextIsOr;
80228   t->isPrefix = 0;
80229   q->nextIsOr = 0;
80230   t->iColumn = q->nextColumn;
80231   q->nextColumn = q->dfltColumn;
80232 }
80233
80234 /*
80235 ** Check to see if the string zToken[0...nToken-1] matches any
80236 ** column name in the virtual table.   If it does,
80237 ** return the zero-indexed column number.  If not, return -1.
80238 */
80239 static int checkColumnSpecifier(
80240   fulltext_vtab *pVtab,    /* The virtual table */
80241   const char *zToken,      /* Text of the token */
80242   int nToken               /* Number of characters in the token */
80243 ){
80244   int i;
80245   for(i=0; i<pVtab->nColumn; i++){
80246     if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
80247         && pVtab->azColumn[i][nToken]==0 ){
80248       return i;
80249     }
80250   }
80251   return -1;
80252 }
80253
80254 /*
80255 ** Parse the text at pSegment[0..nSegment-1].  Add additional terms
80256 ** to the query being assemblied in pQuery.
80257 **
80258 ** inPhrase is true if pSegment[0..nSegement-1] is contained within
80259 ** double-quotes.  If inPhrase is true, then the first term
80260 ** is marked with the number of terms in the phrase less one and
80261 ** OR and "-" syntax is ignored.  If inPhrase is false, then every
80262 ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
80263 */
80264 static int tokenizeSegment(
80265   sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
80266   const char *pSegment, int nSegment,     /* Query expression being parsed */
80267   int inPhrase,                           /* True if within "..." */
80268   Query *pQuery                           /* Append results here */
80269 ){
80270   const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
80271   sqlite3_tokenizer_cursor *pCursor;
80272   int firstIndex = pQuery->nTerms;
80273   int iCol;
80274   int nTerm = 1;
80275   
80276   int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
80277   if( rc!=SQLITE_OK ) return rc;
80278   pCursor->pTokenizer = pTokenizer;
80279
80280   while( 1 ){
80281     const char *pToken;
80282     int nToken, iBegin, iEnd, iPos;
80283
80284     rc = pModule->xNext(pCursor,
80285                         &pToken, &nToken,
80286                         &iBegin, &iEnd, &iPos);
80287     if( rc!=SQLITE_OK ) break;
80288     if( !inPhrase &&
80289         pSegment[iEnd]==':' &&
80290          (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){
80291       pQuery->nextColumn = iCol;
80292       continue;
80293     }
80294     if( !inPhrase && pQuery->nTerms>0 && nToken==2 
80295      && pSegment[iBegin+0]=='O'
80296      && pSegment[iBegin+1]=='R' 
80297     ){
80298       pQuery->nextIsOr = 1;
80299       continue;
80300     }
80301     if( !inPhrase && pQuery->nTerms>0 && !pQuery->nextIsOr && nToken==4 
80302       && pSegment[iBegin+0]=='N' 
80303       && pSegment[iBegin+1]=='E' 
80304       && pSegment[iBegin+2]=='A' 
80305       && pSegment[iBegin+3]=='R' 
80306     ){
80307       QueryTerm *pTerm = &pQuery->pTerms[pQuery->nTerms-1];
80308       if( (iBegin+6)<nSegment 
80309        && pSegment[iBegin+4] == '/'
80310        && pSegment[iBegin+5]>='0' && pSegment[iBegin+5]<='9'
80311       ){
80312         pTerm->nNear = (pSegment[iBegin+5] - '0');
80313         nToken += 2;
80314         if( pSegment[iBegin+6]>='0' && pSegment[iBegin+6]<=9 ){
80315           pTerm->nNear = pTerm->nNear * 10 + (pSegment[iBegin+6] - '0');
80316           iEnd++;
80317         }
80318         pModule->xNext(pCursor, &pToken, &nToken, &iBegin, &iEnd, &iPos);
80319       } else {
80320         pTerm->nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
80321       }
80322       pTerm->nNear++;
80323       continue;
80324     }
80325
80326     queryAdd(pQuery, pToken, nToken);
80327     if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){
80328       pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
80329     }
80330     if( iEnd<nSegment && pSegment[iEnd]=='*' ){
80331       pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
80332     }
80333     pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
80334     if( inPhrase ){
80335       nTerm++;
80336     }
80337   }
80338
80339   if( inPhrase && pQuery->nTerms>firstIndex ){
80340     pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
80341   }
80342
80343   return pModule->xClose(pCursor);
80344 }
80345
80346 /* Parse a query string, yielding a Query object pQuery.
80347 **
80348 ** The calling function will need to queryClear() to clean up
80349 ** the dynamically allocated memory held by pQuery.
80350 */
80351 static int parseQuery(
80352   fulltext_vtab *v,        /* The fulltext index */
80353   const char *zInput,      /* Input text of the query string */
80354   int nInput,              /* Size of the input text */
80355   int dfltColumn,          /* Default column of the index to match against */
80356   Query *pQuery            /* Write the parse results here. */
80357 ){
80358   int iInput, inPhrase = 0;
80359   int ii;
80360   QueryTerm *aTerm;
80361
80362   if( zInput==0 ) nInput = 0;
80363   if( nInput<0 ) nInput = strlen(zInput);
80364   pQuery->nTerms = 0;
80365   pQuery->pTerms = NULL;
80366   pQuery->nextIsOr = 0;
80367   pQuery->nextColumn = dfltColumn;
80368   pQuery->dfltColumn = dfltColumn;
80369   pQuery->pFts = v;
80370
80371   for(iInput=0; iInput<nInput; ++iInput){
80372     int i;
80373     for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
80374     if( i>iInput ){
80375       tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
80376                        pQuery);
80377     }
80378     iInput = i;
80379     if( i<nInput ){
80380       assert( zInput[i]=='"' );
80381       inPhrase = !inPhrase;
80382     }
80383   }
80384
80385   if( inPhrase ){
80386     /* unmatched quote */
80387     queryClear(pQuery);
80388     return SQLITE_ERROR;
80389   }
80390
80391   /* Modify the values of the QueryTerm.nPhrase variables to account for
80392   ** the NEAR operator. For the purposes of QueryTerm.nPhrase, phrases
80393   ** and tokens connected by the NEAR operator are handled as a single
80394   ** phrase. See comments above the QueryTerm structure for details.
80395   */
80396   aTerm = pQuery->pTerms;
80397   for(ii=0; ii<pQuery->nTerms; ii++){
80398     if( aTerm[ii].nNear || aTerm[ii].nPhrase ){
80399       while (aTerm[ii+aTerm[ii].nPhrase].nNear) {
80400         aTerm[ii].nPhrase += (1 + aTerm[ii+aTerm[ii].nPhrase+1].nPhrase);
80401       }
80402     }
80403   }
80404
80405   return SQLITE_OK;
80406 }
80407
80408 /* TODO(shess) Refactor the code to remove this forward decl. */
80409 static int flushPendingTerms(fulltext_vtab *v);
80410
80411 /* Perform a full-text query using the search expression in
80412 ** zInput[0..nInput-1].  Return a list of matching documents
80413 ** in pResult.
80414 **
80415 ** Queries must match column iColumn.  Or if iColumn>=nColumn
80416 ** they are allowed to match against any column.
80417 */
80418 static int fulltextQuery(
80419   fulltext_vtab *v,      /* The full text index */
80420   int iColumn,           /* Match against this column by default */
80421   const char *zInput,    /* The query string */
80422   int nInput,            /* Number of bytes in zInput[] */
80423   DataBuffer *pResult,   /* Write the result doclist here */
80424   Query *pQuery          /* Put parsed query string here */
80425 ){
80426   int i, iNext, rc;
80427   DataBuffer left, right, or, new;
80428   int nNot = 0;
80429   QueryTerm *aTerm;
80430
80431   /* TODO(shess) Instead of flushing pendingTerms, we could query for
80432   ** the relevant term and merge the doclist into what we receive from
80433   ** the database.  Wait and see if this is a common issue, first.
80434   **
80435   ** A good reason not to flush is to not generate update-related
80436   ** error codes from here.
80437   */
80438
80439   /* Flush any buffered updates before executing the query. */
80440   rc = flushPendingTerms(v);
80441   if( rc!=SQLITE_OK ) return rc;
80442
80443   /* TODO(shess) I think that the queryClear() calls below are not
80444   ** necessary, because fulltextClose() already clears the query.
80445   */
80446   rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
80447   if( rc!=SQLITE_OK ) return rc;
80448
80449   /* Empty or NULL queries return no results. */
80450   if( pQuery->nTerms==0 ){
80451     dataBufferInit(pResult, 0);
80452     return SQLITE_OK;
80453   }
80454
80455   /* Merge AND terms. */
80456   /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
80457   aTerm = pQuery->pTerms;
80458   for(i = 0; i<pQuery->nTerms; i=iNext){
80459     if( aTerm[i].isNot ){
80460       /* Handle all NOT terms in a separate pass */
80461       nNot++;
80462       iNext = i + aTerm[i].nPhrase+1;
80463       continue;
80464     }
80465     iNext = i + aTerm[i].nPhrase + 1;
80466     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
80467     if( rc ){
80468       if( i!=nNot ) dataBufferDestroy(&left);
80469       queryClear(pQuery);
80470       return rc;
80471     }
80472     while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
80473       rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
80474       iNext += aTerm[iNext].nPhrase + 1;
80475       if( rc ){
80476         if( i!=nNot ) dataBufferDestroy(&left);
80477         dataBufferDestroy(&right);
80478         queryClear(pQuery);
80479         return rc;
80480       }
80481       dataBufferInit(&new, 0);
80482       docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
80483       dataBufferDestroy(&right);
80484       dataBufferDestroy(&or);
80485       right = new;
80486     }
80487     if( i==nNot ){           /* first term processed. */
80488       left = right;
80489     }else{
80490       dataBufferInit(&new, 0);
80491       docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
80492       dataBufferDestroy(&right);
80493       dataBufferDestroy(&left);
80494       left = new;
80495     }
80496   }
80497
80498   if( nNot==pQuery->nTerms ){
80499     /* We do not yet know how to handle a query of only NOT terms */
80500     return SQLITE_ERROR;
80501   }
80502
80503   /* Do the EXCEPT terms */
80504   for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
80505     if( !aTerm[i].isNot ) continue;
80506     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
80507     if( rc ){
80508       queryClear(pQuery);
80509       dataBufferDestroy(&left);
80510       return rc;
80511     }
80512     dataBufferInit(&new, 0);
80513     docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
80514     dataBufferDestroy(&right);
80515     dataBufferDestroy(&left);
80516     left = new;
80517   }
80518
80519   *pResult = left;
80520   return rc;
80521 }
80522
80523 /*
80524 ** This is the xFilter interface for the virtual table.  See
80525 ** the virtual table xFilter method documentation for additional
80526 ** information.
80527 **
80528 ** If idxNum==QUERY_GENERIC then do a full table scan against
80529 ** the %_content table.
80530 **
80531 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
80532 ** in the %_content table.
80533 **
80534 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
80535 ** column on the left-hand side of the MATCH operator is column
80536 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
80537 ** side of the MATCH operator.
80538 */
80539 /* TODO(shess) Upgrade the cursor initialization and destruction to
80540 ** account for fulltextFilter() being called multiple times on the
80541 ** same cursor.  The current solution is very fragile.  Apply fix to
80542 ** fts3 as appropriate.
80543 */
80544 static int fulltextFilter(
80545   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
80546   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
80547   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
80548 ){
80549   fulltext_cursor *c = (fulltext_cursor *) pCursor;
80550   fulltext_vtab *v = cursor_vtab(c);
80551   int rc;
80552   StringBuffer sb;
80553
80554   FTSTRACE(("FTS3 Filter %p\n",pCursor));
80555
80556   initStringBuffer(&sb);
80557   append(&sb, "SELECT docid, ");
80558   appendList(&sb, v->nColumn, v->azContentColumn);
80559   append(&sb, " FROM %_content");
80560   if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
80561   sqlite3_finalize(c->pStmt);
80562   rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, stringBufferData(&sb));
80563   stringBufferDestroy(&sb);
80564   if( rc!=SQLITE_OK ) return rc;
80565
80566   c->iCursorType = idxNum;
80567   switch( idxNum ){
80568     case QUERY_GENERIC:
80569       break;
80570
80571     case QUERY_DOCID:
80572       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
80573       if( rc!=SQLITE_OK ) return rc;
80574       break;
80575
80576     default:   /* full-text search */
80577     {
80578       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
80579       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
80580       assert( argc==1 );
80581       queryClear(&c->q);
80582       if( c->result.nData!=0 ){
80583         /* This case happens if the same cursor is used repeatedly. */
80584         dlrDestroy(&c->reader);
80585         dataBufferReset(&c->result);
80586       }else{
80587         dataBufferInit(&c->result, 0);
80588       }
80589       rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
80590       if( rc!=SQLITE_OK ) return rc;
80591       if( c->result.nData!=0 ){
80592         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
80593       }
80594       break;
80595     }
80596   }
80597
80598   return fulltextNext(pCursor);
80599 }
80600
80601 /* This is the xEof method of the virtual table.  The SQLite core
80602 ** calls this routine to find out if it has reached the end of
80603 ** a query's results set.
80604 */
80605 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
80606   fulltext_cursor *c = (fulltext_cursor *) pCursor;
80607   return c->eof;
80608 }
80609
80610 /* This is the xColumn method of the virtual table.  The SQLite
80611 ** core calls this method during a query when it needs the value
80612 ** of a column from the virtual table.  This method needs to use
80613 ** one of the sqlite3_result_*() routines to store the requested
80614 ** value back in the pContext.
80615 */
80616 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
80617                           sqlite3_context *pContext, int idxCol){
80618   fulltext_cursor *c = (fulltext_cursor *) pCursor;
80619   fulltext_vtab *v = cursor_vtab(c);
80620
80621   if( idxCol<v->nColumn ){
80622     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
80623     sqlite3_result_value(pContext, pVal);
80624   }else if( idxCol==v->nColumn ){
80625     /* The extra column whose name is the same as the table.
80626     ** Return a blob which is a pointer to the cursor
80627     */
80628     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
80629   }else if( idxCol==v->nColumn+1 ){
80630     /* The docid column, which is an alias for rowid. */
80631     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
80632     sqlite3_result_value(pContext, pVal);
80633   }
80634   return SQLITE_OK;
80635 }
80636
80637 /* This is the xRowid method.  The SQLite core calls this routine to
80638 ** retrieve the rowid for the current row of the result set.  fts3
80639 ** exposes %_content.docid as the rowid for the virtual table.  The
80640 ** rowid should be written to *pRowid.
80641 */
80642 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
80643   fulltext_cursor *c = (fulltext_cursor *) pCursor;
80644
80645   *pRowid = sqlite3_column_int64(c->pStmt, 0);
80646   return SQLITE_OK;
80647 }
80648
80649 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
80650 ** we also store positions and offsets in the hash table using that
80651 ** column number.
80652 */
80653 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
80654                       const char *zText, int iColumn){
80655   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
80656   sqlite3_tokenizer_cursor *pCursor;
80657   const char *pToken;
80658   int nTokenBytes;
80659   int iStartOffset, iEndOffset, iPosition;
80660   int rc;
80661
80662   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
80663   if( rc!=SQLITE_OK ) return rc;
80664
80665   pCursor->pTokenizer = pTokenizer;
80666   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
80667                                                    &pToken, &nTokenBytes,
80668                                                    &iStartOffset, &iEndOffset,
80669                                                    &iPosition)) ){
80670     DLCollector *p;
80671     int nData;                   /* Size of doclist before our update. */
80672
80673     /* Positions can't be negative; we use -1 as a terminator
80674      * internally.  Token can't be NULL or empty. */
80675     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
80676       rc = SQLITE_ERROR;
80677       break;
80678     }
80679
80680     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
80681     if( p==NULL ){
80682       nData = 0;
80683       p = dlcNew(iDocid, DL_DEFAULT);
80684       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
80685
80686       /* Overhead for our hash table entry, the key, and the value. */
80687       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
80688     }else{
80689       nData = p->b.nData;
80690       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
80691     }
80692     if( iColumn>=0 ){
80693       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
80694     }
80695
80696     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
80697     v->nPendingData += p->b.nData-nData;
80698   }
80699
80700   /* TODO(shess) Check return?  Should this be able to cause errors at
80701   ** this point?  Actually, same question about sqlite3_finalize(),
80702   ** though one could argue that failure there means that the data is
80703   ** not durable.  *ponder*
80704   */
80705   pTokenizer->pModule->xClose(pCursor);
80706   if( SQLITE_DONE == rc ) return SQLITE_OK;
80707   return rc;
80708 }
80709
80710 /* Add doclists for all terms in [pValues] to pendingTerms table. */
80711 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
80712                        sqlite3_value **pValues){
80713   int i;
80714   for(i = 0; i < v->nColumn ; ++i){
80715     char *zText = (char*)sqlite3_value_text(pValues[i]);
80716     int rc = buildTerms(v, iDocid, zText, i);
80717     if( rc!=SQLITE_OK ) return rc;
80718   }
80719   return SQLITE_OK;
80720 }
80721
80722 /* Add empty doclists for all terms in the given row's content to
80723 ** pendingTerms.
80724 */
80725 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
80726   const char **pValues;
80727   int i, rc;
80728
80729   /* TODO(shess) Should we allow such tables at all? */
80730   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
80731
80732   rc = content_select(v, iDocid, &pValues);
80733   if( rc!=SQLITE_OK ) return rc;
80734
80735   for(i = 0 ; i < v->nColumn; ++i) {
80736     rc = buildTerms(v, iDocid, pValues[i], -1);
80737     if( rc!=SQLITE_OK ) break;
80738   }
80739
80740   freeStringArray(v->nColumn, pValues);
80741   return SQLITE_OK;
80742 }
80743
80744 /* TODO(shess) Refactor the code to remove this forward decl. */
80745 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
80746
80747 /* Insert a row into the %_content table; set *piDocid to be the ID of the
80748 ** new row.  Add doclists for terms to pendingTerms.
80749 */
80750 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
80751                         sqlite3_value **pValues, sqlite_int64 *piDocid){
80752   int rc;
80753
80754   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
80755   if( rc!=SQLITE_OK ) return rc;
80756
80757   /* docid column is an alias for rowid. */
80758   *piDocid = sqlite3_last_insert_rowid(v->db);
80759   rc = initPendingTerms(v, *piDocid);
80760   if( rc!=SQLITE_OK ) return rc;
80761
80762   return insertTerms(v, *piDocid, pValues);
80763 }
80764
80765 /* Delete a row from the %_content table; add empty doclists for terms
80766 ** to pendingTerms.
80767 */
80768 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
80769   int rc = initPendingTerms(v, iRow);
80770   if( rc!=SQLITE_OK ) return rc;
80771
80772   rc = deleteTerms(v, iRow);
80773   if( rc!=SQLITE_OK ) return rc;
80774
80775   return content_delete(v, iRow);  /* execute an SQL DELETE */
80776 }
80777
80778 /* Update a row in the %_content table; add delete doclists to
80779 ** pendingTerms for old terms not in the new data, add insert doclists
80780 ** to pendingTerms for terms in the new data.
80781 */
80782 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
80783                         sqlite3_value **pValues){
80784   int rc = initPendingTerms(v, iRow);
80785   if( rc!=SQLITE_OK ) return rc;
80786
80787   /* Generate an empty doclist for each term that previously appeared in this
80788    * row. */
80789   rc = deleteTerms(v, iRow);
80790   if( rc!=SQLITE_OK ) return rc;
80791
80792   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
80793   if( rc!=SQLITE_OK ) return rc;
80794
80795   /* Now add positions for terms which appear in the updated row. */
80796   return insertTerms(v, iRow, pValues);
80797 }
80798
80799 /*******************************************************************/
80800 /* InteriorWriter is used to collect terms and block references into
80801 ** interior nodes in %_segments.  See commentary at top of file for
80802 ** format.
80803 */
80804
80805 /* How large interior nodes can grow. */
80806 #define INTERIOR_MAX 2048
80807
80808 /* Minimum number of terms per interior node (except the root). This
80809 ** prevents large terms from making the tree too skinny - must be >0
80810 ** so that the tree always makes progress.  Note that the min tree
80811 ** fanout will be INTERIOR_MIN_TERMS+1.
80812 */
80813 #define INTERIOR_MIN_TERMS 7
80814 #if INTERIOR_MIN_TERMS<1
80815 # error INTERIOR_MIN_TERMS must be greater than 0.
80816 #endif
80817
80818 /* ROOT_MAX controls how much data is stored inline in the segment
80819 ** directory.
80820 */
80821 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
80822 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
80823 ** can both see it, but if the caller passed it in, we wouldn't even
80824 ** need a define.
80825 */
80826 #define ROOT_MAX 1024
80827 #if ROOT_MAX<VARINT_MAX*2
80828 # error ROOT_MAX must have enough space for a header.
80829 #endif
80830
80831 /* InteriorBlock stores a linked-list of interior blocks while a lower
80832 ** layer is being constructed.
80833 */
80834 typedef struct InteriorBlock {
80835   DataBuffer term;           /* Leftmost term in block's subtree. */
80836   DataBuffer data;           /* Accumulated data for the block. */
80837   struct InteriorBlock *next;
80838 } InteriorBlock;
80839
80840 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
80841                                        const char *pTerm, int nTerm){
80842   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
80843   char c[VARINT_MAX+VARINT_MAX];
80844   int n;
80845
80846   if( block ){
80847     memset(block, 0, sizeof(*block));
80848     dataBufferInit(&block->term, 0);
80849     dataBufferReplace(&block->term, pTerm, nTerm);
80850
80851     n = fts3PutVarint(c, iHeight);
80852     n += fts3PutVarint(c+n, iChildBlock);
80853     dataBufferInit(&block->data, INTERIOR_MAX);
80854     dataBufferReplace(&block->data, c, n);
80855   }
80856   return block;
80857 }
80858
80859 #ifndef NDEBUG
80860 /* Verify that the data is readable as an interior node. */
80861 static void interiorBlockValidate(InteriorBlock *pBlock){
80862   const char *pData = pBlock->data.pData;
80863   int nData = pBlock->data.nData;
80864   int n, iDummy;
80865   sqlite_int64 iBlockid;
80866
80867   assert( nData>0 );
80868   assert( pData!=0 );
80869   assert( pData+nData>pData );
80870
80871   /* Must lead with height of node as a varint(n), n>0 */
80872   n = fts3GetVarint32(pData, &iDummy);
80873   assert( n>0 );
80874   assert( iDummy>0 );
80875   assert( n<nData );
80876   pData += n;
80877   nData -= n;
80878
80879   /* Must contain iBlockid. */
80880   n = fts3GetVarint(pData, &iBlockid);
80881   assert( n>0 );
80882   assert( n<=nData );
80883   pData += n;
80884   nData -= n;
80885
80886   /* Zero or more terms of positive length */
80887   if( nData!=0 ){
80888     /* First term is not delta-encoded. */
80889     n = fts3GetVarint32(pData, &iDummy);
80890     assert( n>0 );
80891     assert( iDummy>0 );
80892     assert( n+iDummy>0);
80893     assert( n+iDummy<=nData );
80894     pData += n+iDummy;
80895     nData -= n+iDummy;
80896
80897     /* Following terms delta-encoded. */
80898     while( nData!=0 ){
80899       /* Length of shared prefix. */
80900       n = fts3GetVarint32(pData, &iDummy);
80901       assert( n>0 );
80902       assert( iDummy>=0 );
80903       assert( n<nData );
80904       pData += n;
80905       nData -= n;
80906
80907       /* Length and data of distinct suffix. */
80908       n = fts3GetVarint32(pData, &iDummy);
80909       assert( n>0 );
80910       assert( iDummy>0 );
80911       assert( n+iDummy>0);
80912       assert( n+iDummy<=nData );
80913       pData += n+iDummy;
80914       nData -= n+iDummy;
80915     }
80916   }
80917 }
80918 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
80919 #else
80920 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
80921 #endif
80922
80923 typedef struct InteriorWriter {
80924   int iHeight;                   /* from 0 at leaves. */
80925   InteriorBlock *first, *last;
80926   struct InteriorWriter *parentWriter;
80927
80928   DataBuffer term;               /* Last term written to block "last". */
80929   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
80930 #ifndef NDEBUG
80931   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
80932 #endif
80933 } InteriorWriter;
80934
80935 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
80936 ** term in the tree.  iChildBlock is the leftmost child block at the
80937 ** next level down the tree.
80938 */
80939 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
80940                                sqlite_int64 iChildBlock,
80941                                InteriorWriter *pWriter){
80942   InteriorBlock *block;
80943   assert( iHeight>0 );
80944   CLEAR(pWriter);
80945
80946   pWriter->iHeight = iHeight;
80947   pWriter->iOpeningChildBlock = iChildBlock;
80948 #ifndef NDEBUG
80949   pWriter->iLastChildBlock = iChildBlock;
80950 #endif
80951   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
80952   pWriter->last = pWriter->first = block;
80953   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
80954   dataBufferInit(&pWriter->term, 0);
80955 }
80956
80957 /* Append the child node rooted at iChildBlock to the interior node,
80958 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
80959 */
80960 static void interiorWriterAppend(InteriorWriter *pWriter,
80961                                  const char *pTerm, int nTerm,
80962                                  sqlite_int64 iChildBlock){
80963   char c[VARINT_MAX+VARINT_MAX];
80964   int n, nPrefix = 0;
80965
80966   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
80967
80968   /* The first term written into an interior node is actually
80969   ** associated with the second child added (the first child was added
80970   ** in interiorWriterInit, or in the if clause at the bottom of this
80971   ** function).  That term gets encoded straight up, with nPrefix left
80972   ** at 0.
80973   */
80974   if( pWriter->term.nData==0 ){
80975     n = fts3PutVarint(c, nTerm);
80976   }else{
80977     while( nPrefix<pWriter->term.nData &&
80978            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
80979       nPrefix++;
80980     }
80981
80982     n = fts3PutVarint(c, nPrefix);
80983     n += fts3PutVarint(c+n, nTerm-nPrefix);
80984   }
80985
80986 #ifndef NDEBUG
80987   pWriter->iLastChildBlock++;
80988 #endif
80989   assert( pWriter->iLastChildBlock==iChildBlock );
80990
80991   /* Overflow to a new block if the new term makes the current block
80992   ** too big, and the current block already has enough terms.
80993   */
80994   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
80995       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
80996     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
80997                                            pTerm, nTerm);
80998     pWriter->last = pWriter->last->next;
80999     pWriter->iOpeningChildBlock = iChildBlock;
81000     dataBufferReset(&pWriter->term);
81001   }else{
81002     dataBufferAppend2(&pWriter->last->data, c, n,
81003                       pTerm+nPrefix, nTerm-nPrefix);
81004     dataBufferReplace(&pWriter->term, pTerm, nTerm);
81005   }
81006   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
81007 }
81008
81009 /* Free the space used by pWriter, including the linked-list of
81010 ** InteriorBlocks, and parentWriter, if present.
81011 */
81012 static int interiorWriterDestroy(InteriorWriter *pWriter){
81013   InteriorBlock *block = pWriter->first;
81014
81015   while( block!=NULL ){
81016     InteriorBlock *b = block;
81017     block = block->next;
81018     dataBufferDestroy(&b->term);
81019     dataBufferDestroy(&b->data);
81020     sqlite3_free(b);
81021   }
81022   if( pWriter->parentWriter!=NULL ){
81023     interiorWriterDestroy(pWriter->parentWriter);
81024     sqlite3_free(pWriter->parentWriter);
81025   }
81026   dataBufferDestroy(&pWriter->term);
81027   SCRAMBLE(pWriter);
81028   return SQLITE_OK;
81029 }
81030
81031 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
81032 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
81033 ** pWriter to %_segments, building a new layer of interior nodes, and
81034 ** recursively ask for their root into.
81035 */
81036 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
81037                                   char **ppRootInfo, int *pnRootInfo,
81038                                   sqlite_int64 *piEndBlockid){
81039   InteriorBlock *block = pWriter->first;
81040   sqlite_int64 iBlockid = 0;
81041   int rc;
81042
81043   /* If we can fit the segment inline */
81044   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
81045     *ppRootInfo = block->data.pData;
81046     *pnRootInfo = block->data.nData;
81047     return SQLITE_OK;
81048   }
81049
81050   /* Flush the first block to %_segments, and create a new level of
81051   ** interior node.
81052   */
81053   ASSERT_VALID_INTERIOR_BLOCK(block);
81054   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
81055   if( rc!=SQLITE_OK ) return rc;
81056   *piEndBlockid = iBlockid;
81057
81058   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
81059   interiorWriterInit(pWriter->iHeight+1,
81060                      block->term.pData, block->term.nData,
81061                      iBlockid, pWriter->parentWriter);
81062
81063   /* Flush additional blocks and append to the higher interior
81064   ** node.
81065   */
81066   for(block=block->next; block!=NULL; block=block->next){
81067     ASSERT_VALID_INTERIOR_BLOCK(block);
81068     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
81069     if( rc!=SQLITE_OK ) return rc;
81070     *piEndBlockid = iBlockid;
81071
81072     interiorWriterAppend(pWriter->parentWriter,
81073                          block->term.pData, block->term.nData, iBlockid);
81074   }
81075
81076   /* Parent node gets the chance to be the root. */
81077   return interiorWriterRootInfo(v, pWriter->parentWriter,
81078                                 ppRootInfo, pnRootInfo, piEndBlockid);
81079 }
81080
81081 /****************************************************************/
81082 /* InteriorReader is used to read off the data from an interior node
81083 ** (see comment at top of file for the format).
81084 */
81085 typedef struct InteriorReader {
81086   const char *pData;
81087   int nData;
81088
81089   DataBuffer term;          /* previous term, for decoding term delta. */
81090
81091   sqlite_int64 iBlockid;
81092 } InteriorReader;
81093
81094 static void interiorReaderDestroy(InteriorReader *pReader){
81095   dataBufferDestroy(&pReader->term);
81096   SCRAMBLE(pReader);
81097 }
81098
81099 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
81100 ** and the blob is empty or otherwise contains suspect data?
81101 */
81102 static void interiorReaderInit(const char *pData, int nData,
81103                                InteriorReader *pReader){
81104   int n, nTerm;
81105
81106   /* Require at least the leading flag byte */
81107   assert( nData>0 );
81108   assert( pData[0]!='\0' );
81109
81110   CLEAR(pReader);
81111
81112   /* Decode the base blockid, and set the cursor to the first term. */
81113   n = fts3GetVarint(pData+1, &pReader->iBlockid);
81114   assert( 1+n<=nData );
81115   pReader->pData = pData+1+n;
81116   pReader->nData = nData-(1+n);
81117
81118   /* A single-child interior node (such as when a leaf node was too
81119   ** large for the segment directory) won't have any terms.
81120   ** Otherwise, decode the first term.
81121   */
81122   if( pReader->nData==0 ){
81123     dataBufferInit(&pReader->term, 0);
81124   }else{
81125     n = fts3GetVarint32(pReader->pData, &nTerm);
81126     dataBufferInit(&pReader->term, nTerm);
81127     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
81128     assert( n+nTerm<=pReader->nData );
81129     pReader->pData += n+nTerm;
81130     pReader->nData -= n+nTerm;
81131   }
81132 }
81133
81134 static int interiorReaderAtEnd(InteriorReader *pReader){
81135   return pReader->term.nData==0;
81136 }
81137
81138 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
81139   return pReader->iBlockid;
81140 }
81141
81142 static int interiorReaderTermBytes(InteriorReader *pReader){
81143   assert( !interiorReaderAtEnd(pReader) );
81144   return pReader->term.nData;
81145 }
81146 static const char *interiorReaderTerm(InteriorReader *pReader){
81147   assert( !interiorReaderAtEnd(pReader) );
81148   return pReader->term.pData;
81149 }
81150
81151 /* Step forward to the next term in the node. */
81152 static void interiorReaderStep(InteriorReader *pReader){
81153   assert( !interiorReaderAtEnd(pReader) );
81154
81155   /* If the last term has been read, signal eof, else construct the
81156   ** next term.
81157   */
81158   if( pReader->nData==0 ){
81159     dataBufferReset(&pReader->term);
81160   }else{
81161     int n, nPrefix, nSuffix;
81162
81163     n = fts3GetVarint32(pReader->pData, &nPrefix);
81164     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
81165
81166     /* Truncate the current term and append suffix data. */
81167     pReader->term.nData = nPrefix;
81168     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
81169
81170     assert( n+nSuffix<=pReader->nData );
81171     pReader->pData += n+nSuffix;
81172     pReader->nData -= n+nSuffix;
81173   }
81174   pReader->iBlockid++;
81175 }
81176
81177 /* Compare the current term to pTerm[nTerm], returning strcmp-style
81178 ** results.  If isPrefix, equality means equal through nTerm bytes.
81179 */
81180 static int interiorReaderTermCmp(InteriorReader *pReader,
81181                                  const char *pTerm, int nTerm, int isPrefix){
81182   const char *pReaderTerm = interiorReaderTerm(pReader);
81183   int nReaderTerm = interiorReaderTermBytes(pReader);
81184   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
81185
81186   if( n==0 ){
81187     if( nReaderTerm>0 ) return -1;
81188     if( nTerm>0 ) return 1;
81189     return 0;
81190   }
81191
81192   c = memcmp(pReaderTerm, pTerm, n);
81193   if( c!=0 ) return c;
81194   if( isPrefix && n==nTerm ) return 0;
81195   return nReaderTerm - nTerm;
81196 }
81197
81198 /****************************************************************/
81199 /* LeafWriter is used to collect terms and associated doclist data
81200 ** into leaf blocks in %_segments (see top of file for format info).
81201 ** Expected usage is:
81202 **
81203 ** LeafWriter writer;
81204 ** leafWriterInit(0, 0, &writer);
81205 ** while( sorted_terms_left_to_process ){
81206 **   // data is doclist data for that term.
81207 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
81208 **   if( rc!=SQLITE_OK ) goto err;
81209 ** }
81210 ** rc = leafWriterFinalize(v, &writer);
81211 **err:
81212 ** leafWriterDestroy(&writer);
81213 ** return rc;
81214 **
81215 ** leafWriterStep() may write a collected leaf out to %_segments.
81216 ** leafWriterFinalize() finishes writing any buffered data and stores
81217 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
81218 ** InteriorWriters allocated as part of writing this segment.
81219 **
81220 ** TODO(shess) Document leafWriterStepMerge().
81221 */
81222
81223 /* Put terms with data this big in their own block. */
81224 #define STANDALONE_MIN 1024
81225
81226 /* Keep leaf blocks below this size. */
81227 #define LEAF_MAX 2048
81228
81229 typedef struct LeafWriter {
81230   int iLevel;
81231   int idx;
81232   sqlite_int64 iStartBlockid;     /* needed to create the root info */
81233   sqlite_int64 iEndBlockid;       /* when we're done writing. */
81234
81235   DataBuffer term;                /* previous encoded term */
81236   DataBuffer data;                /* encoding buffer */
81237
81238   /* bytes of first term in the current node which distinguishes that
81239   ** term from the last term of the previous node.
81240   */
81241   int nTermDistinct;
81242
81243   InteriorWriter parentWriter;    /* if we overflow */
81244   int has_parent;
81245 } LeafWriter;
81246
81247 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
81248   CLEAR(pWriter);
81249   pWriter->iLevel = iLevel;
81250   pWriter->idx = idx;
81251
81252   dataBufferInit(&pWriter->term, 32);
81253
81254   /* Start out with a reasonably sized block, though it can grow. */
81255   dataBufferInit(&pWriter->data, LEAF_MAX);
81256 }
81257
81258 #ifndef NDEBUG
81259 /* Verify that the data is readable as a leaf node. */
81260 static void leafNodeValidate(const char *pData, int nData){
81261   int n, iDummy;
81262
81263   if( nData==0 ) return;
81264   assert( nData>0 );
81265   assert( pData!=0 );
81266   assert( pData+nData>pData );
81267
81268   /* Must lead with a varint(0) */
81269   n = fts3GetVarint32(pData, &iDummy);
81270   assert( iDummy==0 );
81271   assert( n>0 );
81272   assert( n<nData );
81273   pData += n;
81274   nData -= n;
81275
81276   /* Leading term length and data must fit in buffer. */
81277   n = fts3GetVarint32(pData, &iDummy);
81278   assert( n>0 );
81279   assert( iDummy>0 );
81280   assert( n+iDummy>0 );
81281   assert( n+iDummy<nData );
81282   pData += n+iDummy;
81283   nData -= n+iDummy;
81284
81285   /* Leading term's doclist length and data must fit. */
81286   n = fts3GetVarint32(pData, &iDummy);
81287   assert( n>0 );
81288   assert( iDummy>0 );
81289   assert( n+iDummy>0 );
81290   assert( n+iDummy<=nData );
81291   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
81292   pData += n+iDummy;
81293   nData -= n+iDummy;
81294
81295   /* Verify that trailing terms and doclists also are readable. */
81296   while( nData!=0 ){
81297     n = fts3GetVarint32(pData, &iDummy);
81298     assert( n>0 );
81299     assert( iDummy>=0 );
81300     assert( n<nData );
81301     pData += n;
81302     nData -= n;
81303     n = fts3GetVarint32(pData, &iDummy);
81304     assert( n>0 );
81305     assert( iDummy>0 );
81306     assert( n+iDummy>0 );
81307     assert( n+iDummy<nData );
81308     pData += n+iDummy;
81309     nData -= n+iDummy;
81310
81311     n = fts3GetVarint32(pData, &iDummy);
81312     assert( n>0 );
81313     assert( iDummy>0 );
81314     assert( n+iDummy>0 );
81315     assert( n+iDummy<=nData );
81316     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
81317     pData += n+iDummy;
81318     nData -= n+iDummy;
81319   }
81320 }
81321 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
81322 #else
81323 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
81324 #endif
81325
81326 /* Flush the current leaf node to %_segments, and adding the resulting
81327 ** blockid and the starting term to the interior node which will
81328 ** contain it.
81329 */
81330 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
81331                                    int iData, int nData){
81332   sqlite_int64 iBlockid = 0;
81333   const char *pStartingTerm;
81334   int nStartingTerm, rc, n;
81335
81336   /* Must have the leading varint(0) flag, plus at least some
81337   ** valid-looking data.
81338   */
81339   assert( nData>2 );
81340   assert( iData>=0 );
81341   assert( iData+nData<=pWriter->data.nData );
81342   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
81343
81344   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
81345   if( rc!=SQLITE_OK ) return rc;
81346   assert( iBlockid!=0 );
81347
81348   /* Reconstruct the first term in the leaf for purposes of building
81349   ** the interior node.
81350   */
81351   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
81352   pStartingTerm = pWriter->data.pData+iData+1+n;
81353   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
81354   assert( pWriter->nTermDistinct>0 );
81355   assert( pWriter->nTermDistinct<=nStartingTerm );
81356   nStartingTerm = pWriter->nTermDistinct;
81357
81358   if( pWriter->has_parent ){
81359     interiorWriterAppend(&pWriter->parentWriter,
81360                          pStartingTerm, nStartingTerm, iBlockid);
81361   }else{
81362     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
81363                        &pWriter->parentWriter);
81364     pWriter->has_parent = 1;
81365   }
81366
81367   /* Track the span of this segment's leaf nodes. */
81368   if( pWriter->iEndBlockid==0 ){
81369     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
81370   }else{
81371     pWriter->iEndBlockid++;
81372     assert( iBlockid==pWriter->iEndBlockid );
81373   }
81374
81375   return SQLITE_OK;
81376 }
81377 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
81378   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
81379   if( rc!=SQLITE_OK ) return rc;
81380
81381   /* Re-initialize the output buffer. */
81382   dataBufferReset(&pWriter->data);
81383
81384   return SQLITE_OK;
81385 }
81386
81387 /* Fetch the root info for the segment.  If the entire leaf fits
81388 ** within ROOT_MAX, then it will be returned directly, otherwise it
81389 ** will be flushed and the root info will be returned from the
81390 ** interior node.  *piEndBlockid is set to the blockid of the last
81391 ** interior or leaf node written to disk (0 if none are written at
81392 ** all).
81393 */
81394 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
81395                               char **ppRootInfo, int *pnRootInfo,
81396                               sqlite_int64 *piEndBlockid){
81397   /* we can fit the segment entirely inline */
81398   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
81399     *ppRootInfo = pWriter->data.pData;
81400     *pnRootInfo = pWriter->data.nData;
81401     *piEndBlockid = 0;
81402     return SQLITE_OK;
81403   }
81404
81405   /* Flush remaining leaf data. */
81406   if( pWriter->data.nData>0 ){
81407     int rc = leafWriterFlush(v, pWriter);
81408     if( rc!=SQLITE_OK ) return rc;
81409   }
81410
81411   /* We must have flushed a leaf at some point. */
81412   assert( pWriter->has_parent );
81413
81414   /* Tenatively set the end leaf blockid as the end blockid.  If the
81415   ** interior node can be returned inline, this will be the final
81416   ** blockid, otherwise it will be overwritten by
81417   ** interiorWriterRootInfo().
81418   */
81419   *piEndBlockid = pWriter->iEndBlockid;
81420
81421   return interiorWriterRootInfo(v, &pWriter->parentWriter,
81422                                 ppRootInfo, pnRootInfo, piEndBlockid);
81423 }
81424
81425 /* Collect the rootInfo data and store it into the segment directory.
81426 ** This has the effect of flushing the segment's leaf data to
81427 ** %_segments, and also flushing any interior nodes to %_segments.
81428 */
81429 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
81430   sqlite_int64 iEndBlockid;
81431   char *pRootInfo;
81432   int rc, nRootInfo;
81433
81434   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
81435   if( rc!=SQLITE_OK ) return rc;
81436
81437   /* Don't bother storing an entirely empty segment. */
81438   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
81439
81440   return segdir_set(v, pWriter->iLevel, pWriter->idx,
81441                     pWriter->iStartBlockid, pWriter->iEndBlockid,
81442                     iEndBlockid, pRootInfo, nRootInfo);
81443 }
81444
81445 static void leafWriterDestroy(LeafWriter *pWriter){
81446   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
81447   dataBufferDestroy(&pWriter->term);
81448   dataBufferDestroy(&pWriter->data);
81449 }
81450
81451 /* Encode a term into the leafWriter, delta-encoding as appropriate.
81452 ** Returns the length of the new term which distinguishes it from the
81453 ** previous term, which can be used to set nTermDistinct when a node
81454 ** boundary is crossed.
81455 */
81456 static int leafWriterEncodeTerm(LeafWriter *pWriter,
81457                                 const char *pTerm, int nTerm){
81458   char c[VARINT_MAX+VARINT_MAX];
81459   int n, nPrefix = 0;
81460
81461   assert( nTerm>0 );
81462   while( nPrefix<pWriter->term.nData &&
81463          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
81464     nPrefix++;
81465     /* Failing this implies that the terms weren't in order. */
81466     assert( nPrefix<nTerm );
81467   }
81468
81469   if( pWriter->data.nData==0 ){
81470     /* Encode the node header and leading term as:
81471     **  varint(0)
81472     **  varint(nTerm)
81473     **  char pTerm[nTerm]
81474     */
81475     n = fts3PutVarint(c, '\0');
81476     n += fts3PutVarint(c+n, nTerm);
81477     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
81478   }else{
81479     /* Delta-encode the term as:
81480     **  varint(nPrefix)
81481     **  varint(nSuffix)
81482     **  char pTermSuffix[nSuffix]
81483     */
81484     n = fts3PutVarint(c, nPrefix);
81485     n += fts3PutVarint(c+n, nTerm-nPrefix);
81486     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
81487   }
81488   dataBufferReplace(&pWriter->term, pTerm, nTerm);
81489
81490   return nPrefix+1;
81491 }
81492
81493 /* Used to avoid a memmove when a large amount of doclist data is in
81494 ** the buffer.  This constructs a node and term header before
81495 ** iDoclistData and flushes the resulting complete node using
81496 ** leafWriterInternalFlush().
81497 */
81498 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
81499                                  const char *pTerm, int nTerm,
81500                                  int iDoclistData){
81501   char c[VARINT_MAX+VARINT_MAX];
81502   int iData, n = fts3PutVarint(c, 0);
81503   n += fts3PutVarint(c+n, nTerm);
81504
81505   /* There should always be room for the header.  Even if pTerm shared
81506   ** a substantial prefix with the previous term, the entire prefix
81507   ** could be constructed from earlier data in the doclist, so there
81508   ** should be room.
81509   */
81510   assert( iDoclistData>=n+nTerm );
81511
81512   iData = iDoclistData-(n+nTerm);
81513   memcpy(pWriter->data.pData+iData, c, n);
81514   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
81515
81516   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
81517 }
81518
81519 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
81520 ** %_segments.
81521 */
81522 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
81523                                const char *pTerm, int nTerm,
81524                                DLReader *pReaders, int nReaders){
81525   char c[VARINT_MAX+VARINT_MAX];
81526   int iTermData = pWriter->data.nData, iDoclistData;
81527   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
81528
81529   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
81530   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
81531
81532   /* Remember nTermDistinct if opening a new node. */
81533   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
81534
81535   iDoclistData = pWriter->data.nData;
81536
81537   /* Estimate the length of the merged doclist so we can leave space
81538   ** to encode it.
81539   */
81540   for(i=0, nData=0; i<nReaders; i++){
81541     nData += dlrAllDataBytes(&pReaders[i]);
81542   }
81543   n = fts3PutVarint(c, nData);
81544   dataBufferAppend(&pWriter->data, c, n);
81545
81546   docListMerge(&pWriter->data, pReaders, nReaders);
81547   ASSERT_VALID_DOCLIST(DL_DEFAULT,
81548                        pWriter->data.pData+iDoclistData+n,
81549                        pWriter->data.nData-iDoclistData-n, NULL);
81550
81551   /* The actual amount of doclist data at this point could be smaller
81552   ** than the length we encoded.  Additionally, the space required to
81553   ** encode this length could be smaller.  For small doclists, this is
81554   ** not a big deal, we can just use memmove() to adjust things.
81555   */
81556   nActualData = pWriter->data.nData-(iDoclistData+n);
81557   nActual = fts3PutVarint(c, nActualData);
81558   assert( nActualData<=nData );
81559   assert( nActual<=n );
81560
81561   /* If the new doclist is big enough for force a standalone leaf
81562   ** node, we can immediately flush it inline without doing the
81563   ** memmove().
81564   */
81565   /* TODO(shess) This test matches leafWriterStep(), which does this
81566   ** test before it knows the cost to varint-encode the term and
81567   ** doclist lengths.  At some point, change to
81568   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
81569   */
81570   if( nTerm+nActualData>STANDALONE_MIN ){
81571     /* Push leaf node from before this term. */
81572     if( iTermData>0 ){
81573       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
81574       if( rc!=SQLITE_OK ) return rc;
81575
81576       pWriter->nTermDistinct = nTermDistinct;
81577     }
81578
81579     /* Fix the encoded doclist length. */
81580     iDoclistData += n - nActual;
81581     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
81582
81583     /* Push the standalone leaf node. */
81584     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
81585     if( rc!=SQLITE_OK ) return rc;
81586
81587     /* Leave the node empty. */
81588     dataBufferReset(&pWriter->data);
81589
81590     return rc;
81591   }
81592
81593   /* At this point, we know that the doclist was small, so do the
81594   ** memmove if indicated.
81595   */
81596   if( nActual<n ){
81597     memmove(pWriter->data.pData+iDoclistData+nActual,
81598             pWriter->data.pData+iDoclistData+n,
81599             pWriter->data.nData-(iDoclistData+n));
81600     pWriter->data.nData -= n-nActual;
81601   }
81602
81603   /* Replace written length with actual length. */
81604   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
81605
81606   /* If the node is too large, break things up. */
81607   /* TODO(shess) This test matches leafWriterStep(), which does this
81608   ** test before it knows the cost to varint-encode the term and
81609   ** doclist lengths.  At some point, change to
81610   ** pWriter->data.nData>LEAF_MAX.
81611   */
81612   if( iTermData+nTerm+nActualData>LEAF_MAX ){
81613     /* Flush out the leading data as a node */
81614     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
81615     if( rc!=SQLITE_OK ) return rc;
81616
81617     pWriter->nTermDistinct = nTermDistinct;
81618
81619     /* Rebuild header using the current term */
81620     n = fts3PutVarint(pWriter->data.pData, 0);
81621     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
81622     memcpy(pWriter->data.pData+n, pTerm, nTerm);
81623     n += nTerm;
81624
81625     /* There should always be room, because the previous encoding
81626     ** included all data necessary to construct the term.
81627     */
81628     assert( n<iDoclistData );
81629     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
81630     ** following memcpy() is safe (as opposed to needing a memmove).
81631     */
81632     assert( 2*STANDALONE_MIN<=LEAF_MAX );
81633     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
81634     memcpy(pWriter->data.pData+n,
81635            pWriter->data.pData+iDoclistData,
81636            pWriter->data.nData-iDoclistData);
81637     pWriter->data.nData -= iDoclistData-n;
81638   }
81639   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
81640
81641   return SQLITE_OK;
81642 }
81643
81644 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
81645 ** %_segments.
81646 */
81647 /* TODO(shess) Revise writeZeroSegment() so that doclists are
81648 ** constructed directly in pWriter->data.
81649 */
81650 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
81651                           const char *pTerm, int nTerm,
81652                           const char *pData, int nData){
81653   int rc;
81654   DLReader reader;
81655
81656   dlrInit(&reader, DL_DEFAULT, pData, nData);
81657   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
81658   dlrDestroy(&reader);
81659
81660   return rc;
81661 }
81662
81663
81664 /****************************************************************/
81665 /* LeafReader is used to iterate over an individual leaf node. */
81666 typedef struct LeafReader {
81667   DataBuffer term;          /* copy of current term. */
81668
81669   const char *pData;        /* data for current term. */
81670   int nData;
81671 } LeafReader;
81672
81673 static void leafReaderDestroy(LeafReader *pReader){
81674   dataBufferDestroy(&pReader->term);
81675   SCRAMBLE(pReader);
81676 }
81677
81678 static int leafReaderAtEnd(LeafReader *pReader){
81679   return pReader->nData<=0;
81680 }
81681
81682 /* Access the current term. */
81683 static int leafReaderTermBytes(LeafReader *pReader){
81684   return pReader->term.nData;
81685 }
81686 static const char *leafReaderTerm(LeafReader *pReader){
81687   assert( pReader->term.nData>0 );
81688   return pReader->term.pData;
81689 }
81690
81691 /* Access the doclist data for the current term. */
81692 static int leafReaderDataBytes(LeafReader *pReader){
81693   int nData;
81694   assert( pReader->term.nData>0 );
81695   fts3GetVarint32(pReader->pData, &nData);
81696   return nData;
81697 }
81698 static const char *leafReaderData(LeafReader *pReader){
81699   int n, nData;
81700   assert( pReader->term.nData>0 );
81701   n = fts3GetVarint32(pReader->pData, &nData);
81702   return pReader->pData+n;
81703 }
81704
81705 static void leafReaderInit(const char *pData, int nData,
81706                            LeafReader *pReader){
81707   int nTerm, n;
81708
81709   assert( nData>0 );
81710   assert( pData[0]=='\0' );
81711
81712   CLEAR(pReader);
81713
81714   /* Read the first term, skipping the header byte. */
81715   n = fts3GetVarint32(pData+1, &nTerm);
81716   dataBufferInit(&pReader->term, nTerm);
81717   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
81718
81719   /* Position after the first term. */
81720   assert( 1+n+nTerm<nData );
81721   pReader->pData = pData+1+n+nTerm;
81722   pReader->nData = nData-1-n-nTerm;
81723 }
81724
81725 /* Step the reader forward to the next term. */
81726 static void leafReaderStep(LeafReader *pReader){
81727   int n, nData, nPrefix, nSuffix;
81728   assert( !leafReaderAtEnd(pReader) );
81729
81730   /* Skip previous entry's data block. */
81731   n = fts3GetVarint32(pReader->pData, &nData);
81732   assert( n+nData<=pReader->nData );
81733   pReader->pData += n+nData;
81734   pReader->nData -= n+nData;
81735
81736   if( !leafReaderAtEnd(pReader) ){
81737     /* Construct the new term using a prefix from the old term plus a
81738     ** suffix from the leaf data.
81739     */
81740     n = fts3GetVarint32(pReader->pData, &nPrefix);
81741     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
81742     assert( n+nSuffix<pReader->nData );
81743     pReader->term.nData = nPrefix;
81744     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
81745
81746     pReader->pData += n+nSuffix;
81747     pReader->nData -= n+nSuffix;
81748   }
81749 }
81750
81751 /* strcmp-style comparison of pReader's current term against pTerm.
81752 ** If isPrefix, equality means equal through nTerm bytes.
81753 */
81754 static int leafReaderTermCmp(LeafReader *pReader,
81755                              const char *pTerm, int nTerm, int isPrefix){
81756   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
81757   if( n==0 ){
81758     if( pReader->term.nData>0 ) return -1;
81759     if(nTerm>0 ) return 1;
81760     return 0;
81761   }
81762
81763   c = memcmp(pReader->term.pData, pTerm, n);
81764   if( c!=0 ) return c;
81765   if( isPrefix && n==nTerm ) return 0;
81766   return pReader->term.nData - nTerm;
81767 }
81768
81769
81770 /****************************************************************/
81771 /* LeavesReader wraps LeafReader to allow iterating over the entire
81772 ** leaf layer of the tree.
81773 */
81774 typedef struct LeavesReader {
81775   int idx;                  /* Index within the segment. */
81776
81777   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
81778   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
81779
81780   LeafReader leafReader;    /* reader for the current leaf. */
81781   DataBuffer rootData;      /* root data for inline. */
81782 } LeavesReader;
81783
81784 /* Access the current term. */
81785 static int leavesReaderTermBytes(LeavesReader *pReader){
81786   assert( !pReader->eof );
81787   return leafReaderTermBytes(&pReader->leafReader);
81788 }
81789 static const char *leavesReaderTerm(LeavesReader *pReader){
81790   assert( !pReader->eof );
81791   return leafReaderTerm(&pReader->leafReader);
81792 }
81793
81794 /* Access the doclist data for the current term. */
81795 static int leavesReaderDataBytes(LeavesReader *pReader){
81796   assert( !pReader->eof );
81797   return leafReaderDataBytes(&pReader->leafReader);
81798 }
81799 static const char *leavesReaderData(LeavesReader *pReader){
81800   assert( !pReader->eof );
81801   return leafReaderData(&pReader->leafReader);
81802 }
81803
81804 static int leavesReaderAtEnd(LeavesReader *pReader){
81805   return pReader->eof;
81806 }
81807
81808 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
81809 ** leaving the statement handle open, which locks the table.
81810 */
81811 /* TODO(shess) This "solution" is not satisfactory.  Really, there
81812 ** should be check-in function for all statement handles which
81813 ** arranges to call sqlite3_reset().  This most likely will require
81814 ** modification to control flow all over the place, though, so for now
81815 ** just punt.
81816 **
81817 ** Note the the current system assumes that segment merges will run to
81818 ** completion, which is why this particular probably hasn't arisen in
81819 ** this case.  Probably a brittle assumption.
81820 */
81821 static int leavesReaderReset(LeavesReader *pReader){
81822   return sqlite3_reset(pReader->pStmt);
81823 }
81824
81825 static void leavesReaderDestroy(LeavesReader *pReader){
81826   leafReaderDestroy(&pReader->leafReader);
81827   dataBufferDestroy(&pReader->rootData);
81828   SCRAMBLE(pReader);
81829 }
81830
81831 /* Initialize pReader with the given root data (if iStartBlockid==0
81832 ** the leaf data was entirely contained in the root), or from the
81833 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
81834 */
81835 static int leavesReaderInit(fulltext_vtab *v,
81836                             int idx,
81837                             sqlite_int64 iStartBlockid,
81838                             sqlite_int64 iEndBlockid,
81839                             const char *pRootData, int nRootData,
81840                             LeavesReader *pReader){
81841   CLEAR(pReader);
81842   pReader->idx = idx;
81843
81844   dataBufferInit(&pReader->rootData, 0);
81845   if( iStartBlockid==0 ){
81846     /* Entire leaf level fit in root data. */
81847     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
81848     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
81849                    &pReader->leafReader);
81850   }else{
81851     sqlite3_stmt *s;
81852     int rc = sql_get_leaf_statement(v, idx, &s);
81853     if( rc!=SQLITE_OK ) return rc;
81854
81855     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
81856     if( rc!=SQLITE_OK ) return rc;
81857
81858     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
81859     if( rc!=SQLITE_OK ) return rc;
81860
81861     rc = sqlite3_step(s);
81862     if( rc==SQLITE_DONE ){
81863       pReader->eof = 1;
81864       return SQLITE_OK;
81865     }
81866     if( rc!=SQLITE_ROW ) return rc;
81867
81868     pReader->pStmt = s;
81869     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
81870                    sqlite3_column_bytes(pReader->pStmt, 0),
81871                    &pReader->leafReader);
81872   }
81873   return SQLITE_OK;
81874 }
81875
81876 /* Step the current leaf forward to the next term.  If we reach the
81877 ** end of the current leaf, step forward to the next leaf block.
81878 */
81879 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
81880   assert( !leavesReaderAtEnd(pReader) );
81881   leafReaderStep(&pReader->leafReader);
81882
81883   if( leafReaderAtEnd(&pReader->leafReader) ){
81884     int rc;
81885     if( pReader->rootData.pData ){
81886       pReader->eof = 1;
81887       return SQLITE_OK;
81888     }
81889     rc = sqlite3_step(pReader->pStmt);
81890     if( rc!=SQLITE_ROW ){
81891       pReader->eof = 1;
81892       return rc==SQLITE_DONE ? SQLITE_OK : rc;
81893     }
81894     leafReaderDestroy(&pReader->leafReader);
81895     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
81896                    sqlite3_column_bytes(pReader->pStmt, 0),
81897                    &pReader->leafReader);
81898   }
81899   return SQLITE_OK;
81900 }
81901
81902 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
81903 ** always sort to the end.
81904 */
81905 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
81906   if( leavesReaderAtEnd(lr1) ){
81907     if( leavesReaderAtEnd(lr2) ) return 0;
81908     return 1;
81909   }
81910   if( leavesReaderAtEnd(lr2) ) return -1;
81911
81912   return leafReaderTermCmp(&lr1->leafReader,
81913                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
81914                            0);
81915 }
81916
81917 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
81918 ** so that older segments sort before newer segments.
81919 */
81920 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
81921   int c = leavesReaderTermCmp(lr1, lr2);
81922   if( c!=0 ) return c;
81923   return lr1->idx-lr2->idx;
81924 }
81925
81926 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
81927 ** sorted position.
81928 */
81929 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
81930   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
81931     LeavesReader tmp = pLr[0];
81932     pLr[0] = pLr[1];
81933     pLr[1] = tmp;
81934     nLr--;
81935     pLr++;
81936   }
81937 }
81938
81939 /* Initializes pReaders with the segments from level iLevel, returning
81940 ** the number of segments in *piReaders.  Leaves pReaders in sorted
81941 ** order.
81942 */
81943 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
81944                              LeavesReader *pReaders, int *piReaders){
81945   sqlite3_stmt *s;
81946   int i, rc = sql_get_statement(v, SEGDIR_SELECT_STMT, &s);
81947   if( rc!=SQLITE_OK ) return rc;
81948
81949   rc = sqlite3_bind_int(s, 1, iLevel);
81950   if( rc!=SQLITE_OK ) return rc;
81951
81952   i = 0;
81953   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
81954     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
81955     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
81956     const char *pRootData = sqlite3_column_blob(s, 2);
81957     int nRootData = sqlite3_column_bytes(s, 2);
81958
81959     assert( i<MERGE_COUNT );
81960     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
81961                           &pReaders[i]);
81962     if( rc!=SQLITE_OK ) break;
81963
81964     i++;
81965   }
81966   if( rc!=SQLITE_DONE ){
81967     while( i-->0 ){
81968       leavesReaderDestroy(&pReaders[i]);
81969     }
81970     return rc;
81971   }
81972
81973   *piReaders = i;
81974
81975   /* Leave our results sorted by term, then age. */
81976   while( i-- ){
81977     leavesReaderReorder(pReaders+i, *piReaders-i);
81978   }
81979   return SQLITE_OK;
81980 }
81981
81982 /* Merge doclists from pReaders[nReaders] into a single doclist, which
81983 ** is written to pWriter.  Assumes pReaders is ordered oldest to
81984 ** newest.
81985 */
81986 /* TODO(shess) Consider putting this inline in segmentMerge(). */
81987 static int leavesReadersMerge(fulltext_vtab *v,
81988                               LeavesReader *pReaders, int nReaders,
81989                               LeafWriter *pWriter){
81990   DLReader dlReaders[MERGE_COUNT];
81991   const char *pTerm = leavesReaderTerm(pReaders);
81992   int i, nTerm = leavesReaderTermBytes(pReaders);
81993
81994   assert( nReaders<=MERGE_COUNT );
81995
81996   for(i=0; i<nReaders; i++){
81997     dlrInit(&dlReaders[i], DL_DEFAULT,
81998             leavesReaderData(pReaders+i),
81999             leavesReaderDataBytes(pReaders+i));
82000   }
82001
82002   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
82003 }
82004
82005 /* Forward ref due to mutual recursion with segdirNextIndex(). */
82006 static int segmentMerge(fulltext_vtab *v, int iLevel);
82007
82008 /* Put the next available index at iLevel into *pidx.  If iLevel
82009 ** already has MERGE_COUNT segments, they are merged to a higher
82010 ** level to make room.
82011 */
82012 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
82013   int rc = segdir_max_index(v, iLevel, pidx);
82014   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
82015     *pidx = 0;
82016   }else if( rc==SQLITE_ROW ){
82017     if( *pidx==(MERGE_COUNT-1) ){
82018       rc = segmentMerge(v, iLevel);
82019       if( rc!=SQLITE_OK ) return rc;
82020       *pidx = 0;
82021     }else{
82022       (*pidx)++;
82023     }
82024   }else{
82025     return rc;
82026   }
82027   return SQLITE_OK;
82028 }
82029
82030 /* Merge MERGE_COUNT segments at iLevel into a new segment at
82031 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
82032 ** merged to make room.
82033 */
82034 static int segmentMerge(fulltext_vtab *v, int iLevel){
82035   LeafWriter writer;
82036   LeavesReader lrs[MERGE_COUNT];
82037   int i, rc, idx = 0;
82038
82039   /* Determine the next available segment index at the next level,
82040   ** merging as necessary.
82041   */
82042   rc = segdirNextIndex(v, iLevel+1, &idx);
82043   if( rc!=SQLITE_OK ) return rc;
82044
82045   /* TODO(shess) This assumes that we'll always see exactly
82046   ** MERGE_COUNT segments to merge at a given level.  That will be
82047   ** broken if we allow the developer to request preemptive or
82048   ** deferred merging.
82049   */
82050   memset(&lrs, '\0', sizeof(lrs));
82051   rc = leavesReadersInit(v, iLevel, lrs, &i);
82052   if( rc!=SQLITE_OK ) return rc;
82053   assert( i==MERGE_COUNT );
82054
82055   leafWriterInit(iLevel+1, idx, &writer);
82056
82057   /* Since leavesReaderReorder() pushes readers at eof to the end,
82058   ** when the first reader is empty, all will be empty.
82059   */
82060   while( !leavesReaderAtEnd(lrs) ){
82061     /* Figure out how many readers share their next term. */
82062     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
82063       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
82064     }
82065
82066     rc = leavesReadersMerge(v, lrs, i, &writer);
82067     if( rc!=SQLITE_OK ) goto err;
82068
82069     /* Step forward those that were merged. */
82070     while( i-->0 ){
82071       rc = leavesReaderStep(v, lrs+i);
82072       if( rc!=SQLITE_OK ) goto err;
82073
82074       /* Reorder by term, then by age. */
82075       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
82076     }
82077   }
82078
82079   for(i=0; i<MERGE_COUNT; i++){
82080     leavesReaderDestroy(&lrs[i]);
82081   }
82082
82083   rc = leafWriterFinalize(v, &writer);
82084   leafWriterDestroy(&writer);
82085   if( rc!=SQLITE_OK ) return rc;
82086
82087   /* Delete the merged segment data. */
82088   return segdir_delete(v, iLevel);
82089
82090  err:
82091   for(i=0; i<MERGE_COUNT; i++){
82092     leavesReaderDestroy(&lrs[i]);
82093   }
82094   leafWriterDestroy(&writer);
82095   return rc;
82096 }
82097
82098 /* Accumulate the union of *acc and *pData into *acc. */
82099 static void docListAccumulateUnion(DataBuffer *acc,
82100                                    const char *pData, int nData) {
82101   DataBuffer tmp = *acc;
82102   dataBufferInit(acc, tmp.nData+nData);
82103   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
82104   dataBufferDestroy(&tmp);
82105 }
82106
82107 /* TODO(shess) It might be interesting to explore different merge
82108 ** strategies, here.  For instance, since this is a sorted merge, we
82109 ** could easily merge many doclists in parallel.  With some
82110 ** comprehension of the storage format, we could merge all of the
82111 ** doclists within a leaf node directly from the leaf node's storage.
82112 ** It may be worthwhile to merge smaller doclists before larger
82113 ** doclists, since they can be traversed more quickly - but the
82114 ** results may have less overlap, making them more expensive in a
82115 ** different way.
82116 */
82117
82118 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
82119 ** *out (any doclists with duplicate docids overwrite those in *out).
82120 ** Internal function for loadSegmentLeaf().
82121 */
82122 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
82123                                 const char *pTerm, int nTerm, int isPrefix,
82124                                 DataBuffer *out){
82125   /* doclist data is accumulated into pBuffers similar to how one does
82126   ** increment in binary arithmetic.  If index 0 is empty, the data is
82127   ** stored there.  If there is data there, it is merged and the
82128   ** results carried into position 1, with further merge-and-carry
82129   ** until an empty position is found.
82130   */
82131   DataBuffer *pBuffers = NULL;
82132   int nBuffers = 0, nMaxBuffers = 0, rc;
82133
82134   assert( nTerm>0 );
82135
82136   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
82137       rc=leavesReaderStep(v, pReader)){
82138     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
82139     ** already taken to compare the terms of two LeavesReaders.  Think
82140     ** on a better name.  [Meanwhile, break encapsulation rather than
82141     ** use a confusing name.]
82142     */
82143     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
82144     if( c>0 ) break;      /* Past any possible matches. */
82145     if( c==0 ){
82146       const char *pData = leavesReaderData(pReader);
82147       int iBuffer, nData = leavesReaderDataBytes(pReader);
82148
82149       /* Find the first empty buffer. */
82150       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
82151         if( 0==pBuffers[iBuffer].nData ) break;
82152       }
82153
82154       /* Out of buffers, add an empty one. */
82155       if( iBuffer==nBuffers ){
82156         if( nBuffers==nMaxBuffers ){
82157           DataBuffer *p;
82158           nMaxBuffers += 20;
82159
82160           /* Manual realloc so we can handle NULL appropriately. */
82161           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
82162           if( p==NULL ){
82163             rc = SQLITE_NOMEM;
82164             break;
82165           }
82166
82167           if( nBuffers>0 ){
82168             assert(pBuffers!=NULL);
82169             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
82170             sqlite3_free(pBuffers);
82171           }
82172           pBuffers = p;
82173         }
82174         dataBufferInit(&(pBuffers[nBuffers]), 0);
82175         nBuffers++;
82176       }
82177
82178       /* At this point, must have an empty at iBuffer. */
82179       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
82180
82181       /* If empty was first buffer, no need for merge logic. */
82182       if( iBuffer==0 ){
82183         dataBufferReplace(&(pBuffers[0]), pData, nData);
82184       }else{
82185         /* pAcc is the empty buffer the merged data will end up in. */
82186         DataBuffer *pAcc = &(pBuffers[iBuffer]);
82187         DataBuffer *p = &(pBuffers[0]);
82188
82189         /* Handle position 0 specially to avoid need to prime pAcc
82190         ** with pData/nData.
82191         */
82192         dataBufferSwap(p, pAcc);
82193         docListAccumulateUnion(pAcc, pData, nData);
82194
82195         /* Accumulate remaining doclists into pAcc. */
82196         for(++p; p<pAcc; ++p){
82197           docListAccumulateUnion(pAcc, p->pData, p->nData);
82198
82199           /* dataBufferReset() could allow a large doclist to blow up
82200           ** our memory requirements.
82201           */
82202           if( p->nCapacity<1024 ){
82203             dataBufferReset(p);
82204           }else{
82205             dataBufferDestroy(p);
82206             dataBufferInit(p, 0);
82207           }
82208         }
82209       }
82210     }
82211   }
82212
82213   /* Union all the doclists together into *out. */
82214   /* TODO(shess) What if *out is big?  Sigh. */
82215   if( rc==SQLITE_OK && nBuffers>0 ){
82216     int iBuffer;
82217     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
82218       if( pBuffers[iBuffer].nData>0 ){
82219         if( out->nData==0 ){
82220           dataBufferSwap(out, &(pBuffers[iBuffer]));
82221         }else{
82222           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
82223                                  pBuffers[iBuffer].nData);
82224         }
82225       }
82226     }
82227   }
82228
82229   while( nBuffers-- ){
82230     dataBufferDestroy(&(pBuffers[nBuffers]));
82231   }
82232   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
82233
82234   return rc;
82235 }
82236
82237 /* Call loadSegmentLeavesInt() with pData/nData as input. */
82238 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
82239                            const char *pTerm, int nTerm, int isPrefix,
82240                            DataBuffer *out){
82241   LeavesReader reader;
82242   int rc;
82243
82244   assert( nData>1 );
82245   assert( *pData=='\0' );
82246   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
82247   if( rc!=SQLITE_OK ) return rc;
82248
82249   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
82250   leavesReaderReset(&reader);
82251   leavesReaderDestroy(&reader);
82252   return rc;
82253 }
82254
82255 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
82256 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
82257 ** out.
82258 */
82259 static int loadSegmentLeaves(fulltext_vtab *v,
82260                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
82261                              const char *pTerm, int nTerm, int isPrefix,
82262                              DataBuffer *out){
82263   int rc;
82264   LeavesReader reader;
82265
82266   assert( iStartLeaf<=iEndLeaf );
82267   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
82268   if( rc!=SQLITE_OK ) return rc;
82269
82270   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
82271   leavesReaderReset(&reader);
82272   leavesReaderDestroy(&reader);
82273   return rc;
82274 }
82275
82276 /* Taking pData/nData as an interior node, find the sequence of child
82277 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
82278 ** interior node terms logically come between the blocks, so there is
82279 ** one more blockid than there are terms (that block contains terms >=
82280 ** the last interior-node term).
82281 */
82282 /* TODO(shess) The calling code may already know that the end child is
82283 ** not worth calculating, because the end may be in a later sibling
82284 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
82285 ** it is not worthwhile.
82286 */
82287 static void getChildrenContaining(const char *pData, int nData,
82288                                   const char *pTerm, int nTerm, int isPrefix,
82289                                   sqlite_int64 *piStartChild,
82290                                   sqlite_int64 *piEndChild){
82291   InteriorReader reader;
82292
82293   assert( nData>1 );
82294   assert( *pData!='\0' );
82295   interiorReaderInit(pData, nData, &reader);
82296
82297   /* Scan for the first child which could contain pTerm/nTerm. */
82298   while( !interiorReaderAtEnd(&reader) ){
82299     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
82300     interiorReaderStep(&reader);
82301   }
82302   *piStartChild = interiorReaderCurrentBlockid(&reader);
82303
82304   /* Keep scanning to find a term greater than our term, using prefix
82305   ** comparison if indicated.  If isPrefix is false, this will be the
82306   ** same blockid as the starting block.
82307   */
82308   while( !interiorReaderAtEnd(&reader) ){
82309     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
82310     interiorReaderStep(&reader);
82311   }
82312   *piEndChild = interiorReaderCurrentBlockid(&reader);
82313
82314   interiorReaderDestroy(&reader);
82315
82316   /* Children must ascend, and if !prefix, both must be the same. */
82317   assert( *piEndChild>=*piStartChild );
82318   assert( isPrefix || *piStartChild==*piEndChild );
82319 }
82320
82321 /* Read block at iBlockid and pass it with other params to
82322 ** getChildrenContaining().
82323 */
82324 static int loadAndGetChildrenContaining(
82325   fulltext_vtab *v,
82326   sqlite_int64 iBlockid,
82327   const char *pTerm, int nTerm, int isPrefix,
82328   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
82329 ){
82330   sqlite3_stmt *s = NULL;
82331   int rc;
82332
82333   assert( iBlockid!=0 );
82334   assert( pTerm!=NULL );
82335   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
82336   assert( piStartChild!=NULL );
82337   assert( piEndChild!=NULL );
82338
82339   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
82340   if( rc!=SQLITE_OK ) return rc;
82341
82342   rc = sqlite3_bind_int64(s, 1, iBlockid);
82343   if( rc!=SQLITE_OK ) return rc;
82344
82345   rc = sqlite3_step(s);
82346   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
82347   if( rc!=SQLITE_ROW ) return rc;
82348
82349   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
82350                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
82351
82352   /* We expect only one row.  We must execute another sqlite3_step()
82353    * to complete the iteration; otherwise the table will remain
82354    * locked. */
82355   rc = sqlite3_step(s);
82356   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
82357   if( rc!=SQLITE_DONE ) return rc;
82358
82359   return SQLITE_OK;
82360 }
82361
82362 /* Traverse the tree represented by pData[nData] looking for
82363 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
82364 ** loadSegment() to make error-handling cleaner.
82365 */
82366 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
82367                           sqlite_int64 iLeavesEnd,
82368                           const char *pTerm, int nTerm, int isPrefix,
82369                           DataBuffer *out){
82370   /* Special case where root is a leaf. */
82371   if( *pData=='\0' ){
82372     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
82373   }else{
82374     int rc;
82375     sqlite_int64 iStartChild, iEndChild;
82376
82377     /* Process pData as an interior node, then loop down the tree
82378     ** until we find the set of leaf nodes to scan for the term.
82379     */
82380     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
82381                           &iStartChild, &iEndChild);
82382     while( iStartChild>iLeavesEnd ){
82383       sqlite_int64 iNextStart, iNextEnd;
82384       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
82385                                         &iNextStart, &iNextEnd);
82386       if( rc!=SQLITE_OK ) return rc;
82387
82388       /* If we've branched, follow the end branch, too. */
82389       if( iStartChild!=iEndChild ){
82390         sqlite_int64 iDummy;
82391         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
82392                                           &iDummy, &iNextEnd);
82393         if( rc!=SQLITE_OK ) return rc;
82394       }
82395
82396       assert( iNextStart<=iNextEnd );
82397       iStartChild = iNextStart;
82398       iEndChild = iNextEnd;
82399     }
82400     assert( iStartChild<=iLeavesEnd );
82401     assert( iEndChild<=iLeavesEnd );
82402
82403     /* Scan through the leaf segments for doclists. */
82404     return loadSegmentLeaves(v, iStartChild, iEndChild,
82405                              pTerm, nTerm, isPrefix, out);
82406   }
82407 }
82408
82409 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
82410 ** merge its doclist over *out (any duplicate doclists read from the
82411 ** segment rooted at pData will overwrite those in *out).
82412 */
82413 /* TODO(shess) Consider changing this to determine the depth of the
82414 ** leaves using either the first characters of interior nodes (when
82415 ** ==1, we're one level above the leaves), or the first character of
82416 ** the root (which will describe the height of the tree directly).
82417 ** Either feels somewhat tricky to me.
82418 */
82419 /* TODO(shess) The current merge is likely to be slow for large
82420 ** doclists (though it should process from newest/smallest to
82421 ** oldest/largest, so it may not be that bad).  It might be useful to
82422 ** modify things to allow for N-way merging.  This could either be
82423 ** within a segment, with pairwise merges across segments, or across
82424 ** all segments at once.
82425 */
82426 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
82427                        sqlite_int64 iLeavesEnd,
82428                        const char *pTerm, int nTerm, int isPrefix,
82429                        DataBuffer *out){
82430   DataBuffer result;
82431   int rc;
82432
82433   assert( nData>1 );
82434
82435   /* This code should never be called with buffered updates. */
82436   assert( v->nPendingData<0 );
82437
82438   dataBufferInit(&result, 0);
82439   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
82440                       pTerm, nTerm, isPrefix, &result);
82441   if( rc==SQLITE_OK && result.nData>0 ){
82442     if( out->nData==0 ){
82443       DataBuffer tmp = *out;
82444       *out = result;
82445       result = tmp;
82446     }else{
82447       DataBuffer merged;
82448       DLReader readers[2];
82449
82450       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
82451       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
82452       dataBufferInit(&merged, out->nData+result.nData);
82453       docListMerge(&merged, readers, 2);
82454       dataBufferDestroy(out);
82455       *out = merged;
82456       dlrDestroy(&readers[0]);
82457       dlrDestroy(&readers[1]);
82458     }
82459   }
82460   dataBufferDestroy(&result);
82461   return rc;
82462 }
82463
82464 /* Scan the database and merge together the posting lists for the term
82465 ** into *out.
82466 */
82467 static int termSelect(fulltext_vtab *v, int iColumn,
82468                       const char *pTerm, int nTerm, int isPrefix,
82469                       DocListType iType, DataBuffer *out){
82470   DataBuffer doclist;
82471   sqlite3_stmt *s;
82472   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
82473   if( rc!=SQLITE_OK ) return rc;
82474
82475   /* This code should never be called with buffered updates. */
82476   assert( v->nPendingData<0 );
82477
82478   dataBufferInit(&doclist, 0);
82479
82480   /* Traverse the segments from oldest to newest so that newer doclist
82481   ** elements for given docids overwrite older elements.
82482   */
82483   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
82484     const char *pData = sqlite3_column_blob(s, 0);
82485     const int nData = sqlite3_column_bytes(s, 0);
82486     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
82487     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
82488                      &doclist);
82489     if( rc!=SQLITE_OK ) goto err;
82490   }
82491   if( rc==SQLITE_DONE ){
82492     if( doclist.nData!=0 ){
82493       /* TODO(shess) The old term_select_all() code applied the column
82494       ** restrict as we merged segments, leading to smaller buffers.
82495       ** This is probably worthwhile to bring back, once the new storage
82496       ** system is checked in.
82497       */
82498       if( iColumn==v->nColumn) iColumn = -1;
82499       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
82500                   iColumn, iType, out);
82501     }
82502     rc = SQLITE_OK;
82503   }
82504
82505  err:
82506   dataBufferDestroy(&doclist);
82507   return rc;
82508 }
82509
82510 /****************************************************************/
82511 /* Used to hold hashtable data for sorting. */
82512 typedef struct TermData {
82513   const char *pTerm;
82514   int nTerm;
82515   DLCollector *pCollector;
82516 } TermData;
82517
82518 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
82519 ** for equal, >0 for greater-than).
82520 */
82521 static int termDataCmp(const void *av, const void *bv){
82522   const TermData *a = (const TermData *)av;
82523   const TermData *b = (const TermData *)bv;
82524   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
82525   int c = memcmp(a->pTerm, b->pTerm, n);
82526   if( c!=0 ) return c;
82527   return a->nTerm-b->nTerm;
82528 }
82529
82530 /* Order pTerms data by term, then write a new level 0 segment using
82531 ** LeafWriter.
82532 */
82533 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
82534   fts3HashElem *e;
82535   int idx, rc, i, n;
82536   TermData *pData;
82537   LeafWriter writer;
82538   DataBuffer dl;
82539
82540   /* Determine the next index at level 0, merging as necessary. */
82541   rc = segdirNextIndex(v, 0, &idx);
82542   if( rc!=SQLITE_OK ) return rc;
82543
82544   n = fts3HashCount(pTerms);
82545   pData = sqlite3_malloc(n*sizeof(TermData));
82546
82547   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
82548     assert( i<n );
82549     pData[i].pTerm = fts3HashKey(e);
82550     pData[i].nTerm = fts3HashKeysize(e);
82551     pData[i].pCollector = fts3HashData(e);
82552   }
82553   assert( i==n );
82554
82555   /* TODO(shess) Should we allow user-defined collation sequences,
82556   ** here?  I think we only need that once we support prefix searches.
82557   */
82558   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
82559
82560   /* TODO(shess) Refactor so that we can write directly to the segment
82561   ** DataBuffer, as happens for segment merges.
82562   */
82563   leafWriterInit(0, idx, &writer);
82564   dataBufferInit(&dl, 0);
82565   for(i=0; i<n; i++){
82566     dataBufferReset(&dl);
82567     dlcAddDoclist(pData[i].pCollector, &dl);
82568     rc = leafWriterStep(v, &writer,
82569                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
82570     if( rc!=SQLITE_OK ) goto err;
82571   }
82572   rc = leafWriterFinalize(v, &writer);
82573
82574  err:
82575   dataBufferDestroy(&dl);
82576   sqlite3_free(pData);
82577   leafWriterDestroy(&writer);
82578   return rc;
82579 }
82580
82581 /* If pendingTerms has data, free it. */
82582 static int clearPendingTerms(fulltext_vtab *v){
82583   if( v->nPendingData>=0 ){
82584     fts3HashElem *e;
82585     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
82586       dlcDelete(fts3HashData(e));
82587     }
82588     fts3HashClear(&v->pendingTerms);
82589     v->nPendingData = -1;
82590   }
82591   return SQLITE_OK;
82592 }
82593
82594 /* If pendingTerms has data, flush it to a level-zero segment, and
82595 ** free it.
82596 */
82597 static int flushPendingTerms(fulltext_vtab *v){
82598   if( v->nPendingData>=0 ){
82599     int rc = writeZeroSegment(v, &v->pendingTerms);
82600     if( rc==SQLITE_OK ) clearPendingTerms(v);
82601     return rc;
82602   }
82603   return SQLITE_OK;
82604 }
82605
82606 /* If pendingTerms is "too big", or docid is out of order, flush it.
82607 ** Regardless, be certain that pendingTerms is initialized for use.
82608 */
82609 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
82610   /* TODO(shess) Explore whether partially flushing the buffer on
82611   ** forced-flush would provide better performance.  I suspect that if
82612   ** we ordered the doclists by size and flushed the largest until the
82613   ** buffer was half empty, that would let the less frequent terms
82614   ** generate longer doclists.
82615   */
82616   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
82617     int rc = flushPendingTerms(v);
82618     if( rc!=SQLITE_OK ) return rc;
82619   }
82620   if( v->nPendingData<0 ){
82621     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
82622     v->nPendingData = 0;
82623   }
82624   v->iPrevDocid = iDocid;
82625   return SQLITE_OK;
82626 }
82627
82628 /* This function implements the xUpdate callback; it is the top-level entry
82629  * point for inserting, deleting or updating a row in a full-text table. */
82630 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
82631                           sqlite_int64 *pRowid){
82632   fulltext_vtab *v = (fulltext_vtab *) pVtab;
82633   int rc;
82634
82635   FTSTRACE(("FTS3 Update %p\n", pVtab));
82636
82637   if( nArg<2 ){
82638     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
82639   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
82640     /* An update:
82641      * ppArg[0] = old rowid
82642      * ppArg[1] = new rowid
82643      * ppArg[2..2+v->nColumn-1] = values
82644      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
82645      * ppArg[2+v->nColumn+1] = value for docid
82646      */
82647     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
82648     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
82649         sqlite3_value_int64(ppArg[1]) != rowid ){
82650       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
82651     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
82652               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
82653       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
82654     }else{
82655       assert( nArg==2+v->nColumn+2);
82656       rc = index_update(v, rowid, &ppArg[2]);
82657     }
82658   } else {
82659     /* An insert:
82660      * ppArg[1] = requested rowid
82661      * ppArg[2..2+v->nColumn-1] = values
82662      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
82663      * ppArg[2+v->nColumn+1] = value for docid
82664      */
82665     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
82666     assert( nArg==2+v->nColumn+2);
82667     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
82668         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
82669       /* TODO(shess) Consider allowing this to work if the values are
82670       ** identical.  I'm inclined to discourage that usage, though,
82671       ** given that both rowid and docid are special columns.  Better
82672       ** would be to define one or the other as the default winner,
82673       ** but should it be fts3-centric (docid) or SQLite-centric
82674       ** (rowid)?
82675       */
82676       rc = SQLITE_ERROR;
82677     }else{
82678       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
82679         pRequestDocid = ppArg[1];
82680       }
82681       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
82682     }
82683   }
82684
82685   return rc;
82686 }
82687
82688 static int fulltextSync(sqlite3_vtab *pVtab){
82689   FTSTRACE(("FTS3 xSync()\n"));
82690   return flushPendingTerms((fulltext_vtab *)pVtab);
82691 }
82692
82693 static int fulltextBegin(sqlite3_vtab *pVtab){
82694   fulltext_vtab *v = (fulltext_vtab *) pVtab;
82695   FTSTRACE(("FTS3 xBegin()\n"));
82696
82697   /* Any buffered updates should have been cleared by the previous
82698   ** transaction.
82699   */
82700   assert( v->nPendingData<0 );
82701   return clearPendingTerms(v);
82702 }
82703
82704 static int fulltextCommit(sqlite3_vtab *pVtab){
82705   fulltext_vtab *v = (fulltext_vtab *) pVtab;
82706   FTSTRACE(("FTS3 xCommit()\n"));
82707
82708   /* Buffered updates should have been cleared by fulltextSync(). */
82709   assert( v->nPendingData<0 );
82710   return clearPendingTerms(v);
82711 }
82712
82713 static int fulltextRollback(sqlite3_vtab *pVtab){
82714   FTSTRACE(("FTS3 xRollback()\n"));
82715   return clearPendingTerms((fulltext_vtab *)pVtab);
82716 }
82717
82718 /*
82719 ** Implementation of the snippet() function for FTS3
82720 */
82721 static void snippetFunc(
82722   sqlite3_context *pContext,
82723   int argc,
82724   sqlite3_value **argv
82725 ){
82726   fulltext_cursor *pCursor;
82727   if( argc<1 ) return;
82728   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
82729       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
82730     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
82731   }else{
82732     const char *zStart = "<b>";
82733     const char *zEnd = "</b>";
82734     const char *zEllipsis = "<b>...</b>";
82735     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
82736     if( argc>=2 ){
82737       zStart = (const char*)sqlite3_value_text(argv[1]);
82738       if( argc>=3 ){
82739         zEnd = (const char*)sqlite3_value_text(argv[2]);
82740         if( argc>=4 ){
82741           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
82742         }
82743       }
82744     }
82745     snippetAllOffsets(pCursor);
82746     snippetText(pCursor, zStart, zEnd, zEllipsis);
82747     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
82748                         pCursor->snippet.nSnippet, SQLITE_STATIC);
82749   }
82750 }
82751
82752 /*
82753 ** Implementation of the offsets() function for FTS3
82754 */
82755 static void snippetOffsetsFunc(
82756   sqlite3_context *pContext,
82757   int argc,
82758   sqlite3_value **argv
82759 ){
82760   fulltext_cursor *pCursor;
82761   if( argc<1 ) return;
82762   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
82763       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
82764     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
82765   }else{
82766     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
82767     snippetAllOffsets(pCursor);
82768     snippetOffsetText(&pCursor->snippet);
82769     sqlite3_result_text(pContext,
82770                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
82771                         SQLITE_STATIC);
82772   }
82773 }
82774
82775 /*
82776 ** This routine implements the xFindFunction method for the FTS3
82777 ** virtual table.
82778 */
82779 static int fulltextFindFunction(
82780   sqlite3_vtab *pVtab,
82781   int nArg,
82782   const char *zName,
82783   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
82784   void **ppArg
82785 ){
82786   if( strcmp(zName,"snippet")==0 ){
82787     *pxFunc = snippetFunc;
82788     return 1;
82789   }else if( strcmp(zName,"offsets")==0 ){
82790     *pxFunc = snippetOffsetsFunc;
82791     return 1;
82792   }
82793   return 0;
82794 }
82795
82796 /*
82797 ** Rename an fts3 table.
82798 */
82799 static int fulltextRename(
82800   sqlite3_vtab *pVtab,
82801   const char *zName
82802 ){
82803   fulltext_vtab *p = (fulltext_vtab *)pVtab;
82804   int rc = SQLITE_NOMEM;
82805   char *zSql = sqlite3_mprintf(
82806     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
82807     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
82808     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
82809     , p->zDb, p->zName, zName 
82810     , p->zDb, p->zName, zName 
82811     , p->zDb, p->zName, zName
82812   );
82813   if( zSql ){
82814     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
82815     sqlite3_free(zSql);
82816   }
82817   return rc;
82818 }
82819
82820 static const sqlite3_module fts3Module = {
82821   /* iVersion      */ 0,
82822   /* xCreate       */ fulltextCreate,
82823   /* xConnect      */ fulltextConnect,
82824   /* xBestIndex    */ fulltextBestIndex,
82825   /* xDisconnect   */ fulltextDisconnect,
82826   /* xDestroy      */ fulltextDestroy,
82827   /* xOpen         */ fulltextOpen,
82828   /* xClose        */ fulltextClose,
82829   /* xFilter       */ fulltextFilter,
82830   /* xNext         */ fulltextNext,
82831   /* xEof          */ fulltextEof,
82832   /* xColumn       */ fulltextColumn,
82833   /* xRowid        */ fulltextRowid,
82834   /* xUpdate       */ fulltextUpdate,
82835   /* xBegin        */ fulltextBegin,
82836   /* xSync         */ fulltextSync,
82837   /* xCommit       */ fulltextCommit,
82838   /* xRollback     */ fulltextRollback,
82839   /* xFindFunction */ fulltextFindFunction,
82840   /* xRename */       fulltextRename,
82841 };
82842
82843 static void hashDestroy(void *p){
82844   fts3Hash *pHash = (fts3Hash *)p;
82845   sqlite3Fts3HashClear(pHash);
82846   sqlite3_free(pHash);
82847 }
82848
82849 /*
82850 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
82851 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
82852 ** two forward declarations are for functions declared in these files
82853 ** used to retrieve the respective implementations.
82854 **
82855 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
82856 ** to by the argument to point a the "simple" tokenizer implementation.
82857 ** Function ...PorterTokenizerModule() sets *pModule to point to the
82858 ** porter tokenizer/stemmer implementation.
82859 */
82860 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
82861 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
82862 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
82863
82864 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
82865
82866 /*
82867 ** Initialise the fts3 extension. If this extension is built as part
82868 ** of the sqlite library, then this function is called directly by
82869 ** SQLite. If fts3 is built as a dynamically loadable extension, this
82870 ** function is called by the sqlite3_extension_init() entry point.
82871 */
82872 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
82873   int rc = SQLITE_OK;
82874   fts3Hash *pHash = 0;
82875   const sqlite3_tokenizer_module *pSimple = 0;
82876   const sqlite3_tokenizer_module *pPorter = 0;
82877   const sqlite3_tokenizer_module *pIcu = 0;
82878
82879   sqlite3Fts3SimpleTokenizerModule(&pSimple);
82880   sqlite3Fts3PorterTokenizerModule(&pPorter);
82881 #ifdef SQLITE_ENABLE_ICU
82882   sqlite3Fts3IcuTokenizerModule(&pIcu);
82883 #endif
82884
82885   /* Allocate and initialise the hash-table used to store tokenizers. */
82886   pHash = sqlite3_malloc(sizeof(fts3Hash));
82887   if( !pHash ){
82888     rc = SQLITE_NOMEM;
82889   }else{
82890     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
82891   }
82892
82893   /* Load the built-in tokenizers into the hash table */
82894   if( rc==SQLITE_OK ){
82895     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
82896      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
82897      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
82898     ){
82899       rc = SQLITE_NOMEM;
82900     }
82901   }
82902
82903   /* Create the virtual table wrapper around the hash-table and overload 
82904   ** the two scalar functions. If this is successful, register the
82905   ** module with sqlite.
82906   */
82907   if( SQLITE_OK==rc 
82908    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
82909    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
82910    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
82911   ){
82912     return sqlite3_create_module_v2(
82913         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
82914     );
82915   }
82916
82917   /* An error has occured. Delete the hash table and return the error code. */
82918   assert( rc!=SQLITE_OK );
82919   if( pHash ){
82920     sqlite3Fts3HashClear(pHash);
82921     sqlite3_free(pHash);
82922   }
82923   return rc;
82924 }
82925
82926 #if !SQLITE_CORE
82927 SQLITE_API int sqlite3_extension_init(
82928   sqlite3 *db, 
82929   char **pzErrMsg,
82930   const sqlite3_api_routines *pApi
82931 ){
82932   SQLITE_EXTENSION_INIT2(pApi)
82933   return sqlite3Fts3Init(db);
82934 }
82935 #endif
82936
82937 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
82938
82939 /************** End of fts3.c ************************************************/
82940 /************** Begin file fts3_hash.c ***************************************/
82941 /*
82942 ** 2001 September 22
82943 **
82944 ** The author disclaims copyright to this source code.  In place of
82945 ** a legal notice, here is a blessing:
82946 **
82947 **    May you do good and not evil.
82948 **    May you find forgiveness for yourself and forgive others.
82949 **    May you share freely, never taking more than you give.
82950 **
82951 *************************************************************************
82952 ** This is the implementation of generic hash-tables used in SQLite.
82953 ** We've modified it slightly to serve as a standalone hash table
82954 ** implementation for the full-text indexing module.
82955 */
82956
82957 /*
82958 ** The code in this file is only compiled if:
82959 **
82960 **     * The FTS3 module is being built as an extension
82961 **       (in which case SQLITE_CORE is not defined), or
82962 **
82963 **     * The FTS3 module is being built into the core of
82964 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
82965 */
82966 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
82967
82968
82969
82970 /*
82971 ** Malloc and Free functions
82972 */
82973 static void *fts3HashMalloc(int n){
82974   void *p = sqlite3_malloc(n);
82975   if( p ){
82976     memset(p, 0, n);
82977   }
82978   return p;
82979 }
82980 static void fts3HashFree(void *p){
82981   sqlite3_free(p);
82982 }
82983
82984 /* Turn bulk memory into a hash table object by initializing the
82985 ** fields of the Hash structure.
82986 **
82987 ** "pNew" is a pointer to the hash table that is to be initialized.
82988 ** keyClass is one of the constants 
82989 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
82990 ** determines what kind of key the hash table will use.  "copyKey" is
82991 ** true if the hash table should make its own private copy of keys and
82992 ** false if it should just use the supplied pointer.
82993 */
82994 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
82995   assert( pNew!=0 );
82996   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
82997   pNew->keyClass = keyClass;
82998   pNew->copyKey = copyKey;
82999   pNew->first = 0;
83000   pNew->count = 0;
83001   pNew->htsize = 0;
83002   pNew->ht = 0;
83003 }
83004
83005 /* Remove all entries from a hash table.  Reclaim all memory.
83006 ** Call this routine to delete a hash table or to reset a hash table
83007 ** to the empty state.
83008 */
83009 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
83010   fts3HashElem *elem;         /* For looping over all elements of the table */
83011
83012   assert( pH!=0 );
83013   elem = pH->first;
83014   pH->first = 0;
83015   fts3HashFree(pH->ht);
83016   pH->ht = 0;
83017   pH->htsize = 0;
83018   while( elem ){
83019     fts3HashElem *next_elem = elem->next;
83020     if( pH->copyKey && elem->pKey ){
83021       fts3HashFree(elem->pKey);
83022     }
83023     fts3HashFree(elem);
83024     elem = next_elem;
83025   }
83026   pH->count = 0;
83027 }
83028
83029 /*
83030 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
83031 */
83032 static int fts3StrHash(const void *pKey, int nKey){
83033   const char *z = (const char *)pKey;
83034   int h = 0;
83035   if( nKey<=0 ) nKey = (int) strlen(z);
83036   while( nKey > 0  ){
83037     h = (h<<3) ^ h ^ *z++;
83038     nKey--;
83039   }
83040   return h & 0x7fffffff;
83041 }
83042 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
83043   if( n1!=n2 ) return 1;
83044   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
83045 }
83046
83047 /*
83048 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
83049 */
83050 static int fts3BinHash(const void *pKey, int nKey){
83051   int h = 0;
83052   const char *z = (const char *)pKey;
83053   while( nKey-- > 0 ){
83054     h = (h<<3) ^ h ^ *(z++);
83055   }
83056   return h & 0x7fffffff;
83057 }
83058 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
83059   if( n1!=n2 ) return 1;
83060   return memcmp(pKey1,pKey2,n1);
83061 }
83062
83063 /*
83064 ** Return a pointer to the appropriate hash function given the key class.
83065 **
83066 ** The C syntax in this function definition may be unfamilar to some 
83067 ** programmers, so we provide the following additional explanation:
83068 **
83069 ** The name of the function is "ftsHashFunction".  The function takes a
83070 ** single parameter "keyClass".  The return value of ftsHashFunction()
83071 ** is a pointer to another function.  Specifically, the return value
83072 ** of ftsHashFunction() is a pointer to a function that takes two parameters
83073 ** with types "const void*" and "int" and returns an "int".
83074 */
83075 static int (*ftsHashFunction(int keyClass))(const void*,int){
83076   if( keyClass==FTS3_HASH_STRING ){
83077     return &fts3StrHash;
83078   }else{
83079     assert( keyClass==FTS3_HASH_BINARY );
83080     return &fts3BinHash;
83081   }
83082 }
83083
83084 /*
83085 ** Return a pointer to the appropriate hash function given the key class.
83086 **
83087 ** For help in interpreted the obscure C code in the function definition,
83088 ** see the header comment on the previous function.
83089 */
83090 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
83091   if( keyClass==FTS3_HASH_STRING ){
83092     return &fts3StrCompare;
83093   }else{
83094     assert( keyClass==FTS3_HASH_BINARY );
83095     return &fts3BinCompare;
83096   }
83097 }
83098
83099 /* Link an element into the hash table
83100 */
83101 static void fts3HashInsertElement(
83102   fts3Hash *pH,            /* The complete hash table */
83103   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
83104   fts3HashElem *pNew       /* The element to be inserted */
83105 ){
83106   fts3HashElem *pHead;     /* First element already in pEntry */
83107   pHead = pEntry->chain;
83108   if( pHead ){
83109     pNew->next = pHead;
83110     pNew->prev = pHead->prev;
83111     if( pHead->prev ){ pHead->prev->next = pNew; }
83112     else             { pH->first = pNew; }
83113     pHead->prev = pNew;
83114   }else{
83115     pNew->next = pH->first;
83116     if( pH->first ){ pH->first->prev = pNew; }
83117     pNew->prev = 0;
83118     pH->first = pNew;
83119   }
83120   pEntry->count++;
83121   pEntry->chain = pNew;
83122 }
83123
83124
83125 /* Resize the hash table so that it cantains "new_size" buckets.
83126 ** "new_size" must be a power of 2.  The hash table might fail 
83127 ** to resize if sqliteMalloc() fails.
83128 */
83129 static void fts3Rehash(fts3Hash *pH, int new_size){
83130   struct _fts3ht *new_ht;          /* The new hash table */
83131   fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
83132   int (*xHash)(const void*,int);   /* The hash function */
83133
83134   assert( (new_size & (new_size-1))==0 );
83135   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
83136   if( new_ht==0 ) return;
83137   fts3HashFree(pH->ht);
83138   pH->ht = new_ht;
83139   pH->htsize = new_size;
83140   xHash = ftsHashFunction(pH->keyClass);
83141   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
83142     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
83143     next_elem = elem->next;
83144     fts3HashInsertElement(pH, &new_ht[h], elem);
83145   }
83146 }
83147
83148 /* This function (for internal use only) locates an element in an
83149 ** hash table that matches the given key.  The hash for this key has
83150 ** already been computed and is passed as the 4th parameter.
83151 */
83152 static fts3HashElem *fts3FindElementByHash(
83153   const fts3Hash *pH, /* The pH to be searched */
83154   const void *pKey,   /* The key we are searching for */
83155   int nKey,
83156   int h               /* The hash for this key. */
83157 ){
83158   fts3HashElem *elem;            /* Used to loop thru the element list */
83159   int count;                     /* Number of elements left to test */
83160   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
83161
83162   if( pH->ht ){
83163     struct _fts3ht *pEntry = &pH->ht[h];
83164     elem = pEntry->chain;
83165     count = pEntry->count;
83166     xCompare = ftsCompareFunction(pH->keyClass);
83167     while( count-- && elem ){
83168       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
83169         return elem;
83170       }
83171       elem = elem->next;
83172     }
83173   }
83174   return 0;
83175 }
83176
83177 /* Remove a single entry from the hash table given a pointer to that
83178 ** element and a hash on the element's key.
83179 */
83180 static void fts3RemoveElementByHash(
83181   fts3Hash *pH,         /* The pH containing "elem" */
83182   fts3HashElem* elem,   /* The element to be removed from the pH */
83183   int h                 /* Hash value for the element */
83184 ){
83185   struct _fts3ht *pEntry;
83186   if( elem->prev ){
83187     elem->prev->next = elem->next; 
83188   }else{
83189     pH->first = elem->next;
83190   }
83191   if( elem->next ){
83192     elem->next->prev = elem->prev;
83193   }
83194   pEntry = &pH->ht[h];
83195   if( pEntry->chain==elem ){
83196     pEntry->chain = elem->next;
83197   }
83198   pEntry->count--;
83199   if( pEntry->count<=0 ){
83200     pEntry->chain = 0;
83201   }
83202   if( pH->copyKey && elem->pKey ){
83203     fts3HashFree(elem->pKey);
83204   }
83205   fts3HashFree( elem );
83206   pH->count--;
83207   if( pH->count<=0 ){
83208     assert( pH->first==0 );
83209     assert( pH->count==0 );
83210     fts3HashClear(pH);
83211   }
83212 }
83213
83214 /* Attempt to locate an element of the hash table pH with a key
83215 ** that matches pKey,nKey.  Return the data for this element if it is
83216 ** found, or NULL if there is no match.
83217 */
83218 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
83219   int h;                 /* A hash on key */
83220   fts3HashElem *elem;    /* The element that matches key */
83221   int (*xHash)(const void*,int);  /* The hash function */
83222
83223   if( pH==0 || pH->ht==0 ) return 0;
83224   xHash = ftsHashFunction(pH->keyClass);
83225   assert( xHash!=0 );
83226   h = (*xHash)(pKey,nKey);
83227   assert( (pH->htsize & (pH->htsize-1))==0 );
83228   elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
83229   return elem ? elem->data : 0;
83230 }
83231
83232 /* Insert an element into the hash table pH.  The key is pKey,nKey
83233 ** and the data is "data".
83234 **
83235 ** If no element exists with a matching key, then a new
83236 ** element is created.  A copy of the key is made if the copyKey
83237 ** flag is set.  NULL is returned.
83238 **
83239 ** If another element already exists with the same key, then the
83240 ** new data replaces the old data and the old data is returned.
83241 ** The key is not copied in this instance.  If a malloc fails, then
83242 ** the new data is returned and the hash table is unchanged.
83243 **
83244 ** If the "data" parameter to this function is NULL, then the
83245 ** element corresponding to "key" is removed from the hash table.
83246 */
83247 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
83248   fts3Hash *pH,        /* The hash table to insert into */
83249   const void *pKey,    /* The key */
83250   int nKey,            /* Number of bytes in the key */
83251   void *data           /* The data */
83252 ){
83253   int hraw;                 /* Raw hash value of the key */
83254   int h;                    /* the hash of the key modulo hash table size */
83255   fts3HashElem *elem;       /* Used to loop thru the element list */
83256   fts3HashElem *new_elem;   /* New element added to the pH */
83257   int (*xHash)(const void*,int);  /* The hash function */
83258
83259   assert( pH!=0 );
83260   xHash = ftsHashFunction(pH->keyClass);
83261   assert( xHash!=0 );
83262   hraw = (*xHash)(pKey, nKey);
83263   assert( (pH->htsize & (pH->htsize-1))==0 );
83264   h = hraw & (pH->htsize-1);
83265   elem = fts3FindElementByHash(pH,pKey,nKey,h);
83266   if( elem ){
83267     void *old_data = elem->data;
83268     if( data==0 ){
83269       fts3RemoveElementByHash(pH,elem,h);
83270     }else{
83271       elem->data = data;
83272     }
83273     return old_data;
83274   }
83275   if( data==0 ) return 0;
83276   new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
83277   if( new_elem==0 ) return data;
83278   if( pH->copyKey && pKey!=0 ){
83279     new_elem->pKey = fts3HashMalloc( nKey );
83280     if( new_elem->pKey==0 ){
83281       fts3HashFree(new_elem);
83282       return data;
83283     }
83284     memcpy((void*)new_elem->pKey, pKey, nKey);
83285   }else{
83286     new_elem->pKey = (void*)pKey;
83287   }
83288   new_elem->nKey = nKey;
83289   pH->count++;
83290   if( pH->htsize==0 ){
83291     fts3Rehash(pH,8);
83292     if( pH->htsize==0 ){
83293       pH->count = 0;
83294       fts3HashFree(new_elem);
83295       return data;
83296     }
83297   }
83298   if( pH->count > pH->htsize ){
83299     fts3Rehash(pH,pH->htsize*2);
83300   }
83301   assert( pH->htsize>0 );
83302   assert( (pH->htsize & (pH->htsize-1))==0 );
83303   h = hraw & (pH->htsize-1);
83304   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
83305   new_elem->data = data;
83306   return 0;
83307 }
83308
83309 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
83310
83311 /************** End of fts3_hash.c *******************************************/
83312 /************** Begin file fts3_porter.c *************************************/
83313 /*
83314 ** 2006 September 30
83315 **
83316 ** The author disclaims copyright to this source code.  In place of
83317 ** a legal notice, here is a blessing:
83318 **
83319 **    May you do good and not evil.
83320 **    May you find forgiveness for yourself and forgive others.
83321 **    May you share freely, never taking more than you give.
83322 **
83323 *************************************************************************
83324 ** Implementation of the full-text-search tokenizer that implements
83325 ** a Porter stemmer.
83326 */
83327
83328 /*
83329 ** The code in this file is only compiled if:
83330 **
83331 **     * The FTS3 module is being built as an extension
83332 **       (in which case SQLITE_CORE is not defined), or
83333 **
83334 **     * The FTS3 module is being built into the core of
83335 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
83336 */
83337 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
83338
83339
83340
83341
83342 /*
83343 ** Class derived from sqlite3_tokenizer
83344 */
83345 typedef struct porter_tokenizer {
83346   sqlite3_tokenizer base;      /* Base class */
83347 } porter_tokenizer;
83348
83349 /*
83350 ** Class derived from sqlit3_tokenizer_cursor
83351 */
83352 typedef struct porter_tokenizer_cursor {
83353   sqlite3_tokenizer_cursor base;
83354   const char *zInput;          /* input we are tokenizing */
83355   int nInput;                  /* size of the input */
83356   int iOffset;                 /* current position in zInput */
83357   int iToken;                  /* index of next token to be returned */
83358   char *zToken;                /* storage for current token */
83359   int nAllocated;              /* space allocated to zToken buffer */
83360 } porter_tokenizer_cursor;
83361
83362
83363 /* Forward declaration */
83364 static const sqlite3_tokenizer_module porterTokenizerModule;
83365
83366
83367 /*
83368 ** Create a new tokenizer instance.
83369 */
83370 static int porterCreate(
83371   int argc, const char * const *argv,
83372   sqlite3_tokenizer **ppTokenizer
83373 ){
83374   porter_tokenizer *t;
83375   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
83376   if( t==NULL ) return SQLITE_NOMEM;
83377   memset(t, 0, sizeof(*t));
83378   *ppTokenizer = &t->base;
83379   return SQLITE_OK;
83380 }
83381
83382 /*
83383 ** Destroy a tokenizer
83384 */
83385 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
83386   sqlite3_free(pTokenizer);
83387   return SQLITE_OK;
83388 }
83389
83390 /*
83391 ** Prepare to begin tokenizing a particular string.  The input
83392 ** string to be tokenized is zInput[0..nInput-1].  A cursor
83393 ** used to incrementally tokenize this string is returned in 
83394 ** *ppCursor.
83395 */
83396 static int porterOpen(
83397   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
83398   const char *zInput, int nInput,        /* String to be tokenized */
83399   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
83400 ){
83401   porter_tokenizer_cursor *c;
83402
83403   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
83404   if( c==NULL ) return SQLITE_NOMEM;
83405
83406   c->zInput = zInput;
83407   if( zInput==0 ){
83408     c->nInput = 0;
83409   }else if( nInput<0 ){
83410     c->nInput = (int)strlen(zInput);
83411   }else{
83412     c->nInput = nInput;
83413   }
83414   c->iOffset = 0;                 /* start tokenizing at the beginning */
83415   c->iToken = 0;
83416   c->zToken = NULL;               /* no space allocated, yet. */
83417   c->nAllocated = 0;
83418
83419   *ppCursor = &c->base;
83420   return SQLITE_OK;
83421 }
83422
83423 /*
83424 ** Close a tokenization cursor previously opened by a call to
83425 ** porterOpen() above.
83426 */
83427 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
83428   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
83429   sqlite3_free(c->zToken);
83430   sqlite3_free(c);
83431   return SQLITE_OK;
83432 }
83433 /*
83434 ** Vowel or consonant
83435 */
83436 static const char cType[] = {
83437    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
83438    1, 1, 1, 2, 1
83439 };
83440
83441 /*
83442 ** isConsonant() and isVowel() determine if their first character in
83443 ** the string they point to is a consonant or a vowel, according
83444 ** to Porter ruls.  
83445 **
83446 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
83447 ** 'Y' is a consonant unless it follows another consonant,
83448 ** in which case it is a vowel.
83449 **
83450 ** In these routine, the letters are in reverse order.  So the 'y' rule
83451 ** is that 'y' is a consonant unless it is followed by another
83452 ** consonent.
83453 */
83454 static int isVowel(const char*);
83455 static int isConsonant(const char *z){
83456   int j;
83457   char x = *z;
83458   if( x==0 ) return 0;
83459   assert( x>='a' && x<='z' );
83460   j = cType[x-'a'];
83461   if( j<2 ) return j;
83462   return z[1]==0 || isVowel(z + 1);
83463 }
83464 static int isVowel(const char *z){
83465   int j;
83466   char x = *z;
83467   if( x==0 ) return 0;
83468   assert( x>='a' && x<='z' );
83469   j = cType[x-'a'];
83470   if( j<2 ) return 1-j;
83471   return isConsonant(z + 1);
83472 }
83473
83474 /*
83475 ** Let any sequence of one or more vowels be represented by V and let
83476 ** C be sequence of one or more consonants.  Then every word can be
83477 ** represented as:
83478 **
83479 **           [C] (VC){m} [V]
83480 **
83481 ** In prose:  A word is an optional consonant followed by zero or
83482 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
83483 ** number of vowel consonant pairs.  This routine computes the value
83484 ** of m for the first i bytes of a word.
83485 **
83486 ** Return true if the m-value for z is 1 or more.  In other words,
83487 ** return true if z contains at least one vowel that is followed
83488 ** by a consonant.
83489 **
83490 ** In this routine z[] is in reverse order.  So we are really looking
83491 ** for an instance of of a consonant followed by a vowel.
83492 */
83493 static int m_gt_0(const char *z){
83494   while( isVowel(z) ){ z++; }
83495   if( *z==0 ) return 0;
83496   while( isConsonant(z) ){ z++; }
83497   return *z!=0;
83498 }
83499
83500 /* Like mgt0 above except we are looking for a value of m which is
83501 ** exactly 1
83502 */
83503 static int m_eq_1(const char *z){
83504   while( isVowel(z) ){ z++; }
83505   if( *z==0 ) return 0;
83506   while( isConsonant(z) ){ z++; }
83507   if( *z==0 ) return 0;
83508   while( isVowel(z) ){ z++; }
83509   if( *z==0 ) return 1;
83510   while( isConsonant(z) ){ z++; }
83511   return *z==0;
83512 }
83513
83514 /* Like mgt0 above except we are looking for a value of m>1 instead
83515 ** or m>0
83516 */
83517 static int m_gt_1(const char *z){
83518   while( isVowel(z) ){ z++; }
83519   if( *z==0 ) return 0;
83520   while( isConsonant(z) ){ z++; }
83521   if( *z==0 ) return 0;
83522   while( isVowel(z) ){ z++; }
83523   if( *z==0 ) return 0;
83524   while( isConsonant(z) ){ z++; }
83525   return *z!=0;
83526 }
83527
83528 /*
83529 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
83530 */
83531 static int hasVowel(const char *z){
83532   while( isConsonant(z) ){ z++; }
83533   return *z!=0;
83534 }
83535
83536 /*
83537 ** Return TRUE if the word ends in a double consonant.
83538 **
83539 ** The text is reversed here. So we are really looking at
83540 ** the first two characters of z[].
83541 */
83542 static int doubleConsonant(const char *z){
83543   return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
83544 }
83545
83546 /*
83547 ** Return TRUE if the word ends with three letters which
83548 ** are consonant-vowel-consonent and where the final consonant
83549 ** is not 'w', 'x', or 'y'.
83550 **
83551 ** The word is reversed here.  So we are really checking the
83552 ** first three letters and the first one cannot be in [wxy].
83553 */
83554 static int star_oh(const char *z){
83555   return
83556     z[0]!=0 && isConsonant(z) &&
83557     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
83558     z[1]!=0 && isVowel(z+1) &&
83559     z[2]!=0 && isConsonant(z+2);
83560 }
83561
83562 /*
83563 ** If the word ends with zFrom and xCond() is true for the stem
83564 ** of the word that preceeds the zFrom ending, then change the 
83565 ** ending to zTo.
83566 **
83567 ** The input word *pz and zFrom are both in reverse order.  zTo
83568 ** is in normal order. 
83569 **
83570 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
83571 ** match.  Not that TRUE is returned even if xCond() fails and
83572 ** no substitution occurs.
83573 */
83574 static int stem(
83575   char **pz,             /* The word being stemmed (Reversed) */
83576   const char *zFrom,     /* If the ending matches this... (Reversed) */
83577   const char *zTo,       /* ... change the ending to this (not reversed) */
83578   int (*xCond)(const char*)   /* Condition that must be true */
83579 ){
83580   char *z = *pz;
83581   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
83582   if( *zFrom!=0 ) return 0;
83583   if( xCond && !xCond(z) ) return 1;
83584   while( *zTo ){
83585     *(--z) = *(zTo++);
83586   }
83587   *pz = z;
83588   return 1;
83589 }
83590
83591 /*
83592 ** This is the fallback stemmer used when the porter stemmer is
83593 ** inappropriate.  The input word is copied into the output with
83594 ** US-ASCII case folding.  If the input word is too long (more
83595 ** than 20 bytes if it contains no digits or more than 6 bytes if
83596 ** it contains digits) then word is truncated to 20 or 6 bytes
83597 ** by taking 10 or 3 bytes from the beginning and end.
83598 */
83599 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
83600   int i, mx, j;
83601   int hasDigit = 0;
83602   for(i=0; i<nIn; i++){
83603     int c = zIn[i];
83604     if( c>='A' && c<='Z' ){
83605       zOut[i] = c - 'A' + 'a';
83606     }else{
83607       if( c>='0' && c<='9' ) hasDigit = 1;
83608       zOut[i] = c;
83609     }
83610   }
83611   mx = hasDigit ? 3 : 10;
83612   if( nIn>mx*2 ){
83613     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
83614       zOut[j] = zOut[i];
83615     }
83616     i = j;
83617   }
83618   zOut[i] = 0;
83619   *pnOut = i;
83620 }
83621
83622
83623 /*
83624 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
83625 ** zOut is at least big enough to hold nIn bytes.  Write the actual
83626 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
83627 **
83628 ** Any upper-case characters in the US-ASCII character set ([A-Z])
83629 ** are converted to lower case.  Upper-case UTF characters are
83630 ** unchanged.
83631 **
83632 ** Words that are longer than about 20 bytes are stemmed by retaining
83633 ** a few bytes from the beginning and the end of the word.  If the
83634 ** word contains digits, 3 bytes are taken from the beginning and
83635 ** 3 bytes from the end.  For long words without digits, 10 bytes
83636 ** are taken from each end.  US-ASCII case folding still applies.
83637 ** 
83638 ** If the input word contains not digits but does characters not 
83639 ** in [a-zA-Z] then no stemming is attempted and this routine just 
83640 ** copies the input into the input into the output with US-ASCII
83641 ** case folding.
83642 **
83643 ** Stemming never increases the length of the word.  So there is
83644 ** no chance of overflowing the zOut buffer.
83645 */
83646 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
83647   int i, j, c;
83648   char zReverse[28];
83649   char *z, *z2;
83650   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
83651     /* The word is too big or too small for the porter stemmer.
83652     ** Fallback to the copy stemmer */
83653     copy_stemmer(zIn, nIn, zOut, pnOut);
83654     return;
83655   }
83656   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
83657     c = zIn[i];
83658     if( c>='A' && c<='Z' ){
83659       zReverse[j] = c + 'a' - 'A';
83660     }else if( c>='a' && c<='z' ){
83661       zReverse[j] = c;
83662     }else{
83663       /* The use of a character not in [a-zA-Z] means that we fallback
83664       ** to the copy stemmer */
83665       copy_stemmer(zIn, nIn, zOut, pnOut);
83666       return;
83667     }
83668   }
83669   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
83670   z = &zReverse[j+1];
83671
83672
83673   /* Step 1a */
83674   if( z[0]=='s' ){
83675     if(
83676      !stem(&z, "sess", "ss", 0) &&
83677      !stem(&z, "sei", "i", 0)  &&
83678      !stem(&z, "ss", "ss", 0)
83679     ){
83680       z++;
83681     }
83682   }
83683
83684   /* Step 1b */  
83685   z2 = z;
83686   if( stem(&z, "dee", "ee", m_gt_0) ){
83687     /* Do nothing.  The work was all in the test */
83688   }else if( 
83689      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
83690       && z!=z2
83691   ){
83692      if( stem(&z, "ta", "ate", 0) ||
83693          stem(&z, "lb", "ble", 0) ||
83694          stem(&z, "zi", "ize", 0) ){
83695        /* Do nothing.  The work was all in the test */
83696      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
83697        z++;
83698      }else if( m_eq_1(z) && star_oh(z) ){
83699        *(--z) = 'e';
83700      }
83701   }
83702
83703   /* Step 1c */
83704   if( z[0]=='y' && hasVowel(z+1) ){
83705     z[0] = 'i';
83706   }
83707
83708   /* Step 2 */
83709   switch( z[1] ){
83710    case 'a':
83711      stem(&z, "lanoita", "ate", m_gt_0) ||
83712      stem(&z, "lanoit", "tion", m_gt_0);
83713      break;
83714    case 'c':
83715      stem(&z, "icne", "ence", m_gt_0) ||
83716      stem(&z, "icna", "ance", m_gt_0);
83717      break;
83718    case 'e':
83719      stem(&z, "rezi", "ize", m_gt_0);
83720      break;
83721    case 'g':
83722      stem(&z, "igol", "log", m_gt_0);
83723      break;
83724    case 'l':
83725      stem(&z, "ilb", "ble", m_gt_0) ||
83726      stem(&z, "illa", "al", m_gt_0) ||
83727      stem(&z, "iltne", "ent", m_gt_0) ||
83728      stem(&z, "ile", "e", m_gt_0) ||
83729      stem(&z, "ilsuo", "ous", m_gt_0);
83730      break;
83731    case 'o':
83732      stem(&z, "noitazi", "ize", m_gt_0) ||
83733      stem(&z, "noita", "ate", m_gt_0) ||
83734      stem(&z, "rota", "ate", m_gt_0);
83735      break;
83736    case 's':
83737      stem(&z, "msila", "al", m_gt_0) ||
83738      stem(&z, "ssenevi", "ive", m_gt_0) ||
83739      stem(&z, "ssenluf", "ful", m_gt_0) ||
83740      stem(&z, "ssensuo", "ous", m_gt_0);
83741      break;
83742    case 't':
83743      stem(&z, "itila", "al", m_gt_0) ||
83744      stem(&z, "itivi", "ive", m_gt_0) ||
83745      stem(&z, "itilib", "ble", m_gt_0);
83746      break;
83747   }
83748
83749   /* Step 3 */
83750   switch( z[0] ){
83751    case 'e':
83752      stem(&z, "etaci", "ic", m_gt_0) ||
83753      stem(&z, "evita", "", m_gt_0)   ||
83754      stem(&z, "ezila", "al", m_gt_0);
83755      break;
83756    case 'i':
83757      stem(&z, "itici", "ic", m_gt_0);
83758      break;
83759    case 'l':
83760      stem(&z, "laci", "ic", m_gt_0) ||
83761      stem(&z, "luf", "", m_gt_0);
83762      break;
83763    case 's':
83764      stem(&z, "ssen", "", m_gt_0);
83765      break;
83766   }
83767
83768   /* Step 4 */
83769   switch( z[1] ){
83770    case 'a':
83771      if( z[0]=='l' && m_gt_1(z+2) ){
83772        z += 2;
83773      }
83774      break;
83775    case 'c':
83776      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
83777        z += 4;
83778      }
83779      break;
83780    case 'e':
83781      if( z[0]=='r' && m_gt_1(z+2) ){
83782        z += 2;
83783      }
83784      break;
83785    case 'i':
83786      if( z[0]=='c' && m_gt_1(z+2) ){
83787        z += 2;
83788      }
83789      break;
83790    case 'l':
83791      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
83792        z += 4;
83793      }
83794      break;
83795    case 'n':
83796      if( z[0]=='t' ){
83797        if( z[2]=='a' ){
83798          if( m_gt_1(z+3) ){
83799            z += 3;
83800          }
83801        }else if( z[2]=='e' ){
83802          stem(&z, "tneme", "", m_gt_1) ||
83803          stem(&z, "tnem", "", m_gt_1) ||
83804          stem(&z, "tne", "", m_gt_1);
83805        }
83806      }
83807      break;
83808    case 'o':
83809      if( z[0]=='u' ){
83810        if( m_gt_1(z+2) ){
83811          z += 2;
83812        }
83813      }else if( z[3]=='s' || z[3]=='t' ){
83814        stem(&z, "noi", "", m_gt_1);
83815      }
83816      break;
83817    case 's':
83818      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
83819        z += 3;
83820      }
83821      break;
83822    case 't':
83823      stem(&z, "eta", "", m_gt_1) ||
83824      stem(&z, "iti", "", m_gt_1);
83825      break;
83826    case 'u':
83827      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
83828        z += 3;
83829      }
83830      break;
83831    case 'v':
83832    case 'z':
83833      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
83834        z += 3;
83835      }
83836      break;
83837   }
83838
83839   /* Step 5a */
83840   if( z[0]=='e' ){
83841     if( m_gt_1(z+1) ){
83842       z++;
83843     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
83844       z++;
83845     }
83846   }
83847
83848   /* Step 5b */
83849   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
83850     z++;
83851   }
83852
83853   /* z[] is now the stemmed word in reverse order.  Flip it back
83854   ** around into forward order and return.
83855   */
83856   *pnOut = i = strlen(z);
83857   zOut[i] = 0;
83858   while( *z ){
83859     zOut[--i] = *(z++);
83860   }
83861 }
83862
83863 /*
83864 ** Characters that can be part of a token.  We assume any character
83865 ** whose value is greater than 0x80 (any UTF character) can be
83866 ** part of a token.  In other words, delimiters all must have
83867 ** values of 0x7f or lower.
83868 */
83869 static const char porterIdChar[] = {
83870 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
83871     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
83872     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
83873     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
83874     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
83875     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
83876 };
83877 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
83878
83879 /*
83880 ** Extract the next token from a tokenization cursor.  The cursor must
83881 ** have been opened by a prior call to porterOpen().
83882 */
83883 static int porterNext(
83884   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
83885   const char **pzToken,               /* OUT: *pzToken is the token text */
83886   int *pnBytes,                       /* OUT: Number of bytes in token */
83887   int *piStartOffset,                 /* OUT: Starting offset of token */
83888   int *piEndOffset,                   /* OUT: Ending offset of token */
83889   int *piPosition                     /* OUT: Position integer of token */
83890 ){
83891   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
83892   const char *z = c->zInput;
83893
83894   while( c->iOffset<c->nInput ){
83895     int iStartOffset, ch;
83896
83897     /* Scan past delimiter characters */
83898     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
83899       c->iOffset++;
83900     }
83901
83902     /* Count non-delimiter characters. */
83903     iStartOffset = c->iOffset;
83904     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
83905       c->iOffset++;
83906     }
83907
83908     if( c->iOffset>iStartOffset ){
83909       int n = c->iOffset-iStartOffset;
83910       if( n>c->nAllocated ){
83911         c->nAllocated = n+20;
83912         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
83913         if( c->zToken==NULL ) return SQLITE_NOMEM;
83914       }
83915       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
83916       *pzToken = c->zToken;
83917       *piStartOffset = iStartOffset;
83918       *piEndOffset = c->iOffset;
83919       *piPosition = c->iToken++;
83920       return SQLITE_OK;
83921     }
83922   }
83923   return SQLITE_DONE;
83924 }
83925
83926 /*
83927 ** The set of routines that implement the porter-stemmer tokenizer
83928 */
83929 static const sqlite3_tokenizer_module porterTokenizerModule = {
83930   0,
83931   porterCreate,
83932   porterDestroy,
83933   porterOpen,
83934   porterClose,
83935   porterNext,
83936 };
83937
83938 /*
83939 ** Allocate a new porter tokenizer.  Return a pointer to the new
83940 ** tokenizer in *ppModule
83941 */
83942 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
83943   sqlite3_tokenizer_module const**ppModule
83944 ){
83945   *ppModule = &porterTokenizerModule;
83946 }
83947
83948 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
83949
83950 /************** End of fts3_porter.c *****************************************/
83951 /************** Begin file fts3_tokenizer.c **********************************/
83952 /*
83953 ** 2007 June 22
83954 **
83955 ** The author disclaims copyright to this source code.  In place of
83956 ** a legal notice, here is a blessing:
83957 **
83958 **    May you do good and not evil.
83959 **    May you find forgiveness for yourself and forgive others.
83960 **    May you share freely, never taking more than you give.
83961 **
83962 ******************************************************************************
83963 **
83964 ** This is part of an SQLite module implementing full-text search.
83965 ** This particular file implements the generic tokenizer interface.
83966 */
83967
83968 /*
83969 ** The code in this file is only compiled if:
83970 **
83971 **     * The FTS3 module is being built as an extension
83972 **       (in which case SQLITE_CORE is not defined), or
83973 **
83974 **     * The FTS3 module is being built into the core of
83975 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
83976 */
83977 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
83978
83979 #ifndef SQLITE_CORE
83980   SQLITE_EXTENSION_INIT1
83981 #endif
83982
83983
83984 /*
83985 ** Implementation of the SQL scalar function for accessing the underlying 
83986 ** hash table. This function may be called as follows:
83987 **
83988 **   SELECT <function-name>(<key-name>);
83989 **   SELECT <function-name>(<key-name>, <pointer>);
83990 **
83991 ** where <function-name> is the name passed as the second argument
83992 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
83993 **
83994 ** If the <pointer> argument is specified, it must be a blob value
83995 ** containing a pointer to be stored as the hash data corresponding
83996 ** to the string <key-name>. If <pointer> is not specified, then
83997 ** the string <key-name> must already exist in the has table. Otherwise,
83998 ** an error is returned.
83999 **
84000 ** Whether or not the <pointer> argument is specified, the value returned
84001 ** is a blob containing the pointer stored as the hash data corresponding
84002 ** to string <key-name> (after the hash-table is updated, if applicable).
84003 */
84004 static void scalarFunc(
84005   sqlite3_context *context,
84006   int argc,
84007   sqlite3_value **argv
84008 ){
84009   fts3Hash *pHash;
84010   void *pPtr = 0;
84011   const unsigned char *zName;
84012   int nName;
84013
84014   assert( argc==1 || argc==2 );
84015
84016   pHash = (fts3Hash *)sqlite3_user_data(context);
84017
84018   zName = sqlite3_value_text(argv[0]);
84019   nName = sqlite3_value_bytes(argv[0])+1;
84020
84021   if( argc==2 ){
84022     void *pOld;
84023     int n = sqlite3_value_bytes(argv[1]);
84024     if( n!=sizeof(pPtr) ){
84025       sqlite3_result_error(context, "argument type mismatch", -1);
84026       return;
84027     }
84028     pPtr = *(void **)sqlite3_value_blob(argv[1]);
84029     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
84030     if( pOld==pPtr ){
84031       sqlite3_result_error(context, "out of memory", -1);
84032       return;
84033     }
84034   }else{
84035     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
84036     if( !pPtr ){
84037       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
84038       sqlite3_result_error(context, zErr, -1);
84039       sqlite3_free(zErr);
84040       return;
84041     }
84042   }
84043
84044   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
84045 }
84046
84047 #ifdef SQLITE_TEST
84048
84049
84050 /*
84051 ** Implementation of a special SQL scalar function for testing tokenizers 
84052 ** designed to be used in concert with the Tcl testing framework. This
84053 ** function must be called with two arguments:
84054 **
84055 **   SELECT <function-name>(<key-name>, <input-string>);
84056 **   SELECT <function-name>(<key-name>, <pointer>);
84057 **
84058 ** where <function-name> is the name passed as the second argument
84059 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
84060 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
84061 **
84062 ** The return value is a string that may be interpreted as a Tcl
84063 ** list. For each token in the <input-string>, three elements are
84064 ** added to the returned list. The first is the token position, the 
84065 ** second is the token text (folded, stemmed, etc.) and the third is the
84066 ** substring of <input-string> associated with the token. For example, 
84067 ** using the built-in "simple" tokenizer:
84068 **
84069 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
84070 **
84071 ** will return the string:
84072 **
84073 **   "{0 i I 1 dont don't 2 see see 3 how how}"
84074 **   
84075 */
84076 static void testFunc(
84077   sqlite3_context *context,
84078   int argc,
84079   sqlite3_value **argv
84080 ){
84081   fts3Hash *pHash;
84082   sqlite3_tokenizer_module *p;
84083   sqlite3_tokenizer *pTokenizer = 0;
84084   sqlite3_tokenizer_cursor *pCsr = 0;
84085
84086   const char *zErr = 0;
84087
84088   const char *zName;
84089   int nName;
84090   const char *zInput;
84091   int nInput;
84092
84093   const char *zArg = 0;
84094
84095   const char *zToken;
84096   int nToken;
84097   int iStart;
84098   int iEnd;
84099   int iPos;
84100
84101   Tcl_Obj *pRet;
84102
84103   assert( argc==2 || argc==3 );
84104
84105   nName = sqlite3_value_bytes(argv[0]);
84106   zName = (const char *)sqlite3_value_text(argv[0]);
84107   nInput = sqlite3_value_bytes(argv[argc-1]);
84108   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
84109
84110   if( argc==3 ){
84111     zArg = (const char *)sqlite3_value_text(argv[1]);
84112   }
84113
84114   pHash = (fts3Hash *)sqlite3_user_data(context);
84115   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
84116
84117   if( !p ){
84118     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
84119     sqlite3_result_error(context, zErr, -1);
84120     sqlite3_free(zErr);
84121     return;
84122   }
84123
84124   pRet = Tcl_NewObj();
84125   Tcl_IncrRefCount(pRet);
84126
84127   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
84128     zErr = "error in xCreate()";
84129     goto finish;
84130   }
84131   pTokenizer->pModule = p;
84132   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
84133     zErr = "error in xOpen()";
84134     goto finish;
84135   }
84136   pCsr->pTokenizer = pTokenizer;
84137
84138   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
84139     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
84140     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
84141     zToken = &zInput[iStart];
84142     nToken = iEnd-iStart;
84143     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
84144   }
84145
84146   if( SQLITE_OK!=p->xClose(pCsr) ){
84147     zErr = "error in xClose()";
84148     goto finish;
84149   }
84150   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
84151     zErr = "error in xDestroy()";
84152     goto finish;
84153   }
84154
84155 finish:
84156   if( zErr ){
84157     sqlite3_result_error(context, zErr, -1);
84158   }else{
84159     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
84160   }
84161   Tcl_DecrRefCount(pRet);
84162 }
84163
84164 static
84165 int registerTokenizer(
84166   sqlite3 *db, 
84167   char *zName, 
84168   const sqlite3_tokenizer_module *p
84169 ){
84170   int rc;
84171   sqlite3_stmt *pStmt;
84172   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
84173
84174   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
84175   if( rc!=SQLITE_OK ){
84176     return rc;
84177   }
84178
84179   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
84180   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
84181   sqlite3_step(pStmt);
84182
84183   return sqlite3_finalize(pStmt);
84184 }
84185
84186 static
84187 int queryTokenizer(
84188   sqlite3 *db, 
84189   char *zName,  
84190   const sqlite3_tokenizer_module **pp
84191 ){
84192   int rc;
84193   sqlite3_stmt *pStmt;
84194   const char zSql[] = "SELECT fts3_tokenizer(?)";
84195
84196   *pp = 0;
84197   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
84198   if( rc!=SQLITE_OK ){
84199     return rc;
84200   }
84201
84202   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
84203   if( SQLITE_ROW==sqlite3_step(pStmt) ){
84204     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
84205       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
84206     }
84207   }
84208
84209   return sqlite3_finalize(pStmt);
84210 }
84211
84212 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
84213
84214 /*
84215 ** Implementation of the scalar function fts3_tokenizer_internal_test().
84216 ** This function is used for testing only, it is not included in the
84217 ** build unless SQLITE_TEST is defined.
84218 **
84219 ** The purpose of this is to test that the fts3_tokenizer() function
84220 ** can be used as designed by the C-code in the queryTokenizer and
84221 ** registerTokenizer() functions above. These two functions are repeated
84222 ** in the README.tokenizer file as an example, so it is important to
84223 ** test them.
84224 **
84225 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
84226 ** function with no arguments. An assert() will fail if a problem is
84227 ** detected. i.e.:
84228 **
84229 **     SELECT fts3_tokenizer_internal_test();
84230 **
84231 */
84232 static void intTestFunc(
84233   sqlite3_context *context,
84234   int argc,
84235   sqlite3_value **argv
84236 ){
84237   int rc;
84238   const sqlite3_tokenizer_module *p1;
84239   const sqlite3_tokenizer_module *p2;
84240   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
84241
84242   /* Test the query function */
84243   sqlite3Fts3SimpleTokenizerModule(&p1);
84244   rc = queryTokenizer(db, "simple", &p2);
84245   assert( rc==SQLITE_OK );
84246   assert( p1==p2 );
84247   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
84248   assert( rc==SQLITE_ERROR );
84249   assert( p2==0 );
84250   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
84251
84252   /* Test the storage function */
84253   rc = registerTokenizer(db, "nosuchtokenizer", p1);
84254   assert( rc==SQLITE_OK );
84255   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
84256   assert( rc==SQLITE_OK );
84257   assert( p2==p1 );
84258
84259   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
84260 }
84261
84262 #endif
84263
84264 /*
84265 ** Set up SQL objects in database db used to access the contents of
84266 ** the hash table pointed to by argument pHash. The hash table must
84267 ** been initialised to use string keys, and to take a private copy 
84268 ** of the key when a value is inserted. i.e. by a call similar to:
84269 **
84270 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
84271 **
84272 ** This function adds a scalar function (see header comment above
84273 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
84274 ** defined at compilation time, a temporary virtual table (see header 
84275 ** comment above struct HashTableVtab) to the database schema. Both 
84276 ** provide read/write access to the contents of *pHash.
84277 **
84278 ** The third argument to this function, zName, is used as the name
84279 ** of both the scalar and, if created, the virtual table.
84280 */
84281 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
84282   sqlite3 *db, 
84283   fts3Hash *pHash, 
84284   const char *zName
84285 ){
84286   int rc = SQLITE_OK;
84287   void *p = (void *)pHash;
84288   const int any = SQLITE_ANY;
84289   char *zTest = 0;
84290   char *zTest2 = 0;
84291
84292 #ifdef SQLITE_TEST
84293   void *pdb = (void *)db;
84294   zTest = sqlite3_mprintf("%s_test", zName);
84295   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
84296   if( !zTest || !zTest2 ){
84297     rc = SQLITE_NOMEM;
84298   }
84299 #endif
84300
84301   if( rc!=SQLITE_OK
84302    || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
84303    || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
84304 #ifdef SQLITE_TEST
84305    || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
84306    || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
84307    || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
84308 #endif
84309   );
84310
84311   sqlite3_free(zTest);
84312   sqlite3_free(zTest2);
84313   return rc;
84314 }
84315
84316 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
84317
84318 /************** End of fts3_tokenizer.c **************************************/
84319 /************** Begin file fts3_tokenizer1.c *********************************/
84320 /*
84321 ** 2006 Oct 10
84322 **
84323 ** The author disclaims copyright to this source code.  In place of
84324 ** a legal notice, here is a blessing:
84325 **
84326 **    May you do good and not evil.
84327 **    May you find forgiveness for yourself and forgive others.
84328 **    May you share freely, never taking more than you give.
84329 **
84330 ******************************************************************************
84331 **
84332 ** Implementation of the "simple" full-text-search tokenizer.
84333 */
84334
84335 /*
84336 ** The code in this file is only compiled if:
84337 **
84338 **     * The FTS3 module is being built as an extension
84339 **       (in which case SQLITE_CORE is not defined), or
84340 **
84341 **     * The FTS3 module is being built into the core of
84342 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
84343 */
84344 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
84345
84346
84347
84348
84349 typedef struct simple_tokenizer {
84350   sqlite3_tokenizer base;
84351   char delim[128];             /* flag ASCII delimiters */
84352 } simple_tokenizer;
84353
84354 typedef struct simple_tokenizer_cursor {
84355   sqlite3_tokenizer_cursor base;
84356   const char *pInput;          /* input we are tokenizing */
84357   int nBytes;                  /* size of the input */
84358   int iOffset;                 /* current position in pInput */
84359   int iToken;                  /* index of next token to be returned */
84360   char *pToken;                /* storage for current token */
84361   int nTokenAllocated;         /* space allocated to zToken buffer */
84362 } simple_tokenizer_cursor;
84363
84364
84365 /* Forward declaration */
84366 static const sqlite3_tokenizer_module simpleTokenizerModule;
84367
84368 static int simpleDelim(simple_tokenizer *t, unsigned char c){
84369   return c<0x80 && t->delim[c];
84370 }
84371
84372 /*
84373 ** Create a new tokenizer instance.
84374 */
84375 static int simpleCreate(
84376   int argc, const char * const *argv,
84377   sqlite3_tokenizer **ppTokenizer
84378 ){
84379   simple_tokenizer *t;
84380
84381   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
84382   if( t==NULL ) return SQLITE_NOMEM;
84383   memset(t, 0, sizeof(*t));
84384
84385   /* TODO(shess) Delimiters need to remain the same from run to run,
84386   ** else we need to reindex.  One solution would be a meta-table to
84387   ** track such information in the database, then we'd only want this
84388   ** information on the initial create.
84389   */
84390   if( argc>1 ){
84391     int i, n = strlen(argv[1]);
84392     for(i=0; i<n; i++){
84393       unsigned char ch = argv[1][i];
84394       /* We explicitly don't support UTF-8 delimiters for now. */
84395       if( ch>=0x80 ){
84396         sqlite3_free(t);
84397         return SQLITE_ERROR;
84398       }
84399       t->delim[ch] = 1;
84400     }
84401   } else {
84402     /* Mark non-alphanumeric ASCII characters as delimiters */
84403     int i;
84404     for(i=1; i<0x80; i++){
84405       t->delim[i] = !isalnum(i);
84406     }
84407   }
84408
84409   *ppTokenizer = &t->base;
84410   return SQLITE_OK;
84411 }
84412
84413 /*
84414 ** Destroy a tokenizer
84415 */
84416 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
84417   sqlite3_free(pTokenizer);
84418   return SQLITE_OK;
84419 }
84420
84421 /*
84422 ** Prepare to begin tokenizing a particular string.  The input
84423 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
84424 ** used to incrementally tokenize this string is returned in 
84425 ** *ppCursor.
84426 */
84427 static int simpleOpen(
84428   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
84429   const char *pInput, int nBytes,        /* String to be tokenized */
84430   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
84431 ){
84432   simple_tokenizer_cursor *c;
84433
84434   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
84435   if( c==NULL ) return SQLITE_NOMEM;
84436
84437   c->pInput = pInput;
84438   if( pInput==0 ){
84439     c->nBytes = 0;
84440   }else if( nBytes<0 ){
84441     c->nBytes = (int)strlen(pInput);
84442   }else{
84443     c->nBytes = nBytes;
84444   }
84445   c->iOffset = 0;                 /* start tokenizing at the beginning */
84446   c->iToken = 0;
84447   c->pToken = NULL;               /* no space allocated, yet. */
84448   c->nTokenAllocated = 0;
84449
84450   *ppCursor = &c->base;
84451   return SQLITE_OK;
84452 }
84453
84454 /*
84455 ** Close a tokenization cursor previously opened by a call to
84456 ** simpleOpen() above.
84457 */
84458 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
84459   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
84460   sqlite3_free(c->pToken);
84461   sqlite3_free(c);
84462   return SQLITE_OK;
84463 }
84464
84465 /*
84466 ** Extract the next token from a tokenization cursor.  The cursor must
84467 ** have been opened by a prior call to simpleOpen().
84468 */
84469 static int simpleNext(
84470   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
84471   const char **ppToken,               /* OUT: *ppToken is the token text */
84472   int *pnBytes,                       /* OUT: Number of bytes in token */
84473   int *piStartOffset,                 /* OUT: Starting offset of token */
84474   int *piEndOffset,                   /* OUT: Ending offset of token */
84475   int *piPosition                     /* OUT: Position integer of token */
84476 ){
84477   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
84478   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
84479   unsigned char *p = (unsigned char *)c->pInput;
84480
84481   while( c->iOffset<c->nBytes ){
84482     int iStartOffset;
84483
84484     /* Scan past delimiter characters */
84485     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
84486       c->iOffset++;
84487     }
84488
84489     /* Count non-delimiter characters. */
84490     iStartOffset = c->iOffset;
84491     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
84492       c->iOffset++;
84493     }
84494
84495     if( c->iOffset>iStartOffset ){
84496       int i, n = c->iOffset-iStartOffset;
84497       if( n>c->nTokenAllocated ){
84498         c->nTokenAllocated = n+20;
84499         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
84500         if( c->pToken==NULL ) return SQLITE_NOMEM;
84501       }
84502       for(i=0; i<n; i++){
84503         /* TODO(shess) This needs expansion to handle UTF-8
84504         ** case-insensitivity.
84505         */
84506         unsigned char ch = p[iStartOffset+i];
84507         c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
84508       }
84509       *ppToken = c->pToken;
84510       *pnBytes = n;
84511       *piStartOffset = iStartOffset;
84512       *piEndOffset = c->iOffset;
84513       *piPosition = c->iToken++;
84514
84515       return SQLITE_OK;
84516     }
84517   }
84518   return SQLITE_DONE;
84519 }
84520
84521 /*
84522 ** The set of routines that implement the simple tokenizer
84523 */
84524 static const sqlite3_tokenizer_module simpleTokenizerModule = {
84525   0,
84526   simpleCreate,
84527   simpleDestroy,
84528   simpleOpen,
84529   simpleClose,
84530   simpleNext,
84531 };
84532
84533 /*
84534 ** Allocate a new simple tokenizer.  Return a pointer to the new
84535 ** tokenizer in *ppModule
84536 */
84537 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
84538   sqlite3_tokenizer_module const**ppModule
84539 ){
84540   *ppModule = &simpleTokenizerModule;
84541 }
84542
84543 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
84544
84545 /************** End of fts3_tokenizer1.c *************************************/