9044ec504c5784f96768b158ceab574089157832
[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.9.  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 ** 5638 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-05-14 16:20:58 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.704 2008/05/13 13:27:34 drh Exp $
45 */
46 #ifndef _SQLITEINT_H_
47 #define _SQLITEINT_H_
48
49 /*
50 ** Include the configuration header output by 'configure' if we're using the
51 ** autoconf-based build
52 */
53 #ifdef _HAVE_SQLITE_CONFIG_H
54 #include "config.h"
55 #endif
56
57 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
58 /************** Begin file sqliteLimit.h *************************************/
59 /*
60 ** 2007 May 7
61 **
62 ** The author disclaims copyright to this source code.  In place of
63 ** a legal notice, here is a blessing:
64 **
65 **    May you do good and not evil.
66 **    May you find forgiveness for yourself and forgive others.
67 **    May you share freely, never taking more than you give.
68 **
69 *************************************************************************
70 ** 
71 ** This file defines various limits of what SQLite can process.
72 **
73 ** @(#) $Id: sqliteLimit.h,v 1.8 2008/03/26 15:56:22 drh Exp $
74 */
75
76 /*
77 ** The maximum length of a TEXT or BLOB in bytes.   This also
78 ** limits the size of a row in a table or index.
79 **
80 ** The hard limit is the ability of a 32-bit signed integer
81 ** to count the size: 2^31-1 or 2147483647.
82 */
83 #ifndef SQLITE_MAX_LENGTH
84 # define SQLITE_MAX_LENGTH 1000000000
85 #endif
86
87 /*
88 ** This is the maximum number of
89 **
90 **    * Columns in a table
91 **    * Columns in an index
92 **    * Columns in a view
93 **    * Terms in the SET clause of an UPDATE statement
94 **    * Terms in the result set of a SELECT statement
95 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
96 **    * Terms in the VALUES clause of an INSERT statement
97 **
98 ** The hard upper limit here is 32676.  Most database people will
99 ** tell you that in a well-normalized database, you usually should
100 ** not have more than a dozen or so columns in any table.  And if
101 ** that is the case, there is no point in having more than a few
102 ** dozen values in any of the other situations described above.
103 */
104 #ifndef SQLITE_MAX_COLUMN
105 # define SQLITE_MAX_COLUMN 2000
106 #endif
107
108 /*
109 ** The maximum length of a single SQL statement in bytes.
110 **
111 ** It used to be the case that setting this value to zero would
112 ** turn the limit off.  That is no longer true.  It is not possible
113 ** to turn this limit off.
114 */
115 #ifndef SQLITE_MAX_SQL_LENGTH
116 # define SQLITE_MAX_SQL_LENGTH 1000000000
117 #endif
118
119 /*
120 ** The maximum depth of an expression tree. This is limited to 
121 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
122 ** want to place more severe limits on the complexity of an 
123 ** expression.
124 **
125 ** A value of 0 used to mean that the limit was not enforced.
126 ** But that is no longer true.  The limit is now strictly enforced
127 ** at all times.
128 */
129 #ifndef SQLITE_MAX_EXPR_DEPTH
130 # define SQLITE_MAX_EXPR_DEPTH 1000
131 #endif
132
133 /*
134 ** The maximum number of terms in a compound SELECT statement.
135 ** The code generator for compound SELECT statements does one
136 ** level of recursion for each term.  A stack overflow can result
137 ** if the number of terms is too large.  In practice, most SQL
138 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
139 ** any limit on the number of terms in a compount SELECT.
140 */
141 #ifndef SQLITE_MAX_COMPOUND_SELECT
142 # define SQLITE_MAX_COMPOUND_SELECT 500
143 #endif
144
145 /*
146 ** The maximum number of opcodes in a VDBE program.
147 ** Not currently enforced.
148 */
149 #ifndef SQLITE_MAX_VDBE_OP
150 # define SQLITE_MAX_VDBE_OP 25000
151 #endif
152
153 /*
154 ** The maximum number of arguments to an SQL function.
155 */
156 #ifndef SQLITE_MAX_FUNCTION_ARG
157 # define SQLITE_MAX_FUNCTION_ARG 100
158 #endif
159
160 /*
161 ** The maximum number of in-memory pages to use for the main database
162 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
163 */
164 #ifndef SQLITE_DEFAULT_CACHE_SIZE
165 # define SQLITE_DEFAULT_CACHE_SIZE  2000
166 #endif
167 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
168 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
169 #endif
170
171 /*
172 ** The maximum number of attached databases.  This must be between 0
173 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
174 ** is used internally to track attached databases.
175 */
176 #ifndef SQLITE_MAX_ATTACHED
177 # define SQLITE_MAX_ATTACHED 10
178 #endif
179
180
181 /*
182 ** The maximum value of a ?nnn wildcard that the parser will accept.
183 */
184 #ifndef SQLITE_MAX_VARIABLE_NUMBER
185 # define SQLITE_MAX_VARIABLE_NUMBER 999
186 #endif
187
188 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
189 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
190 ** and the fact that the page size must be a power of 2.
191 */
192 #ifndef SQLITE_MAX_PAGE_SIZE
193 # define SQLITE_MAX_PAGE_SIZE 32768
194 #endif
195
196
197 /*
198 ** The default size of a database page.
199 */
200 #ifndef SQLITE_DEFAULT_PAGE_SIZE
201 # define SQLITE_DEFAULT_PAGE_SIZE 1024
202 #endif
203 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
204 # undef SQLITE_DEFAULT_PAGE_SIZE
205 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
206 #endif
207
208 /*
209 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
210 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
211 ** device characteristics (sector-size and atomic write() support),
212 ** SQLite may choose a larger value. This constant is the maximum value
213 ** SQLite will choose on its own.
214 */
215 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
216 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
217 #endif
218 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
219 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
220 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
221 #endif
222
223
224 /*
225 ** Maximum number of pages in one database file.
226 **
227 ** This is really just the default value for the max_page_count pragma.
228 ** This value can be lowered (or raised) at run-time using that the
229 ** max_page_count macro.
230 */
231 #ifndef SQLITE_MAX_PAGE_COUNT
232 # define SQLITE_MAX_PAGE_COUNT 1073741823
233 #endif
234
235 /*
236 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
237 ** operator.
238 */
239 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
240 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
241 #endif
242
243 /************** End of sqliteLimit.h *****************************************/
244 /************** Continuing where we left off in sqliteInt.h ******************/
245
246 /* Disable nuisance warnings on Borland compilers */
247 #if defined(__BORLANDC__)
248 #pragma warn -rch /* unreachable code */
249 #pragma warn -ccc /* Condition is always true or false */
250 #pragma warn -aus /* Assigned value is never used */
251 #pragma warn -csu /* Comparing signed and unsigned */
252 #pragma warn -spa /* Suspicous pointer arithmetic */
253 #endif
254
255 /* Needed for various definitions... */
256 #define _GNU_SOURCE
257
258 /*
259 ** Include standard header files as necessary
260 */
261 #ifdef HAVE_STDINT_H
262 #include <stdint.h>
263 #endif
264 #ifdef HAVE_INTTYPES_H
265 #include <inttypes.h>
266 #endif
267
268 /*
269 ** A macro used to aid in coverage testing.  When doing coverage
270 ** testing, the condition inside the argument must be evaluated 
271 ** both true and false in order to get full branch coverage.
272 ** This macro can be inserted to ensure adequate test coverage
273 ** in places where simple condition/decision coverage is inadequate.
274 */
275 #ifdef SQLITE_COVERAGE_TEST
276 SQLITE_PRIVATE   void sqlite3Coverage(int);
277 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
278 #else
279 # define testcase(X)
280 #endif
281
282
283 /*
284 ** The macro unlikely() is a hint that surrounds a boolean
285 ** expression that is usually false.  Macro likely() surrounds
286 ** a boolean expression that is usually true.  GCC is able to
287 ** use these hints to generate better code, sometimes.
288 */
289 #if defined(__GNUC__) && 0
290 # define likely(X)    __builtin_expect((X),1)
291 # define unlikely(X)  __builtin_expect((X),0)
292 #else
293 # define likely(X)    !!(X)
294 # define unlikely(X)  !!(X)
295 #endif
296
297
298 /*
299 ** These #defines should enable >2GB file support on Posix if the
300 ** underlying operating system supports it.  If the OS lacks
301 ** large file support, or if the OS is windows, these should be no-ops.
302 **
303 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
304 ** system #includes.  Hence, this block of code must be the very first
305 ** code in all source files.
306 **
307 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
308 ** on the compiler command line.  This is necessary if you are compiling
309 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
310 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
311 ** without this option, LFS is enable.  But LFS does not exist in the kernel
312 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
313 ** portability you should omit LFS.
314 **
315 ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
316 */
317 #ifndef SQLITE_DISABLE_LFS
318 # define _LARGE_FILE       1
319 # ifndef _FILE_OFFSET_BITS
320 #   define _FILE_OFFSET_BITS 64
321 # endif
322 # define _LARGEFILE_SOURCE 1
323 #endif
324
325
326 /*
327 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
328 ** Older versions of SQLite used an optional THREADSAFE macro.
329 ** We support that for legacy
330 */
331 #if !defined(SQLITE_THREADSAFE)
332 #if defined(THREADSAFE)
333 # define SQLITE_THREADSAFE THREADSAFE
334 #else
335 # define SQLITE_THREADSAFE 1
336 #endif
337 #endif
338
339 /*
340 ** Exactly one of the following macros must be defined in order to
341 ** specify which memory allocation subsystem to use.
342 **
343 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
344 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
345 **     SQLITE_MEMORY_SIZE            // internal allocator #1
346 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
347 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
348 **
349 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
350 ** the default.
351 */
352 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
353     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
354     defined(SQLITE_POW2_MEMORY_SIZE)>1
355 # error "At most one of the following compile-time configuration options\
356  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
357  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
358 #endif
359 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
360     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
361     defined(SQLITE_POW2_MEMORY_SIZE)==0
362 # define SQLITE_SYSTEM_MALLOC 1
363 #endif
364
365 /*
366 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
367 ** sizes of memory allocations below this value where possible.
368 */
369 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
370 # define SQLITE_MALLOC_SOFT_LIMIT 1024
371 #endif
372
373 /*
374 ** We need to define _XOPEN_SOURCE as follows in order to enable
375 ** recursive mutexes on most unix systems.  But Mac OS X is different.
376 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
377 ** so it is omitted there.  See ticket #2673.
378 **
379 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
380 ** implemented on some systems.  So we avoid defining it at all
381 ** if it is already defined or if it is unneeded because we are
382 ** not doing a threadsafe build.  Ticket #2681.
383 **
384 ** See also ticket #2741.
385 */
386 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
387 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
388 #endif
389
390 #if defined(SQLITE_TCL) || defined(TCLSH)
391 # include <tcl.h>
392 #endif
393
394 /*
395 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
396 ** Setting NDEBUG makes the code smaller and run faster.  So the following
397 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
398 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
399 ** feature.
400 */
401 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
402 # define NDEBUG 1
403 #endif
404
405 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
406 /************** Begin file sqlite3.h *****************************************/
407 /*
408 ** 2001 September 15
409 **
410 ** The author disclaims copyright to this source code.  In place of
411 ** a legal notice, here is a blessing:
412 **
413 **    May you do good and not evil.
414 **    May you find forgiveness for yourself and forgive others.
415 **    May you share freely, never taking more than you give.
416 **
417 *************************************************************************
418 ** This header file defines the interface that the SQLite library
419 ** presents to client programs.  If a C-function, structure, datatype,
420 ** or constant definition does not appear in this file, then it is
421 ** not a published API of SQLite, is subject to change without
422 ** notice, and should not be referenced by programs that use SQLite.
423 **
424 ** Some of the definitions that are in this file are marked as
425 ** "experimental".  Experimental interfaces are normally new
426 ** features recently added to SQLite.  We do not anticipate changes 
427 ** to experimental interfaces but reserve to make minor changes if
428 ** experience from use "in the wild" suggest such changes are prudent.
429 **
430 ** The official C-language API documentation for SQLite is derived
431 ** from comments in this file.  This file is the authoritative source
432 ** on how SQLite interfaces are suppose to operate.
433 **
434 ** The name of this file under configuration management is "sqlite.h.in".
435 ** The makefile makes some minor changes to this file (such as inserting
436 ** the version number) and changes its name to "sqlite3.h" as
437 ** part of the build process.
438 **
439 ** @(#) $Id: sqlite.h.in,v 1.312 2008/05/12 12:39:56 drh Exp $
440 */
441 #ifndef _SQLITE3_H_
442 #define _SQLITE3_H_
443 #include <stdarg.h>     /* Needed for the definition of va_list */
444
445 /*
446 ** Make sure we can call this stuff from C++.
447 */
448 #if 0
449 extern "C" {
450 #endif
451
452
453 /*
454 ** Add the ability to override 'extern'
455 */
456 #ifndef SQLITE_EXTERN
457 # define SQLITE_EXTERN extern
458 #endif
459
460 /*
461 ** Make sure these symbols where not defined by some previous header
462 ** file.
463 */
464 #ifdef SQLITE_VERSION
465 # undef SQLITE_VERSION
466 #endif
467 #ifdef SQLITE_VERSION_NUMBER
468 # undef SQLITE_VERSION_NUMBER
469 #endif
470
471 /*
472 ** CAPI3REF: Compile-Time Library Version Numbers {F10010}
473 **
474 ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
475 ** the sqlite3.h file specify the version of SQLite with which
476 ** that header file is associated.
477 **
478 ** The "version" of SQLite is a string of the form "X.Y.Z".
479 ** The phrase "alpha" or "beta" might be appended after the Z.
480 ** The X value is major version number always 3 in SQLite3.
481 ** The X value only changes when  backwards compatibility is
482 ** broken and we intend to never break
483 ** backwards compatibility.  The Y value is the minor version
484 ** number and only changes when
485 ** there are major feature enhancements that are forwards compatible
486 ** but not backwards compatible.  The Z value is release number
487 ** and is incremented with
488 ** each release but resets back to 0 when Y is incremented.
489 **
490 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
491 **
492 ** INVARIANTS:
493 **
494 ** {F10011} The SQLITE_VERSION #define in the sqlite3.h header file
495 **          evaluates to a string literal that is the SQLite version
496 **          with which the header file is associated.
497 **
498 ** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer
499 **          with the value  (X*1000000 + Y*1000 + Z) where X, Y, and
500 **          Z are the major version, minor version, and release number.
501 */
502 #define SQLITE_VERSION         "3.5.9"
503 #define SQLITE_VERSION_NUMBER  3005009
504
505 /*
506 ** CAPI3REF: Run-Time Library Version Numbers {F10020}
507 ** KEYWORDS: sqlite3_version
508 **
509 ** These features provide the same information as the [SQLITE_VERSION]
510 ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated
511 ** with the library instead of the header file.  Cautious programmers might
512 ** include a check in their application to verify that 
513 ** sqlite3_libversion_number() always returns the value 
514 ** [SQLITE_VERSION_NUMBER].
515 **
516 ** The sqlite3_libversion() function returns the same information as is
517 ** in the sqlite3_version[] string constant.  The function is provided
518 ** for use in DLLs since DLL users usually do not have direct access to string
519 ** constants within the DLL.
520 **
521 ** INVARIANTS:
522 **
523 ** {F10021} The [sqlite3_libversion_number()] interface returns an integer
524 **          equal to [SQLITE_VERSION_NUMBER]. 
525 **
526 ** {F10022} The [sqlite3_version] string constant contains the text of the
527 **          [SQLITE_VERSION] string. 
528 **
529 ** {F10023} The [sqlite3_libversion()] function returns
530 **          a pointer to the [sqlite3_version] string constant.
531 */
532 SQLITE_API const char sqlite3_version[];
533 SQLITE_API const char *sqlite3_libversion(void);
534 SQLITE_API int sqlite3_libversion_number(void);
535
536 /*
537 ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100}
538 **
539 ** SQLite can be compiled with or without mutexes.  When
540 ** the SQLITE_THREADSAFE C preprocessor macro is true, mutexes
541 ** are enabled and SQLite is threadsafe.  When that macro is false,
542 ** the mutexes are omitted.  Without the mutexes, it is not safe
543 ** to use SQLite from more than one thread.
544 **
545 ** There is a measurable performance penalty for enabling mutexes.
546 ** So if speed is of utmost importance, it makes sense to disable
547 ** the mutexes.  But for maximum safety, mutexes should be enabled.
548 ** The default behavior is for mutexes to be enabled.
549 **
550 ** This interface can be used by a program to make sure that the
551 ** version of SQLite that it is linking against was compiled with
552 ** the desired setting of the SQLITE_THREADSAFE macro.
553 **
554 ** INVARIANTS:
555 **
556 ** {F10101} The [sqlite3_threadsafe()] function returns nonzero if
557 **          SQLite was compiled with its mutexes enabled or zero
558 **          if SQLite was compiled with mutexes disabled.
559 */
560 SQLITE_API int sqlite3_threadsafe(void);
561
562 /*
563 ** CAPI3REF: Database Connection Handle {F12000}
564 ** KEYWORDS: {database connection} {database connections}
565 **
566 ** Each open SQLite database is represented by pointer to an instance of the
567 ** opaque structure named "sqlite3".  It is useful to think of an sqlite3
568 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
569 ** [sqlite3_open_v2()] interfaces are its constructors
570 ** and [sqlite3_close()] is its destructor.  There are many other interfaces
571 ** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and
572 ** [sqlite3_busy_timeout()] to name but three) that are methods on this
573 ** object.
574 */
575 typedef struct sqlite3 sqlite3;
576
577
578 /*
579 ** CAPI3REF: 64-Bit Integer Types {F10200}
580 ** KEYWORDS: sqlite_int64 sqlite_uint64
581 **
582 ** Because there is no cross-platform way to specify 64-bit integer types
583 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
584 **
585 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type
586 ** definitions.  The sqlite_int64 and sqlite_uint64 types are
587 ** supported for backwards compatibility only.
588 **
589 ** INVARIANTS:
590 **
591 ** {F10201} The [sqlite_int64] and [sqlite3_int64] types specify a
592 **          64-bit signed integer.
593 **
594 ** {F10202} The [sqlite_uint64] and [sqlite3_uint64] types specify
595 **          a 64-bit unsigned integer.
596 */
597 #ifdef SQLITE_INT64_TYPE
598   typedef SQLITE_INT64_TYPE sqlite_int64;
599   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
600 #elif defined(_MSC_VER) || defined(__BORLANDC__)
601   typedef __int64 sqlite_int64;
602   typedef unsigned __int64 sqlite_uint64;
603 #else
604   typedef long long int sqlite_int64;
605   typedef unsigned long long int sqlite_uint64;
606 #endif
607 typedef sqlite_int64 sqlite3_int64;
608 typedef sqlite_uint64 sqlite3_uint64;
609
610 /*
611 ** If compiling for a processor that lacks floating point support,
612 ** substitute integer for floating-point
613 */
614 #ifdef SQLITE_OMIT_FLOATING_POINT
615 # define double sqlite3_int64
616 #endif
617
618 /*
619 ** CAPI3REF: Closing A Database Connection {F12010}
620 **
621 ** This routine is the destructor for the [sqlite3] object.  
622 **
623 ** Applications should [sqlite3_finalize | finalize] all
624 ** [prepared statements] and
625 ** [sqlite3_blob_close | close] all [sqlite3_blob | BLOBs] 
626 ** associated with the [sqlite3] object prior
627 ** to attempting to close the [sqlite3] object.
628 **
629 ** <todo>What happens to pending transactions?  Are they
630 ** rolled back, or abandoned?</todo>
631 **
632 ** INVARIANTS:
633 **
634 ** {F12011} The [sqlite3_close()] interface destroys an [sqlite3] object
635 **          allocated by a prior call to [sqlite3_open()],
636 **          [sqlite3_open16()], or [sqlite3_open_v2()].
637 **
638 ** {F12012} The [sqlite3_close()] function releases all memory used by the
639 **          connection and closes all open files.
640 **
641 ** {F12013} If the database connection contains
642 **          [prepared statements] that have not been
643 **          finalized by [sqlite3_finalize()], then [sqlite3_close()]
644 **          returns [SQLITE_BUSY] and leaves the connection open.
645 **
646 ** {F12014} Giving sqlite3_close() a NULL pointer is a harmless no-op.
647 **
648 ** LIMITATIONS:
649 **
650 ** {U12015} The parameter to [sqlite3_close()] must be an [sqlite3] object
651 **          pointer previously obtained from [sqlite3_open()] or the 
652 **          equivalent, or NULL.
653 **
654 ** {U12016} The parameter to [sqlite3_close()] must not have been previously
655 **          closed.
656 */
657 SQLITE_API int sqlite3_close(sqlite3 *);
658
659 /*
660 ** The type for a callback function.
661 ** This is legacy and deprecated.  It is included for historical
662 ** compatibility and is not documented.
663 */
664 typedef int (*sqlite3_callback)(void*,int,char**, char**);
665
666 /*
667 ** CAPI3REF: One-Step Query Execution Interface {F12100}
668 **
669 ** The sqlite3_exec() interface is a convenient way of running
670 ** one or more SQL statements without a lot of C code.  The
671 ** SQL statements are passed in as the second parameter to
672 ** sqlite3_exec().  The statements are evaluated one by one
673 ** until either an error or an interrupt is encountered or
674 ** until they are all done.  The 3rd parameter is an optional
675 ** callback that is invoked once for each row of any query results
676 ** produced by the SQL statements.  The 5th parameter tells where
677 ** to write any error messages.
678 **
679 ** The sqlite3_exec() interface is implemented in terms of
680 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
681 ** The sqlite3_exec() routine does nothing that cannot be done
682 ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
683 ** The sqlite3_exec() is just a convenient wrapper.
684 **
685 ** INVARIANTS:
686 ** 
687 ** {F12101} The [sqlite3_exec()] interface evaluates zero or more UTF-8
688 **          encoded, semicolon-separated, SQL statements in the
689 **          zero-terminated string of its 2nd parameter within the
690 **          context of the [sqlite3] object given in the 1st parameter.
691 **
692 ** {F12104} The return value of [sqlite3_exec()] is SQLITE_OK if all
693 **          SQL statements run successfully.
694 **
695 ** {F12105} The return value of [sqlite3_exec()] is an appropriate 
696 **          non-zero error code if any SQL statement fails.
697 **
698 ** {F12107} If one or more of the SQL statements handed to [sqlite3_exec()]
699 **          return results and the 3rd parameter is not NULL, then
700 **          the callback function specified by the 3rd parameter is
701 **          invoked once for each row of result.
702 **
703 ** {F12110} If the callback returns a non-zero value then [sqlite3_exec()]
704 **          will aborted the SQL statement it is currently evaluating,
705 **          skip all subsequent SQL statements, and return [SQLITE_ABORT].
706 **          <todo>What happens to *errmsg here?  Does the result code for
707 **          sqlite3_errcode() get set?</todo>
708 **
709 ** {F12113} The [sqlite3_exec()] routine will pass its 4th parameter through
710 **          as the 1st parameter of the callback.
711 **
712 ** {F12116} The [sqlite3_exec()] routine sets the 2nd parameter of its
713 **          callback to be the number of columns in the current row of
714 **          result.
715 **
716 ** {F12119} The [sqlite3_exec()] routine sets the 3rd parameter of its 
717 **          callback to be an array of pointers to strings holding the
718 **          values for each column in the current result set row as
719 **          obtained from [sqlite3_column_text()].
720 **
721 ** {F12122} The [sqlite3_exec()] routine sets the 4th parameter of its
722 **          callback to be an array of pointers to strings holding the
723 **          names of result columns as obtained from [sqlite3_column_name()].
724 **
725 ** {F12125} If the 3rd parameter to [sqlite3_exec()] is NULL then
726 **          [sqlite3_exec()] never invokes a callback.  All query
727 **          results are silently discarded.
728 **
729 ** {F12128} If an error occurs while parsing or evaluating any of the SQL
730 **          statements handed to [sqlite3_exec()] then [sqlite3_exec()] will
731 **          return an [error code] other than [SQLITE_OK].
732 **
733 ** {F12131} If an error occurs while parsing or evaluating any of the SQL
734 **          handed to [sqlite3_exec()] and if the 5th parameter (errmsg)
735 **          to [sqlite3_exec()] is not NULL, then an error message is
736 **          allocated using the equivalent of [sqlite3_mprintf()] and
737 **          *errmsg is made to point to that message.
738 **
739 ** {F12134} The [sqlite3_exec()] routine does not change the value of
740 **          *errmsg if errmsg is NULL or if there are no errors.
741 **
742 ** {F12137} The [sqlite3_exec()] function sets the error code and message
743 **          accessible via [sqlite3_errcode()], [sqlite3_errmsg()], and
744 **          [sqlite3_errmsg16()].
745 **
746 ** LIMITATIONS:
747 **
748 ** {U12141} The first parameter to [sqlite3_exec()] must be an valid and open
749 **          [database connection].
750 **
751 ** {U12142} The database connection must not be closed while
752 **          [sqlite3_exec()] is running.
753 ** 
754 ** {U12143} The calling function is should use [sqlite3_free()] to free
755 **          the memory that *errmsg is left pointing at once the error
756 **          message is no longer needed.
757 **
758 ** {U12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()]
759 **          must remain unchanged while [sqlite3_exec()] is running.
760 */
761 SQLITE_API int sqlite3_exec(
762   sqlite3*,                                  /* An open database */
763   const char *sql,                           /* SQL to be evaluted */
764   int (*callback)(void*,int,char**,char**),  /* Callback function */
765   void *,                                    /* 1st argument to callback */
766   char **errmsg                              /* Error msg written here */
767 );
768
769 /*
770 ** CAPI3REF: Result Codes {F10210}
771 ** KEYWORDS: SQLITE_OK {error code} {error codes}
772 **
773 ** Many SQLite functions return an integer result code from the set shown
774 ** here in order to indicates success or failure.
775 **
776 ** See also: [SQLITE_IOERR_READ | extended result codes]
777 */
778 #define SQLITE_OK           0   /* Successful result */
779 /* beginning-of-error-codes */
780 #define SQLITE_ERROR        1   /* SQL error or missing database */
781 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
782 #define SQLITE_PERM         3   /* Access permission denied */
783 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
784 #define SQLITE_BUSY         5   /* The database file is locked */
785 #define SQLITE_LOCKED       6   /* A table in the database is locked */
786 #define SQLITE_NOMEM        7   /* A malloc() failed */
787 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
788 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
789 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
790 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
791 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
792 #define SQLITE_FULL        13   /* Insertion failed because database is full */
793 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
794 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
795 #define SQLITE_EMPTY       16   /* Database is empty */
796 #define SQLITE_SCHEMA      17   /* The database schema changed */
797 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
798 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
799 #define SQLITE_MISMATCH    20   /* Data type mismatch */
800 #define SQLITE_MISUSE      21   /* Library used incorrectly */
801 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
802 #define SQLITE_AUTH        23   /* Authorization denied */
803 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
804 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
805 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
806 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
807 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
808 /* end-of-error-codes */
809
810 /*
811 ** CAPI3REF: Extended Result Codes {F10220}
812 ** KEYWORDS: {extended error code} {extended error codes}
813 ** KEYWORDS: {extended result codes}
814 **
815 ** In its default configuration, SQLite API routines return one of 26 integer
816 ** [SQLITE_OK | result codes].  However, experience has shown that
817 ** many of these result codes are too course-grained.  They do not provide as
818 ** much information about problems as programmers might like.  In an effort to
819 ** address this, newer versions of SQLite (version 3.3.8 and later) include
820 ** support for additional result codes that provide more detailed information
821 ** about errors. The extended result codes are enabled or disabled
822 ** for each database connection using the [sqlite3_extended_result_codes()]
823 ** API.
824 ** 
825 ** Some of the available extended result codes are listed here.
826 ** One may expect the number of extended result codes will be expand
827 ** over time.  Software that uses extended result codes should expect
828 ** to see new result codes in future releases of SQLite.
829 **
830 ** The SQLITE_OK result code will never be extended.  It will always
831 ** be exactly zero.
832 ** 
833 ** INVARIANTS:
834 **
835 ** {F10223} The symbolic name for an extended result code always contains
836 **          a related primary result code as a prefix.
837 **
838 ** {F10224} Primary result code names contain a single "_" character.
839 **
840 ** {F10225} Extended result code names contain two or more "_" characters.
841 **
842 ** {F10226} The numeric value of an extended result code contains the
843 **          numeric value of its corresponding primary result code in
844 **          its least significant 8 bits.
845 */
846 #define SQLITE_IOERR_READ          (SQLITE_IOERR | (1<<8))
847 #define SQLITE_IOERR_SHORT_READ    (SQLITE_IOERR | (2<<8))
848 #define SQLITE_IOERR_WRITE         (SQLITE_IOERR | (3<<8))
849 #define SQLITE_IOERR_FSYNC         (SQLITE_IOERR | (4<<8))
850 #define SQLITE_IOERR_DIR_FSYNC     (SQLITE_IOERR | (5<<8))
851 #define SQLITE_IOERR_TRUNCATE      (SQLITE_IOERR | (6<<8))
852 #define SQLITE_IOERR_FSTAT         (SQLITE_IOERR | (7<<8))
853 #define SQLITE_IOERR_UNLOCK        (SQLITE_IOERR | (8<<8))
854 #define SQLITE_IOERR_RDLOCK        (SQLITE_IOERR | (9<<8))
855 #define SQLITE_IOERR_DELETE        (SQLITE_IOERR | (10<<8))
856 #define SQLITE_IOERR_BLOCKED       (SQLITE_IOERR | (11<<8))
857 #define SQLITE_IOERR_NOMEM         (SQLITE_IOERR | (12<<8))
858
859 /*
860 ** CAPI3REF: Flags For File Open Operations {F10230}
861 **
862 ** These bit values are intended for use in the
863 ** 3rd parameter to the [sqlite3_open_v2()] interface and
864 ** in the 4th parameter to the xOpen method of the
865 ** [sqlite3_vfs] object.
866 */
867 #define SQLITE_OPEN_READONLY         0x00000001
868 #define SQLITE_OPEN_READWRITE        0x00000002
869 #define SQLITE_OPEN_CREATE           0x00000004
870 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
871 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
872 #define SQLITE_OPEN_MAIN_DB          0x00000100
873 #define SQLITE_OPEN_TEMP_DB          0x00000200
874 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
875 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
876 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
877 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
878 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
879
880 /*
881 ** CAPI3REF: Device Characteristics {F10240}
882 **
883 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
884 ** object returns an integer which is a vector of the these
885 ** bit values expressing I/O characteristics of the mass storage
886 ** device that holds the file that the [sqlite3_io_methods]
887 ** refers to.
888 **
889 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
890 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
891 ** mean that writes of blocks that are nnn bytes in size and
892 ** are aligned to an address which is an integer multiple of
893 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
894 ** that when data is appended to a file, the data is appended
895 ** first then the size of the file is extended, never the other
896 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
897 ** information is written to disk in the same order as calls
898 ** to xWrite().
899 */
900 #define SQLITE_IOCAP_ATOMIC          0x00000001
901 #define SQLITE_IOCAP_ATOMIC512       0x00000002
902 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
903 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
904 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
905 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
906 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
907 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
908 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
909 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
910 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
911
912 /*
913 ** CAPI3REF: File Locking Levels {F10250}
914 **
915 ** SQLite uses one of these integer values as the second
916 ** argument to calls it makes to the xLock() and xUnlock() methods
917 ** of an [sqlite3_io_methods] object.
918 */
919 #define SQLITE_LOCK_NONE          0
920 #define SQLITE_LOCK_SHARED        1
921 #define SQLITE_LOCK_RESERVED      2
922 #define SQLITE_LOCK_PENDING       3
923 #define SQLITE_LOCK_EXCLUSIVE     4
924
925 /*
926 ** CAPI3REF: Synchronization Type Flags {F10260}
927 **
928 ** When SQLite invokes the xSync() method of an
929 ** [sqlite3_io_methods] object it uses a combination of
930 ** these integer values as the second argument.
931 **
932 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
933 ** sync operation only needs to flush data to mass storage.  Inode
934 ** information need not be flushed. The SQLITE_SYNC_NORMAL flag means 
935 ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means 
936 ** to use Mac OS-X style fullsync instead of fsync().
937 */
938 #define SQLITE_SYNC_NORMAL        0x00002
939 #define SQLITE_SYNC_FULL          0x00003
940 #define SQLITE_SYNC_DATAONLY      0x00010
941
942
943 /*
944 ** CAPI3REF: OS Interface Open File Handle {F11110}
945 **
946 ** An [sqlite3_file] object represents an open file in the OS
947 ** interface layer.  Individual OS interface implementations will
948 ** want to subclass this object by appending additional fields
949 ** for their own use.  The pMethods entry is a pointer to an
950 ** [sqlite3_io_methods] object that defines methods for performing
951 ** I/O operations on the open file.
952 */
953 typedef struct sqlite3_file sqlite3_file;
954 struct sqlite3_file {
955   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
956 };
957
958 /*
959 ** CAPI3REF: OS Interface File Virtual Methods Object {F11120}
960 **
961 ** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to
962 ** an instance of this object.  This object defines the
963 ** methods used to perform various operations against the open file.
964 **
965 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
966 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
967 *  The second choice is an
968 ** OS-X style fullsync.  The SQLITE_SYNC_DATA flag may be ORed in to
969 ** indicate that only the data of the file and not its inode needs to be
970 ** synced.
971 ** 
972 ** The integer values to xLock() and xUnlock() are one of
973 ** <ul>
974 ** <li> [SQLITE_LOCK_NONE],
975 ** <li> [SQLITE_LOCK_SHARED],
976 ** <li> [SQLITE_LOCK_RESERVED],
977 ** <li> [SQLITE_LOCK_PENDING], or
978 ** <li> [SQLITE_LOCK_EXCLUSIVE].
979 ** </ul>
980 ** xLock() increases the lock. xUnlock() decreases the lock.  
981 ** The xCheckReservedLock() method looks
982 ** to see if any database connection, either in this
983 ** process or in some other process, is holding an RESERVED,
984 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
985 ** if such a lock exists and false if not.
986 ** 
987 ** The xFileControl() method is a generic interface that allows custom
988 ** VFS implementations to directly control an open file using the
989 ** [sqlite3_file_control()] interface.  The second "op" argument
990 ** is an integer opcode.   The third
991 ** argument is a generic pointer which is intended to be a pointer
992 ** to a structure that may contain arguments or space in which to
993 ** write return values.  Potential uses for xFileControl() might be
994 ** functions to enable blocking locks with timeouts, to change the
995 ** locking strategy (for example to use dot-file locks), to inquire
996 ** about the status of a lock, or to break stale locks.  The SQLite
997 ** core reserves opcodes less than 100 for its own use. 
998 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
999 ** Applications that define a custom xFileControl method should use opcodes 
1000 ** greater than 100 to avoid conflicts.
1001 **
1002 ** The xSectorSize() method returns the sector size of the
1003 ** device that underlies the file.  The sector size is the
1004 ** minimum write that can be performed without disturbing
1005 ** other bytes in the file.  The xDeviceCharacteristics()
1006 ** method returns a bit vector describing behaviors of the
1007 ** underlying device:
1008 **
1009 ** <ul>
1010 ** <li> [SQLITE_IOCAP_ATOMIC]
1011 ** <li> [SQLITE_IOCAP_ATOMIC512]
1012 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1013 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1014 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1015 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1016 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1017 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1018 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1019 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1020 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1021 ** </ul>
1022 **
1023 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1024 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1025 ** mean that writes of blocks that are nnn bytes in size and
1026 ** are aligned to an address which is an integer multiple of
1027 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1028 ** that when data is appended to a file, the data is appended
1029 ** first then the size of the file is extended, never the other
1030 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1031 ** information is written to disk in the same order as calls
1032 ** to xWrite().
1033 */
1034 typedef struct sqlite3_io_methods sqlite3_io_methods;
1035 struct sqlite3_io_methods {
1036   int iVersion;
1037   int (*xClose)(sqlite3_file*);
1038   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1039   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1040   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1041   int (*xSync)(sqlite3_file*, int flags);
1042   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1043   int (*xLock)(sqlite3_file*, int);
1044   int (*xUnlock)(sqlite3_file*, int);
1045   int (*xCheckReservedLock)(sqlite3_file*);
1046   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1047   int (*xSectorSize)(sqlite3_file*);
1048   int (*xDeviceCharacteristics)(sqlite3_file*);
1049   /* Additional methods may be added in future releases */
1050 };
1051
1052 /*
1053 ** CAPI3REF: Standard File Control Opcodes {F11310}
1054 **
1055 ** These integer constants are opcodes for the xFileControl method
1056 ** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()]
1057 ** interface.
1058 **
1059 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1060 ** opcode causes the xFileControl method to write the current state of
1061 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1062 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1063 ** into an integer that the pArg argument points to. This capability
1064 ** is used during testing and only needs to be supported when SQLITE_TEST
1065 ** is defined.
1066 */
1067 #define SQLITE_FCNTL_LOCKSTATE        1
1068
1069 /*
1070 ** CAPI3REF: Mutex Handle {F17110}
1071 **
1072 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1073 ** abstract type for a mutex object.  The SQLite core never looks
1074 ** at the internal representation of an [sqlite3_mutex].  It only
1075 ** deals with pointers to the [sqlite3_mutex] object.
1076 **
1077 ** Mutexes are created using [sqlite3_mutex_alloc()].
1078 */
1079 typedef struct sqlite3_mutex sqlite3_mutex;
1080
1081 /*
1082 ** CAPI3REF: OS Interface Object {F11140}
1083 **
1084 ** An instance of this object defines the interface between the
1085 ** SQLite core and the underlying operating system.  The "vfs"
1086 ** in the name of the object stands for "virtual file system".
1087 **
1088 ** The iVersion field is initially 1 but may be larger for future
1089 ** versions of SQLite.  Additional fields may be appended to this
1090 ** object when the iVersion value is increased.
1091 **
1092 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1093 ** structure used by this VFS.  mxPathname is the maximum length of
1094 ** a pathname in this VFS.
1095 **
1096 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1097 ** the pNext pointer.  The [sqlite3_vfs_register()]
1098 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1099 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1100 ** searches the list.
1101 **
1102 ** The pNext field is the only field in the sqlite3_vfs 
1103 ** structure that SQLite will ever modify.  SQLite will only access
1104 ** or modify this field while holding a particular static mutex.
1105 ** The application should never modify anything within the sqlite3_vfs
1106 ** object once the object has been registered.
1107 **
1108 ** The zName field holds the name of the VFS module.  The name must
1109 ** be unique across all VFS modules.
1110 **
1111 ** {F11141} SQLite will guarantee that the zFilename string passed to
1112 ** xOpen() is a full pathname as generated by xFullPathname() and
1113 ** that the string will be valid and unchanged until xClose() is
1114 ** called.  {END} So the [sqlite3_file] can store a pointer to the
1115 ** filename if it needs to remember the filename for some reason.
1116 **
1117 ** {F11142} The flags argument to xOpen() includes all bits set in
1118 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1119 ** or [sqlite3_open16()] is used, then flags includes at least
1120 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
1121 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1122 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be
1123 ** set.
1124 ** 
1125 ** {F11143} SQLite will also add one of the following flags to the xOpen()
1126 ** call, depending on the object being opened:
1127 ** 
1128 ** <ul>
1129 ** <li>  [SQLITE_OPEN_MAIN_DB]
1130 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1131 ** <li>  [SQLITE_OPEN_TEMP_DB]
1132 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1133 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1134 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1135 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1136 ** </ul> {END}
1137 **
1138 ** The file I/O implementation can use the object type flags to
1139 ** changes the way it deals with files.  For example, an application
1140 ** that does not care about crash recovery or rollback might make
1141 ** the open of a journal file a no-op.  Writes to this journal would
1142 ** also be no-ops, and any attempt to read the journal would return 
1143 ** SQLITE_IOERR.  Or the implementation might recognize that a database 
1144 ** file will be doing page-aligned sector reads and writes in a random 
1145 ** order and set up its I/O subsystem accordingly.
1146 ** 
1147 ** SQLite might also add one of the following flags to the xOpen
1148 ** method:
1149 ** 
1150 ** <ul>
1151 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1152 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1153 ** </ul>
1154 ** 
1155 ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1156 ** deleted when it is closed.  {F11146} The [SQLITE_OPEN_DELETEONCLOSE]
1157 ** will be set for TEMP  databases, journals and for subjournals. 
1158 ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
1159 ** for exclusive access.  This flag is set for all files except
1160 ** for the main database file. {END}
1161 ** 
1162 ** {F11148} At least szOsFile bytes of memory are allocated by SQLite 
1163 ** to hold the  [sqlite3_file] structure passed as the third 
1164 ** argument to xOpen.  {END}  The xOpen method does not have to
1165 ** allocate the structure; it should just fill it in.
1166 ** 
1167 ** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] 
1168 ** to test for the existance of a file,
1169 ** or [SQLITE_ACCESS_READWRITE] to test to see
1170 ** if a file is readable and writable, or [SQLITE_ACCESS_READ]
1171 ** to test to see if a file is at least readable.  {END} The file can be a 
1172 ** directory.
1173 ** 
1174 ** {F11150} SQLite will always allocate at least mxPathname+1 bytes for
1175 ** the output buffers for xGetTempname and xFullPathname. {F11151} The exact
1176 ** size of the output buffer is also passed as a parameter to both 
1177 ** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN
1178 ** should be returned. As this is handled as a fatal error by SQLite,
1179 ** vfs implementations should endeavor to prevent this by setting 
1180 ** mxPathname to a sufficiently large value.
1181 ** 
1182 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1183 ** are not strictly a part of the filesystem, but they are
1184 ** included in the VFS structure for completeness.
1185 ** The xRandomness() function attempts to return nBytes bytes
1186 ** of good-quality randomness into zOut.  The return value is
1187 ** the actual number of bytes of randomness obtained.  The
1188 ** xSleep() method causes the calling thread to sleep for at
1189 ** least the number of microseconds given.  The xCurrentTime()
1190 ** method returns a Julian Day Number for the current date and
1191 ** time.
1192 */
1193 typedef struct sqlite3_vfs sqlite3_vfs;
1194 struct sqlite3_vfs {
1195   int iVersion;            /* Structure version number */
1196   int szOsFile;            /* Size of subclassed sqlite3_file */
1197   int mxPathname;          /* Maximum file pathname length */
1198   sqlite3_vfs *pNext;      /* Next registered VFS */
1199   const char *zName;       /* Name of this virtual file system */
1200   void *pAppData;          /* Pointer to application-specific data */
1201   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1202                int flags, int *pOutFlags);
1203   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1204   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
1205   int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut);
1206   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1207   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1208   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1209   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
1210   void (*xDlClose)(sqlite3_vfs*, void*);
1211   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1212   int (*xSleep)(sqlite3_vfs*, int microseconds);
1213   int (*xCurrentTime)(sqlite3_vfs*, double*);
1214   /* New fields may be appended in figure versions.  The iVersion
1215   ** value will increment whenever this happens. */
1216 };
1217
1218 /*
1219 ** CAPI3REF: Flags for the xAccess VFS method {F11190}
1220 **
1221 ** {F11191} These integer constants can be used as the third parameter to
1222 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
1223 ** what kind of permissions the xAccess method is
1224 ** looking for.  {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method
1225 ** simply checks to see if the file exists. {F11193} With
1226 ** SQLITE_ACCESS_READWRITE, the xAccess method checks to see
1227 ** if the file is both readable and writable.  {F11194} With
1228 ** SQLITE_ACCESS_READ the xAccess method
1229 ** checks to see if the file is readable.
1230 */
1231 #define SQLITE_ACCESS_EXISTS    0
1232 #define SQLITE_ACCESS_READWRITE 1
1233 #define SQLITE_ACCESS_READ      2
1234
1235 /*
1236 ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200}
1237 **
1238 ** The sqlite3_extended_result_codes() routine enables or disables the
1239 ** [SQLITE_IOERR_READ | extended result codes] feature of SQLite.
1240 ** The extended result codes are disabled by default for historical
1241 ** compatibility.
1242 **
1243 ** INVARIANTS:
1244 **
1245 ** {F12201} Each new [database connection] has the 
1246 **          [extended result codes] feature
1247 **          disabled by default.
1248 **
1249 ** {F12202} The [sqlite3_extended_result_codes(D,F)] interface will enable
1250 **          [extended result codes] for the 
1251 **          [database connection] D if the F parameter
1252 **          is true, or disable them if F is false.
1253 */
1254 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1255
1256 /*
1257 ** CAPI3REF: Last Insert Rowid {F12220}
1258 **
1259 ** Each entry in an SQLite table has a unique 64-bit signed
1260 ** integer key called the "rowid". The rowid is always available
1261 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1262 ** names are not also used by explicitly declared columns. If
1263 ** the table has a column of type INTEGER PRIMARY KEY then that column
1264 ** is another alias for the rowid.
1265 **
1266 ** This routine returns the rowid of the most recent
1267 ** successful INSERT into the database from the database connection
1268 ** shown in the first argument.  If no successful inserts
1269 ** have ever occurred on this database connection, zero is returned.
1270 **
1271 ** If an INSERT occurs within a trigger, then the rowid of the
1272 ** inserted row is returned by this routine as long as the trigger
1273 ** is running.  But once the trigger terminates, the value returned
1274 ** by this routine reverts to the last value inserted before the
1275 ** trigger fired.
1276 **
1277 ** An INSERT that fails due to a constraint violation is not a
1278 ** successful insert and does not change the value returned by this
1279 ** routine.  Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1280 ** and INSERT OR ABORT make no changes to the return value of this
1281 ** routine when their insertion fails.  When INSERT OR REPLACE 
1282 ** encounters a constraint violation, it does not fail.  The
1283 ** INSERT continues to completion after deleting rows that caused
1284 ** the constraint problem so INSERT OR REPLACE will always change
1285 ** the return value of this interface. 
1286 **
1287 ** For the purposes of this routine, an insert is considered to
1288 ** be successful even if it is subsequently rolled back.
1289 **
1290 ** INVARIANTS:
1291 **
1292 ** {F12221} The [sqlite3_last_insert_rowid()] function returns the
1293 **          rowid of the most recent successful insert done
1294 **          on the same database connection and within the same
1295 **          trigger context, or zero if there have
1296 **          been no qualifying inserts on that connection.
1297 **
1298 ** {F12223} The [sqlite3_last_insert_rowid()] function returns
1299 **          same value when called from the same trigger context
1300 **          immediately before and after a ROLLBACK.
1301 **
1302 ** LIMITATIONS:
1303 **
1304 ** {U12232} If a separate thread does a new insert on the same
1305 **          database connection while the [sqlite3_last_insert_rowid()]
1306 **          function is running and thus changes the last insert rowid,
1307 **          then the value returned by [sqlite3_last_insert_rowid()] is
1308 **          unpredictable and might not equal either the old or the new
1309 **          last insert rowid.
1310 */
1311 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1312
1313 /*
1314 ** CAPI3REF: Count The Number Of Rows Modified {F12240}
1315 **
1316 ** This function returns the number of database rows that were changed
1317 ** or inserted or deleted by the most recently completed SQL statement
1318 ** on the connection specified by the first parameter.  Only
1319 ** changes that are directly specified by the INSERT, UPDATE, or
1320 ** DELETE statement are counted.  Auxiliary changes caused by
1321 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1322 ** to find the total number of changes including changes caused by triggers.
1323 **
1324 ** A "row change" is a change to a single row of a single table
1325 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1326 ** are changed as side effects of REPLACE constraint resolution,
1327 ** rollback, ABORT processing, DROP TABLE, or by any other
1328 ** mechanisms do not count as direct row changes.
1329 **
1330 ** A "trigger context" is a scope of execution that begins and
1331 ** ends with the script of a trigger.  Most SQL statements are
1332 ** evaluated outside of any trigger.  This is the "top level"
1333 ** trigger context.  If a trigger fires from the top level, a
1334 ** new trigger context is entered for the duration of that one
1335 ** trigger.  Subtriggers create subcontexts for their duration.
1336 **
1337 ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1338 ** not create a new trigger context.
1339 **
1340 ** This function returns the number of direct row changes in the
1341 ** most recent INSERT, UPDATE, or DELETE statement within the same
1342 ** trigger context.
1343 **
1344 ** So when called from the top level, this function returns the
1345 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1346 ** that also occurred at the top level.
1347 ** Within the body of a trigger, the sqlite3_changes() interface
1348 ** can be called to find the number of
1349 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1350 ** statement within the body of the same trigger.
1351 ** However, the number returned does not include in changes
1352 ** caused by subtriggers since they have their own context.
1353 **
1354 ** SQLite implements the command "DELETE FROM table" without
1355 ** a WHERE clause by dropping and recreating the table.  (This is much
1356 ** faster than going through and deleting individual elements from the
1357 ** table.)  Because of this optimization, the deletions in
1358 ** "DELETE FROM table" are not row changes and will not be counted
1359 ** by the sqlite3_changes() or [sqlite3_total_changes()] functions.
1360 ** To get an accurate count of the number of rows deleted, use
1361 ** "DELETE FROM table WHERE 1" instead.
1362 **
1363 ** INVARIANTS:
1364 **
1365 ** {F12241} The [sqlite3_changes()] function returns the number of
1366 **          row changes caused by the most recent INSERT, UPDATE,
1367 **          or DELETE statement on the same database connection and
1368 **          within the same trigger context, or zero if there have
1369 **          not been any qualifying row changes.
1370 **
1371 ** LIMITATIONS:
1372 **
1373 ** {U12252} If a separate thread makes changes on the same database connection
1374 **          while [sqlite3_changes()] is running then the value returned
1375 **          is unpredictable and unmeaningful.
1376 */
1377 SQLITE_API int sqlite3_changes(sqlite3*);
1378
1379 /*
1380 ** CAPI3REF: Total Number Of Rows Modified {F12260}
1381 ***
1382 ** This function returns the number of row changes caused
1383 ** by INSERT, UPDATE or DELETE statements since the database handle
1384 ** was opened.  The count includes all changes from all trigger
1385 ** contexts.  But the count does not include changes used to
1386 ** implement REPLACE constraints, do rollbacks or ABORT processing,
1387 ** or DROP table processing.
1388 ** The changes
1389 ** are counted as soon as the statement that makes them is completed 
1390 ** (when the statement handle is passed to [sqlite3_reset()] or 
1391 ** [sqlite3_finalize()]).
1392 **
1393 ** SQLite implements the command "DELETE FROM table" without
1394 ** a WHERE clause by dropping and recreating the table.  (This is much
1395 ** faster than going
1396 ** through and deleting individual elements from the table.)  Because of
1397 ** this optimization, the change count for "DELETE FROM table" will be
1398 ** zero regardless of the number of elements that were originally in the
1399 ** table. To get an accurate count of the number of rows deleted, use
1400 ** "DELETE FROM table WHERE 1" instead.
1401 **
1402 ** See also the [sqlite3_changes()] interface.
1403 **
1404 ** INVARIANTS:
1405 ** 
1406 ** {F12261} The [sqlite3_total_changes()] returns the total number
1407 **          of row changes caused by INSERT, UPDATE, and/or DELETE
1408 **          statements on the same [database connection], in any
1409 **          trigger context, since the database connection was
1410 **          created.
1411 **
1412 ** LIMITATIONS:
1413 **
1414 ** {U12264} If a separate thread makes changes on the same database connection
1415 **          while [sqlite3_total_changes()] is running then the value 
1416 **          returned is unpredictable and unmeaningful.
1417 */
1418 SQLITE_API int sqlite3_total_changes(sqlite3*);
1419
1420 /*
1421 ** CAPI3REF: Interrupt A Long-Running Query {F12270}
1422 **
1423 ** This function causes any pending database operation to abort and
1424 ** return at its earliest opportunity. This routine is typically
1425 ** called in response to a user action such as pressing "Cancel"
1426 ** or Ctrl-C where the user wants a long query operation to halt
1427 ** immediately.
1428 **
1429 ** It is safe to call this routine from a thread different from the
1430 ** thread that is currently running the database operation.  But it
1431 ** is not safe to call this routine with a database connection that
1432 ** is closed or might close before sqlite3_interrupt() returns.
1433 **
1434 ** If an SQL is very nearly finished at the time when sqlite3_interrupt()
1435 ** is called, then it might not have an opportunity to be interrupted.
1436 ** It might continue to completion.
1437 ** An SQL operation that is interrupted will return
1438 ** [SQLITE_INTERRUPT].  If the interrupted SQL operation is an
1439 ** INSERT, UPDATE, or DELETE that is inside an explicit transaction, 
1440 ** then the entire transaction will be rolled back automatically.
1441 ** A call to sqlite3_interrupt() has no effect on SQL statements
1442 ** that are started after sqlite3_interrupt() returns.
1443 **
1444 ** INVARIANTS:
1445 **
1446 ** {F12271} The [sqlite3_interrupt()] interface will force all running
1447 **          SQL statements associated with the same database connection
1448 **          to halt after processing at most one additional row of
1449 **          data.
1450 **
1451 ** {F12272} Any SQL statement that is interrupted by [sqlite3_interrupt()]
1452 **          will return [SQLITE_INTERRUPT].
1453 **
1454 ** LIMITATIONS:
1455 **
1456 ** {U12279} If the database connection closes while [sqlite3_interrupt()]
1457 **          is running then bad things will likely happen.
1458 */
1459 SQLITE_API void sqlite3_interrupt(sqlite3*);
1460
1461 /*
1462 ** CAPI3REF: Determine If An SQL Statement Is Complete {F10510}
1463 **
1464 ** These routines are useful for command-line input to determine if the
1465 ** currently entered text seems to form complete a SQL statement or
1466 ** if additional input is needed before sending the text into
1467 ** SQLite for parsing.  These routines return true if the input string
1468 ** appears to be a complete SQL statement.  A statement is judged to be
1469 ** complete if it ends with a semicolon token and is not a fragment of a
1470 ** CREATE TRIGGER statement.  Semicolons that are embedded within
1471 ** string literals or quoted identifier names or comments are not
1472 ** independent tokens (they are part of the token in which they are
1473 ** embedded) and thus do not count as a statement terminator.
1474 **
1475 ** These routines do not parse the SQL and
1476 ** so will not detect syntactically incorrect SQL.
1477 **
1478 ** INVARIANTS:
1479 **
1480 ** {F10511} The sqlite3_complete() and sqlite3_complete16() functions
1481 **          return true (non-zero) if and only if the last
1482 **          non-whitespace token in their input is a semicolon that
1483 **          is not in between the BEGIN and END of a CREATE TRIGGER
1484 **          statement.
1485 **
1486 ** LIMITATIONS:
1487 **
1488 ** {U10512} The input to sqlite3_complete() must be a zero-terminated
1489 **          UTF-8 string.
1490 **
1491 ** {U10513} The input to sqlite3_complete16() must be a zero-terminated
1492 **          UTF-16 string in native byte order.
1493 */
1494 SQLITE_API int sqlite3_complete(const char *sql);
1495 SQLITE_API int sqlite3_complete16(const void *sql);
1496
1497 /*
1498 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310}
1499 **
1500 ** This routine identifies a callback function that might be
1501 ** invoked whenever an attempt is made to open a database table 
1502 ** that another thread or process has locked.
1503 ** If the busy callback is NULL, then [SQLITE_BUSY]
1504 ** or [SQLITE_IOERR_BLOCKED]
1505 ** is returned immediately upon encountering the lock.
1506 ** If the busy callback is not NULL, then the
1507 ** callback will be invoked with two arguments.  The
1508 ** first argument to the handler is a copy of the void* pointer which
1509 ** is the third argument to this routine.  The second argument to
1510 ** the handler is the number of times that the busy handler has
1511 ** been invoked for this locking event.   If the
1512 ** busy callback returns 0, then no additional attempts are made to
1513 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
1514 ** If the callback returns non-zero, then another attempt
1515 ** is made to open the database for reading and the cycle repeats.
1516 **
1517 ** The presence of a busy handler does not guarantee that
1518 ** it will be invoked when there is lock contention.
1519 ** If SQLite determines that invoking the busy handler could result in
1520 ** a deadlock, it will go ahead and return [SQLITE_BUSY] or
1521 ** [SQLITE_IOERR_BLOCKED] instead of invoking the
1522 ** busy handler.
1523 ** Consider a scenario where one process is holding a read lock that
1524 ** it is trying to promote to a reserved lock and
1525 ** a second process is holding a reserved lock that it is trying
1526 ** to promote to an exclusive lock.  The first process cannot proceed
1527 ** because it is blocked by the second and the second process cannot
1528 ** proceed because it is blocked by the first.  If both processes
1529 ** invoke the busy handlers, neither will make any progress.  Therefore,
1530 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
1531 ** will induce the first process to release its read lock and allow
1532 ** the second process to proceed.
1533 **
1534 ** The default busy callback is NULL.
1535 **
1536 ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
1537 ** when SQLite is in the middle of a large transaction where all the
1538 ** changes will not fit into the in-memory cache.  SQLite will
1539 ** already hold a RESERVED lock on the database file, but it needs
1540 ** to promote this lock to EXCLUSIVE so that it can spill cache
1541 ** pages into the database file without harm to concurrent
1542 ** readers.  If it is unable to promote the lock, then the in-memory
1543 ** cache will be left in an inconsistent state and so the error
1544 ** code is promoted from the relatively benign [SQLITE_BUSY] to
1545 ** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
1546 ** forces an automatic rollback of the changes.  See the
1547 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
1548 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
1549 ** this is important.
1550 **      
1551 ** There can only be a single busy handler defined for each database
1552 ** connection.  Setting a new busy handler clears any previous one. 
1553 ** Note that calling [sqlite3_busy_timeout()] will also set or clear
1554 ** the busy handler.
1555 **
1556 ** INVARIANTS:
1557 **
1558 ** {F12311} The [sqlite3_busy_handler()] function replaces the busy handler
1559 **          callback in the database connection identified by the 1st
1560 **          parameter with a new busy handler identified by the 2nd and 3rd
1561 **          parameters.
1562 **
1563 ** {F12312} The default busy handler for new database connections is NULL.
1564 **
1565 ** {F12314} When two or more database connection share a common cache,
1566 **          the busy handler for the database connection currently using
1567 **          the cache is invoked when the cache encounters a lock.
1568 **
1569 ** {F12316} If a busy handler callback returns zero, then the SQLite
1570 **          interface that provoked the locking event will return
1571 **          [SQLITE_BUSY].
1572 **
1573 ** {F12318} SQLite will invokes the busy handler with two argument which
1574 **          are a copy of the pointer supplied by the 3rd parameter to
1575 **          [sqlite3_busy_handler()] and a count of the number of prior
1576 **          invocations of the busy handler for the same locking event.
1577 **
1578 ** LIMITATIONS:
1579 **
1580 ** {U12319} A busy handler should not call close the database connection
1581 **          or prepared statement that invoked the busy handler.
1582 */
1583 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
1584
1585 /*
1586 ** CAPI3REF: Set A Busy Timeout {F12340}
1587 **
1588 ** This routine sets a [sqlite3_busy_handler | busy handler]
1589 ** that sleeps for a while when a
1590 ** table is locked.  The handler will sleep multiple times until 
1591 ** at least "ms" milliseconds of sleeping have been done. {F12343} After
1592 ** "ms" milliseconds of sleeping, the handler returns 0 which
1593 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
1594 **
1595 ** Calling this routine with an argument less than or equal to zero
1596 ** turns off all busy handlers.
1597 **
1598 ** There can only be a single busy handler for a particular database
1599 ** connection.  If another busy handler was defined  
1600 ** (using [sqlite3_busy_handler()]) prior to calling
1601 ** this routine, that other busy handler is cleared.
1602 **
1603 ** INVARIANTS:
1604 **
1605 ** {F12341} The [sqlite3_busy_timeout()] function overrides any prior
1606 **          [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting
1607 **          on the same database connection.
1608 **
1609 ** {F12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than
1610 **          or equal to zero, then the busy handler is cleared so that
1611 **          all subsequent locking events immediately return [SQLITE_BUSY].
1612 **
1613 ** {F12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive
1614 **          number N, then a busy handler is set that repeatedly calls
1615 **          the xSleep() method in the VFS interface until either the
1616 **          lock clears or until the cumulative sleep time reported back
1617 **          by xSleep() exceeds N milliseconds.
1618 */
1619 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
1620
1621 /*
1622 ** CAPI3REF: Convenience Routines For Running Queries {F12370}
1623 **
1624 ** Definition: A <b>result table</b> is memory data structure created by the
1625 ** [sqlite3_get_table()] interface.  A result table records the
1626 ** complete query results from one or more queries.
1627 **
1628 ** The table conceptually has a number of rows and columns.  But
1629 ** these numbers are not part of the result table itself.  These
1630 ** numbers are obtained separately.  Let N be the number of rows
1631 ** and M be the number of columns.
1632 **
1633 ** A result table is an array of pointers to zero-terminated
1634 ** UTF-8 strings.  There are (N+1)*M elements in the array.  
1635 ** The first M pointers point to zero-terminated strings that 
1636 ** contain the names of the columns.
1637 ** The remaining entries all point to query results.  NULL
1638 ** values are give a NULL pointer.  All other values are in
1639 ** their UTF-8 zero-terminated string representation as returned by
1640 ** [sqlite3_column_text()].
1641 **
1642 ** A result table might consists of one or more memory allocations.
1643 ** It is not safe to pass a result table directly to [sqlite3_free()].
1644 ** A result table should be deallocated using [sqlite3_free_table()].
1645 **
1646 ** As an example of the result table format, suppose a query result
1647 ** is as follows:
1648 **
1649 ** <blockquote><pre>
1650 **        Name        | Age
1651 **        -----------------------
1652 **        Alice       | 43
1653 **        Bob         | 28
1654 **        Cindy       | 21
1655 ** </pre></blockquote>
1656 **
1657 ** There are two column (M==2) and three rows (N==3).  Thus the
1658 ** result table has 8 entries.  Suppose the result table is stored
1659 ** in an array names azResult.  Then azResult holds this content:
1660 **
1661 ** <blockquote><pre>
1662 **        azResult&#91;0] = "Name";
1663 **        azResult&#91;1] = "Age";
1664 **        azResult&#91;2] = "Alice";
1665 **        azResult&#91;3] = "43";
1666 **        azResult&#91;4] = "Bob";
1667 **        azResult&#91;5] = "28";
1668 **        azResult&#91;6] = "Cindy";
1669 **        azResult&#91;7] = "21";
1670 ** </pre></blockquote>
1671 **
1672 ** The sqlite3_get_table() function evaluates one or more
1673 ** semicolon-separated SQL statements in the zero-terminated UTF-8
1674 ** string of its 2nd parameter.  It returns a result table to the
1675 ** pointer given in its 3rd parameter.
1676 **
1677 ** After the calling function has finished using the result, it should 
1678 ** pass the pointer to the result table to sqlite3_free_table() in order to 
1679 ** release the memory that was malloc-ed.  Because of the way the 
1680 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
1681 ** function must not try to call [sqlite3_free()] directly.  Only 
1682 ** [sqlite3_free_table()] is able to release the memory properly and safely.
1683 **
1684 ** The sqlite3_get_table() interface is implemented as a wrapper around
1685 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
1686 ** to any internal data structures of SQLite.  It uses only the public
1687 ** interface defined here.  As a consequence, errors that occur in the
1688 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
1689 ** reflected in subsequent calls to [sqlite3_errcode()] or
1690 ** [sqlite3_errmsg()].
1691 **
1692 ** INVARIANTS:
1693 **
1694 ** {F12371} If a [sqlite3_get_table()] fails a memory allocation, then
1695 **          it frees the result table under construction, aborts the
1696 **          query in process, skips any subsequent queries, sets the
1697 **          *resultp output pointer to NULL and returns [SQLITE_NOMEM].
1698 **
1699 ** {F12373} If the ncolumn parameter to [sqlite3_get_table()] is not NULL
1700 **          then [sqlite3_get_table()] write the number of columns in the
1701 **          result set of the query into *ncolumn if the query is
1702 **          successful (if the function returns SQLITE_OK).
1703 **
1704 ** {F12374} If the nrow parameter to [sqlite3_get_table()] is not NULL
1705 **          then [sqlite3_get_table()] write the number of rows in the
1706 **          result set of the query into *nrow if the query is
1707 **          successful (if the function returns SQLITE_OK).
1708 **
1709 ** {F12376} The [sqlite3_get_table()] function sets its *ncolumn value
1710 **          to the number of columns in the result set of the query in the
1711 **          sql parameter, or to zero if the query in sql has an empty
1712 **          result set.
1713 */
1714 SQLITE_API int sqlite3_get_table(
1715   sqlite3*,             /* An open database */
1716   const char *sql,      /* SQL to be evaluated */
1717   char ***pResult,      /* Results of the query */
1718   int *nrow,            /* Number of result rows written here */
1719   int *ncolumn,         /* Number of result columns written here */
1720   char **errmsg         /* Error msg written here */
1721 );
1722 SQLITE_API void sqlite3_free_table(char **result);
1723
1724 /*
1725 ** CAPI3REF: Formatted String Printing Functions {F17400}
1726 **
1727 ** These routines are workalikes of the "printf()" family of functions
1728 ** from the standard C library.
1729 **
1730 ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
1731 ** results into memory obtained from [sqlite3_malloc()].
1732 ** The strings returned by these two routines should be
1733 ** released by [sqlite3_free()].   Both routines return a
1734 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
1735 ** memory to hold the resulting string.
1736 **
1737 ** In sqlite3_snprintf() routine is similar to "snprintf()" from
1738 ** the standard C library.  The result is written into the
1739 ** buffer supplied as the second parameter whose size is given by
1740 ** the first parameter. Note that the order of the
1741 ** first two parameters is reversed from snprintf().  This is an
1742 ** historical accident that cannot be fixed without breaking
1743 ** backwards compatibility.  Note also that sqlite3_snprintf()
1744 ** returns a pointer to its buffer instead of the number of
1745 ** characters actually written into the buffer.  We admit that
1746 ** the number of characters written would be a more useful return
1747 ** value but we cannot change the implementation of sqlite3_snprintf()
1748 ** now without breaking compatibility.
1749 **
1750 ** As long as the buffer size is greater than zero, sqlite3_snprintf()
1751 ** guarantees that the buffer is always zero-terminated.  The first
1752 ** parameter "n" is the total size of the buffer, including space for
1753 ** the zero terminator.  So the longest string that can be completely
1754 ** written will be n-1 characters.
1755 **
1756 ** These routines all implement some additional formatting
1757 ** options that are useful for constructing SQL statements.
1758 ** All of the usual printf formatting options apply.  In addition, there
1759 ** is are "%q", "%Q", and "%z" options.
1760 **
1761 ** The %q option works like %s in that it substitutes a null-terminated
1762 ** string from the argument list.  But %q also doubles every '\'' character.
1763 ** %q is designed for use inside a string literal.  By doubling each '\''
1764 ** character it escapes that character and allows it to be inserted into
1765 ** the string.
1766 **
1767 ** For example, so some string variable contains text as follows:
1768 **
1769 ** <blockquote><pre>
1770 **  char *zText = "It's a happy day!";
1771 ** </pre></blockquote>
1772 **
1773 ** One can use this text in an SQL statement as follows:
1774 **
1775 ** <blockquote><pre>
1776 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
1777 **  sqlite3_exec(db, zSQL, 0, 0, 0);
1778 **  sqlite3_free(zSQL);
1779 ** </pre></blockquote>
1780 **
1781 ** Because the %q format string is used, the '\'' character in zText
1782 ** is escaped and the SQL generated is as follows:
1783 **
1784 ** <blockquote><pre>
1785 **  INSERT INTO table1 VALUES('It''s a happy day!')
1786 ** </pre></blockquote>
1787 **
1788 ** This is correct.  Had we used %s instead of %q, the generated SQL
1789 ** would have looked like this:
1790 **
1791 ** <blockquote><pre>
1792 **  INSERT INTO table1 VALUES('It's a happy day!');
1793 ** </pre></blockquote>
1794 **
1795 ** This second example is an SQL syntax error.  As a general rule you
1796 ** should always use %q instead of %s when inserting text into a string 
1797 ** literal.
1798 **
1799 ** The %Q option works like %q except it also adds single quotes around
1800 ** the outside of the total string.  Or if the parameter in the argument
1801 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
1802 ** quotes) in place of the %Q option. {END}  So, for example, one could say:
1803 **
1804 ** <blockquote><pre>
1805 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
1806 **  sqlite3_exec(db, zSQL, 0, 0, 0);
1807 **  sqlite3_free(zSQL);
1808 ** </pre></blockquote>
1809 **
1810 ** The code above will render a correct SQL statement in the zSQL
1811 ** variable even if the zText variable is a NULL pointer.
1812 **
1813 ** The "%z" formatting option works exactly like "%s" with the
1814 ** addition that after the string has been read and copied into
1815 ** the result, [sqlite3_free()] is called on the input string. {END}
1816 **
1817 ** INVARIANTS:
1818 **
1819 ** {F17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
1820 **           return either pointers to zero-terminated UTF-8 strings held in
1821 **           memory obtained from [sqlite3_malloc()] or NULL pointers if
1822 **           a call to [sqlite3_malloc()] fails.
1823 **
1824 ** {F17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
1825 **           UTF-8 string into the buffer pointed to by the second parameter
1826 **           provided that the first parameter is greater than zero.
1827 **
1828 ** {F17407}  The [sqlite3_snprintf()] interface does not writes slots of
1829 **           its output buffer (the second parameter) outside the range
1830 **           of 0 through N-1 (where N is the first parameter)
1831 **           regardless of the length of the string
1832 **           requested by the format specification.
1833 **   
1834 */
1835 SQLITE_API char *sqlite3_mprintf(const char*,...);
1836 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
1837 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
1838
1839 /*
1840 ** CAPI3REF: Memory Allocation Subsystem {F17300}
1841 **
1842 ** The SQLite core  uses these three routines for all of its own
1843 ** internal memory allocation needs. "Core" in the previous sentence
1844 ** does not include operating-system specific VFS implementation.  The
1845 ** windows VFS uses native malloc and free for some operations.
1846 **
1847 ** The sqlite3_malloc() routine returns a pointer to a block
1848 ** of memory at least N bytes in length, where N is the parameter.
1849 ** If sqlite3_malloc() is unable to obtain sufficient free
1850 ** memory, it returns a NULL pointer.  If the parameter N to
1851 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
1852 ** a NULL pointer.
1853 **
1854 ** Calling sqlite3_free() with a pointer previously returned
1855 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
1856 ** that it might be reused.  The sqlite3_free() routine is
1857 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
1858 ** to sqlite3_free() is harmless.  After being freed, memory
1859 ** should neither be read nor written.  Even reading previously freed
1860 ** memory might result in a segmentation fault or other severe error.
1861 ** Memory corruption, a segmentation fault, or other severe error
1862 ** might result if sqlite3_free() is called with a non-NULL pointer that
1863 ** was not obtained from sqlite3_malloc() or sqlite3_free().
1864 **
1865 ** The sqlite3_realloc() interface attempts to resize a
1866 ** prior memory allocation to be at least N bytes, where N is the
1867 ** second parameter.  The memory allocation to be resized is the first
1868 ** parameter.  If the first parameter to sqlite3_realloc()
1869 ** is a NULL pointer then its behavior is identical to calling
1870 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
1871 ** If the second parameter to sqlite3_realloc() is zero or
1872 ** negative then the behavior is exactly the same as calling
1873 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
1874 ** Sqlite3_realloc() returns a pointer to a memory allocation
1875 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
1876 ** If M is the size of the prior allocation, then min(N,M) bytes
1877 ** of the prior allocation are copied into the beginning of buffer returned
1878 ** by sqlite3_realloc() and the prior allocation is freed.
1879 ** If sqlite3_realloc() returns NULL, then the prior allocation
1880 ** is not freed.
1881 **
1882 ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
1883 ** is always aligned to at least an 8 byte boundary. {END}
1884 **
1885 ** The default implementation
1886 ** of the memory allocation subsystem uses the malloc(), realloc()
1887 ** and free() provided by the standard C library. {F17382} However, if 
1888 ** SQLite is compiled with the following C preprocessor macro
1889 **
1890 ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote>
1891 **
1892 ** where <i>NNN</i> is an integer, then SQLite create a static
1893 ** array of at least <i>NNN</i> bytes in size and use that array
1894 ** for all of its dynamic memory allocation needs. {END}  Additional
1895 ** memory allocator options may be added in future releases.
1896 **
1897 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
1898 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
1899 ** implementation of these routines to be omitted.  That capability
1900 ** is no longer provided.  Only built-in memory allocators can be
1901 ** used.
1902 **
1903 ** The windows OS interface layer calls
1904 ** the system malloc() and free() directly when converting
1905 ** filenames between the UTF-8 encoding used by SQLite
1906 ** and whatever filename encoding is used by the particular windows
1907 ** installation.  Memory allocation errors are detected, but
1908 ** they are reported back as [SQLITE_CANTOPEN] or
1909 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
1910 **
1911 ** INVARIANTS:
1912 **
1913 ** {F17303}  The [sqlite3_malloc(N)] interface returns either a pointer to 
1914 **           newly checked-out block of at least N bytes of memory
1915 **           that is 8-byte aligned, 
1916 **           or it returns NULL if it is unable to fulfill the request.
1917 **
1918 ** {F17304}  The [sqlite3_malloc(N)] interface returns a NULL pointer if
1919 **           N is less than or equal to zero.
1920 **
1921 ** {F17305}  The [sqlite3_free(P)] interface releases memory previously
1922 **           returned from [sqlite3_malloc()] or [sqlite3_realloc()],
1923 **           making it available for reuse.
1924 **
1925 ** {F17306}  A call to [sqlite3_free(NULL)] is a harmless no-op.
1926 **
1927 ** {F17310}  A call to [sqlite3_realloc(0,N)] is equivalent to a call
1928 **           to [sqlite3_malloc(N)].
1929 **
1930 ** {F17312}  A call to [sqlite3_realloc(P,0)] is equivalent to a call
1931 **           to [sqlite3_free(P)].
1932 **
1933 ** {F17315}  The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()],
1934 **           and [sqlite3_free()] for all of its memory allocation and
1935 **           deallocation needs.
1936 **
1937 ** {F17318}  The [sqlite3_realloc(P,N)] interface returns either a pointer
1938 **           to a block of checked-out memory of at least N bytes in size
1939 **           that is 8-byte aligned, or a NULL pointer.
1940 **
1941 ** {F17321}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
1942 **           copies the first K bytes of content from P into the newly allocated
1943 **           where K is the lessor of N and the size of the buffer P.
1944 **
1945 ** {F17322}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
1946 **           releases the buffer P.
1947 **
1948 ** {F17323}  When [sqlite3_realloc(P,N)] returns NULL, the buffer P is
1949 **           not modified or released.
1950 **
1951 ** LIMITATIONS:
1952 **
1953 ** {U17350}  The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
1954 **           must be either NULL or else a pointer obtained from a prior
1955 **           invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that has
1956 **           not been released.
1957 **
1958 ** {U17351}  The application must not read or write any part of 
1959 **           a block of memory after it has been released using
1960 **           [sqlite3_free()] or [sqlite3_realloc()].
1961 **
1962 */
1963 SQLITE_API void *sqlite3_malloc(int);
1964 SQLITE_API void *sqlite3_realloc(void*, int);
1965 SQLITE_API void sqlite3_free(void*);
1966
1967 /*
1968 ** CAPI3REF: Memory Allocator Statistics {F17370}
1969 **
1970 ** SQLite provides these two interfaces for reporting on the status
1971 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
1972 ** the memory allocation subsystem included within the SQLite.
1973 **
1974 ** INVARIANTS:
1975 **
1976 ** {F17371} The [sqlite3_memory_used()] routine returns the
1977 **          number of bytes of memory currently outstanding 
1978 **          (malloced but not freed).
1979 **
1980 ** {F17373} The [sqlite3_memory_highwater()] routine returns the maximum
1981 **          value of [sqlite3_memory_used()] 
1982 **          since the highwater mark was last reset.
1983 **
1984 ** {F17374} The values returned by [sqlite3_memory_used()] and
1985 **          [sqlite3_memory_highwater()] include any overhead
1986 **          added by SQLite in its implementation of [sqlite3_malloc()],
1987 **          but not overhead added by the any underlying system library
1988 **          routines that [sqlite3_malloc()] may call.
1989 ** 
1990 ** {F17375} The memory highwater mark is reset to the current value of
1991 **          [sqlite3_memory_used()] if and only if the parameter to
1992 **          [sqlite3_memory_highwater()] is true.  The value returned
1993 **          by [sqlite3_memory_highwater(1)] is the highwater mark
1994 **          prior to the reset.
1995 */
1996 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
1997 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
1998
1999 /*
2000 ** CAPI3REF: Pseudo-Random Number Generator {F17390}
2001 **
2002 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2003 ** select random ROWIDs when inserting new records into a table that
2004 ** already uses the largest possible ROWID.  The PRNG is also used for
2005 ** the build-in random() and randomblob() SQL functions.  This interface allows
2006 ** appliations to access the same PRNG for other purposes.
2007 **
2008 ** A call to this routine stores N bytes of randomness into buffer P.
2009 **
2010 ** The first time this routine is invoked (either internally or by
2011 ** the application) the PRNG is seeded using randomness obtained
2012 ** from the xRandomness method of the default [sqlite3_vfs] object.
2013 ** On all subsequent invocations, the pseudo-randomness is generated
2014 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2015 ** method.
2016 **
2017 ** INVARIANTS:
2018 **
2019 ** {F17392} The [sqlite3_randomness(N,P)] interface writes N bytes of
2020 **          high-quality pseudo-randomness into buffer P.
2021 */
2022 SQLITE_API void sqlite3_randomness(int N, void *P);
2023
2024 /*
2025 ** CAPI3REF: Compile-Time Authorization Callbacks {F12500}
2026 **
2027 ** This routine registers a authorizer callback with a particular
2028 ** [database connection], supplied in the first argument.
2029 ** The authorizer callback is invoked as SQL statements are being compiled
2030 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2031 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
2032 ** points during the compilation process, as logic is being created
2033 ** to perform various actions, the authorizer callback is invoked to
2034 ** see if those actions are allowed.  The authorizer callback should
2035 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2036 ** specific action but allow the SQL statement to continue to be
2037 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2038 ** rejected with an error.   If the authorizer callback returns
2039 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2040 ** then [sqlite3_prepare_v2()] or equivalent call that triggered
2041 ** the authorizer will fail with an error message.
2042 **
2043 ** When the callback returns [SQLITE_OK], that means the operation
2044 ** requested is ok.  When the callback returns [SQLITE_DENY], the
2045 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2046 ** authorizer will fail with an error message explaining that
2047 ** access is denied.  If the authorizer code is [SQLITE_READ]
2048 ** and the callback returns [SQLITE_IGNORE] then the
2049 ** [prepared statement] statement is constructed to substitute
2050 ** a NULL value in place of the table column that would have
2051 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2052 ** return can be used to deny an untrusted user access to individual
2053 ** columns of a table.
2054 **
2055 ** The first parameter to the authorizer callback is a copy of
2056 ** the third parameter to the sqlite3_set_authorizer() interface.
2057 ** The second parameter to the callback is an integer 
2058 ** [SQLITE_COPY | action code] that specifies the particular action
2059 ** to be authorized. The third through sixth
2060 ** parameters to the callback are zero-terminated strings that contain 
2061 ** additional details about the action to be authorized.
2062 **
2063 ** An authorizer is used when [sqlite3_prepare | preparing]
2064 ** SQL statements from an untrusted
2065 ** source, to ensure that the SQL statements do not try to access data
2066 ** that they are not allowed to see, or that they do not try to
2067 ** execute malicious statements that damage the database.  For
2068 ** example, an application may allow a user to enter arbitrary
2069 ** SQL queries for evaluation by a database.  But the application does
2070 ** not want the user to be able to make arbitrary changes to the
2071 ** database.  An authorizer could then be put in place while the
2072 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2073 ** disallows everything except [SELECT] statements.
2074 **
2075 ** Applications that need to process SQL from untrusted sources
2076 ** might also consider lowering resource limits using [sqlite3_limit()]
2077 ** and limiting database size using the [max_page_count] [PRAGMA]
2078 ** in addition to using an authorizer.
2079 **
2080 ** Only a single authorizer can be in place on a database connection
2081 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2082 ** previous call.  Disable the authorizer by installing a NULL callback.
2083 ** The authorizer is disabled by default.
2084 **
2085 ** Note that the authorizer callback is invoked only during 
2086 ** [sqlite3_prepare()] or its variants.  Authorization is not
2087 ** performed during statement evaluation in [sqlite3_step()].
2088 **
2089 ** INVARIANTS:
2090 **
2091 ** {F12501} The [sqlite3_set_authorizer(D,...)] interface registers a
2092 **          authorizer callback with database connection D.
2093 **
2094 ** {F12502} The authorizer callback is invoked as SQL statements are
2095 **          being compiled
2096 **
2097 ** {F12503} If the authorizer callback returns any value other than
2098 **          [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] then
2099 **          the [sqlite3_prepare_v2()] or equivalent call that caused
2100 **          the authorizer callback to run shall fail with an
2101 **          [SQLITE_ERROR] error code and an appropriate error message.
2102 **
2103 ** {F12504} When the authorizer callback returns [SQLITE_OK], the operation
2104 **          described is coded normally.
2105 **
2106 ** {F12505} When the authorizer callback returns [SQLITE_DENY], the
2107 **          [sqlite3_prepare_v2()] or equivalent call that caused the
2108 **          authorizer callback to run shall fail
2109 **          with an [SQLITE_ERROR] error code and an error message
2110 **          explaining that access is denied.
2111 **
2112 ** {F12506} If the authorizer code (the 2nd parameter to the authorizer
2113 **          callback) is [SQLITE_READ] and the authorizer callback returns
2114 **          [SQLITE_IGNORE] then the prepared statement is constructed to
2115 **          insert a NULL value in place of the table column that would have
2116 **          been read if [SQLITE_OK] had been returned.
2117 **
2118 ** {F12507} If the authorizer code (the 2nd parameter to the authorizer
2119 **          callback) is anything other than [SQLITE_READ], then
2120 **          a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. 
2121 **
2122 ** {F12510} The first parameter to the authorizer callback is a copy of
2123 **          the third parameter to the [sqlite3_set_authorizer()] interface.
2124 **
2125 ** {F12511} The second parameter to the callback is an integer 
2126 **          [SQLITE_COPY | action code] that specifies the particular action
2127 **          to be authorized.
2128 **
2129 ** {F12512} The third through sixth parameters to the callback are
2130 **          zero-terminated strings that contain 
2131 **          additional details about the action to be authorized.
2132 **
2133 ** {F12520} Each call to [sqlite3_set_authorizer()] overrides the
2134 **          any previously installed authorizer.
2135 **
2136 ** {F12521} A NULL authorizer means that no authorization
2137 **          callback is invoked.
2138 **
2139 ** {F12522} The default authorizer is NULL.
2140 */
2141 SQLITE_API int sqlite3_set_authorizer(
2142   sqlite3*,
2143   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2144   void *pUserData
2145 );
2146
2147 /*
2148 ** CAPI3REF: Authorizer Return Codes {F12590}
2149 **
2150 ** The [sqlite3_set_authorizer | authorizer callback function] must
2151 ** return either [SQLITE_OK] or one of these two constants in order
2152 ** to signal SQLite whether or not the action is permitted.  See the
2153 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2154 ** information.
2155 */
2156 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2157 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2158
2159 /*
2160 ** CAPI3REF: Authorizer Action Codes {F12550}
2161 **
2162 ** The [sqlite3_set_authorizer()] interface registers a callback function
2163 ** that is invoked to authorizer certain SQL statement actions.  The
2164 ** second parameter to the callback is an integer code that specifies
2165 ** what action is being authorized.  These are the integer action codes that
2166 ** the authorizer callback may be passed.
2167 **
2168 ** These action code values signify what kind of operation is to be 
2169 ** authorized.  The 3rd and 4th parameters to the authorization
2170 ** callback function will be parameters or NULL depending on which of these
2171 ** codes is used as the second parameter.  The 5th parameter to the
2172 ** authorizer callback is the name of the database ("main", "temp", 
2173 ** etc.) if applicable.  The 6th parameter to the authorizer callback
2174 ** is the name of the inner-most trigger or view that is responsible for
2175 ** the access attempt or NULL if this access attempt is directly from 
2176 ** top-level SQL code.
2177 **
2178 ** INVARIANTS:
2179 **
2180 ** {F12551} The second parameter to an 
2181 **          [sqlite3_set_authorizer | authorizer callback is always an integer
2182 **          [SQLITE_COPY | authorizer code] that specifies what action
2183 **          is being authorized.
2184 **
2185 ** {F12552} The 3rd and 4th parameters to the 
2186 **          [sqlite3_set_authorizer | authorization callback function]
2187 **          will be parameters or NULL depending on which 
2188 **          [SQLITE_COPY | authorizer code] is used as the second parameter.
2189 **
2190 ** {F12553} The 5th parameter to the
2191 **          [sqlite3_set_authorizer | authorizer callback] is the name
2192 **          of the database (example: "main", "temp", etc.) if applicable.
2193 **
2194 ** {F12554} The 6th parameter to the
2195 **          [sqlite3_set_authorizer | authorizer callback] is the name
2196 **          of the inner-most trigger or view that is responsible for
2197 **          the access attempt or NULL if this access attempt is directly from 
2198 **          top-level SQL code.
2199 */
2200 /******************************************* 3rd ************ 4th ***********/
2201 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2202 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2203 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2204 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2205 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2206 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2207 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2208 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2209 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2210 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2211 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2212 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2213 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2214 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2215 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2216 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2217 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2218 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2219 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2220 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2221 #define SQLITE_SELECT               21   /* NULL            NULL            */
2222 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
2223 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2224 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2225 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2226 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2227 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2228 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2229 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2230 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2231 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
2232 #define SQLITE_COPY                  0   /* No longer used */
2233
2234 /*
2235 ** CAPI3REF: Tracing And Profiling Functions {F12280}
2236 **
2237 ** These routines register callback functions that can be used for
2238 ** tracing and profiling the execution of SQL statements.
2239 **
2240 ** The callback function registered by sqlite3_trace() is invoked at
2241 ** various times when an SQL statement is being run by [sqlite3_step()].
2242 ** The callback returns a UTF-8 rendering of the SQL statement text
2243 ** as the statement first begins executing.  Additional callbacks occur
2244 ** as each triggersubprogram is entered.  The callbacks for triggers
2245 ** contain a UTF-8 SQL comment that identifies the trigger.
2246 ** 
2247 ** The callback function registered by sqlite3_profile() is invoked
2248 ** as each SQL statement finishes.  The profile callback contains
2249 ** the original statement text and an estimate of wall-clock time
2250 ** of how long that statement took to run.
2251 **
2252 ** The sqlite3_profile() API is currently considered experimental and
2253 ** is subject to change or removal in a future release.
2254 **
2255 ** The trigger reporting feature of the trace callback is considered
2256 ** experimental and is subject to change or removal in future releases.
2257 ** Future versions of SQLite might also add new trace callback 
2258 ** invocations.
2259 **
2260 ** INVARIANTS:
2261 **
2262 ** {F12281} The callback function registered by [sqlite3_trace()] is
2263 **          whenever an SQL statement first begins to execute and
2264 **          whenever a trigger subprogram first begins to run.
2265 **
2266 ** {F12282} Each call to [sqlite3_trace()] overrides the previously
2267 **          registered trace callback.
2268 **
2269 ** {F12283} A NULL trace callback disables tracing.
2270 **
2271 ** {F12284} The first argument to the trace callback is a copy of
2272 **          the pointer which was the 3rd argument to [sqlite3_trace()].
2273 **
2274 ** {F12285} The second argument to the trace callback is a
2275 **          zero-terminated UTF8 string containing the original text
2276 **          of the SQL statement as it was passed into [sqlite3_prepare_v2()]
2277 **          or the equivalent, or an SQL comment indicating the beginning
2278 **          of a trigger subprogram.
2279 **
2280 ** {F12287} The callback function registered by [sqlite3_profile()] is invoked
2281 **          as each SQL statement finishes.
2282 **
2283 ** {F12288} The first parameter to the profile callback is a copy of
2284 **          the 3rd parameter to [sqlite3_profile()].
2285 **
2286 ** {F12289} The second parameter to the profile callback is a
2287 **          zero-terminated UTF-8 string that contains the complete text of
2288 **          the SQL statement as it was processed by [sqlite3_prepare_v2()]
2289 **          or the equivalent.
2290 **
2291 ** {F12290} The third parameter to the profile  callback is an estimate
2292 **          of the number of nanoseconds of wall-clock time required to
2293 **          run the SQL statement from start to finish.
2294 */
2295 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2296 SQLITE_API void *sqlite3_profile(sqlite3*,
2297    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2298
2299 /*
2300 ** CAPI3REF: Query Progress Callbacks {F12910}
2301 **
2302 ** This routine configures a callback function - the
2303 ** progress callback - that is invoked periodically during long
2304 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2305 ** [sqlite3_get_table()].   An example use for this 
2306 ** interface is to keep a GUI updated during a large query.
2307 **
2308 ** If the progress callback returns non-zero, the opertion is
2309 ** interrupted.  This feature can be used to implement a
2310 ** "Cancel" button on a GUI dialog box.
2311 **
2312 ** INVARIANTS:
2313 **
2314 ** {F12911} The callback function registered by [sqlite3_progress_handler()]
2315 **          is invoked periodically during long running calls to
2316 **          [sqlite3_step()].
2317 **
2318 ** {F12912} The progress callback is invoked once for every N virtual
2319 **          machine opcodes, where N is the second argument to 
2320 **          the [sqlite3_progress_handler()] call that registered
2321 **          the callback.  <todo>What if N is less than 1?</todo>
2322 **
2323 ** {F12913} The progress callback itself is identified by the third
2324 **          argument to [sqlite3_progress_handler()].
2325 **
2326 ** {F12914} The fourth argument [sqlite3_progress_handler()] is a
2327 ***         void pointer passed to the progress callback
2328 **          function each time it is invoked.
2329 **
2330 ** {F12915} If a call to [sqlite3_step()] results in fewer than
2331 **          N opcodes being executed,
2332 **          then the progress callback is never invoked. {END}
2333 ** 
2334 ** {F12916} Every call to [sqlite3_progress_handler()]
2335 **          overwrites any previously registere progress handler.
2336 **
2337 ** {F12917} If the progress handler callback is NULL then no progress
2338 **          handler is invoked.
2339 **
2340 ** {F12918} If the progress callback returns a result other than 0, then
2341 **          the behavior is a if [sqlite3_interrupt()] had been called.
2342 */
2343 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2344
2345 /*
2346 ** CAPI3REF: Opening A New Database Connection {F12700}
2347 **
2348 ** These routines open an SQLite database file whose name
2349 ** is given by the filename argument.
2350 ** The filename argument is interpreted as UTF-8
2351 ** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
2352 ** in the native byte order for [sqlite3_open16()].
2353 ** An [sqlite3*] handle is usually returned in *ppDb, even
2354 ** if an error occurs.  The only exception is if SQLite is unable
2355 ** to allocate memory to hold the [sqlite3] object, a NULL will
2356 ** be written into *ppDb instead of a pointer to the [sqlite3] object.
2357 ** If the database is opened (and/or created)
2358 ** successfully, then [SQLITE_OK] is returned.  Otherwise an
2359 ** error code is returned.  The
2360 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()]  routines can be used to obtain
2361 ** an English language description of the error.
2362 **
2363 ** The default encoding for the database will be UTF-8 if
2364 ** [sqlite3_open()] or [sqlite3_open_v2()] is called and
2365 ** UTF-16 in the native byte order if [sqlite3_open16()] is used.
2366 **
2367 ** Whether or not an error occurs when it is opened, resources
2368 ** associated with the [sqlite3*] handle should be released by passing it
2369 ** to [sqlite3_close()] when it is no longer required.
2370 **
2371 ** The [sqlite3_open_v2()] interface works like [sqlite3_open()] 
2372 ** except that it acccepts two additional parameters for additional control
2373 ** over the new database connection.  The flags parameter can be
2374 ** one of:
2375 **
2376 ** <ol>
2377 ** <li>  [SQLITE_OPEN_READONLY]
2378 ** <li>  [SQLITE_OPEN_READWRITE]
2379 ** <li>  [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
2380 ** </ol>
2381 **
2382 ** The first value opens the database read-only. 
2383 ** If the database does not previously exist, an error is returned.
2384 ** The second option opens
2385 ** the database for reading and writing if possible, or reading only if
2386 ** if the file is write protected.  In either case the database
2387 ** must already exist or an error is returned.  The third option
2388 ** opens the database for reading and writing and creates it if it does
2389 ** not already exist.
2390 ** The third options is behavior that is always used for [sqlite3_open()]
2391 ** and [sqlite3_open16()].
2392 **
2393 ** If the 3rd parameter to [sqlite3_open_v2()] is not one of the
2394 ** combinations shown above then the behavior is undefined.
2395 **
2396 ** If the filename is ":memory:", then an private
2397 ** in-memory database is created for the connection.  This in-memory
2398 ** database will vanish when the database connection is closed.  Future
2399 ** version of SQLite might make use of additional special filenames
2400 ** that begin with the ":" character.  It is recommended that 
2401 ** when a database filename really does begin with
2402 ** ":" that you prefix the filename with a pathname like "./" to
2403 ** avoid ambiguity.
2404 **
2405 ** If the filename is an empty string, then a private temporary
2406 ** on-disk database will be created.  This private database will be
2407 ** automatically deleted as soon as the database connection is closed.
2408 **
2409 ** The fourth parameter to sqlite3_open_v2() is the name of the
2410 ** [sqlite3_vfs] object that defines the operating system 
2411 ** interface that the new database connection should use.  If the
2412 ** fourth parameter is a NULL pointer then the default [sqlite3_vfs]
2413 ** object is used.
2414 **
2415 ** <b>Note to windows users:</b>  The encoding used for the filename argument
2416 ** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever
2417 ** codepage is currently defined.  Filenames containing international
2418 ** characters must be converted to UTF-8 prior to passing them into
2419 ** [sqlite3_open()] or [sqlite3_open_v2()].
2420 **
2421 ** INVARIANTS:
2422 **
2423 ** {F12701} The [sqlite3_open()], [sqlite3_open16()], and
2424 **          [sqlite3_open_v2()] interfaces create a new
2425 **          [database connection] associated with
2426 **          the database file given in their first parameter.
2427 **
2428 ** {F12702} The filename argument is interpreted as UTF-8
2429 **          for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
2430 **          in the native byte order for [sqlite3_open16()].
2431 **
2432 ** {F12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()], 
2433 **          or [sqlite3_open_v2()] writes a pointer to a new
2434 **          [database connection] into *ppDb.
2435 **
2436 ** {F12704} The [sqlite3_open()], [sqlite3_open16()], and
2437 **          [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success,
2438 **          or an appropriate [error code] on failure.
2439 **
2440 ** {F12706} The default text encoding for a new database created using
2441 **          [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8.
2442 **
2443 ** {F12707} The default text encoding for a new database created using
2444 **          [sqlite3_open16()] will be UTF-16.
2445 **
2446 ** {F12709} The [sqlite3_open(F,D)] interface is equivalent to
2447 **          [sqlite3_open_v2(F,D,G,0)] where the G parameter is
2448 **          [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE].
2449 **
2450 ** {F12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2451 **          bit value [SQLITE_OPEN_READONLY] then the database is opened
2452 **          for reading only.
2453 **
2454 ** {F12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
2455 **          bit value [SQLITE_OPEN_READWRITE] then the database is opened
2456 **          reading and writing if possible, or for reading only if the
2457 **          file is write protected by the operating system.
2458 **
2459 ** {F12713} If the G parameter to [sqlite3_open(v2(F,D,G,V)] omits the
2460 **          bit value [SQLITE_OPEN_CREATE] and the database does not
2461 **          previously exist, an error is returned.
2462 **
2463 ** {F12714} If the G parameter to [sqlite3_open(v2(F,D,G,V)] contains the
2464 **          bit value [SQLITE_OPEN_CREATE] and the database does not
2465 **          previously exist, then an attempt is made to create and
2466 **          initialize the database.
2467 **
2468 ** {F12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()],
2469 **          or [sqlite3_open_v2()] is ":memory:", then an private,
2470 **          ephemeral, in-memory database is created for the connection.
2471 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
2472 **          in sqlite3_open_v2()?</todo>
2473 **
2474 ** {F12719} If the filename is NULL or an empty string, then a private,
2475 **          ephermeral on-disk database will be created.
2476 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
2477 **          in sqlite3_open_v2()?</todo>
2478 **
2479 ** {F12721} The [database connection] created by 
2480 **          [sqlite3_open_v2(F,D,G,V)] will use the
2481 **          [sqlite3_vfs] object identified by the V parameter, or
2482 **          the default [sqlite3_vfs] object is V is a NULL pointer.
2483 */
2484 SQLITE_API int sqlite3_open(
2485   const char *filename,   /* Database filename (UTF-8) */
2486   sqlite3 **ppDb          /* OUT: SQLite db handle */
2487 );
2488 SQLITE_API int sqlite3_open16(
2489   const void *filename,   /* Database filename (UTF-16) */
2490   sqlite3 **ppDb          /* OUT: SQLite db handle */
2491 );
2492 SQLITE_API int sqlite3_open_v2(
2493   const char *filename,   /* Database filename (UTF-8) */
2494   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2495   int flags,              /* Flags */
2496   const char *zVfs        /* Name of VFS module to use */
2497 );
2498
2499 /*
2500 ** CAPI3REF: Error Codes And Messages {F12800}
2501 **
2502 ** The sqlite3_errcode() interface returns the numeric
2503 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
2504 ** for the most recent failed sqlite3_* API call associated
2505 ** with [sqlite3] handle 'db'. If a prior API call failed but the
2506 ** most recent API call succeeded, the return value from sqlite3_errcode()
2507 ** is undefined.
2508 **
2509 ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2510 ** text that describes the error, as either UTF8 or UTF16 respectively.
2511 ** Memory to hold the error message string is managed internally.
2512 ** The application does not need to worry with freeing the result.
2513 ** However, the error string might be overwritten or deallocated by
2514 ** subsequent calls to other SQLite interface functions.
2515 **
2516 ** INVARIANTS:
2517 **
2518 ** {F12801} The [sqlite3_errcode(D)] interface returns the numeric
2519 **          [SQLITE_OK | result code] or
2520 **          [SQLITE_IOERR_READ | extended result code]
2521 **          for the most recently failed interface call associated
2522 **          with [database connection] D.
2523 **
2524 ** {F12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)]
2525 **          interfaces return English-language text that describes
2526 **          the error in the mostly recently failed interface call,
2527 **          encoded as either UTF8 or UTF16 respectively.
2528 **
2529 ** {F12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]
2530 **          are valid until the next SQLite interface call.
2531 **
2532 ** {F12808} Calls to API routines that do not return an error code
2533 **          (example: [sqlite3_data_count()]) do not
2534 **          change the error code or message returned by
2535 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
2536 **
2537 ** {F12809} Interfaces that are not associated with a specific
2538 **          [database connection] (examples:
2539 **          [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()]
2540 **          do not change the values returned by
2541 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
2542 */
2543 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2544 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2545 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2546
2547 /*
2548 ** CAPI3REF: SQL Statement Object {F13000}
2549 ** KEYWORDS: {prepared statement} {prepared statements}
2550 **
2551 ** An instance of this object represent single SQL statements.  This
2552 ** object is variously known as a "prepared statement" or a 
2553 ** "compiled SQL statement" or simply as a "statement".
2554 ** 
2555 ** The life of a statement object goes something like this:
2556 **
2557 ** <ol>
2558 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2559 **      function.
2560 ** <li> Bind values to host parameters using
2561 **      [sqlite3_bind_blob | sqlite3_bind_* interfaces].
2562 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2563 ** <li> Reset the statement using [sqlite3_reset()] then go back
2564 **      to step 2.  Do this zero or more times.
2565 ** <li> Destroy the object using [sqlite3_finalize()].
2566 ** </ol>
2567 **
2568 ** Refer to documentation on individual methods above for additional
2569 ** information.
2570 */
2571 typedef struct sqlite3_stmt sqlite3_stmt;
2572
2573 /*
2574 ** CAPI3REF: Run-time Limits {F12760}
2575 **
2576 ** This interface allows the size of various constructs to be limited
2577 ** on a connection by connection basis.  The first parameter is the
2578 ** [database connection] whose limit is to be set or queried.  The
2579 ** second parameter is one of the [limit categories] that define a
2580 ** class of constructs to be size limited.  The third parameter is the
2581 ** new limit for that construct.  The function returns the old limit.
2582 **
2583 ** If the new limit is a negative number, the limit is unchanged.
2584 ** For the limit category of SQLITE_LIMIT_XYZ there is a hard upper
2585 ** bound set by a compile-time C-preprocess macro named SQLITE_MAX_XYZ.
2586 ** (The "_LIMIT_" in the name is changed to "_MAX_".)
2587 ** Attempts to increase a limit above its hard upper bound are
2588 ** silently truncated to the hard upper limit.
2589 **
2590 ** Run time limits are intended for use in applications that manage
2591 ** both their own internal database and also databases that are controlled
2592 ** by untrusted external sources.  An example application might be a
2593 ** webbrowser that has its own databases for storing history and
2594 ** separate databases controlled by javascript applications downloaded
2595 ** off the internet.  The internal databases can be given the
2596 ** large, default limits.  Databases managed by external sources can
2597 ** be given much smaller limits designed to prevent a denial of service
2598 ** attach.  Developers might also want to use the [sqlite3_set_authorizer()]
2599 ** interface to further control untrusted SQL.  The size of the database
2600 ** created by an untrusted script can be contained using the
2601 ** [max_page_count] [PRAGMA].
2602 **
2603 ** This interface is currently considered experimental and is subject
2604 ** to change or removal without prior notice.
2605 **
2606 ** INVARIANTS:
2607 **
2608 ** {F12762} A successful call to [sqlite3_limit(D,C,V)] where V is
2609 **          positive changes the
2610 **          limit on the size of construct C in [database connection] D
2611 **          to the lessor of V and the hard upper bound on the size
2612 **          of C that is set at compile-time.
2613 **
2614 ** {F12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative
2615 **          leaves the state of [database connection] D unchanged.
2616 **
2617 ** {F12769} A successful call to [sqlite3_limit(D,C,V)] returns the
2618 **          value of the limit on the size of construct C in
2619 **          in [database connection] D as it was prior to the call.
2620 */
2621 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2622
2623 /*
2624 ** CAPI3REF: Run-Time Limit Categories {F12790}
2625 ** KEYWORDS: {limit category} {limit categories}
2626 ** 
2627 ** These constants define various aspects of a [database connection]
2628 ** that can be limited in size by calls to [sqlite3_limit()].
2629 ** The meanings of the various limits are as follows:
2630 **
2631 ** <dl>
2632 ** <dt>SQLITE_LIMIT_LENGTH</dt>
2633 ** <dd>The maximum size of any
2634 ** string or blob or table row.<dd>
2635 **
2636 ** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2637 ** <dd>The maximum length of an SQL statement.</dd>
2638 **
2639 ** <dt>SQLITE_LIMIT_COLUMN</dt>
2640 ** <dd>The maximum number of columns in a table definition or in the
2641 ** result set of a SELECT or the maximum number of columns in an index
2642 ** or in an ORDER BY or GROUP BY clause.</dd>
2643 **
2644 ** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2645 ** <dd>The maximum depth of the parse tree on any expression.</dd>
2646 **
2647 ** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2648 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>
2649 **
2650 ** <dt>SQLITE_LIMIT_VDBE_OP</dt>
2651 ** <dd>The maximum number of instructions in a virtual machine program
2652 ** used to implement an SQL statement.</dd>
2653 **
2654 ** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2655 ** <dd>The maximum number of arguments on a function.</dd>
2656 **
2657 ** <dt>SQLITE_LIMIT_ATTACHED</dt>
2658 ** <dd>The maximum number of attached databases.</dd>
2659 **
2660 ** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2661 ** <dd>The maximum length of the pattern argument to the LIKE or
2662 ** GLOB operators.</dd>
2663 **
2664 ** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2665 ** <dd>The maximum number of variables in an SQL statement that can
2666 ** be bound.</dd>
2667 ** </dl>
2668 */
2669 #define SQLITE_LIMIT_LENGTH                    0
2670 #define SQLITE_LIMIT_SQL_LENGTH                1
2671 #define SQLITE_LIMIT_COLUMN                    2
2672 #define SQLITE_LIMIT_EXPR_DEPTH                3
2673 #define SQLITE_LIMIT_COMPOUND_SELECT           4
2674 #define SQLITE_LIMIT_VDBE_OP                   5
2675 #define SQLITE_LIMIT_FUNCTION_ARG              6
2676 #define SQLITE_LIMIT_ATTACHED                  7
2677 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
2678 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
2679
2680 /*
2681 ** CAPI3REF: Compiling An SQL Statement {F13010}
2682 **
2683 ** To execute an SQL query, it must first be compiled into a byte-code
2684 ** program using one of these routines. 
2685 **
2686 ** The first argument "db" is an [database connection] 
2687 ** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()]
2688 ** or [sqlite3_open16()]. 
2689 ** The second argument "zSql" is the statement to be compiled, encoded
2690 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
2691 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
2692 ** use UTF-16. {END}
2693 **
2694 ** If the nByte argument is less
2695 ** than zero, then zSql is read up to the first zero terminator.
2696 ** If nByte is non-negative, then it is the maximum number of 
2697 ** bytes read from zSql.  When nByte is non-negative, the
2698 ** zSql string ends at either the first '\000' or '\u0000' character or 
2699 ** the nByte-th byte, whichever comes first. If the caller knows
2700 ** that the supplied string is nul-terminated, then there is a small
2701 ** performance advantage to be had by passing an nByte parameter that 
2702 ** is equal to the number of bytes in the input string <i>including</i> 
2703 ** the nul-terminator bytes.{END}
2704 **
2705 ** *pzTail is made to point to the first byte past the end of the
2706 ** first SQL statement in zSql.  These routines only compiles the first
2707 ** statement in zSql, so *pzTail is left pointing to what remains
2708 ** uncompiled.
2709 **
2710 ** *ppStmt is left pointing to a compiled [prepared statement] that can be
2711 ** executed using [sqlite3_step()].  Or if there is an error, *ppStmt is
2712 ** set to NULL.  If the input text contains no SQL (if the input
2713 ** is and empty string or a comment) then *ppStmt is set to NULL.
2714 ** {U13018} The calling procedure is responsible for deleting the
2715 ** compiled SQL statement
2716 ** using [sqlite3_finalize()] after it has finished with it.
2717 **
2718 ** On success, [SQLITE_OK] is returned.  Otherwise an 
2719 ** [error code] is returned.
2720 **
2721 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
2722 ** recommended for all new programs. The two older interfaces are retained
2723 ** for backwards compatibility, but their use is discouraged.
2724 ** In the "v2" interfaces, the prepared statement
2725 ** that is returned (the [sqlite3_stmt] object) contains a copy of the 
2726 ** original SQL text. {END} This causes the [sqlite3_step()] interface to
2727 ** behave a differently in two ways:
2728 **
2729 ** <ol>
2730 ** <li>
2731 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2732 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
2733 ** statement and try to run it again.  If the schema has changed in
2734 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
2735 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, 
2736 ** [SQLITE_SCHEMA] is now a fatal error.  Calling
2737 ** [sqlite3_prepare_v2()] again will not make the
2738 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
2739 ** of the parsing error that results in an [SQLITE_SCHEMA] return. {END}
2740 ** </li>
2741 **
2742 ** <li>
2743 ** When an error occurs, 
2744 ** [sqlite3_step()] will return one of the detailed 
2745 ** [error codes] or [extended error codes]. 
2746 ** The legacy behavior was that [sqlite3_step()] would only return a generic
2747 ** [SQLITE_ERROR] result code and you would have to make a second call to
2748 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
2749 ** With the "v2" prepare interfaces, the underlying reason for the error is
2750 ** returned immediately.
2751 ** </li>
2752 ** </ol>
2753 **
2754 ** INVARIANTS:
2755 **
2756 ** {F13011} The [sqlite3_prepare(db,zSql,...)] and
2757 **          [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the
2758 **          text in their zSql parameter as UTF-8.
2759 **
2760 ** {F13012} The [sqlite3_prepare16(db,zSql,...)] and
2761 **          [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the
2762 **          text in their zSql parameter as UTF-16 in the native byte order.
2763 **
2764 ** {F13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
2765 **          and its variants is less than zero, then SQL text is
2766 **          read from zSql is read up to the first zero terminator.
2767 **
2768 ** {F13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
2769 **          and its variants is non-negative, then at most nBytes bytes
2770 **          SQL text is read from zSql.
2771 **
2772 ** {F13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants
2773 **          if the zSql input text contains more than one SQL statement
2774 **          and pzTail is not NULL, then *pzTail is made to point to the
2775 **          first byte past the end of the first SQL statement in zSql.
2776 **          <todo>What does *pzTail point to if there is one statement?</todo>
2777 **
2778 ** {F13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)]
2779 **          or one of its variants writes into *ppStmt a pointer to a new
2780 **          [prepared statement] or a pointer to NULL
2781 **          if zSql contains nothing other than whitespace or comments. 
2782 **
2783 ** {F13019} The [sqlite3_prepare_v2()] interface and its variants return
2784 **          [SQLITE_OK] or an appropriate [error code] upon failure.
2785 **
2786 ** {F13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its
2787 **          variants returns an error (any value other than [SQLITE_OK])
2788 **          it first sets *ppStmt to NULL.
2789 */
2790 SQLITE_API int sqlite3_prepare(
2791   sqlite3 *db,            /* Database handle */
2792   const char *zSql,       /* SQL statement, UTF-8 encoded */
2793   int nByte,              /* Maximum length of zSql in bytes. */
2794   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2795   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2796 );
2797 SQLITE_API int sqlite3_prepare_v2(
2798   sqlite3 *db,            /* Database handle */
2799   const char *zSql,       /* SQL statement, UTF-8 encoded */
2800   int nByte,              /* Maximum length of zSql in bytes. */
2801   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2802   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2803 );
2804 SQLITE_API int sqlite3_prepare16(
2805   sqlite3 *db,            /* Database handle */
2806   const void *zSql,       /* SQL statement, UTF-16 encoded */
2807   int nByte,              /* Maximum length of zSql in bytes. */
2808   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2809   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2810 );
2811 SQLITE_API int sqlite3_prepare16_v2(
2812   sqlite3 *db,            /* Database handle */
2813   const void *zSql,       /* SQL statement, UTF-16 encoded */
2814   int nByte,              /* Maximum length of zSql in bytes. */
2815   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2816   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2817 );
2818
2819 /*
2820 ** CAPIREF: Retrieving Statement SQL {F13100}
2821 **
2822 ** This intereface can be used to retrieve a saved copy of the original
2823 ** SQL text used to create a [prepared statement].
2824 **
2825 ** INVARIANTS:
2826 **
2827 ** {F13101} If the [prepared statement] passed as 
2828 **          the an argument to [sqlite3_sql()] was compiled
2829 **          compiled using either [sqlite3_prepare_v2()] or
2830 **          [sqlite3_prepare16_v2()],
2831 **          then [sqlite3_sql()] function returns a pointer to a
2832 **          zero-terminated string containing a UTF-8 rendering
2833 **          of the original SQL statement.
2834 **
2835 ** {F13102} If the [prepared statement] passed as 
2836 **          the an argument to [sqlite3_sql()] was compiled
2837 **          compiled using either [sqlite3_prepare()] or
2838 **          [sqlite3_prepare16()],
2839 **          then [sqlite3_sql()] function returns a NULL pointer.
2840 **
2841 ** {F13103} The string returned by [sqlite3_sql(S)] is valid until the
2842 **          [prepared statement] S is deleted using [sqlite3_finalize(S)].
2843 */
2844 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
2845
2846 /*
2847 ** CAPI3REF:  Dynamically Typed Value Object  {F15000}
2848 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
2849 **
2850 ** SQLite uses the sqlite3_value object to represent all values
2851 ** that can be stored in a database table.
2852 ** SQLite uses dynamic typing for the values it stores.  
2853 ** Values stored in sqlite3_value objects can be
2854 ** be integers, floating point values, strings, BLOBs, or NULL.
2855 **
2856 ** An sqlite3_value object may be either "protected" or "unprotected".
2857 ** Some interfaces require a protected sqlite3_value.  Other interfaces
2858 ** will accept either a protected or an unprotected sqlite3_value.
2859 ** Every interface that accepts sqlite3_value arguments specifies 
2860 ** whether or not it requires a protected sqlite3_value.
2861 **
2862 ** The terms "protected" and "unprotected" refer to whether or not
2863 ** a mutex is held.  A internal mutex is held for a protected
2864 ** sqlite3_value object but no mutex is held for an unprotected
2865 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
2866 ** (with SQLITE_THREADSAFE=0 and with [sqlite3_threadsafe()] returning 0)
2867 ** then there is no distinction between
2868 ** protected and unprotected sqlite3_value objects and they can be
2869 ** used interchangable.  However, for maximum code portability it
2870 ** is recommended that applications make the distinction between
2871 ** between protected and unprotected sqlite3_value objects even if
2872 ** they are single threaded.
2873 **
2874 ** The sqlite3_value objects that are passed as parameters into the
2875 ** implementation of application-defined SQL functions are protected.
2876 ** The sqlite3_value object returned by
2877 ** [sqlite3_column_value()] is unprotected.
2878 ** Unprotected sqlite3_value objects may only be used with
2879 ** [sqlite3_result_value()] and [sqlite3_bind_value()].  All other
2880 ** interfaces that use sqlite3_value require protected sqlite3_value objects.
2881 */
2882 typedef struct Mem sqlite3_value;
2883
2884 /*
2885 ** CAPI3REF:  SQL Function Context Object {F16001}
2886 **
2887 ** The context in which an SQL function executes is stored in an
2888 ** sqlite3_context object.  A pointer to an sqlite3_context
2889 ** object is always first parameter to application-defined SQL functions.
2890 */
2891 typedef struct sqlite3_context sqlite3_context;
2892
2893 /*
2894 ** CAPI3REF:  Binding Values To Prepared Statements {F13500}
2895 **
2896 ** In the SQL strings input to [sqlite3_prepare_v2()] and its
2897 ** variants, literals may be replace by a parameter in one
2898 ** of these forms:
2899 **
2900 ** <ul>
2901 ** <li>  ?
2902 ** <li>  ?NNN
2903 ** <li>  :VVV
2904 ** <li>  @VVV
2905 ** <li>  $VVV
2906 ** </ul>
2907 **
2908 ** In the parameter forms shown above NNN is an integer literal,
2909 ** VVV alpha-numeric parameter name.
2910 ** The values of these parameters (also called "host parameter names"
2911 ** or "SQL parameters")
2912 ** can be set using the sqlite3_bind_*() routines defined here.
2913 **
2914 ** The first argument to the sqlite3_bind_*() routines always
2915 ** is a pointer to the [sqlite3_stmt] object returned from
2916 ** [sqlite3_prepare_v2()] or its variants. The second
2917 ** argument is the index of the parameter to be set. The
2918 ** first parameter has an index of 1.  When the same named
2919 ** parameter is used more than once, second and subsequent
2920 ** occurrences have the same index as the first occurrence. 
2921 ** The index for named parameters can be looked up using the
2922 ** [sqlite3_bind_parameter_name()] API if desired.  The index
2923 ** for "?NNN" parameters is the value of NNN.
2924 ** The NNN value must be between 1 and the compile-time
2925 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999).
2926 **
2927 ** The third argument is the value to bind to the parameter.
2928 **
2929 ** In those
2930 ** routines that have a fourth argument, its value is the number of bytes
2931 ** in the parameter.  To be clear: the value is the number of <u>bytes</u>
2932 ** in the value, not the number of characters. 
2933 ** If the fourth parameter is negative, the length of the string is
2934 ** number of bytes up to the first zero terminator.
2935 **
2936 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
2937 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
2938 ** string after SQLite has finished with it. If the fifth argument is
2939 ** the special value [SQLITE_STATIC], then SQLite assumes that the
2940 ** information is in static, unmanaged space and does not need to be freed.
2941 ** If the fifth argument has the value [SQLITE_TRANSIENT], then
2942 ** SQLite makes its own private copy of the data immediately, before
2943 ** the sqlite3_bind_*() routine returns.
2944 **
2945 ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
2946 ** is filled with zeros.  A zeroblob uses a fixed amount of memory
2947 ** (just an integer to hold it size) while it is being processed.
2948 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
2949 ** content is later written using 
2950 ** [sqlite3_blob_open | increment BLOB I/O] routines. A negative
2951 ** value for the zeroblob results in a zero-length BLOB.
2952 **
2953 ** The sqlite3_bind_*() routines must be called after
2954 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
2955 ** before [sqlite3_step()].
2956 ** Bindings are not cleared by the [sqlite3_reset()] routine.
2957 ** Unbound parameters are interpreted as NULL.
2958 **
2959 ** These routines return [SQLITE_OK] on success or an error code if
2960 ** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
2961 ** index is out of range.  [SQLITE_NOMEM] is returned if malloc fails.
2962 ** [SQLITE_MISUSE] might be returned if these routines are called on a
2963 ** virtual machine that is the wrong state or which has already been finalized.
2964 ** Detection of misuse is unreliable.  Applications should not depend
2965 ** on SQLITE_MISUSE returns.  SQLITE_MISUSE is intended to indicate a
2966 ** a logic error in the application.  Future versions of SQLite might
2967 ** panic rather than return SQLITE_MISUSE.
2968 **
2969 ** See also: [sqlite3_bind_parameter_count()],
2970 ** [sqlite3_bind_parameter_name()], and
2971 ** [sqlite3_bind_parameter_index()].
2972 **
2973 ** INVARIANTS:
2974 **
2975 ** {F13506} The [sqlite3_prepare | SQL statement compiler] recognizes
2976 **          tokens of the forms "?", "?NNN", "$VVV", ":VVV", and "@VVV"
2977 **          as SQL parameters, where NNN is any sequence of one or more
2978 **          digits and where VVV is any sequence of one or more 
2979 **          alphanumeric characters or "::" optionally followed by
2980 **          a string containing no spaces and contained within parentheses.
2981 **
2982 ** {F13509} The initial value of an SQL parameter is NULL.
2983 **
2984 ** {F13512} The index of an "?" SQL parameter is one larger than the
2985 **          largest index of SQL parameter to the left, or 1 if
2986 **          the "?" is the leftmost SQL parameter.
2987 **
2988 ** {F13515} The index of an "?NNN" SQL parameter is the integer NNN.
2989 **
2990 ** {F13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is
2991 **          the same as the index of leftmost occurances of the same
2992 **          parameter, or one more than the largest index over all
2993 **          parameters to the left if this is the first occurrance
2994 **          of this parameter, or 1 if this is the leftmost parameter.
2995 **
2996 ** {F13521} The [sqlite3_prepare | SQL statement compiler] fail with
2997 **          an [SQLITE_RANGE] error if the index of an SQL parameter
2998 **          is less than 1 or greater than SQLITE_MAX_VARIABLE_NUMBER.
2999 **
3000 ** {F13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)]
3001 **          associate the value V with all SQL parameters having an
3002 **          index of N in the [prepared statement] S.
3003 **
3004 ** {F13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)]
3005 **          override prior calls with the same values of S and N.
3006 **
3007 ** {F13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)]
3008 **          persist across calls to [sqlite3_reset(S)].
3009 **
3010 ** {F13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3011 **          [sqlite3_bind_text(S,N,V,L,D)], or
3012 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L
3013 **          bytes of the blob or string pointed to by V, when L
3014 **          is non-negative.
3015 **
3016 ** {F13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or
3017 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters
3018 **          from V through the first zero character when L is negative.
3019 **
3020 ** {F13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3021 **          [sqlite3_bind_text(S,N,V,L,D)], or
3022 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3023 **          constant [SQLITE_STATIC], SQLite assumes that the value V
3024 **          is held in static unmanaged space that will not change
3025 **          during the lifetime of the binding.
3026 **
3027 ** {F13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3028 **          [sqlite3_bind_text(S,N,V,L,D)], or
3029 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3030 **          constant [SQLITE_TRANSIENT], the routine makes a 
3031 **          private copy of V value before it returns.
3032 **
3033 ** {F13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3034 **          [sqlite3_bind_text(S,N,V,L,D)], or
3035 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to
3036 **          a function, SQLite invokes that function to destroy the
3037 **          V value after it has finished using the V value.
3038 **
3039 ** {F13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound
3040 **          is a blob of L bytes, or a zero-length blob if L is negative.
3041 **
3042 ** {F13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may
3043 **          be either a [protected sqlite3_value] object or an
3044 **          [unprotected sqlite3_value] object.
3045 */
3046 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3047 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3048 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3049 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3050 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3051 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3052 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3053 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3054 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3055
3056 /*
3057 ** CAPI3REF: Number Of SQL Parameters {F13600}
3058 **
3059 ** This routine can be used to find the number of SQL parameters
3060 ** in a prepared statement.  SQL parameters are tokens of the
3061 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3062 ** place-holders for values that are [sqlite3_bind_blob | bound]
3063 ** to the parameters at a later time.
3064 **
3065 ** This routine actually returns the index of the largest parameter.
3066 ** For all forms except ?NNN, this will correspond to the number of
3067 ** unique parameters.  If parameters of the ?NNN are used, there may
3068 ** be gaps in the list.
3069 **
3070 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3071 ** [sqlite3_bind_parameter_name()], and
3072 ** [sqlite3_bind_parameter_index()].
3073 **
3074 ** INVARIANTS:
3075 **
3076 ** {F13601} The [sqlite3_bind_parameter_count(S)] interface returns
3077 **          the largest index of all SQL parameters in the
3078 **          [prepared statement] S, or 0 if S
3079 **          contains no SQL parameters.
3080 */
3081 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3082
3083 /*
3084 ** CAPI3REF: Name Of A Host Parameter {F13620}
3085 **
3086 ** This routine returns a pointer to the name of the n-th
3087 ** SQL parameter in a [prepared statement].
3088 ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3089 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3090 ** respectively.
3091 ** In other words, the initial ":" or "$" or "@" or "?"
3092 ** is included as part of the name.
3093 ** Parameters of the form "?" without a following integer have no name.
3094 **
3095 ** The first host parameter has an index of 1, not 0.
3096 **
3097 ** If the value n is out of range or if the n-th parameter is
3098 ** nameless, then NULL is returned.  The returned string is
3099 ** always in the UTF-8 encoding even if the named parameter was
3100 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3101 ** [sqlite3_prepare16_v2()].
3102 **
3103 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3104 ** [sqlite3_bind_parameter_count()], and
3105 ** [sqlite3_bind_parameter_index()].
3106 **
3107 ** INVARIANTS:
3108 **
3109 ** {F13621} The [sqlite3_bind_parameter_name(S,N)] interface returns
3110 **          a UTF-8 rendering of the name of the SQL parameter in
3111 **          [prepared statement] S having index N, or
3112 **          NULL if there is no SQL parameter with index N or if the
3113 **          parameter with index N is an anonymous parameter "?".
3114 */
3115 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3116
3117 /*
3118 ** CAPI3REF: Index Of A Parameter With A Given Name {F13640}
3119 **
3120 ** Return the index of an SQL parameter given its name.  The
3121 ** index value returned is suitable for use as the second
3122 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  A zero
3123 ** is returned if no matching parameter is found.  The parameter
3124 ** name must be given in UTF-8 even if the original statement
3125 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3126 **
3127 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3128 ** [sqlite3_bind_parameter_count()], and
3129 ** [sqlite3_bind_parameter_index()].
3130 **
3131 ** INVARIANTS:
3132 **
3133 ** {F13641} The [sqlite3_bind_parameter_index(S,N)] interface returns
3134 **          the index of SQL parameter in [prepared statement]
3135 **          S whose name matches the UTF-8 string N, or 0 if there is
3136 **          no match.
3137 */
3138 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3139
3140 /*
3141 ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660}
3142 **
3143 ** Contrary to the intuition of many, [sqlite3_reset()] does not
3144 ** reset the [sqlite3_bind_blob | bindings] on a 
3145 ** [prepared statement].  Use this routine to
3146 ** reset all host parameters to NULL.
3147 **
3148 ** INVARIANTS:
3149 **
3150 ** {F13661} The [sqlite3_clear_bindings(S)] interface resets all
3151 **          SQL parameter bindings in [prepared statement] S
3152 **          back to NULL.
3153 */
3154 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3155
3156 /*
3157 ** CAPI3REF: Number Of Columns In A Result Set {F13710}
3158 **
3159 ** Return the number of columns in the result set returned by the 
3160 ** [prepared statement]. This routine returns 0
3161 ** if pStmt is an SQL statement that does not return data (for 
3162 ** example an UPDATE).
3163 **
3164 ** INVARIANTS:
3165 **
3166 ** {F13711} The [sqlite3_column_count(S)] interface returns the number of
3167 **          columns in the result set generated by the
3168 **          [prepared statement] S, or 0 if S does not generate
3169 **          a result set.
3170 */
3171 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3172
3173 /*
3174 ** CAPI3REF: Column Names In A Result Set {F13720}
3175 **
3176 ** These routines return the name assigned to a particular column
3177 ** in the result set of a SELECT statement.  The sqlite3_column_name()
3178 ** interface returns a pointer to a zero-terminated UTF8 string
3179 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3180 ** UTF16 string.  The first parameter is the
3181 ** [prepared statement] that implements the SELECT statement.
3182 ** The second parameter is the column number.  The left-most column is
3183 ** number 0.
3184 **
3185 ** The returned string pointer is valid until either the 
3186 ** [prepared statement] is destroyed by [sqlite3_finalize()]
3187 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
3188 ** on the same column.
3189 **
3190 ** If sqlite3_malloc() fails during the processing of either routine
3191 ** (for example during a conversion from UTF-8 to UTF-16) then a
3192 ** NULL pointer is returned.
3193 **
3194 ** The name of a result column is the value of the "AS" clause for
3195 ** that column, if there is an AS clause.  If there is no AS clause
3196 ** then the name of the column is unspecified and may change from
3197 ** one release of SQLite to the next.
3198 **
3199 ** INVARIANTS:
3200 **
3201 ** {F13721} A successful invocation of the [sqlite3_column_name(S,N)]
3202 **          interface returns the name
3203 **          of the Nth column (where 0 is the left-most column) for the
3204 **          result set of [prepared statement] S as a
3205 **          zero-terminated UTF-8 string.
3206 **
3207 ** {F13723} A successful invocation of the [sqlite3_column_name16(S,N)]
3208 **          interface returns the name
3209 **          of the Nth column (where 0 is the left-most column) for the
3210 **          result set of [prepared statement] S as a
3211 **          zero-terminated UTF-16 string in the native byte order.
3212 **
3213 ** {F13724} The [sqlite3_column_name()] and [sqlite3_column_name16()]
3214 **          interfaces return a NULL pointer if they are unable to
3215 **          allocate memory memory to hold there normal return strings.
3216 **
3217 ** {F13725} If the N parameter to [sqlite3_column_name(S,N)] or
3218 **          [sqlite3_column_name16(S,N)] is out of range, then the
3219 **          interfaces returns a NULL pointer.
3220 ** 
3221 ** {F13726} The strings returned by [sqlite3_column_name(S,N)] and
3222 **          [sqlite3_column_name16(S,N)] are valid until the next
3223 **          call to either routine with the same S and N parameters
3224 **          or until [sqlite3_finalize(S)] is called.
3225 **
3226 ** {F13727} When a result column of a [SELECT] statement contains
3227 **          an AS clause, the name of that column is the indentifier
3228 **          to the right of the AS keyword.
3229 */
3230 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3231 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3232
3233 /*
3234 ** CAPI3REF: Source Of Data In A Query Result {F13740}
3235 **
3236 ** These routines provide a means to determine what column of what
3237 ** table in which database a result of a SELECT statement comes from.
3238 ** The name of the database or table or column can be returned as
3239 ** either a UTF8 or UTF16 string.  The _database_ routines return
3240 ** the database name, the _table_ routines return the table name, and
3241 ** the origin_ routines return the column name.
3242 ** The returned string is valid until
3243 ** the [prepared statement] is destroyed using
3244 ** [sqlite3_finalize()] or until the same information is requested
3245 ** again in a different encoding.
3246 **
3247 ** The names returned are the original un-aliased names of the
3248 ** database, table, and column.
3249 **
3250 ** The first argument to the following calls is a [prepared statement].
3251 ** These functions return information about the Nth column returned by 
3252 ** the statement, where N is the second function argument.
3253 **
3254 ** If the Nth column returned by the statement is an expression
3255 ** or subquery and is not a column value, then all of these functions
3256 ** return NULL.  These routine might also return NULL if a memory
3257 ** allocation error occurs.  Otherwise, they return the 
3258 ** name of the attached database, table and column that query result
3259 ** column was extracted from.
3260 **
3261 ** As with all other SQLite APIs, those postfixed with "16" return
3262 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
3263 **
3264 ** These APIs are only available if the library was compiled with the 
3265 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
3266 **
3267 ** {U13751}
3268 ** If two or more threads call one or more of these routines against the same
3269 ** prepared statement and column at the same time then the results are
3270 ** undefined.
3271 **
3272 ** INVARIANTS:
3273 **
3274 ** {F13741} The [sqlite3_column_database_name(S,N)] interface returns either
3275 **          the UTF-8 zero-terminated name of the database from which the 
3276 **          Nth result column of [prepared statement] S 
3277 **          is extracted, or NULL if the the Nth column of S is a
3278 **          general expression or if unable to allocate memory
3279 **          to store the name.
3280 **          
3281 ** {F13742} The [sqlite3_column_database_name16(S,N)] interface returns either
3282 **          the UTF-16 native byte order
3283 **          zero-terminated name of the database from which the 
3284 **          Nth result column of [prepared statement] S 
3285 **          is extracted, or NULL if the the Nth column of S is a
3286 **          general expression or if unable to allocate memory
3287 **          to store the name.
3288 **          
3289 ** {F13743} The [sqlite3_column_table_name(S,N)] interface returns either
3290 **          the UTF-8 zero-terminated name of the table from which the 
3291 **          Nth result column of [prepared statement] S 
3292 **          is extracted, or NULL if the the Nth column of S is a
3293 **          general expression or if unable to allocate memory
3294 **          to store the name.
3295 **          
3296 ** {F13744} The [sqlite3_column_table_name16(S,N)] interface returns either
3297 **          the UTF-16 native byte order
3298 **          zero-terminated name of the table from which the 
3299 **          Nth result column of [prepared statement] S 
3300 **          is extracted, or NULL if the the Nth column of S is a
3301 **          general expression or if unable to allocate memory
3302 **          to store the name.
3303 **          
3304 ** {F13745} The [sqlite3_column_origin_name(S,N)] interface returns either
3305 **          the UTF-8 zero-terminated name of the table column from which the 
3306 **          Nth result column of [prepared statement] S 
3307 **          is extracted, or NULL if the the Nth column of S is a
3308 **          general expression or if unable to allocate memory
3309 **          to store the name.
3310 **          
3311 ** {F13746} The [sqlite3_column_origin_name16(S,N)] interface returns either
3312 **          the UTF-16 native byte order
3313 **          zero-terminated name of the table column from which the 
3314 **          Nth result column of [prepared statement] S 
3315 **          is extracted, or NULL if the the Nth column of S is a
3316 **          general expression or if unable to allocate memory
3317 **          to store the name.
3318 **          
3319 ** {F13748} The return values from
3320 **          [sqlite3_column_database_name|column metadata interfaces]
3321 **          are valid
3322 **          for the lifetime of the [prepared statement]
3323 **          or until the encoding is changed by another metadata
3324 **          interface call for the same prepared statement and column.
3325 **
3326 ** LIMITATIONS:
3327 **
3328 ** {U13751} If two or more threads call one or more
3329 **          [sqlite3_column_database_name|column metadata interfaces]
3330 **          the same [prepared statement] and result column
3331 **          at the same time then the results are undefined.
3332 */
3333 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3334 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3335 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3336 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3337 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3338 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3339
3340 /*
3341 ** CAPI3REF: Declared Datatype Of A Query Result {F13760}
3342 **
3343 ** The first parameter is a [prepared statement]. 
3344 ** If this statement is a SELECT statement and the Nth column of the 
3345 ** returned result set of that SELECT is a table column (not an
3346 ** expression or subquery) then the declared type of the table
3347 ** column is returned.  If the Nth column of the result set is an
3348 ** expression or subquery, then a NULL pointer is returned.
3349 ** The returned string is always UTF-8 encoded.  {END} 
3350 ** For example, in the database schema:
3351 **
3352 ** CREATE TABLE t1(c1 VARIANT);
3353 **
3354 ** And the following statement compiled:
3355 **
3356 ** SELECT c1 + 1, c1 FROM t1;
3357 **
3358 ** Then this routine would return the string "VARIANT" for the second
3359 ** result column (i==1), and a NULL pointer for the first result column
3360 ** (i==0).
3361 **
3362 ** SQLite uses dynamic run-time typing.  So just because a column
3363 ** is declared to contain a particular type does not mean that the
3364 ** data stored in that column is of the declared type.  SQLite is
3365 ** strongly typed, but the typing is dynamic not static.  Type
3366 ** is associated with individual values, not with the containers
3367 ** used to hold those values.
3368 **
3369 ** INVARIANTS:
3370 **
3371 ** {F13761}  A successful call to [sqlite3_column_decltype(S,N)]
3372 **           returns a zero-terminated UTF-8 string containing the
3373 **           the declared datatype of the table column that appears
3374 **           as the Nth column (numbered from 0) of the result set to the
3375 **           [prepared statement] S.
3376 **
3377 ** {F13762}  A successful call to [sqlite3_column_decltype16(S,N)]
3378 **           returns a zero-terminated UTF-16 native byte order string
3379 **           containing the declared datatype of the table column that appears
3380 **           as the Nth column (numbered from 0) of the result set to the
3381 **           [prepared statement] S.
3382 **
3383 ** {F13763}  If N is less than 0 or N is greater than or equal to
3384 **           the number of columns in [prepared statement] S
3385 **           or if the Nth column of S is an expression or subquery rather
3386 **           than a table column or if a memory allocation failure
3387 **           occurs during encoding conversions, then
3388 **           calls to [sqlite3_column_decltype(S,N)] or
3389 **           [sqlite3_column_decltype16(S,N)] return NULL.
3390 */
3391 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3392 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3393
3394 /* 
3395 ** CAPI3REF:  Evaluate An SQL Statement {F13200}
3396 **
3397 ** After an [prepared statement] has been prepared with a call
3398 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
3399 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
3400 ** then this function must be called one or more times to evaluate the 
3401 ** statement.
3402 **
3403 ** The details of the behavior of this sqlite3_step() interface depend
3404 ** on whether the statement was prepared using the newer "v2" interface
3405 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3406 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3407 ** new "v2" interface is recommended for new applications but the legacy
3408 ** interface will continue to be supported.
3409 **
3410 ** In the legacy interface, the return value will be either [SQLITE_BUSY], 
3411 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3412 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
3413 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
3414 ** well.
3415 **
3416 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
3417 ** database locks it needs to do its job.  If the statement is a COMMIT
3418 ** or occurs outside of an explicit transaction, then you can retry the
3419 ** statement.  If the statement is not a COMMIT and occurs within a
3420 ** explicit transaction then you should rollback the transaction before
3421 ** continuing.
3422 **
3423 ** [SQLITE_DONE] means that the statement has finished executing
3424 ** successfully.  sqlite3_step() should not be called again on this virtual
3425 ** machine without first calling [sqlite3_reset()] to reset the virtual
3426 ** machine back to its initial state.
3427 **
3428 ** If the SQL statement being executed returns any data, then 
3429 ** [SQLITE_ROW] is returned each time a new row of data is ready
3430 ** for processing by the caller. The values may be accessed using
3431 ** the [sqlite3_column_int | column access functions].
3432 ** sqlite3_step() is called again to retrieve the next row of data.
3433 ** 
3434 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
3435 ** violation) has occurred.  sqlite3_step() should not be called again on
3436 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3437 ** With the legacy interface, a more specific error code (example:
3438 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3439 ** can be obtained by calling [sqlite3_reset()] on the
3440 ** [prepared statement].  In the "v2" interface,
3441 ** the more specific error code is returned directly by sqlite3_step().
3442 **
3443 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3444 ** Perhaps it was called on a [prepared statement] that has
3445 ** already been [sqlite3_finalize | finalized] or on one that had 
3446 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3447 ** be the case that the same database connection is being used by two or
3448 ** more threads at the same moment in time.
3449 **
3450 ** <b>Goofy Interface Alert:</b>
3451 ** In the legacy interface, 
3452 ** the sqlite3_step() API always returns a generic error code,
3453 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
3454 ** and [SQLITE_MISUSE].  You must call [sqlite3_reset()] or
3455 ** [sqlite3_finalize()] in order to find one of the specific
3456 ** [error codes] that better describes the error.
3457 ** We admit that this is a goofy design.  The problem has been fixed
3458 ** with the "v2" interface.  If you prepare all of your SQL statements
3459 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3460 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
3461 ** more specific [error codes] are returned directly
3462 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3463 **
3464 ** INVARIANTS:
3465 **
3466 ** {F13202}  If [prepared statement] S is ready to be
3467 **           run, then [sqlite3_step(S)] advances that prepared statement
3468 **           until to completion or until it is ready to return another
3469 **           row of the result set or an interrupt or run-time error occurs.
3470 **
3471 ** {F15304}  When a call to [sqlite3_step(S)] causes the 
3472 **           [prepared statement] S to run to completion,
3473 **           the function returns [SQLITE_DONE].
3474 **
3475 ** {F15306}  When a call to [sqlite3_step(S)] stops because it is ready
3476 **           to return another row of the result set, it returns
3477 **           [SQLITE_ROW].
3478 **
3479 ** {F15308}  If a call to [sqlite3_step(S)] encounters an
3480 **           [sqlite3_interrupt|interrupt] or a run-time error,
3481 **           it returns an appropraite error code that is not one of
3482 **           [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE].
3483 **
3484 ** {F15310}  If an [sqlite3_interrupt|interrupt] or run-time error
3485 **           occurs during a call to [sqlite3_step(S)]
3486 **           for a [prepared statement] S created using
3487 **           legacy interfaces [sqlite3_prepare()] or
3488 **           [sqlite3_prepare16()] then the function returns either
3489 **           [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE].
3490 */
3491 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3492
3493 /*
3494 ** CAPI3REF: Number of columns in a result set {F13770}
3495 **
3496 ** Return the number of values in the current row of the result set.
3497 **
3498 ** INVARIANTS:
3499 **
3500 ** {F13771}  After a call to [sqlite3_step(S)] that returns
3501 **           [SQLITE_ROW], the [sqlite3_data_count(S)] routine
3502 **           will return the same value as the
3503 **           [sqlite3_column_count(S)] function.
3504 **
3505 ** {F13772}  After [sqlite3_step(S)] has returned any value other than
3506 **           [SQLITE_ROW] or before [sqlite3_step(S)] has been 
3507 **           called on the [prepared statement] for
3508 **           the first time since it was [sqlite3_prepare|prepared]
3509 **           or [sqlite3_reset|reset], the [sqlite3_data_count(S)]
3510 **           routine returns zero.
3511 */
3512 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3513
3514 /*
3515 ** CAPI3REF: Fundamental Datatypes {F10265}
3516 ** KEYWORDS: SQLITE_TEXT
3517 **
3518 ** {F10266}Every value in SQLite has one of five fundamental datatypes:
3519 **
3520 ** <ul>
3521 ** <li> 64-bit signed integer
3522 ** <li> 64-bit IEEE floating point number
3523 ** <li> string
3524 ** <li> BLOB
3525 ** <li> NULL
3526 ** </ul> {END}
3527 **
3528 ** These constants are codes for each of those types.
3529 **
3530 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3531 ** for a completely different meaning.  Software that links against both
3532 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
3533 ** SQLITE_TEXT.
3534 */
3535 #define SQLITE_INTEGER  1
3536 #define SQLITE_FLOAT    2
3537 #define SQLITE_BLOB     4
3538 #define SQLITE_NULL     5
3539 #ifdef SQLITE_TEXT
3540 # undef SQLITE_TEXT
3541 #else
3542 # define SQLITE_TEXT     3
3543 #endif
3544 #define SQLITE3_TEXT     3
3545
3546 /*
3547 ** CAPI3REF: Results Values From A Query {F13800}
3548 **
3549 ** These routines form the "result set query" interface.
3550 **
3551 ** These routines return information about
3552 ** a single column of the current result row of a query.  In every
3553 ** case the first argument is a pointer to the 
3554 ** [prepared statement] that is being
3555 ** evaluated (the [sqlite3_stmt*] that was returned from 
3556 ** [sqlite3_prepare_v2()] or one of its variants) and
3557 ** the second argument is the index of the column for which information 
3558 ** should be returned.  The left-most column of the result set
3559 ** has an index of 0.
3560 **
3561 ** If the SQL statement is not currently point to a valid row, or if the
3562 ** the column index is out of range, the result is undefined. 
3563 ** These routines may only be called when the most recent call to
3564 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3565 ** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently.
3566 ** If any of these routines are called after [sqlite3_reset()] or
3567 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3568 ** something other than [SQLITE_ROW], the results are undefined.
3569 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3570 ** are called from a different thread while any of these routines
3571 ** are pending, then the results are undefined.  
3572 **
3573 ** The sqlite3_column_type() routine returns 
3574 ** [SQLITE_INTEGER | datatype code] for the initial data type
3575 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
3576 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3577 ** returned by sqlite3_column_type() is only meaningful if no type
3578 ** conversions have occurred as described below.  After a type conversion,
3579 ** the value returned by sqlite3_column_type() is undefined.  Future
3580 ** versions of SQLite may change the behavior of sqlite3_column_type()
3581 ** following a type conversion.
3582 **
3583 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
3584 ** routine returns the number of bytes in that BLOB or string.
3585 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3586 ** the string to UTF-8 and then returns the number of bytes.
3587 ** If the result is a numeric value then sqlite3_column_bytes() uses
3588 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3589 ** the number of bytes in that string.
3590 ** The value returned does not include the zero terminator at the end
3591 ** of the string.  For clarity: the value returned is the number of
3592 ** bytes in the string, not the number of characters.
3593 **
3594 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3595 ** even empty strings, are always zero terminated.  The return
3596 ** value from sqlite3_column_blob() for a zero-length blob is an arbitrary
3597 ** pointer, possibly even a NULL pointer.
3598 **
3599 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3600 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.  
3601 ** The zero terminator is not included in this count.
3602 **
3603 ** The object returned by [sqlite3_column_value()] is an
3604 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3605 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3606 ** If the [unprotected sqlite3_value] object returned by
3607 ** [sqlite3_column_value()] is used in any other way, including calls
3608 ** to routines like 
3609 ** [sqlite3_value_int()], [sqlite3_value_text()], or [sqlite3_value_bytes()],
3610 ** then the behavior is undefined.
3611 **
3612 ** These routines attempt to convert the value where appropriate.  For
3613 ** example, if the internal representation is FLOAT and a text result
3614 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
3615 ** automatically.  The following table details the conversions that
3616 ** are applied:
3617 **
3618 ** <blockquote>
3619 ** <table border="1">
3620 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3621 **
3622 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3623 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3624 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3625 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3626 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3627 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3628 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as for INTEGER->TEXT
3629 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3630 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3631 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3632 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3633 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3634 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3635 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3636 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3637 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3638 ** </table>
3639 ** </blockquote>
3640 **
3641 ** The table above makes reference to standard C library functions atoi()
3642 ** and atof().  SQLite does not really use these functions.  It has its
3643 ** on equavalent internal routines.  The atoi() and atof() names are
3644 ** used in the table for brevity and because they are familiar to most
3645 ** C programmers.
3646 **
3647 ** Note that when type conversions occur, pointers returned by prior
3648 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3649 ** sqlite3_column_text16() may be invalidated. 
3650 ** Type conversions and pointer invalidations might occur
3651 ** in the following cases:
3652 **
3653 ** <ul>
3654 ** <li><p>  The initial content is a BLOB and sqlite3_column_text() 
3655 **          or sqlite3_column_text16() is called.  A zero-terminator might
3656 **          need to be added to the string.</p></li>
3657 **
3658 ** <li><p>  The initial content is UTF-8 text and sqlite3_column_bytes16() or
3659 **          sqlite3_column_text16() is called.  The content must be converted
3660 **          to UTF-16.</p></li>
3661 **
3662 ** <li><p>  The initial content is UTF-16 text and sqlite3_column_bytes() or
3663 **          sqlite3_column_text() is called.  The content must be converted
3664 **          to UTF-8.</p></li>
3665 ** </ul>
3666 **
3667 ** Conversions between UTF-16be and UTF-16le are always done in place and do
3668 ** not invalidate a prior pointer, though of course the content of the buffer
3669 ** that the prior pointer points to will have been modified.  Other kinds
3670 ** of conversion are done in place when it is possible, but sometime it is
3671 ** not possible and in those cases prior pointers are invalidated.  
3672 **
3673 ** The safest and easiest to remember policy is to invoke these routines
3674 ** in one of the following ways:
3675 **
3676 **  <ul>
3677 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3678 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3679 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3680 **  </ul>
3681 **
3682 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
3683 ** or sqlite3_column_text16() first to force the result into the desired
3684 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
3685 ** find the size of the result.  Do not mix call to sqlite3_column_text() or
3686 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16().  And do not
3687 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
3688 **
3689 ** The pointers returned are valid until a type conversion occurs as
3690 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3691 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
3692 ** and blobs is freed automatically.  Do <b>not</b> pass the pointers returned
3693 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into 
3694 ** [sqlite3_free()].
3695 **
3696 ** If a memory allocation error occurs during the evaluation of any
3697 ** of these routines, a default value is returned.  The default value
3698 ** is either the integer 0, the floating point number 0.0, or a NULL
3699 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3700 ** [SQLITE_NOMEM].
3701 **
3702 ** INVARIANTS:
3703 **
3704 ** {F13803} The [sqlite3_column_blob(S,N)] interface converts the
3705 **          Nth column in the current row of the result set for
3706 **          [prepared statement] S into a blob and then returns a
3707 **          pointer to the converted value.
3708 **
3709 ** {F13806} The [sqlite3_column_bytes(S,N)] interface returns the
3710 **          number of bytes in the blob or string (exclusive of the
3711 **          zero terminator on the string) that was returned by the
3712 **          most recent call to [sqlite3_column_blob(S,N)] or
3713 **          [sqlite3_column_text(S,N)].
3714 **
3715 ** {F13809} The [sqlite3_column_bytes16(S,N)] interface returns the
3716 **          number of bytes in the string (exclusive of the
3717 **          zero terminator on the string) that was returned by the
3718 **          most recent call to [sqlite3_column_text16(S,N)].
3719 **
3720 ** {F13812} The [sqlite3_column_double(S,N)] interface converts the
3721 **          Nth column in the current row of the result set for
3722 **          [prepared statement] S into a floating point value and
3723 **          returns a copy of that value.
3724 **
3725 ** {F13815} The [sqlite3_column_int(S,N)] interface converts the
3726 **          Nth column in the current row of the result set for
3727 **          [prepared statement] S into a 64-bit signed integer and
3728 **          returns the lower 32 bits of that integer.
3729 **
3730 ** {F13818} The [sqlite3_column_int64(S,N)] interface converts the
3731 **          Nth column in the current row of the result set for
3732 **          [prepared statement] S into a 64-bit signed integer and
3733 **          returns a copy of that integer.
3734 **
3735 ** {F13821} The [sqlite3_column_text(S,N)] interface converts the
3736 **          Nth column in the current row of the result set for
3737 **          [prepared statement] S into a zero-terminated UTF-8 
3738 **          string and returns a pointer to that string.
3739 **
3740 ** {F13824} The [sqlite3_column_text16(S,N)] interface converts the
3741 **          Nth column in the current row of the result set for
3742 **          [prepared statement] S into a zero-terminated 2-byte
3743 **          aligned UTF-16 native byte order
3744 **          string and returns a pointer to that string.
3745 **
3746 ** {F13827} The [sqlite3_column_type(S,N)] interface returns
3747 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
3748 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
3749 **          the Nth column in the current row of the result set for
3750 **          [prepared statement] S.
3751 **
3752 ** {F13830} The [sqlite3_column_value(S,N)] interface returns a
3753 **          pointer to an [unprotected sqlite3_value] object for the
3754 **          Nth column in the current row of the result set for
3755 **          [prepared statement] S.
3756 */
3757 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3758 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3759 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3760 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3761 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3762 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3763 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3764 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3765 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3766 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3767
3768 /*
3769 ** CAPI3REF: Destroy A Prepared Statement Object {F13300}
3770 **
3771 ** The sqlite3_finalize() function is called to delete a 
3772 ** [prepared statement]. If the statement was
3773 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
3774 ** If execution of the statement failed then an 
3775 ** [error code] or [extended error code]
3776 ** is returned. 
3777 **
3778 ** This routine can be called at any point during the execution of the
3779 ** [prepared statement].  If the virtual machine has not 
3780 ** completed execution when this routine is called, that is like
3781 ** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
3782 ** Incomplete updates may be rolled back and transactions cancelled,  
3783 ** depending on the circumstances, and the 
3784 ** [error code] returned will be [SQLITE_ABORT].
3785 **
3786 ** INVARIANTS:
3787 **
3788 ** {F11302} The [sqlite3_finalize(S)] interface destroys the
3789 **          [prepared statement] S and releases all
3790 **          memory and file resources held by that object.
3791 **
3792 ** {F11304} If the most recent call to [sqlite3_step(S)] for the
3793 **          [prepared statement] S returned an error,
3794 **          then [sqlite3_finalize(S)] returns that same error.
3795 */
3796 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3797
3798 /*
3799 ** CAPI3REF: Reset A Prepared Statement Object {F13330}
3800 **
3801 ** The sqlite3_reset() function is called to reset a 
3802 ** [prepared statement] object.
3803 ** back to its initial state, ready to be re-executed.
3804 ** Any SQL statement variables that had values bound to them using
3805 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3806 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3807 **
3808 ** {F11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
3809 **          back to the beginning of its program.
3810 **
3811 ** {F11334} If the most recent call to [sqlite3_step(S)] for 
3812 **          [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3813 **          or if [sqlite3_step(S)] has never before been called on S,
3814 **          then [sqlite3_reset(S)] returns [SQLITE_OK].
3815 **
3816 ** {F11336} If the most recent call to [sqlite3_step(S)] for
3817 **          [prepared statement] S indicated an error, then
3818 **          [sqlite3_reset(S)] returns an appropriate [error code].
3819 **
3820 ** {F11338} The [sqlite3_reset(S)] interface does not change the values
3821 **          of any [sqlite3_bind_blob|bindings] on [prepared statement] S.
3822 */
3823 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3824
3825 /*
3826 ** CAPI3REF: Create Or Redefine SQL Functions {F16100}
3827 ** KEYWORDS: {function creation routines} 
3828 **
3829 ** These two functions (collectively known as
3830 ** "function creation routines") are used to add SQL functions or aggregates
3831 ** or to redefine the behavior of existing SQL functions or aggregates.  The
3832 ** difference only between the two is that the second parameter, the
3833 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
3834 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
3835 **
3836 ** The first parameter is the [database connection] to which the SQL
3837 ** function is to be added.  If a single
3838 ** program uses more than one [database connection] internally, then SQL
3839 ** functions must be added individually to each [database connection].
3840 **
3841 ** The second parameter is the name of the SQL function to be created
3842 ** or redefined.
3843 ** The length of the name is limited to 255 bytes, exclusive of the 
3844 ** zero-terminator.  Note that the name length limit is in bytes, not
3845 ** characters.  Any attempt to create a function with a longer name
3846 ** will result in an SQLITE_ERROR error.
3847 **
3848 ** The third parameter is the number of arguments that the SQL function or
3849 ** aggregate takes. If this parameter is negative, then the SQL function or
3850 ** aggregate may take any number of arguments.
3851 **
3852 ** The fourth parameter, eTextRep, specifies what 
3853 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3854 ** its parameters.  Any SQL function implementation should be able to work
3855 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3856 ** more efficient with one encoding than another.  It is allowed to
3857 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3858 ** times with the same function but with different values of eTextRep.
3859 ** When multiple implementations of the same function are available, SQLite
3860 ** will pick the one that involves the least amount of data conversion.
3861 ** If there is only a single implementation which does not care what
3862 ** text encoding is used, then the fourth argument should be
3863 ** [SQLITE_ANY].
3864 **
3865 ** The fifth parameter is an arbitrary pointer.  The implementation
3866 ** of the function can gain access to this pointer using
3867 ** [sqlite3_user_data()].
3868 **
3869 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3870 ** pointers to C-language functions that implement the SQL
3871 ** function or aggregate. A scalar SQL function requires an implementation of
3872 ** the xFunc callback only, NULL pointers should be passed as the xStep
3873 ** and xFinal parameters. An aggregate SQL function requires an implementation
3874 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
3875 ** existing SQL function or aggregate, pass NULL for all three function
3876 ** callback.
3877 **
3878 ** It is permitted to register multiple implementations of the same
3879 ** functions with the same name but with either differing numbers of
3880 ** arguments or differing perferred text encodings.  SQLite will use
3881 ** the implementation most closely matches the way in which the
3882 ** SQL function is used.
3883 **
3884 ** INVARIANTS:
3885 **
3886 ** {F16103} The [sqlite3_create_function16()] interface behaves exactly
3887 **          like [sqlite3_create_function()] in every way except that it
3888 **          interprets the zFunctionName argument as
3889 **          zero-terminated UTF-16 native byte order instead of as a
3890 **          zero-terminated UTF-8.
3891 **
3892 ** {F16106} A successful invocation of
3893 **          the [sqlite3_create_function(D,X,N,E,...)] interface registers
3894 **          or replaces callback functions in [database connection] D
3895 **          used to implement the SQL function named X with N parameters
3896 **          and having a perferred text encoding of E.
3897 **
3898 ** {F16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)]
3899 **          replaces the P, F, S, and L values from any prior calls with
3900 **          the same D, X, N, and E values.
3901 **
3902 ** {F16112} The [sqlite3_create_function(D,X,...)] interface fails with
3903 **          a return code of [SQLITE_ERROR] if the SQL function name X is
3904 **          longer than 255 bytes exclusive of the zero terminator.
3905 **
3906 ** {F16118} Either F must be NULL and S and L are non-NULL or else F
3907 **          is non-NULL and S and L are NULL, otherwise
3908 **          [sqlite3_create_function(D,X,N,E,P,F,S,L)] returns [SQLITE_ERROR].
3909 **
3910 ** {F16121} The [sqlite3_create_function(D,...)] interface fails with an
3911 **          error code of [SQLITE_BUSY] if there exist [prepared statements]
3912 **          associated with the [database connection] D.
3913 **
3914 ** {F16124} The [sqlite3_create_function(D,X,N,...)] interface fails with an
3915 **          error code of [SQLITE_ERROR] if parameter N (specifying the number
3916 **          of arguments to the SQL function being registered) is less
3917 **          than -1 or greater than 127.
3918 **
3919 ** {F16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)]
3920 **          interface causes callbacks to be invoked for the SQL function
3921 **          named X when the number of arguments to the SQL function is
3922 **          exactly N.
3923 **
3924 ** {F16130} When N is -1, the [sqlite3_create_function(D,X,N,...)]
3925 **          interface causes callbacks to be invoked for the SQL function
3926 **          named X with any number of arguments.
3927 **
3928 ** {F16133} When calls to [sqlite3_create_function(D,X,N,...)]
3929 **          specify multiple implementations of the same function X
3930 **          and when one implementation has N>=0 and the other has N=(-1)
3931 **          the implementation with a non-zero N is preferred.
3932 **
3933 ** {F16136} When calls to [sqlite3_create_function(D,X,N,E,...)]
3934 **          specify multiple implementations of the same function X with
3935 **          the same number of arguments N but with different
3936 **          encodings E, then the implementation where E matches the
3937 **          database encoding is preferred.
3938 **
3939 ** {F16139} For an aggregate SQL function created using
3940 **          [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finializer
3941 **          function L will always be invoked exactly once if the
3942 **          step function S is called one or more times.
3943 **
3944 ** {F16142} When SQLite invokes either the xFunc or xStep function of
3945 **          an application-defined SQL function or aggregate created
3946 **          by [sqlite3_create_function()] or [sqlite3_create_function16()],
3947 **          then the array of [sqlite3_value] objects passed as the
3948 **          third parameter are always [protected sqlite3_value] objects.
3949 */
3950 SQLITE_API int sqlite3_create_function(
3951   sqlite3 *db,
3952   const char *zFunctionName,
3953   int nArg,
3954   int eTextRep,
3955   void *pApp,
3956   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3957   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3958   void (*xFinal)(sqlite3_context*)
3959 );
3960 SQLITE_API int sqlite3_create_function16(
3961   sqlite3 *db,
3962   const void *zFunctionName,
3963   int nArg,
3964   int eTextRep,
3965   void *pApp,
3966   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3967   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3968   void (*xFinal)(sqlite3_context*)
3969 );
3970
3971 /*
3972 ** CAPI3REF: Text Encodings {F10267}
3973 **
3974 ** These constant define integer codes that represent the various
3975 ** text encodings supported by SQLite.
3976 */
3977 #define SQLITE_UTF8           1
3978 #define SQLITE_UTF16LE        2
3979 #define SQLITE_UTF16BE        3
3980 #define SQLITE_UTF16          4    /* Use native byte order */
3981 #define SQLITE_ANY            5    /* sqlite3_create_function only */
3982 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3983
3984 /*
3985 ** CAPI3REF: Obsolete Functions
3986 **
3987 ** These functions are all now obsolete.  In order to maintain
3988 ** backwards compatibility with older code, we continue to support
3989 ** these functions.  However, new development projects should avoid
3990 ** the use of these functions.  To help encourage people to avoid
3991 ** using these functions, we are not going to tell you want they do.
3992 */
3993 SQLITE_API int sqlite3_aggregate_count(sqlite3_context*);
3994 SQLITE_API int sqlite3_expired(sqlite3_stmt*);
3995 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3996 SQLITE_API int sqlite3_global_recover(void);
3997 SQLITE_API void sqlite3_thread_cleanup(void);
3998 SQLITE_API int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3999
4000 /*
4001 ** CAPI3REF: Obtaining SQL Function Parameter Values {F15100}
4002 **
4003 ** The C-language implementation of SQL functions and aggregates uses
4004 ** this set of interface routines to access the parameter values on
4005 ** the function or aggregate.
4006 **
4007 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4008 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4009 ** define callbacks that implement the SQL functions and aggregates.
4010 ** The 4th parameter to these callbacks is an array of pointers to
4011 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4012 ** each parameter to the SQL function.  These routines are used to
4013 ** extract values from the [sqlite3_value] objects.
4014 **
4015 ** These routines work only with [protected sqlite3_value] objects.
4016 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4017 ** object results in undefined behavior.
4018 **
4019 ** These routines work just like the corresponding 
4020 ** [sqlite3_column_blob | sqlite3_column_* routines] except that 
4021 ** these routines take a single [protected sqlite3_value] object pointer
4022 ** instead of an [sqlite3_stmt*] pointer and an integer column number.
4023 **
4024 ** The sqlite3_value_text16() interface extracts a UTF16 string
4025 ** in the native byte-order of the host machine.  The
4026 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4027 ** extract UTF16 strings as big-endian and little-endian respectively.
4028 **
4029 ** The sqlite3_value_numeric_type() interface attempts to apply
4030 ** numeric affinity to the value.  This means that an attempt is
4031 ** made to convert the value to an integer or floating point.  If
4032 ** such a conversion is possible without loss of information (in other
4033 ** words if the value is a string that looks like a number)
4034 ** then the conversion is done.  Otherwise no conversion occurs.  The 
4035 ** [SQLITE_INTEGER | datatype] after conversion is returned.
4036 **
4037 ** Please pay particular attention to the fact that the pointer that
4038 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
4039 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4040 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4041 ** or [sqlite3_value_text16()].  
4042 **
4043 ** These routines must be called from the same thread as
4044 ** the SQL function that supplied the [sqlite3_value*] parameters.
4045 **
4046 **
4047 ** INVARIANTS:
4048 **
4049 ** {F15103} The [sqlite3_value_blob(V)] interface converts the
4050 **          [protected sqlite3_value] object V into a blob and then returns a
4051 **          pointer to the converted value.
4052 **
4053 ** {F15106} The [sqlite3_value_bytes(V)] interface returns the
4054 **          number of bytes in the blob or string (exclusive of the
4055 **          zero terminator on the string) that was returned by the
4056 **          most recent call to [sqlite3_value_blob(V)] or
4057 **          [sqlite3_value_text(V)].
4058 **
4059 ** {F15109} The [sqlite3_value_bytes16(V)] interface returns the
4060 **          number of bytes in the string (exclusive of the
4061 **          zero terminator on the string) that was returned by the
4062 **          most recent call to [sqlite3_value_text16(V)],
4063 **          [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)].
4064 **
4065 ** {F15112} The [sqlite3_value_double(V)] interface converts the
4066 **          [protected sqlite3_value] object V into a floating point value and
4067 **          returns a copy of that value.
4068 **
4069 ** {F15115} The [sqlite3_value_int(V)] interface converts the
4070 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4071 **          returns the lower 32 bits of that integer.
4072 **
4073 ** {F15118} The [sqlite3_value_int64(V)] interface converts the
4074 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4075 **          returns a copy of that integer.
4076 **
4077 ** {F15121} The [sqlite3_value_text(V)] interface converts the
4078 **          [protected sqlite3_value] object V into a zero-terminated UTF-8 
4079 **          string and returns a pointer to that string.
4080 **
4081 ** {F15124} The [sqlite3_value_text16(V)] interface converts the
4082 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4083 **          aligned UTF-16 native byte order
4084 **          string and returns a pointer to that string.
4085 **
4086 ** {F15127} The [sqlite3_value_text16be(V)] interface converts the
4087 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4088 **          aligned UTF-16 big-endian
4089 **          string and returns a pointer to that string.
4090 **
4091 ** {F15130} The [sqlite3_value_text16le(V)] interface converts the
4092 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4093 **          aligned UTF-16 little-endian
4094 **          string and returns a pointer to that string.
4095 **
4096 ** {F15133} The [sqlite3_value_type(V)] interface returns
4097 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4098 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4099 **          the [sqlite3_value] object V.
4100 **
4101 ** {F15136} The [sqlite3_value_numeric_type(V)] interface converts
4102 **          the [protected sqlite3_value] object V into either an integer or
4103 **          a floating point value if it can do so without loss of
4104 **          information, and returns one of [SQLITE_NULL],
4105 **          [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or
4106 **          [SQLITE_BLOB] as appropriate for
4107 **          the [protected sqlite3_value] object V after the conversion attempt.
4108 */
4109 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4110 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4111 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4112 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4113 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4114 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4115 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4116 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4117 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4118 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4119 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4120 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4121
4122 /*
4123 ** CAPI3REF: Obtain Aggregate Function Context {F16210}
4124 **
4125 ** The implementation of aggregate SQL functions use this routine to allocate
4126 ** a structure for storing their state.  
4127 ** The first time the sqlite3_aggregate_context() routine is
4128 ** is called for a particular aggregate, SQLite allocates nBytes of memory
4129 ** zeros that memory, and returns a pointer to it.
4130 ** On second and subsequent calls to sqlite3_aggregate_context()
4131 ** for the same aggregate function index, the same buffer is returned.
4132 ** The implementation
4133 ** of the aggregate can use the returned buffer to accumulate data.
4134 **
4135 ** SQLite automatically frees the allocated buffer when the aggregate
4136 ** query concludes.
4137 **
4138 ** The first parameter should be a copy of the 
4139 ** [sqlite3_context | SQL function context] that is the first
4140 ** parameter to the callback routine that implements the aggregate
4141 ** function.
4142 **
4143 ** This routine must be called from the same thread in which
4144 ** the aggregate SQL function is running.
4145 **
4146 ** INVARIANTS:
4147 **
4148 ** {F16211} The first invocation of [sqlite3_aggregate_context(C,N)] for
4149 **          a particular instance of an aggregate function (for a particular
4150 **          context C) causes SQLite to allocation N bytes of memory,
4151 **          zero that memory, and return a pointer to the allocationed
4152 **          memory.
4153 **
4154 ** {F16213} If a memory allocation error occurs during
4155 **          [sqlite3_aggregate_context(C,N)] then the function returns 0.
4156 **
4157 ** {F16215} Second and subsequent invocations of
4158 **          [sqlite3_aggregate_context(C,N)] for the same context pointer C
4159 **          ignore the N parameter and return a pointer to the same
4160 **          block of memory returned by the first invocation.
4161 **
4162 ** {F16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is
4163 **          automatically freed on the next call to [sqlite3_reset()]
4164 **          or [sqlite3_finalize()] for the [prepared statement] containing
4165 **          the aggregate function associated with context C.
4166 */
4167 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4168
4169 /*
4170 ** CAPI3REF: User Data For Functions {F16240}
4171 **
4172 ** The sqlite3_user_data() interface returns a copy of
4173 ** the pointer that was the pUserData parameter (the 5th parameter)
4174 ** of the the [sqlite3_create_function()]
4175 ** and [sqlite3_create_function16()] routines that originally
4176 ** registered the application defined function. {END}
4177 **
4178 ** This routine must be called from the same thread in which
4179 ** the application-defined function is running.
4180 **
4181 ** INVARIANTS:
4182 **
4183 ** {F16243} The [sqlite3_user_data(C)] interface returns a copy of the
4184 **          P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4185 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4186 **          registered the SQL function associated with 
4187 **          [sqlite3_context] C.
4188 */
4189 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4190
4191 /*
4192 ** CAPI3REF: Database Connection For Functions {F16250}
4193 **
4194 ** The sqlite3_context_db_handle() interface returns a copy of
4195 ** the pointer to the [database connection] (the 1st parameter)
4196 ** of the the [sqlite3_create_function()]
4197 ** and [sqlite3_create_function16()] routines that originally
4198 ** registered the application defined function.
4199 **
4200 ** INVARIANTS:
4201 **
4202 ** {F16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the
4203 **          D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4204 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4205 **          registered the SQL function associated with 
4206 **          [sqlite3_context] C.
4207 */
4208 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4209
4210 /*
4211 ** CAPI3REF: Function Auxiliary Data {F16270}
4212 **
4213 ** The following two functions may be used by scalar SQL functions to
4214 ** associate meta-data with argument values. If the same value is passed to
4215 ** multiple invocations of the same SQL function during query execution, under
4216 ** some circumstances the associated meta-data may be preserved. This may
4217 ** be used, for example, to add a regular-expression matching scalar
4218 ** function. The compiled version of the regular expression is stored as
4219 ** meta-data associated with the SQL value passed as the regular expression
4220 ** pattern.  The compiled regular expression can be reused on multiple
4221 ** invocations of the same function so that the original pattern string
4222 ** does not need to be recompiled on each invocation.
4223 **
4224 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
4225 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4226 ** value to the application-defined function.
4227 ** If no meta-data has been ever been set for the Nth
4228 ** argument of the function, or if the cooresponding function parameter
4229 ** has changed since the meta-data was set, then sqlite3_get_auxdata()
4230 ** returns a NULL pointer.
4231 **
4232 ** The sqlite3_set_auxdata() interface saves the meta-data
4233 ** pointed to by its 3rd parameter as the meta-data for the N-th
4234 ** argument of the application-defined function.  Subsequent
4235 ** calls to sqlite3_get_auxdata() might return this data, if it has
4236 ** not been destroyed. 
4237 ** If it is not NULL, SQLite will invoke the destructor 
4238 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4239 ** the meta-data when the corresponding function parameter changes
4240 ** or when the SQL statement completes, whichever comes first.
4241 **
4242 ** SQLite is free to call the destructor and drop meta-data on
4243 ** any parameter of any function at any time.  The only guarantee
4244 ** is that the destructor will be called before the metadata is
4245 ** dropped.
4246 **
4247 ** In practice, meta-data is preserved between function calls for
4248 ** expressions that are constant at compile time. This includes literal
4249 ** values and SQL variables.
4250 **
4251 ** These routines must be called from the same thread in which
4252 ** the SQL function is running.
4253 **
4254 ** INVARIANTS:
4255 **
4256 ** {F16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer
4257 **          to metadata associated with the Nth parameter of the SQL function
4258 **          whose context is C, or NULL if there is no metadata associated
4259 **          with that parameter.
4260 **
4261 ** {F16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata
4262 **          pointer P to the Nth parameter of the SQL function with context
4263 **          C.
4264 **
4265 ** {F16276} SQLite will invoke the destructor D with a single argument
4266 **          which is the metadata pointer P following a call to
4267 **          [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold
4268 **          the metadata.
4269 **
4270 ** {F16277} SQLite ceases to hold metadata for an SQL function parameter
4271 **          when the value of that parameter changes.
4272 **
4273 ** {F16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor
4274 **          is called for any prior metadata associated with the same function
4275 **          context C and parameter N.
4276 **
4277 ** {F16279} SQLite will call destructors for any metadata it is holding
4278 **          in a particular [prepared statement] S when either
4279 **          [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called.
4280 */
4281 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4282 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4283
4284
4285 /*
4286 ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280}
4287 **
4288 ** These are special value for the destructor that is passed in as the
4289 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
4290 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4291 ** and will never change.  It does not need to be destroyed.  The 
4292 ** SQLITE_TRANSIENT value means that the content will likely change in
4293 ** the near future and that SQLite should make its own private copy of
4294 ** the content before returning.
4295 **
4296 ** The typedef is necessary to work around problems in certain
4297 ** C++ compilers.  See ticket #2191.
4298 */
4299 typedef void (*sqlite3_destructor_type)(void*);
4300 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4301 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4302
4303 /*
4304 ** CAPI3REF: Setting The Result Of An SQL Function {F16400}
4305 **
4306 ** These routines are used by the xFunc or xFinal callbacks that
4307 ** implement SQL functions and aggregates.  See
4308 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4309 ** for additional information.
4310 **
4311 ** These functions work very much like the 
4312 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
4313 ** to bind values to host parameters in prepared statements.
4314 ** Refer to the
4315 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
4316 ** additional information.
4317 **
4318 ** The sqlite3_result_blob() interface sets the result from
4319 ** an application defined function to be the BLOB whose content is pointed
4320 ** to by the second parameter and which is N bytes long where N is the
4321 ** third parameter. 
4322 ** The sqlite3_result_zeroblob() inerfaces set the result of
4323 ** the application defined function to be a BLOB containing all zero
4324 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4325 **
4326 ** The sqlite3_result_double() interface sets the result from
4327 ** an application defined function to be a floating point value specified
4328 ** by its 2nd argument.
4329 **
4330 ** The sqlite3_result_error() and sqlite3_result_error16() functions
4331 ** cause the implemented SQL function to throw an exception.
4332 ** SQLite uses the string pointed to by the
4333 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4334 ** as the text of an error message.  SQLite interprets the error
4335 ** message string from sqlite3_result_error() as UTF8. SQLite
4336 ** interprets the string from sqlite3_result_error16() as UTF16 in native
4337 ** byte order.  If the third parameter to sqlite3_result_error()
4338 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4339 ** message all text up through the first zero character.
4340 ** If the third parameter to sqlite3_result_error() or
4341 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4342 ** bytes (not characters) from the 2nd parameter as the error message.
4343 ** The sqlite3_result_error() and sqlite3_result_error16()
4344 ** routines make a copy private copy of the error message text before
4345 ** they return.  Hence, the calling function can deallocate or
4346 ** modify the text after they return without harm.
4347 ** The sqlite3_result_error_code() function changes the error code
4348 ** returned by SQLite as a result of an error in a function.  By default,
4349 ** the error code is SQLITE_ERROR.  A subsequent call to sqlite3_result_error()
4350 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4351 **
4352 ** The sqlite3_result_toobig() interface causes SQLite
4353 ** to throw an error indicating that a string or BLOB is to long
4354 ** to represent.  The sqlite3_result_nomem() interface
4355 ** causes SQLite to throw an exception indicating that the a
4356 ** memory allocation failed.
4357 **
4358 ** The sqlite3_result_int() interface sets the return value
4359 ** of the application-defined function to be the 32-bit signed integer
4360 ** value given in the 2nd argument.
4361 ** The sqlite3_result_int64() interface sets the return value
4362 ** of the application-defined function to be the 64-bit signed integer
4363 ** value given in the 2nd argument.
4364 **
4365 ** The sqlite3_result_null() interface sets the return value
4366 ** of the application-defined function to be NULL.
4367 **
4368 ** The sqlite3_result_text(), sqlite3_result_text16(), 
4369 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4370 ** set the return value of the application-defined function to be
4371 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4372 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4373 ** SQLite takes the text result from the application from
4374 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4375 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4376 ** is negative, then SQLite takes result text from the 2nd parameter 
4377 ** through the first zero character.
4378 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4379 ** is non-negative, then as many bytes (not characters) of the text
4380 ** pointed to by the 2nd parameter are taken as the application-defined
4381 ** function result.
4382 ** If the 4th parameter to the sqlite3_result_text* interfaces
4383 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4384 ** function as the destructor on the text or blob result when it has
4385 ** finished using that result.
4386 ** If the 4th parameter to the sqlite3_result_text* interfaces
4387 ** or sqlite3_result_blob is the special constant SQLITE_STATIC, then
4388 ** SQLite assumes that the text or blob result is constant space and
4389 ** does not copy the space or call a destructor when it has
4390 ** finished using that result.
4391 ** If the 4th parameter to the sqlite3_result_text* interfaces
4392 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4393 ** then SQLite makes a copy of the result into space obtained from
4394 ** from [sqlite3_malloc()] before it returns.
4395 **
4396 ** The sqlite3_result_value() interface sets the result of
4397 ** the application-defined function to be a copy the
4398 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  The
4399 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4400 ** so that [sqlite3_value] specified in the parameter may change or
4401 ** be deallocated after sqlite3_result_value() returns without harm.
4402 ** A [protected sqlite3_value] object may always be used where an
4403 ** [unprotected sqlite3_value] object is required, so either
4404 ** kind of [sqlite3_value] object can be used with this interface.
4405 **
4406 ** If these routines are called from within the different thread 
4407 ** than the one containing the application-defined function that recieved
4408 ** the [sqlite3_context] pointer, the results are undefined.
4409 **
4410 ** INVARIANTS:
4411 **
4412 ** {F16403} The default return value from any SQL function is NULL.
4413 **
4414 ** {F16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the
4415 **          return value of function C to be a blob that is N bytes
4416 **          in length and with content pointed to by V.
4417 **
4418 ** {F16409} The [sqlite3_result_double(C,V)] interface changes the
4419 **          return value of function C to be the floating point value V.
4420 **
4421 ** {F16412} The [sqlite3_result_error(C,V,N)] interface changes the return
4422 **          value of function C to be an exception with error code
4423 **          [SQLITE_ERROR] and a UTF8 error message copied from V up to the
4424 **          first zero byte or until N bytes are read if N is positive.
4425 **
4426 ** {F16415} The [sqlite3_result_error16(C,V,N)] interface changes the return
4427 **          value of function C to be an exception with error code
4428 **          [SQLITE_ERROR] and a UTF16 native byte order error message
4429 **          copied from V up to the first zero terminator or until N bytes
4430 **          are read if N is positive.
4431 **
4432 ** {F16418} The [sqlite3_result_error_toobig(C)] interface changes the return
4433 **          value of the function C to be an exception with error code
4434 **          [SQLITE_TOOBIG] and an appropriate error message.
4435 **
4436 ** {F16421} The [sqlite3_result_error_nomem(C)] interface changes the return
4437 **          value of the function C to be an exception with error code
4438 **          [SQLITE_NOMEM] and an appropriate error message.
4439 **
4440 ** {F16424} The [sqlite3_result_error_code(C,E)] interface changes the return
4441 **          value of the function C to be an exception with error code E.
4442 **          The error message text is unchanged.
4443 **
4444 ** {F16427} The [sqlite3_result_int(C,V)] interface changes the
4445 **          return value of function C to be the 32-bit integer value V.
4446 **
4447 ** {F16430} The [sqlite3_result_int64(C,V)] interface changes the
4448 **          return value of function C to be the 64-bit integer value V.
4449 **
4450 ** {F16433} The [sqlite3_result_null(C)] interface changes the
4451 **          return value of function C to be NULL.
4452 **
4453 ** {F16436} The [sqlite3_result_text(C,V,N,D)] interface changes the
4454 **          return value of function C to be the UTF8 string
4455 **          V up to the first zero if N is negative
4456 **          or the first N bytes of V if N is non-negative.
4457 **
4458 ** {F16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the
4459 **          return value of function C to be the UTF16 native byte order
4460 **          string V up to the first zero if N is
4461 **          negative or the first N bytes of V if N is non-negative.
4462 **
4463 ** {F16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the
4464 **          return value of function C to be the UTF16 big-endian
4465 **          string V up to the first zero if N is
4466 **          is negative or the first N bytes or V if N is non-negative.
4467 **
4468 ** {F16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the
4469 **          return value of function C to be the UTF16 little-endian
4470 **          string V up to the first zero if N is
4471 **          negative or the first N bytes of V if N is non-negative.
4472 **
4473 ** {F16448} The [sqlite3_result_value(C,V)] interface changes the
4474 **          return value of function C to be [unprotected sqlite3_value]
4475 **          object V.
4476 **
4477 ** {F16451} The [sqlite3_result_zeroblob(C,N)] interface changes the
4478 **          return value of function C to be an N-byte blob of all zeros.
4479 **
4480 ** {F16454} The [sqlite3_result_error()] and [sqlite3_result_error16()]
4481 **          interfaces make a copy of their error message strings before
4482 **          returning.
4483 **
4484 ** {F16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4485 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4486 **          [sqlite3_result_text16be(C,V,N,D)], or
4487 **          [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC]
4488 **          then no destructor is ever called on the pointer V and SQLite
4489 **          assumes that V is immutable.
4490 **
4491 ** {F16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4492 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4493 **          [sqlite3_result_text16be(C,V,N,D)], or
4494 **          [sqlite3_result_text16le(C,V,N,D)] is the constant
4495 **          [SQLITE_TRANSIENT] then the interfaces makes a copy of the
4496 **          content of V and retains the copy.
4497 **
4498 ** {F16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
4499 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
4500 **          [sqlite3_result_text16be(C,V,N,D)], or
4501 **          [sqlite3_result_text16le(C,V,N,D)] is some value other than
4502 **          the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then 
4503 **          SQLite will invoke the destructor D with V as its only argument
4504 **          when it has finished with the V value.
4505 */
4506 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4507 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4508 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4509 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4510 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4511 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4512 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4513 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4514 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4515 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4516 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4517 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4518 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4519 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4520 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4521 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4522
4523 /*
4524 ** CAPI3REF: Define New Collating Sequences {F16600}
4525 **
4526 ** These functions are used to add new collation sequences to the
4527 ** [sqlite3*] handle specified as the first argument. 
4528 **
4529 ** The name of the new collation sequence is specified as a UTF-8 string
4530 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4531 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
4532 ** the name is passed as the second function argument.
4533 **
4534 ** The third argument may be one of the constants [SQLITE_UTF8],
4535 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
4536 ** routine expects to be passed pointers to strings encoded using UTF-8,
4537 ** UTF-16 little-endian or UTF-16 big-endian respectively. The
4538 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
4539 ** the routine expects pointers to 16-bit word aligned strings
4540 ** of UTF16 in the native byte order of the host computer.
4541 **
4542 ** A pointer to the user supplied routine must be passed as the fifth
4543 ** argument.  If it is NULL, this is the same as deleting the collation
4544 ** sequence (so that SQLite cannot call it anymore).
4545 ** Each time the application
4546 ** supplied function is invoked, it is passed a copy of the void* passed as
4547 ** the fourth argument to sqlite3_create_collation() or
4548 ** sqlite3_create_collation16() as its first parameter.
4549 **
4550 ** The remaining arguments to the application-supplied routine are two strings,
4551 ** each represented by a (length, data) pair and encoded in the encoding
4552 ** that was passed as the third argument when the collation sequence was
4553 ** registered. {END} The application defined collation routine should
4554 ** return negative, zero or positive if
4555 ** the first string is less than, equal to, or greater than the second
4556 ** string. i.e. (STRING1 - STRING2).
4557 **
4558 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4559 ** excapt that it takes an extra argument which is a destructor for
4560 ** the collation.  The destructor is called when the collation is
4561 ** destroyed and is passed a copy of the fourth parameter void* pointer
4562 ** of the sqlite3_create_collation_v2().
4563 ** Collations are destroyed when
4564 ** they are overridden by later calls to the collation creation functions
4565 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
4566 **
4567 ** INVARIANTS:
4568 **
4569 ** {F16603} A successful call to the
4570 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface
4571 **          registers function F as the comparison function used to
4572 **          implement collation X on [database connection] B for
4573 **          databases having encoding E.
4574 **
4575 ** {F16604} SQLite understands the X parameter to
4576 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated
4577 **          UTF-8 string in which case is ignored for ASCII characters and
4578 **          is significant for non-ASCII characters.
4579 **
4580 ** {F16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4581 **          with the same values for B, X, and E, override prior values
4582 **          of P, F, and D.
4583 **
4584 ** {F16609} The destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4585 **          is not NULL then it is called with argument P when the
4586 **          collating function is dropped by SQLite.
4587 **
4588 ** {F16612} A collating function is dropped when it is overloaded.
4589 **
4590 ** {F16615} A collating function is dropped when the database connection
4591 **          is closed using [sqlite3_close()].
4592 **
4593 ** {F16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
4594 **          is passed through as the first parameter to the comparison
4595 **          function F for all subsequent invocations of F.
4596 **
4597 ** {F16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly
4598 **          the same as a call to [sqlite3_create_collation_v2()] with
4599 **          the same parameters and a NULL destructor.
4600 **
4601 ** {F16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)],
4602 **          SQLite uses the comparison function F for all text comparison
4603 **          operations on [database connection] B on text values that
4604 **          use the collating sequence name X.
4605 **
4606 ** {F16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same
4607 **          as [sqlite3_create_collation(B,X,E,P,F)] except that the
4608 **          collation name X is understood as UTF-16 in native byte order
4609 **          instead of UTF-8.
4610 **
4611 ** {F16630} When multiple comparison functions are available for the same
4612 **          collating sequence, SQLite chooses the one whose text encoding
4613 **          requires the least amount of conversion from the default
4614 **          text encoding of the database.
4615 */
4616 SQLITE_API int sqlite3_create_collation(
4617   sqlite3*, 
4618   const char *zName, 
4619   int eTextRep, 
4620   void*,
4621   int(*xCompare)(void*,int,const void*,int,const void*)
4622 );
4623 SQLITE_API int sqlite3_create_collation_v2(
4624   sqlite3*, 
4625   const char *zName, 
4626   int eTextRep, 
4627   void*,
4628   int(*xCompare)(void*,int,const void*,int,const void*),
4629   void(*xDestroy)(void*)
4630 );
4631 SQLITE_API int sqlite3_create_collation16(
4632   sqlite3*, 
4633   const char *zName, 
4634   int eTextRep, 
4635   void*,
4636   int(*xCompare)(void*,int,const void*,int,const void*)
4637 );
4638
4639 /*
4640 ** CAPI3REF: Collation Needed Callbacks {F16700}
4641 **
4642 ** To avoid having to register all collation sequences before a database
4643 ** can be used, a single callback function may be registered with the
4644 ** database handle to be called whenever an undefined collation sequence is
4645 ** required.
4646 **
4647 ** If the function is registered using the sqlite3_collation_needed() API,
4648 ** then it is passed the names of undefined collation sequences as strings
4649 ** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names
4650 ** are passed as UTF-16 in machine native byte order. A call to either
4651 ** function replaces any existing callback.
4652 **
4653 ** When the callback is invoked, the first argument passed is a copy
4654 ** of the second argument to sqlite3_collation_needed() or
4655 ** sqlite3_collation_needed16().  The second argument is the database
4656 ** handle.  The third argument is one of [SQLITE_UTF8],
4657 ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most
4658 ** desirable form of the collation sequence function required.
4659 ** The fourth parameter is the name of the
4660 ** required collation sequence.
4661 **
4662 ** The callback function should register the desired collation using
4663 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4664 ** [sqlite3_create_collation_v2()].
4665 **
4666 ** INVARIANTS:
4667 **
4668 ** {F16702} A successful call to [sqlite3_collation_needed(D,P,F)]
4669 **          or [sqlite3_collation_needed16(D,P,F)] causes
4670 **          the [database connection] D to invoke callback F with first
4671 **          parameter P whenever it needs a comparison function for a
4672 **          collating sequence that it does not know about.
4673 **
4674 ** {F16704} Each successful call to [sqlite3_collation_needed()] or
4675 **          [sqlite3_collation_needed16()] overrides the callback registered
4676 **          on the same [database connection] by prior calls to either
4677 **          interface.
4678 **
4679 ** {F16706} The name of the requested collating function passed in the
4680 **          4th parameter to the callback is in UTF-8 if the callback
4681 **          was registered using [sqlite3_collation_needed()] and
4682 **          is in UTF-16 native byte order if the callback was
4683 **          registered using [sqlite3_collation_needed16()].
4684 **
4685 ** 
4686 */
4687 SQLITE_API int sqlite3_collation_needed(
4688   sqlite3*, 
4689   void*, 
4690   void(*)(void*,sqlite3*,int eTextRep,const char*)
4691 );
4692 SQLITE_API int sqlite3_collation_needed16(
4693   sqlite3*, 
4694   void*,
4695   void(*)(void*,sqlite3*,int eTextRep,const void*)
4696 );
4697
4698 /*
4699 ** Specify the key for an encrypted database.  This routine should be
4700 ** called right after sqlite3_open().
4701 **
4702 ** The code to implement this API is not available in the public release
4703 ** of SQLite.
4704 */
4705 SQLITE_API int sqlite3_key(
4706   sqlite3 *db,                   /* Database to be rekeyed */
4707   const void *pKey, int nKey     /* The key */
4708 );
4709
4710 /*
4711 ** Change the key on an open database.  If the current database is not
4712 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4713 ** database is decrypted.
4714 **
4715 ** The code to implement this API is not available in the public release
4716 ** of SQLite.
4717 */
4718 SQLITE_API int sqlite3_rekey(
4719   sqlite3 *db,                   /* Database to be rekeyed */
4720   const void *pKey, int nKey     /* The new key */
4721 );
4722
4723 /*
4724 ** CAPI3REF:  Suspend Execution For A Short Time {F10530}
4725 **
4726 ** The sqlite3_sleep() function
4727 ** causes the current thread to suspend execution
4728 ** for at least a number of milliseconds specified in its parameter.
4729 **
4730 ** If the operating system does not support sleep requests with 
4731 ** millisecond time resolution, then the time will be rounded up to 
4732 ** the nearest second. The number of milliseconds of sleep actually 
4733 ** requested from the operating system is returned.
4734 **
4735 ** SQLite implements this interface by calling the xSleep()
4736 ** method of the default [sqlite3_vfs] object.
4737 **
4738 ** INVARIANTS:
4739 **
4740 ** {F10533} The [sqlite3_sleep(M)] interface invokes the xSleep
4741 **          method of the default [sqlite3_vfs|VFS] in order to
4742 **          suspend execution of the current thread for at least
4743 **          M milliseconds.
4744 **
4745 ** {F10536} The [sqlite3_sleep(M)] interface returns the number of
4746 **          milliseconds of sleep actually requested of the operating
4747 **          system, which might be larger than the parameter M.
4748 */
4749 SQLITE_API int sqlite3_sleep(int);
4750
4751 /*
4752 ** CAPI3REF:  Name Of The Folder Holding Temporary Files {F10310}
4753 **
4754 ** If this global variable is made to point to a string which is
4755 ** the name of a folder (a.ka. directory), then all temporary files
4756 ** created by SQLite will be placed in that directory.  If this variable
4757 ** is NULL pointer, then SQLite does a search for an appropriate temporary
4758 ** file directory.
4759 **
4760 ** It is not safe to modify this variable once a database connection
4761 ** has been opened.  It is intended that this variable be set once
4762 ** as part of process initialization and before any SQLite interface
4763 ** routines have been call and remain unchanged thereafter.
4764 */
4765 SQLITE_API char *sqlite3_temp_directory;
4766
4767 /*
4768 ** CAPI3REF:  Test To See If The Database Is In Auto-Commit Mode {F12930}
4769 **
4770 ** The sqlite3_get_autocommit() interfaces returns non-zero or
4771 ** zero if the given database connection is or is not in autocommit mode,
4772 ** respectively.   Autocommit mode is on
4773 ** by default.  Autocommit mode is disabled by a [BEGIN] statement.
4774 ** Autocommit mode is reenabled by a [COMMIT] or [ROLLBACK].
4775 **
4776 ** If certain kinds of errors occur on a statement within a multi-statement
4777 ** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], 
4778 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4779 ** transaction might be rolled back automatically.  The only way to
4780 ** find out if SQLite automatically rolled back the transaction after
4781 ** an error is to use this function.
4782 **
4783 ** INVARIANTS:
4784 **
4785 ** {F12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or
4786 **          zero if the [database connection] D is or is not in autocommit
4787 **          mode, respectively.
4788 **
4789 ** {F12932} Autocommit mode is on by default.
4790 **
4791 ** {F12933} Autocommit mode is disabled by a successful [BEGIN] statement.
4792 **
4793 ** {F12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK]
4794 **          statement.
4795 ** 
4796 **
4797 ** LIMITATIONS:
4798 ***
4799 ** {U12936} If another thread changes the autocommit status of the database
4800 **          connection while this routine is running, then the return value
4801 **          is undefined.
4802 */
4803 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4804
4805 /*
4806 ** CAPI3REF:  Find The Database Handle Of A Prepared Statement {F13120}
4807 **
4808 ** The sqlite3_db_handle interface
4809 ** returns the [sqlite3*] database handle to which a
4810 ** [prepared statement] belongs.
4811 ** The database handle returned by sqlite3_db_handle
4812 ** is the same database handle that was
4813 ** the first argument to the [sqlite3_prepare_v2()] or its variants
4814 ** that was used to create the statement in the first place.
4815 **
4816 ** INVARIANTS:
4817 **
4818 ** {F13123} The [sqlite3_db_handle(S)] interface returns a pointer
4819 **          to the [database connection] associated with
4820 **          [prepared statement] S.
4821 */
4822 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4823
4824
4825 /*
4826 ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950}
4827 **
4828 ** The sqlite3_commit_hook() interface registers a callback
4829 ** function to be invoked whenever a transaction is committed.
4830 ** Any callback set by a previous call to sqlite3_commit_hook()
4831 ** for the same database connection is overridden.
4832 ** The sqlite3_rollback_hook() interface registers a callback
4833 ** function to be invoked whenever a transaction is committed.
4834 ** Any callback set by a previous call to sqlite3_commit_hook()
4835 ** for the same database connection is overridden.
4836 ** The pArg argument is passed through
4837 ** to the callback.  If the callback on a commit hook function 
4838 ** returns non-zero, then the commit is converted into a rollback.
4839 **
4840 ** If another function was previously registered, its
4841 ** pArg value is returned.  Otherwise NULL is returned.
4842 **
4843 ** Registering a NULL function disables the callback.
4844 **
4845 ** For the purposes of this API, a transaction is said to have been 
4846 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4847 ** an error or constraint causes an implicit rollback to occur.
4848 ** The rollback callback is not invoked if a transaction is
4849 ** automatically rolled back because the database connection is closed.
4850 ** The rollback callback is not invoked if a transaction is
4851 ** rolled back because a commit callback returned non-zero.
4852 ** <todo> Check on this </todo>
4853 **
4854 ** These are experimental interfaces and are subject to change.
4855 **
4856 ** INVARIANTS:
4857 **
4858 ** {F12951} The [sqlite3_commit_hook(D,F,P)] interface registers the
4859 **          callback function F to be invoked with argument P whenever
4860 **          a transaction commits on [database connection] D.
4861 **
4862 ** {F12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P
4863 **          argument from the previous call with the same 
4864 **          [database connection ] D , or NULL on the first call
4865 **          for a particular [database connection] D.
4866 **
4867 ** {F12953} Each call to [sqlite3_commit_hook()] overwrites the callback
4868 **          registered by prior calls.
4869 **
4870 ** {F12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL
4871 **          then the commit hook callback is cancelled and no callback
4872 **          is invoked when a transaction commits.
4873 **
4874 ** {F12955} If the commit callback returns non-zero then the commit is
4875 **          converted into a rollback.
4876 **
4877 ** {F12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the
4878 **          callback function F to be invoked with argument P whenever
4879 **          a transaction rolls back on [database connection] D.
4880 **
4881 ** {F12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P
4882 **          argument from the previous call with the same 
4883 **          [database connection ] D , or NULL on the first call
4884 **          for a particular [database connection] D.
4885 **
4886 ** {F12963} Each call to [sqlite3_rollback_hook()] overwrites the callback
4887 **          registered by prior calls.
4888 **
4889 ** {F12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL
4890 **          then the rollback hook callback is cancelled and no callback
4891 **          is invoked when a transaction rolls back.
4892 */
4893 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4894 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4895
4896 /*
4897 ** CAPI3REF: Data Change Notification Callbacks {F12970}
4898 **
4899 ** The sqlite3_update_hook() interface
4900 ** registers a callback function with the database connection identified by the 
4901 ** first argument to be invoked whenever a row is updated, inserted or deleted.
4902 ** Any callback set by a previous call to this function for the same 
4903 ** database connection is overridden.
4904 **
4905 ** The second argument is a pointer to the function to invoke when a 
4906 ** row is updated, inserted or deleted. 
4907 ** The first argument to the callback is
4908 ** a copy of the third argument to sqlite3_update_hook().
4909 ** The second callback 
4910 ** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
4911 ** depending on the operation that caused the callback to be invoked.
4912 ** The third and 
4913 ** fourth arguments to the callback contain pointers to the database and 
4914 ** table name containing the affected row.
4915 ** The final callback parameter is 
4916 ** the rowid of the row.
4917 ** In the case of an update, this is the rowid after 
4918 ** the update takes place.
4919 **
4920 ** The update hook is not invoked when internal system tables are
4921 ** modified (i.e. sqlite_master and sqlite_sequence).
4922 **
4923 ** If another function was previously registered, its pArg value
4924 ** is returned.  Otherwise NULL is returned.
4925 **
4926 ** INVARIANTS:
4927 **
4928 ** {F12971} The [sqlite3_update_hook(D,F,P)] interface causes callback
4929 **          function F to be invoked with first parameter P whenever
4930 **          a table row is modified, inserted, or deleted on
4931 **          [database connection] D.
4932 **
4933 ** {F12973} The [sqlite3_update_hook(D,F,P)] interface returns the value
4934 **          of P for the previous call on the same [database connection] D,
4935 **          or NULL for the first call.
4936 **
4937 ** {F12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)]
4938 **          is NULL then the no update callbacks are made.
4939 **
4940 ** {F12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls
4941 **          to the same interface on the same [database connection] D.
4942 **
4943 ** {F12979} The update hook callback is not invoked when internal system
4944 **          tables such as sqlite_master and sqlite_sequence are modified.
4945 **
4946 ** {F12981} The second parameter to the update callback 
4947 **          is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
4948 **          depending on the operation that caused the callback to be invoked.
4949 **
4950 ** {F12983} The third and fourth arguments to the callback contain pointers
4951 **          to zero-terminated UTF-8 strings which are the names of the
4952 **          database and table that is being updated.
4953
4954 ** {F12985} The final callback parameter is the rowid of the row after
4955 **          the change occurs.
4956 */
4957 SQLITE_API void *sqlite3_update_hook(
4958   sqlite3*, 
4959   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4960   void*
4961 );
4962
4963 /*
4964 ** CAPI3REF:  Enable Or Disable Shared Pager Cache {F10330}
4965 **
4966 ** This routine enables or disables the sharing of the database cache
4967 ** and schema data structures between connections to the same database.
4968 ** Sharing is enabled if the argument is true and disabled if the argument
4969 ** is false.
4970 **
4971 ** Cache sharing is enabled and disabled
4972 ** for an entire process. {END} This is a change as of SQLite version 3.5.0.
4973 ** In prior versions of SQLite, sharing was
4974 ** enabled or disabled for each thread separately.
4975 **
4976 ** The cache sharing mode set by this interface effects all subsequent
4977 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4978 ** Existing database connections continue use the sharing mode
4979 ** that was in effect at the time they were opened.
4980 **
4981 ** Virtual tables cannot be used with a shared cache.   When shared
4982 ** cache is enabled, the [sqlite3_create_module()] API used to register
4983 ** virtual tables will always return an error.
4984 **
4985 ** This routine returns [SQLITE_OK] if shared cache was
4986 ** enabled or disabled successfully.  An [error code]
4987 ** is returned otherwise.
4988 **
4989 ** Shared cache is disabled by default. But this might change in
4990 ** future releases of SQLite.  Applications that care about shared
4991 ** cache setting should set it explicitly.
4992 **
4993 ** INVARIANTS:
4994 ** 
4995 ** {F10331} A successful invocation of [sqlite3_enable_shared_cache(B)]
4996 **          will enable or disable shared cache mode for any subsequently
4997 **          created [database connection] in the same process.
4998 **
4999 ** {F10336} When shared cache is enabled, the [sqlite3_create_module()]
5000 **          interface will always return an error.
5001 **
5002 ** {F10337} The [sqlite3_enable_shared_cache(B)] interface returns
5003 **          [SQLITE_OK] if shared cache was enabled or disabled successfully.
5004 **
5005 ** {F10339} Shared cache is disabled by default.
5006 */
5007 SQLITE_API int sqlite3_enable_shared_cache(int);
5008
5009 /*
5010 ** CAPI3REF:  Attempt To Free Heap Memory {F17340}
5011 **
5012 ** The sqlite3_release_memory() interface attempts to
5013 ** free N bytes of heap memory by deallocating non-essential memory
5014 ** allocations held by the database labrary. {END}  Memory used
5015 ** to cache database pages to improve performance is an example of
5016 ** non-essential memory.  Sqlite3_release_memory() returns
5017 ** the number of bytes actually freed, which might be more or less
5018 ** than the amount requested.
5019 **
5020 ** INVARIANTS:
5021 **
5022 ** {F17341} The [sqlite3_release_memory(N)] interface attempts to
5023 **          free N bytes of heap memory by deallocating non-essential
5024 **          memory allocations held by the database labrary.
5025 **
5026 ** {F16342} The [sqlite3_release_memory(N)] returns the number
5027 **          of bytes actually freed, which might be more or less
5028 **          than the amount requested.
5029 */
5030 SQLITE_API int sqlite3_release_memory(int);
5031
5032 /*
5033 ** CAPI3REF:  Impose A Limit On Heap Size {F17350}
5034 **
5035 ** The sqlite3_soft_heap_limit() interface
5036 ** places a "soft" limit on the amount of heap memory that may be allocated
5037 ** by SQLite. If an internal allocation is requested 
5038 ** that would exceed the soft heap limit, [sqlite3_release_memory()] is
5039 ** invoked one or more times to free up some space before the allocation
5040 ** is made.
5041 **
5042 ** The limit is called "soft", because if
5043 ** [sqlite3_release_memory()] cannot
5044 ** free sufficient memory to prevent the limit from being exceeded,
5045 ** the memory is allocated anyway and the current operation proceeds.
5046 **
5047 ** A negative or zero value for N means that there is no soft heap limit and
5048 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
5049 ** The default value for the soft heap limit is zero.
5050 **
5051 ** SQLite makes a best effort to honor the soft heap limit.  
5052 ** But if the soft heap limit cannot honored, execution will
5053 ** continue without error or notification.  This is why the limit is 
5054 ** called a "soft" limit.  It is advisory only.
5055 **
5056 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
5057 ** allocated by a single thread - the same thread in which this routine
5058 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
5059 ** applied to all threads. The value specified for the soft heap limit
5060 ** is an upper bound on the total memory allocation for all threads. In
5061 ** version 3.5.0 there is no mechanism for limiting the heap usage for
5062 ** individual threads.
5063 **
5064 ** INVARIANTS:
5065 **
5066 ** {F16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit
5067 **          of N bytes on the amount of heap memory that may be allocated
5068 **          using [sqlite3_malloc()] or [sqlite3_realloc()] at any point
5069 **          in time.
5070 **
5071 ** {F16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would
5072 **          cause the total amount of allocated memory to exceed the
5073 **          soft heap limit, then [sqlite3_release_memory()] is invoked
5074 **          in an attempt to reduce the memory usage prior to proceeding
5075 **          with the memory allocation attempt.
5076 **
5077 ** {F16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger
5078 **          attempts to reduce memory usage through the soft heap limit
5079 **          mechanism continue even if the attempt to reduce memory
5080 **          usage is unsuccessful.
5081 **
5082 ** {F16354} A negative or zero value for N in a call to
5083 **          [sqlite3_soft_heap_limit(N)] means that there is no soft
5084 **          heap limit and [sqlite3_release_memory()] will only be
5085 **          called when memory is completely exhausted.
5086 **
5087 ** {F16355} The default value for the soft heap limit is zero.
5088 **
5089 ** {F16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the
5090 **          values set by all prior calls.
5091 */
5092 SQLITE_API void sqlite3_soft_heap_limit(int);
5093
5094 /*
5095 ** CAPI3REF:  Extract Metadata About A Column Of A Table {F12850}
5096 **
5097 ** This routine
5098 ** returns meta-data about a specific column of a specific database
5099 ** table accessible using the connection handle passed as the first function 
5100 ** argument.
5101 **
5102 ** The column is identified by the second, third and fourth parameters to 
5103 ** this function. The second parameter is either the name of the database
5104 ** (i.e. "main", "temp" or an attached database) containing the specified
5105 ** table or NULL. If it is NULL, then all attached databases are searched
5106 ** for the table using the same algorithm as the database engine uses to 
5107 ** resolve unqualified table references.
5108 **
5109 ** The third and fourth parameters to this function are the table and column 
5110 ** name of the desired column, respectively. Neither of these parameters 
5111 ** may be NULL.
5112 **
5113 ** Meta information is returned by writing to the memory locations passed as
5114 ** the 5th and subsequent parameters to this function. Any of these 
5115 ** arguments may be NULL, in which case the corresponding element of meta 
5116 ** information is ommitted.
5117 **
5118 ** <pre>
5119 ** Parameter     Output Type      Description
5120 ** -----------------------------------
5121 **
5122 **   5th         const char*      Data type
5123 **   6th         const char*      Name of the default collation sequence 
5124 **   7th         int              True if the column has a NOT NULL constraint
5125 **   8th         int              True if the column is part of the PRIMARY KEY
5126 **   9th         int              True if the column is AUTOINCREMENT
5127 ** </pre>
5128 **
5129 **
5130 ** The memory pointed to by the character pointers returned for the 
5131 ** declaration type and collation sequence is valid only until the next 
5132 ** call to any sqlite API function.
5133 **
5134 ** If the specified table is actually a view, then an error is returned.
5135 **
5136 ** If the specified column is "rowid", "oid" or "_rowid_" and an 
5137 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output 
5138 ** parameters are set for the explicitly declared column. If there is no
5139 ** explicitly declared IPK column, then the output parameters are set as 
5140 ** follows:
5141 **
5142 ** <pre>
5143 **     data type: "INTEGER"
5144 **     collation sequence: "BINARY"
5145 **     not null: 0
5146 **     primary key: 1
5147 **     auto increment: 0
5148 ** </pre>
5149 **
5150 ** This function may load one or more schemas from database files. If an
5151 ** error occurs during this process, or if the requested table or column
5152 ** cannot be found, an SQLITE error code is returned and an error message
5153 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
5154 **
5155 ** This API is only available if the library was compiled with the
5156 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
5157 */
5158 SQLITE_API int sqlite3_table_column_metadata(
5159   sqlite3 *db,                /* Connection handle */
5160   const char *zDbName,        /* Database name or NULL */
5161   const char *zTableName,     /* Table name */
5162   const char *zColumnName,    /* Column name */
5163   char const **pzDataType,    /* OUTPUT: Declared data type */
5164   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5165   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5166   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5167   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5168 );
5169
5170 /*
5171 ** CAPI3REF: Load An Extension {F12600}
5172 **
5173 ** {F12601} The sqlite3_load_extension() interface
5174 ** attempts to load an SQLite extension library contained in the file
5175 ** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
5176 ** in which case the name of the entry point defaults
5177 ** to "sqlite3_extension_init".
5178 **
5179 ** {F12604} The sqlite3_load_extension() interface shall
5180 ** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5181 **
5182 ** {F12605}
5183 ** If an error occurs and pzErrMsg is not 0, then the
5184 ** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
5185 ** error message text stored in memory obtained from [sqlite3_malloc()].
5186 ** {END}  The calling function should free this memory
5187 ** by calling [sqlite3_free()].
5188 **
5189 ** {F12606}
5190 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
5191 ** prior to calling this API or an error will be returned.
5192 */
5193 SQLITE_API int sqlite3_load_extension(
5194   sqlite3 *db,          /* Load the extension into this database connection */
5195   const char *zFile,    /* Name of the shared library containing extension */
5196   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5197   char **pzErrMsg       /* Put error message here if not 0 */
5198 );
5199
5200 /*
5201 ** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
5202 **
5203 ** So as not to open security holes in older applications that are
5204 ** unprepared to deal with extension loading, and as a means of disabling
5205 ** extension loading while evaluating user-entered SQL, the following
5206 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
5207 ** off.  {F12622} It is off by default. {END} See ticket #1863.
5208 **
5209 ** {F12621} Call the sqlite3_enable_load_extension() routine
5210 ** with onoff==1 to turn extension loading on
5211 ** and call it with onoff==0 to turn it back off again. {END}
5212 */
5213 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5214
5215 /*
5216 ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
5217 **
5218 ** {F12641} This function
5219 ** registers an extension entry point that is automatically invoked
5220 ** whenever a new database connection is opened using
5221 ** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
5222 **
5223 ** This API can be invoked at program startup in order to register
5224 ** one or more statically linked extensions that will be available
5225 ** to all new database connections.
5226 **
5227 ** {F12642} Duplicate extensions are detected so calling this routine multiple
5228 ** times with the same extension is harmless.
5229 **
5230 ** {F12643} This routine stores a pointer to the extension in an array
5231 ** that is obtained from sqlite_malloc(). {END} If you run a memory leak
5232 ** checker on your program and it reports a leak because of this
5233 ** array, then invoke [sqlite3_reset_auto_extension()] prior
5234 ** to shutdown to free the memory.
5235 **
5236 ** {F12644} Automatic extensions apply across all threads. {END}
5237 **
5238 ** This interface is experimental and is subject to change or
5239 ** removal in future releases of SQLite.
5240 */
5241 SQLITE_API int sqlite3_auto_extension(void *xEntryPoint);
5242
5243
5244 /*
5245 ** CAPI3REF: Reset Automatic Extension Loading {F12660}
5246 **
5247 ** {F12661} This function disables all previously registered
5248 ** automatic extensions. {END}  This
5249 ** routine undoes the effect of all prior [sqlite3_auto_extension()]
5250 ** calls.
5251 **
5252 ** {F12662} This call disabled automatic extensions in all threads. {END}
5253 **
5254 ** This interface is experimental and is subject to change or
5255 ** removal in future releases of SQLite.
5256 */
5257 SQLITE_API void sqlite3_reset_auto_extension(void);
5258
5259
5260 /*
5261 ****** EXPERIMENTAL - subject to change without notice **************
5262 **
5263 ** The interface to the virtual-table mechanism is currently considered
5264 ** to be experimental.  The interface might change in incompatible ways.
5265 ** If this is a problem for you, do not use the interface at this time.
5266 **
5267 ** When the virtual-table mechanism stablizes, we will declare the
5268 ** interface fixed, support it indefinitely, and remove this comment.
5269 */
5270
5271 /*
5272 ** Structures used by the virtual table interface
5273 */
5274 typedef struct sqlite3_vtab sqlite3_vtab;
5275 typedef struct sqlite3_index_info sqlite3_index_info;
5276 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5277 typedef struct sqlite3_module sqlite3_module;
5278
5279 /*
5280 ** CAPI3REF: Virtual Table Object {F18000}
5281 ** KEYWORDS: sqlite3_module
5282 **
5283 ** A module is a class of virtual tables.  Each module is defined
5284 ** by an instance of the following structure.  This structure consists
5285 ** mostly of methods for the module.
5286 */
5287 struct sqlite3_module {
5288   int iVersion;
5289   int (*xCreate)(sqlite3*, void *pAux,
5290                int argc, const char *const*argv,
5291                sqlite3_vtab **ppVTab, char**);
5292   int (*xConnect)(sqlite3*, void *pAux,
5293                int argc, const char *const*argv,
5294                sqlite3_vtab **ppVTab, char**);
5295   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5296   int (*xDisconnect)(sqlite3_vtab *pVTab);
5297   int (*xDestroy)(sqlite3_vtab *pVTab);
5298   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5299   int (*xClose)(sqlite3_vtab_cursor*);
5300   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5301                 int argc, sqlite3_value **argv);
5302   int (*xNext)(sqlite3_vtab_cursor*);
5303   int (*xEof)(sqlite3_vtab_cursor*);
5304   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5305   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5306   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5307   int (*xBegin)(sqlite3_vtab *pVTab);
5308   int (*xSync)(sqlite3_vtab *pVTab);
5309   int (*xCommit)(sqlite3_vtab *pVTab);
5310   int (*xRollback)(sqlite3_vtab *pVTab);
5311   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5312                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5313                        void **ppArg);
5314
5315   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5316 };
5317
5318 /*
5319 ** CAPI3REF: Virtual Table Indexing Information {F18100}
5320 ** KEYWORDS: sqlite3_index_info
5321 **
5322 ** The sqlite3_index_info structure and its substructures is used to
5323 ** pass information into and receive the reply from the xBestIndex
5324 ** method of an sqlite3_module.  The fields under **Inputs** are the
5325 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5326 ** results into the **Outputs** fields.
5327 **
5328 ** The aConstraint[] array records WHERE clause constraints of the
5329 ** form:
5330 **
5331 **         column OP expr
5332 **
5333 ** Where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  
5334 ** The particular operator is stored
5335 ** in aConstraint[].op.  The index of the column is stored in 
5336 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
5337 ** expr on the right-hand side can be evaluated (and thus the constraint
5338 ** is usable) and false if it cannot.
5339 **
5340 ** The optimizer automatically inverts terms of the form "expr OP column"
5341 ** and makes other simplifications to the WHERE clause in an attempt to
5342 ** get as many WHERE clause terms into the form shown above as possible.
5343 ** The aConstraint[] array only reports WHERE clause terms in the correct
5344 ** form that refer to the particular virtual table being queried.
5345 **
5346 ** Information about the ORDER BY clause is stored in aOrderBy[].
5347 ** Each term of aOrderBy records a column of the ORDER BY clause.
5348 **
5349 ** The xBestIndex method must fill aConstraintUsage[] with information
5350 ** about what parameters to pass to xFilter.  If argvIndex>0 then
5351 ** the right-hand side of the corresponding aConstraint[] is evaluated
5352 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
5353 ** is true, then the constraint is assumed to be fully handled by the
5354 ** virtual table and is not checked again by SQLite.
5355 **
5356 ** The idxNum and idxPtr values are recorded and passed into xFilter.
5357 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
5358 **
5359 ** The orderByConsumed means that output from xFilter will occur in
5360 ** the correct order to satisfy the ORDER BY clause so that no separate
5361 ** sorting step is required.
5362 **
5363 ** The estimatedCost value is an estimate of the cost of doing the
5364 ** particular lookup.  A full scan of a table with N entries should have
5365 ** a cost of N.  A binary search of a table of N entries should have a
5366 ** cost of approximately log(N).
5367 */
5368 struct sqlite3_index_info {
5369   /* Inputs */
5370   int nConstraint;           /* Number of entries in aConstraint */
5371   struct sqlite3_index_constraint {
5372      int iColumn;              /* Column on left-hand side of constraint */
5373      unsigned char op;         /* Constraint operator */
5374      unsigned char usable;     /* True if this constraint is usable */
5375      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5376   } *aConstraint;            /* Table of WHERE clause constraints */
5377   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5378   struct sqlite3_index_orderby {
5379      int iColumn;              /* Column number */
5380      unsigned char desc;       /* True for DESC.  False for ASC. */
5381   } *aOrderBy;               /* The ORDER BY clause */
5382
5383   /* Outputs */
5384   struct sqlite3_index_constraint_usage {
5385     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5386     unsigned char omit;      /* Do not code a test for this constraint */
5387   } *aConstraintUsage;
5388   int idxNum;                /* Number used to identify the index */
5389   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5390   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5391   int orderByConsumed;       /* True if output is already ordered */
5392   double estimatedCost;      /* Estimated cost of using this index */
5393 };
5394 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5395 #define SQLITE_INDEX_CONSTRAINT_GT    4
5396 #define SQLITE_INDEX_CONSTRAINT_LE    8
5397 #define SQLITE_INDEX_CONSTRAINT_LT    16
5398 #define SQLITE_INDEX_CONSTRAINT_GE    32
5399 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5400
5401 /*
5402 ** CAPI3REF: Register A Virtual Table Implementation {F18200}
5403 **
5404 ** This routine is used to register a new module name with an SQLite
5405 ** connection.  Module names must be registered before creating new
5406 ** virtual tables on the module, or before using preexisting virtual
5407 ** tables of the module.
5408 */
5409 SQLITE_API int sqlite3_create_module(
5410   sqlite3 *db,               /* SQLite connection to register module with */
5411   const char *zName,         /* Name of the module */
5412   const sqlite3_module *,    /* Methods for the module */
5413   void *                     /* Client data for xCreate/xConnect */
5414 );
5415
5416 /*
5417 ** CAPI3REF: Register A Virtual Table Implementation {F18210}
5418 **
5419 ** This routine is identical to the sqlite3_create_module() method above,
5420 ** except that it allows a destructor function to be specified. It is
5421 ** even more experimental than the rest of the virtual tables API.
5422 */
5423 SQLITE_API int sqlite3_create_module_v2(
5424   sqlite3 *db,               /* SQLite connection to register module with */
5425   const char *zName,         /* Name of the module */
5426   const sqlite3_module *,    /* Methods for the module */
5427   void *,                    /* Client data for xCreate/xConnect */
5428   void(*xDestroy)(void*)     /* Module destructor function */
5429 );
5430
5431 /*
5432 ** CAPI3REF: Virtual Table Instance Object {F18010}
5433 ** KEYWORDS: sqlite3_vtab
5434 **
5435 ** Every module implementation uses a subclass of the following structure
5436 ** to describe a particular instance of the module.  Each subclass will
5437 ** be tailored to the specific needs of the module implementation.   The
5438 ** purpose of this superclass is to define certain fields that are common
5439 ** to all module implementations.
5440 **
5441 ** Virtual tables methods can set an error message by assigning a
5442 ** string obtained from sqlite3_mprintf() to zErrMsg.  The method should
5443 ** take care that any prior string is freed by a call to sqlite3_free()
5444 ** prior to assigning a new string to zErrMsg.  After the error message
5445 ** is delivered up to the client application, the string will be automatically
5446 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
5447 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
5448 ** since virtual tables are commonly implemented in loadable extensions which
5449 ** do not have access to sqlite3MPrintf() or sqlite3Free().
5450 */
5451 struct sqlite3_vtab {
5452   const sqlite3_module *pModule;  /* The module for this virtual table */
5453   int nRef;                       /* Used internally */
5454   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5455   /* Virtual table implementations will typically add additional fields */
5456 };
5457
5458 /*
5459 ** CAPI3REF: Virtual Table Cursor Object  {F18020}
5460 ** KEYWORDS: sqlite3_vtab_cursor
5461 **
5462 ** Every module implementation uses a subclass of the following structure
5463 ** to describe cursors that point into the virtual table and are used
5464 ** to loop through the virtual table.  Cursors are created using the
5465 ** xOpen method of the module.  Each module implementation will define
5466 ** the content of a cursor structure to suit its own needs.
5467 **
5468 ** This superclass exists in order to define fields of the cursor that
5469 ** are common to all implementations.
5470 */
5471 struct sqlite3_vtab_cursor {
5472   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5473   /* Virtual table implementations will typically add additional fields */
5474 };
5475
5476 /*
5477 ** CAPI3REF: Declare The Schema Of A Virtual Table {F18280}
5478 **
5479 ** The xCreate and xConnect methods of a module use the following API
5480 ** to declare the format (the names and datatypes of the columns) of
5481 ** the virtual tables they implement.
5482 */
5483 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
5484
5485 /*
5486 ** CAPI3REF: Overload A Function For A Virtual Table {F18300}
5487 **
5488 ** Virtual tables can provide alternative implementations of functions
5489 ** using the xFindFunction method.  But global versions of those functions
5490 ** must exist in order to be overloaded.
5491 **
5492 ** This API makes sure a global version of a function with a particular
5493 ** name and number of parameters exists.  If no such function exists
5494 ** before this API is called, a new function is created.  The implementation
5495 ** of the new function always causes an exception to be thrown.  So
5496 ** the new function is not good for anything by itself.  Its only
5497 ** purpose is to be a place-holder function that can be overloaded
5498 ** by virtual tables.
5499 **
5500 ** This API should be considered part of the virtual table interface,
5501 ** which is experimental and subject to change.
5502 */
5503 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5504
5505 /*
5506 ** The interface to the virtual-table mechanism defined above (back up
5507 ** to a comment remarkably similar to this one) is currently considered
5508 ** to be experimental.  The interface might change in incompatible ways.
5509 ** If this is a problem for you, do not use the interface at this time.
5510 **
5511 ** When the virtual-table mechanism stabilizes, we will declare the
5512 ** interface fixed, support it indefinitely, and remove this comment.
5513 **
5514 ****** EXPERIMENTAL - subject to change without notice **************
5515 */
5516
5517 /*
5518 ** CAPI3REF: A Handle To An Open BLOB {F17800}
5519 **
5520 ** An instance of this object represents an open BLOB on which
5521 ** incremental I/O can be preformed.
5522 ** Objects of this type are created by
5523 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
5524 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5525 ** can be used to read or write small subsections of the blob.
5526 ** The [sqlite3_blob_bytes()] interface returns the size of the
5527 ** blob in bytes.
5528 */
5529 typedef struct sqlite3_blob sqlite3_blob;
5530
5531 /*
5532 ** CAPI3REF: Open A BLOB For Incremental I/O {F17810}
5533 **
5534 ** This interfaces opens a handle to the blob located
5535 ** in row iRow, column zColumn, table zTable in database zDb;
5536 ** in other words,  the same blob that would be selected by:
5537 **
5538 ** <pre>
5539 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
5540 ** </pre> {END}
5541 **
5542 ** If the flags parameter is non-zero, the blob is opened for 
5543 ** read and write access. If it is zero, the blob is opened for read 
5544 ** access.
5545 **
5546 ** Note that the database name is not the filename that contains
5547 ** the database but rather the symbolic name of the database that
5548 ** is assigned when the database is connected using [ATTACH].
5549 ** For the main database file, the database name is "main".  For
5550 ** TEMP tables, the database name is "temp".
5551 **
5552 ** On success, [SQLITE_OK] is returned and the new 
5553 ** [sqlite3_blob | blob handle] is written to *ppBlob. 
5554 ** Otherwise an error code is returned and 
5555 ** any value written to *ppBlob should not be used by the caller.
5556 ** This function sets the database-handle error code and message
5557 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
5558 ** 
5559 ** INVARIANTS:
5560 **
5561 ** {F17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)]
5562 **          interface opens an [sqlite3_blob] object P on the blob
5563 **          in column C of table T in database B on [database connection] D.
5564 **
5565 ** {F17814} A successful invocation of [sqlite3_blob_open(D,...)] starts
5566 **          a new transaction on [database connection] D if that connection
5567 **          is not already in a transaction.
5568 **
5569 ** {F17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface opens the blob
5570 **          for read and write access if and only if the F parameter
5571 **          is non-zero.
5572 **
5573 ** {F17819} The [sqlite3_blob_open()] interface returns [SQLITE_OK] on 
5574 **          success and an appropriate [error code] on failure.
5575 **
5576 ** {F17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)]
5577 **          then subsequent calls to [sqlite3_errcode(D)],
5578 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] will return
5579 **          information approprate for that error.
5580 */
5581 SQLITE_API int sqlite3_blob_open(
5582   sqlite3*,
5583   const char *zDb,
5584   const char *zTable,
5585   const char *zColumn,
5586   sqlite3_int64 iRow,
5587   int flags,
5588   sqlite3_blob **ppBlob
5589 );
5590
5591 /*
5592 ** CAPI3REF:  Close A BLOB Handle {F17830}
5593 **
5594 ** Close an open [sqlite3_blob | blob handle].
5595 **
5596 ** Closing a BLOB shall cause the current transaction to commit
5597 ** if there are no other BLOBs, no pending prepared statements, and the
5598 ** database connection is in autocommit mode.
5599 ** If any writes were made to the BLOB, they might be held in cache
5600 ** until the close operation if they will fit. {END}
5601 ** Closing the BLOB often forces the changes
5602 ** out to disk and so if any I/O errors occur, they will likely occur
5603 ** at the time when the BLOB is closed.  {F17833} Any errors that occur during
5604 ** closing are reported as a non-zero return value.
5605 **
5606 ** The BLOB is closed unconditionally.  Even if this routine returns
5607 ** an error code, the BLOB is still closed.
5608 **
5609 ** INVARIANTS:
5610 **
5611 ** {F17833} The [sqlite3_blob_close(P)] interface closes an
5612 **          [sqlite3_blob] object P previously opened using
5613 **          [sqlite3_blob_open()].
5614 **
5615 ** {F17836} Closing an [sqlite3_blob] object using
5616 **          [sqlite3_blob_close()] shall cause the current transaction to
5617 **          commit if there are no other open [sqlite3_blob] objects
5618 **          or [prepared statements] on the same [database connection] and
5619 **          the [database connection] is in
5620 **          [sqlite3_get_autocommit | autocommit mode].
5621 **
5622 ** {F17839} The [sqlite3_blob_close(P)] interfaces closes the 
5623 **          [sqlite3_blob] object P unconditionally, even if
5624 **          [sqlite3_blob_close(P)] returns something other than [SQLITE_OK].
5625 **          
5626 */
5627 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5628
5629 /*
5630 ** CAPI3REF:  Return The Size Of An Open BLOB {F17840}
5631 **
5632 ** Return the size in bytes of the blob accessible via the open 
5633 ** [sqlite3_blob] object in its only argument.
5634 **
5635 ** INVARIANTS:
5636 **
5637 ** {F17843} The [sqlite3_blob_bytes(P)] interface returns the size
5638 **          in bytes of the BLOB that the [sqlite3_blob] object P
5639 **          refers to.
5640 */
5641 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5642
5643 /*
5644 ** CAPI3REF:  Read Data From A BLOB Incrementally {F17850}
5645 **
5646 ** This function is used to read data from an open 
5647 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
5648 ** N bytes of data are copied into buffer
5649 ** Z from the open blob, starting at offset iOffset.
5650 **
5651 ** If offset iOffset is less than N bytes from the end of the blob, 
5652 ** [SQLITE_ERROR] is returned and no data is read.  If N or iOffset is
5653 ** less than zero [SQLITE_ERROR] is returned and no data is read.
5654 **
5655 ** On success, SQLITE_OK is returned. Otherwise, an 
5656 ** [error code] or an [extended error code] is returned.
5657 **
5658 ** INVARIANTS:
5659 **
5660 ** {F17853} The [sqlite3_blob_read(P,Z,N,X)] interface reads N bytes
5661 **          beginning at offset X from
5662 **          the blob that [sqlite3_blob] object P refers to
5663 **          and writes those N bytes into buffer Z.
5664 **
5665 ** {F17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the blob
5666 **          is less than N+X bytes, then the function returns [SQLITE_ERROR]
5667 **          and nothing is read from the blob.
5668 **
5669 ** {F17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero
5670 **          then the function returns [SQLITE_ERROR]
5671 **          and nothing is read from the blob.
5672 **
5673 ** {F17862} The [sqlite3_blob_read(P,Z,N,X)] interface returns [SQLITE_OK]
5674 **          if N bytes where successfully read into buffer Z.
5675 **
5676 ** {F17865} If the requested read could not be completed,
5677 **          the [sqlite3_blob_read(P,Z,N,X)] interface returns an
5678 **          appropriate [error code] or [extended error code].
5679 **
5680 ** {F17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)]
5681 **          then subsequent calls to [sqlite3_errcode(D)],
5682 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] will return
5683 **          information approprate for that error, where D is the
5684 **          database handle that was used to open blob handle P.
5685 */
5686 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5687
5688 /*
5689 ** CAPI3REF:  Write Data Into A BLOB Incrementally {F17870}
5690 **
5691 ** This function is used to write data into an open 
5692 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
5693 ** n bytes of data are copied from the buffer
5694 ** pointed to by z into the open blob, starting at offset iOffset.
5695 **
5696 ** If the [sqlite3_blob | blob-handle] passed as the first argument
5697 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
5698 *** was zero), this function returns [SQLITE_READONLY].
5699 **
5700 ** This function may only modify the contents of the blob; it is
5701 ** not possible to increase the size of a blob using this API.
5702 ** If offset iOffset is less than n bytes from the end of the blob, 
5703 ** [SQLITE_ERROR] is returned and no data is written.  If n is
5704 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5705 **
5706 ** On success, SQLITE_OK is returned. Otherwise, an 
5707 ** [error code] or an [extended error code] is returned.
5708 **
5709 ** INVARIANTS:
5710 **
5711 ** {F17873} The [sqlite3_blob_write(P,Z,N,X)] interface writes N bytes
5712 **          from buffer Z into
5713 **          the blob that [sqlite3_blob] object P refers to
5714 **          beginning at an offset of X into the blob.
5715 **
5716 ** {F17875} The [sqlite3_blob_write(P,Z,N,X)] interface returns
5717 **          [SQLITE_READONLY] if the [sqlite3_blob] object P was
5718 **          [sqlite3_blob_open | opened] for reading only.
5719 **
5720 ** {F17876} In [sqlite3_blob_write(P,Z,N,X)] if the size of the blob
5721 **          is less than N+X bytes, then the function returns [SQLITE_ERROR]
5722 **          and nothing is written into the blob.
5723 **
5724 ** {F17879} In [sqlite3_blob_write(P,Z,N,X)] if X or N is less than zero
5725 **          then the function returns [SQLITE_ERROR]
5726 **          and nothing is written into the blob.
5727 **
5728 ** {F17882} The [sqlite3_blob_write(P,Z,N,X)] interface returns [SQLITE_OK]
5729 **          if N bytes where successfully written into blob.
5730 **
5731 ** {F17885} If the requested write could not be completed,
5732 **          the [sqlite3_blob_write(P,Z,N,X)] interface returns an
5733 **          appropriate [error code] or [extended error code].
5734 **
5735 ** {F17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)]
5736 **          then subsequent calls to [sqlite3_errcode(D)],
5737 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] will return
5738 **          information approprate for that error.
5739 */
5740 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5741
5742 /*
5743 ** CAPI3REF:  Virtual File System Objects {F11200}
5744 **
5745 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5746 ** that SQLite uses to interact
5747 ** with the underlying operating system.  Most SQLite builds come with a
5748 ** single default VFS that is appropriate for the host computer.
5749 ** New VFSes can be registered and existing VFSes can be unregistered.
5750 ** The following interfaces are provided.
5751 **
5752 ** The sqlite3_vfs_find() interface returns a pointer to 
5753 ** a VFS given its name.  Names are case sensitive.
5754 ** Names are zero-terminated UTF-8 strings.
5755 ** If there is no match, a NULL
5756 ** pointer is returned.  If zVfsName is NULL then the default 
5757 ** VFS is returned. 
5758 **
5759 ** New VFSes are registered with sqlite3_vfs_register().
5760 ** Each new VFS becomes the default VFS if the makeDflt flag is set.
5761 ** The same VFS can be registered multiple times without injury.
5762 ** To make an existing VFS into the default VFS, register it again
5763 ** with the makeDflt flag set.  If two different VFSes with the
5764 ** same name are registered, the behavior is undefined.  If a
5765 ** VFS is registered with a name that is NULL or an empty string,
5766 ** then the behavior is undefined.
5767 ** 
5768 ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
5769 ** If the default VFS is unregistered, another VFS is chosen as
5770 ** the default.  The choice for the new VFS is arbitrary.
5771 **
5772 ** INVARIANTS:
5773 **
5774 ** {F11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the
5775 **          registered [sqlite3_vfs] object whose name exactly matches
5776 **          the zero-terminated UTF-8 string N, or it returns NULL if
5777 **          there is no match.
5778 **
5779 ** {F11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then
5780 **          the function returns a pointer to the default [sqlite3_vfs]
5781 **          object if there is one, or NULL if there is no default 
5782 **          [sqlite3_vfs] object.
5783 **
5784 ** {F11209} The [sqlite3_vfs_register(P,F)] interface registers the
5785 **          well-formed [sqlite3_vfs] object P using the name given
5786 **          by the zName field of the object.
5787 **
5788 ** {F11212} Using the [sqlite3_vfs_register(P,F)] interface to register
5789 **          the same [sqlite3_vfs] object multiple times is a harmless no-op.
5790 **
5791 ** {F11215} The [sqlite3_vfs_register(P,F)] interface makes the
5792 **          the [sqlite3_vfs] object P the default [sqlite3_vfs] object
5793 **          if F is non-zero.
5794 **
5795 ** {F11218} The [sqlite3_vfs_unregister(P)] interface unregisters the
5796 **          [sqlite3_vfs] object P so that it is no longer returned by
5797 **          subsequent calls to [sqlite3_vfs_find()].
5798 */
5799 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5800 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5801 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5802
5803 /*
5804 ** CAPI3REF: Mutexes {F17000}
5805 **
5806 ** The SQLite core uses these routines for thread
5807 ** synchronization.  Though they are intended for internal
5808 ** use by SQLite, code that links against SQLite is
5809 ** permitted to use any of these routines.
5810 **
5811 ** The SQLite source code contains multiple implementations 
5812 ** of these mutex routines.  An appropriate implementation
5813 ** is selected automatically at compile-time.  The following
5814 ** implementations are available in the SQLite core:
5815 **
5816 ** <ul>
5817 ** <li>   SQLITE_MUTEX_OS2
5818 ** <li>   SQLITE_MUTEX_PTHREAD
5819 ** <li>   SQLITE_MUTEX_W32
5820 ** <li>   SQLITE_MUTEX_NOOP
5821 ** </ul>
5822 **
5823 ** The SQLITE_MUTEX_NOOP implementation is a set of routines 
5824 ** that does no real locking and is appropriate for use in 
5825 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
5826 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5827 ** are appropriate for use on os/2, unix, and windows.
5828 ** 
5829 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5830 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5831 ** implementation is included with the library.  The
5832 ** mutex interface routines defined here become external
5833 ** references in the SQLite library for which implementations
5834 ** must be provided by the application.  This facility allows an
5835 ** application that links against SQLite to provide its own mutex
5836 ** implementation without having to modify the SQLite core.
5837 **
5838 ** {F17011} The sqlite3_mutex_alloc() routine allocates a new
5839 ** mutex and returns a pointer to it. {F17012} If it returns NULL
5840 ** that means that a mutex could not be allocated. {F17013} SQLite
5841 ** will unwind its stack and return an error. {F17014} The argument
5842 ** to sqlite3_mutex_alloc() is one of these integer constants:
5843 **
5844 ** <ul>
5845 ** <li>  SQLITE_MUTEX_FAST
5846 ** <li>  SQLITE_MUTEX_RECURSIVE
5847 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5848 ** <li>  SQLITE_MUTEX_STATIC_MEM
5849 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5850 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5851 ** <li>  SQLITE_MUTEX_STATIC_LRU
5852 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5853 ** </ul> {END}
5854 **
5855 ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create
5856 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5857 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
5858 ** The mutex implementation does not need to make a distinction
5859 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5860 ** not want to.  {F17016} But SQLite will only request a recursive mutex in
5861 ** cases where it really needs one.  {END} If a faster non-recursive mutex
5862 ** implementation is available on the host platform, the mutex subsystem
5863 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5864 **
5865 ** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return
5866 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
5867 ** used by the current version of SQLite.  Future versions of SQLite
5868 ** may add additional static mutexes.  Static mutexes are for internal
5869 ** use by SQLite only.  Applications that use SQLite mutexes should
5870 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5871 ** SQLITE_MUTEX_RECURSIVE.
5872 **
5873 ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5874 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5875 ** returns a different mutex on every call.  {F17034} But for the static 
5876 ** mutex types, the same mutex is returned on every call that has
5877 ** the same type number. {END}
5878 **
5879 ** {F17019} The sqlite3_mutex_free() routine deallocates a previously
5880 ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every
5881 ** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in 
5882 ** use when they are deallocated. {U17022} Attempting to deallocate a static
5883 ** mutex results in undefined behavior. {F17023} SQLite never deallocates
5884 ** a static mutex. {END}
5885 **
5886 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5887 ** to enter a mutex. {F17024} If another thread is already within the mutex,
5888 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5889 ** SQLITE_BUSY. {F17025}  The sqlite3_mutex_try() interface returns SQLITE_OK
5890 ** upon successful entry.  {F17026} Mutexes created using
5891 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5892 ** {F17027} In such cases the,
5893 ** mutex must be exited an equal number of times before another thread
5894 ** can enter.  {U17028} If the same thread tries to enter any other
5895 ** kind of mutex more than once, the behavior is undefined.
5896 ** {F17029} SQLite will never exhibit
5897 ** such behavior in its own use of mutexes. {END}
5898 **
5899 ** Some systems (ex: windows95) do not the operation implemented by
5900 ** sqlite3_mutex_try().  On those systems, sqlite3_mutex_try() will
5901 ** always return SQLITE_BUSY.  {F17030} The SQLite core only ever uses
5902 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END}
5903 **
5904 ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was
5905 ** previously entered by the same thread.  {U17032} The behavior
5906 ** is undefined if the mutex is not currently entered by the
5907 ** calling thread or is not currently allocated.  {F17033} SQLite will
5908 ** never do either. {END}
5909 **
5910 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5911 */
5912 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5913 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5914 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5915 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5916 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5917
5918 /*
5919 ** CAPI3REF: Mutex Verifcation Routines {F17080}
5920 **
5921 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5922 ** are intended for use inside assert() statements. {F17081} The SQLite core
5923 ** never uses these routines except inside an assert() and applications
5924 ** are advised to follow the lead of the core.  {F17082} The core only
5925 ** provides implementations for these routines when it is compiled
5926 ** with the SQLITE_DEBUG flag.  {U17087} External mutex implementations
5927 ** are only required to provide these routines if SQLITE_DEBUG is
5928 ** defined and if NDEBUG is not defined.
5929 **
5930 ** {F17083} These routines should return true if the mutex in their argument
5931 ** is held or not held, respectively, by the calling thread. {END}
5932 **
5933 ** {X17084} The implementation is not required to provided versions of these
5934 ** routines that actually work.
5935 ** If the implementation does not provide working
5936 ** versions of these routines, it should at least provide stubs
5937 ** that always return true so that one does not get spurious
5938 ** assertion failures. {END}
5939 **
5940 ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
5941 ** the routine should return 1.  {END} This seems counter-intuitive since
5942 ** clearly the mutex cannot be held if it does not exist.  But the
5943 ** the reason the mutex does not exist is because the build is not
5944 ** using mutexes.  And we do not want the assert() containing the
5945 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5946 ** the appropriate thing to do.  {F17086} The sqlite3_mutex_notheld() 
5947 ** interface should also return 1 when given a NULL pointer.
5948 */
5949 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5950 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5951
5952 /*
5953 ** CAPI3REF: Mutex Types {F17001}
5954 **
5955 ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument
5956 ** which is one of these integer constants. {END}
5957 */
5958 #define SQLITE_MUTEX_FAST             0
5959 #define SQLITE_MUTEX_RECURSIVE        1
5960 #define SQLITE_MUTEX_STATIC_MASTER    2
5961 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5962 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
5963 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5964 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5965 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5966
5967 /*
5968 ** CAPI3REF: Low-Level Control Of Database Files {F11300}
5969 **
5970 ** {F11301} The [sqlite3_file_control()] interface makes a direct call to the
5971 ** xFileControl method for the [sqlite3_io_methods] object associated
5972 ** with a particular database identified by the second argument. {F11302} The
5973 ** name of the database is the name assigned to the database by the
5974 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
5975 ** database. {F11303} To control the main database file, use the name "main"
5976 ** or a NULL pointer. {F11304} The third and fourth parameters to this routine
5977 ** are passed directly through to the second and third parameters of
5978 ** the xFileControl method.  {F11305} The return value of the xFileControl
5979 ** method becomes the return value of this routine.
5980 **
5981 ** {F11306} If the second parameter (zDbName) does not match the name of any
5982 ** open database file, then SQLITE_ERROR is returned. {F11307} This error
5983 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5984 ** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might
5985 ** also return SQLITE_ERROR.  {U11309} There is no way to distinguish between
5986 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5987 ** xFileControl method. {END}
5988 **
5989 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5990 */
5991 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5992
5993 /*
5994 ** CAPI3REF: Testing Interface {F11400}
5995 **
5996 ** The sqlite3_test_control() interface is used to read out internal
5997 ** state of SQLite and to inject faults into SQLite for testing
5998 ** purposes.  The first parameter a operation code that determines
5999 ** the number, meaning, and operation of all subsequent parameters.
6000 **
6001 ** This interface is not for use by applications.  It exists solely
6002 ** for verifying the correct operation of the SQLite library.  Depending
6003 ** on how the SQLite library is compiled, this interface might not exist.
6004 **
6005 ** The details of the operation codes, their meanings, the parameters
6006 ** they take, and what they do are all subject to change without notice.
6007 ** Unlike most of the SQLite API, this function is not guaranteed to
6008 ** operate consistently from one release to the next.
6009 */
6010 SQLITE_API int sqlite3_test_control(int op, ...);
6011
6012 /*
6013 ** CAPI3REF: Testing Interface Operation Codes {F11410}
6014 **
6015 ** These constants are the valid operation code parameters used
6016 ** as the first argument to [sqlite3_test_control()].
6017 **
6018 ** These parameters and their meansing are subject to change
6019 ** without notice.  These values are for testing purposes only.
6020 ** Applications should not use any of these parameters or the
6021 ** [sqlite3_test_control()] interface.
6022 */
6023 #define SQLITE_TESTCTRL_FAULT_CONFIG             1
6024 #define SQLITE_TESTCTRL_FAULT_FAILURES           2
6025 #define SQLITE_TESTCTRL_FAULT_BENIGN_FAILURES    3
6026 #define SQLITE_TESTCTRL_FAULT_PENDING            4
6027 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6028 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6029 #define SQLITE_TESTCTRL_PRNG_RESET               7
6030 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6031
6032
6033 /*
6034 ** Undo the hack that converts floating point types to integer for
6035 ** builds on processors without floating point support.
6036 */
6037 #ifdef SQLITE_OMIT_FLOATING_POINT
6038 # undef double
6039 #endif
6040
6041 #if 0
6042 }  /* End of the 'extern "C"' block */
6043 #endif
6044 #endif
6045
6046 /************** End of sqlite3.h *********************************************/
6047 /************** Continuing where we left off in sqliteInt.h ******************/
6048 /************** Include hash.h in the middle of sqliteInt.h ******************/
6049 /************** Begin file hash.h ********************************************/
6050 /*
6051 ** 2001 September 22
6052 **
6053 ** The author disclaims copyright to this source code.  In place of
6054 ** a legal notice, here is a blessing:
6055 **
6056 **    May you do good and not evil.
6057 **    May you find forgiveness for yourself and forgive others.
6058 **    May you share freely, never taking more than you give.
6059 **
6060 *************************************************************************
6061 ** This is the header file for the generic hash-table implemenation
6062 ** used in SQLite.
6063 **
6064 ** $Id: hash.h,v 1.11 2007/09/04 14:31:47 danielk1977 Exp $
6065 */
6066 #ifndef _SQLITE_HASH_H_
6067 #define _SQLITE_HASH_H_
6068
6069 /* Forward declarations of structures. */
6070 typedef struct Hash Hash;
6071 typedef struct HashElem HashElem;
6072
6073 /* A complete hash table is an instance of the following structure.
6074 ** The internals of this structure are intended to be opaque -- client
6075 ** code should not attempt to access or modify the fields of this structure
6076 ** directly.  Change this structure only by using the routines below.
6077 ** However, many of the "procedures" and "functions" for modifying and
6078 ** accessing this structure are really macros, so we can't really make
6079 ** this structure opaque.
6080 */
6081 struct Hash {
6082   char keyClass;          /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
6083   char copyKey;           /* True if copy of key made on insert */
6084   int count;              /* Number of entries in this table */
6085   int htsize;             /* Number of buckets in the hash table */
6086   HashElem *first;        /* The first element of the array */
6087   struct _ht {            /* the hash table */
6088     int count;               /* Number of entries with this hash */
6089     HashElem *chain;         /* Pointer to first entry with this hash */
6090   } *ht;
6091 };
6092
6093 /* Each element in the hash table is an instance of the following 
6094 ** structure.  All elements are stored on a single doubly-linked list.
6095 **
6096 ** Again, this structure is intended to be opaque, but it can't really
6097 ** be opaque because it is used by macros.
6098 */
6099 struct HashElem {
6100   HashElem *next, *prev;   /* Next and previous elements in the table */
6101   void *data;              /* Data associated with this element */
6102   void *pKey; int nKey;    /* Key associated with this element */
6103 };
6104
6105 /*
6106 ** There are 4 different modes of operation for a hash table:
6107 **
6108 **   SQLITE_HASH_INT         nKey is used as the key and pKey is ignored.
6109 **
6110 **   SQLITE_HASH_POINTER     pKey is used as the key and nKey is ignored.
6111 **
6112 **   SQLITE_HASH_STRING      pKey points to a string that is nKey bytes long
6113 **                           (including the null-terminator, if any).  Case
6114 **                           is ignored in comparisons.
6115 **
6116 **   SQLITE_HASH_BINARY      pKey points to binary data nKey bytes long. 
6117 **                           memcmp() is used to compare keys.
6118 **
6119 ** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
6120 ** if the copyKey parameter to HashInit is 1.  
6121 */
6122 /* #define SQLITE_HASH_INT       1 // NOT USED */
6123 /* #define SQLITE_HASH_POINTER   2 // NOT USED */
6124 #define SQLITE_HASH_STRING    3
6125 #define SQLITE_HASH_BINARY    4
6126
6127 /*
6128 ** Access routines.  To delete, insert a NULL pointer.
6129 */
6130 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int keytype, int copyKey);
6131 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
6132 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
6133 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
6134 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6135
6136 /*
6137 ** Macros for looping over all elements of a hash table.  The idiom is
6138 ** like this:
6139 **
6140 **   Hash h;
6141 **   HashElem *p;
6142 **   ...
6143 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6144 **     SomeStructure *pData = sqliteHashData(p);
6145 **     // do something with pData
6146 **   }
6147 */
6148 #define sqliteHashFirst(H)  ((H)->first)
6149 #define sqliteHashNext(E)   ((E)->next)
6150 #define sqliteHashData(E)   ((E)->data)
6151 #define sqliteHashKey(E)    ((E)->pKey)
6152 #define sqliteHashKeysize(E) ((E)->nKey)
6153
6154 /*
6155 ** Number of entries in a hash table
6156 */
6157 #define sqliteHashCount(H)  ((H)->count)
6158
6159 #endif /* _SQLITE_HASH_H_ */
6160
6161 /************** End of hash.h ************************************************/
6162 /************** Continuing where we left off in sqliteInt.h ******************/
6163 /************** Include parse.h in the middle of sqliteInt.h *****************/
6164 /************** Begin file parse.h *******************************************/
6165 #define TK_SEMI                            1
6166 #define TK_EXPLAIN                         2
6167 #define TK_QUERY                           3
6168 #define TK_PLAN                            4
6169 #define TK_BEGIN                           5
6170 #define TK_TRANSACTION                     6
6171 #define TK_DEFERRED                        7
6172 #define TK_IMMEDIATE                       8
6173 #define TK_EXCLUSIVE                       9
6174 #define TK_COMMIT                         10
6175 #define TK_END                            11
6176 #define TK_ROLLBACK                       12
6177 #define TK_CREATE                         13
6178 #define TK_TABLE                          14
6179 #define TK_IF                             15
6180 #define TK_NOT                            16
6181 #define TK_EXISTS                         17
6182 #define TK_TEMP                           18
6183 #define TK_LP                             19
6184 #define TK_RP                             20
6185 #define TK_AS                             21
6186 #define TK_COMMA                          22
6187 #define TK_ID                             23
6188 #define TK_ABORT                          24
6189 #define TK_AFTER                          25
6190 #define TK_ANALYZE                        26
6191 #define TK_ASC                            27
6192 #define TK_ATTACH                         28
6193 #define TK_BEFORE                         29
6194 #define TK_CASCADE                        30
6195 #define TK_CAST                           31
6196 #define TK_CONFLICT                       32
6197 #define TK_DATABASE                       33
6198 #define TK_DESC                           34
6199 #define TK_DETACH                         35
6200 #define TK_EACH                           36
6201 #define TK_FAIL                           37
6202 #define TK_FOR                            38
6203 #define TK_IGNORE                         39
6204 #define TK_INITIALLY                      40
6205 #define TK_INSTEAD                        41
6206 #define TK_LIKE_KW                        42
6207 #define TK_MATCH                          43
6208 #define TK_KEY                            44
6209 #define TK_OF                             45
6210 #define TK_OFFSET                         46
6211 #define TK_PRAGMA                         47
6212 #define TK_RAISE                          48
6213 #define TK_REPLACE                        49
6214 #define TK_RESTRICT                       50
6215 #define TK_ROW                            51
6216 #define TK_TRIGGER                        52
6217 #define TK_VACUUM                         53
6218 #define TK_VIEW                           54
6219 #define TK_VIRTUAL                        55
6220 #define TK_REINDEX                        56
6221 #define TK_RENAME                         57
6222 #define TK_CTIME_KW                       58
6223 #define TK_ANY                            59
6224 #define TK_OR                             60
6225 #define TK_AND                            61
6226 #define TK_IS                             62
6227 #define TK_BETWEEN                        63
6228 #define TK_IN                             64
6229 #define TK_ISNULL                         65
6230 #define TK_NOTNULL                        66
6231 #define TK_NE                             67
6232 #define TK_EQ                             68
6233 #define TK_GT                             69
6234 #define TK_LE                             70
6235 #define TK_LT                             71
6236 #define TK_GE                             72
6237 #define TK_ESCAPE                         73
6238 #define TK_BITAND                         74
6239 #define TK_BITOR                          75
6240 #define TK_LSHIFT                         76
6241 #define TK_RSHIFT                         77
6242 #define TK_PLUS                           78
6243 #define TK_MINUS                          79
6244 #define TK_STAR                           80
6245 #define TK_SLASH                          81
6246 #define TK_REM                            82
6247 #define TK_CONCAT                         83
6248 #define TK_COLLATE                        84
6249 #define TK_UMINUS                         85
6250 #define TK_UPLUS                          86
6251 #define TK_BITNOT                         87
6252 #define TK_STRING                         88
6253 #define TK_JOIN_KW                        89
6254 #define TK_CONSTRAINT                     90
6255 #define TK_DEFAULT                        91
6256 #define TK_NULL                           92
6257 #define TK_PRIMARY                        93
6258 #define TK_UNIQUE                         94
6259 #define TK_CHECK                          95
6260 #define TK_REFERENCES                     96
6261 #define TK_AUTOINCR                       97
6262 #define TK_ON                             98
6263 #define TK_DELETE                         99
6264 #define TK_UPDATE                         100
6265 #define TK_INSERT                         101
6266 #define TK_SET                            102
6267 #define TK_DEFERRABLE                     103
6268 #define TK_FOREIGN                        104
6269 #define TK_DROP                           105
6270 #define TK_UNION                          106
6271 #define TK_ALL                            107
6272 #define TK_EXCEPT                         108
6273 #define TK_INTERSECT                      109
6274 #define TK_SELECT                         110
6275 #define TK_DISTINCT                       111
6276 #define TK_DOT                            112
6277 #define TK_FROM                           113
6278 #define TK_JOIN                           114
6279 #define TK_USING                          115
6280 #define TK_ORDER                          116
6281 #define TK_BY                             117
6282 #define TK_GROUP                          118
6283 #define TK_HAVING                         119
6284 #define TK_LIMIT                          120
6285 #define TK_WHERE                          121
6286 #define TK_INTO                           122
6287 #define TK_VALUES                         123
6288 #define TK_INTEGER                        124
6289 #define TK_FLOAT                          125
6290 #define TK_BLOB                           126
6291 #define TK_REGISTER                       127
6292 #define TK_VARIABLE                       128
6293 #define TK_CASE                           129
6294 #define TK_WHEN                           130
6295 #define TK_THEN                           131
6296 #define TK_ELSE                           132
6297 #define TK_INDEX                          133
6298 #define TK_ALTER                          134
6299 #define TK_TO                             135
6300 #define TK_ADD                            136
6301 #define TK_COLUMNKW                       137
6302 #define TK_TO_TEXT                        138
6303 #define TK_TO_BLOB                        139
6304 #define TK_TO_NUMERIC                     140
6305 #define TK_TO_INT                         141
6306 #define TK_TO_REAL                        142
6307 #define TK_END_OF_FILE                    143
6308 #define TK_ILLEGAL                        144
6309 #define TK_SPACE                          145
6310 #define TK_UNCLOSED_STRING                146
6311 #define TK_COMMENT                        147
6312 #define TK_FUNCTION                       148
6313 #define TK_COLUMN                         149
6314 #define TK_AGG_FUNCTION                   150
6315 #define TK_AGG_COLUMN                     151
6316 #define TK_CONST_FUNC                     152
6317
6318 /************** End of parse.h ***********************************************/
6319 /************** Continuing where we left off in sqliteInt.h ******************/
6320 #include <stdio.h>
6321 #include <stdlib.h>
6322 #include <string.h>
6323 #include <assert.h>
6324 #include <stddef.h>
6325
6326 /*
6327 ** If compiling for a processor that lacks floating point support,
6328 ** substitute integer for floating-point
6329 */
6330 #ifdef SQLITE_OMIT_FLOATING_POINT
6331 # define double sqlite_int64
6332 # define LONGDOUBLE_TYPE sqlite_int64
6333 # ifndef SQLITE_BIG_DBL
6334 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
6335 # endif
6336 # define SQLITE_OMIT_DATETIME_FUNCS 1
6337 # define SQLITE_OMIT_TRACE 1
6338 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6339 #endif
6340 #ifndef SQLITE_BIG_DBL
6341 # define SQLITE_BIG_DBL (1e99)
6342 #endif
6343
6344 /*
6345 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6346 ** afterward. Having this macro allows us to cause the C compiler 
6347 ** to omit code used by TEMP tables without messy #ifndef statements.
6348 */
6349 #ifdef SQLITE_OMIT_TEMPDB
6350 #define OMIT_TEMPDB 1
6351 #else
6352 #define OMIT_TEMPDB 0
6353 #endif
6354
6355 /*
6356 ** If the following macro is set to 1, then NULL values are considered
6357 ** distinct when determining whether or not two entries are the same
6358 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
6359 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
6360 ** is the way things are suppose to work.
6361 **
6362 ** If the following macro is set to 0, the NULLs are indistinct for
6363 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
6364 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
6365 ** work.
6366 */
6367 #define NULL_DISTINCT_FOR_UNIQUE 1
6368
6369 /*
6370 ** The "file format" number is an integer that is incremented whenever
6371 ** the VDBE-level file format changes.  The following macros define the
6372 ** the default file format for new databases and the maximum file format
6373 ** that the library can read.
6374 */
6375 #define SQLITE_MAX_FILE_FORMAT 4
6376 #ifndef SQLITE_DEFAULT_FILE_FORMAT
6377 # define SQLITE_DEFAULT_FILE_FORMAT 1
6378 #endif
6379
6380 /*
6381 ** Provide a default value for TEMP_STORE in case it is not specified
6382 ** on the command-line
6383 */
6384 #ifndef TEMP_STORE
6385 # define TEMP_STORE 1
6386 #endif
6387
6388 /*
6389 ** GCC does not define the offsetof() macro so we'll have to do it
6390 ** ourselves.
6391 */
6392 #ifndef offsetof
6393 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6394 #endif
6395
6396 /*
6397 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6398 ** not, there are still machines out there that use EBCDIC.)
6399 */
6400 #if 'A' == '\301'
6401 # define SQLITE_EBCDIC 1
6402 #else
6403 # define SQLITE_ASCII 1
6404 #endif
6405
6406 /*
6407 ** Integers of known sizes.  These typedefs might change for architectures
6408 ** where the sizes very.  Preprocessor macros are available so that the
6409 ** types can be conveniently redefined at compile-type.  Like this:
6410 **
6411 **         cc '-DUINTPTR_TYPE=long long int' ...
6412 */
6413 #ifndef UINT32_TYPE
6414 # ifdef HAVE_UINT32_T
6415 #  define UINT32_TYPE uint32_t
6416 # else
6417 #  define UINT32_TYPE unsigned int
6418 # endif
6419 #endif
6420 #ifndef UINT16_TYPE
6421 # ifdef HAVE_UINT16_T
6422 #  define UINT16_TYPE uint16_t
6423 # else
6424 #  define UINT16_TYPE unsigned short int
6425 # endif
6426 #endif
6427 #ifndef INT16_TYPE
6428 # ifdef HAVE_INT16_T
6429 #  define INT16_TYPE int16_t
6430 # else
6431 #  define INT16_TYPE short int
6432 # endif
6433 #endif
6434 #ifndef UINT8_TYPE
6435 # ifdef HAVE_UINT8_T
6436 #  define UINT8_TYPE uint8_t
6437 # else
6438 #  define UINT8_TYPE unsigned char
6439 # endif
6440 #endif
6441 #ifndef INT8_TYPE
6442 # ifdef HAVE_INT8_T
6443 #  define INT8_TYPE int8_t
6444 # else
6445 #  define INT8_TYPE signed char
6446 # endif
6447 #endif
6448 #ifndef LONGDOUBLE_TYPE
6449 # define LONGDOUBLE_TYPE long double
6450 #endif
6451 typedef sqlite_int64 i64;          /* 8-byte signed integer */
6452 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6453 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6454 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6455 typedef INT16_TYPE i16;            /* 2-byte signed integer */
6456 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6457 typedef UINT8_TYPE i8;             /* 1-byte signed integer */
6458
6459 /*
6460 ** Macros to determine whether the machine is big or little endian,
6461 ** evaluated at runtime.
6462 */
6463 #ifdef SQLITE_AMALGAMATION
6464 SQLITE_PRIVATE const int sqlite3one;
6465 #else
6466 SQLITE_PRIVATE const int sqlite3one;
6467 #endif
6468 #if defined(i386) || defined(__i386__) || defined(_M_IX86)
6469 # define SQLITE_BIGENDIAN    0
6470 # define SQLITE_LITTLEENDIAN 1
6471 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6472 #else
6473 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6474 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6475 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6476 #endif
6477
6478 /*
6479 ** Constants for the largest and smallest possible 64-bit signed integers.
6480 ** These macros are designed to work correctly on both 32-bit and 64-bit
6481 ** compilers.
6482 */
6483 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6484 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6485
6486 /*
6487 ** An instance of the following structure is used to store the busy-handler
6488 ** callback for a given sqlite handle. 
6489 **
6490 ** The sqlite.busyHandler member of the sqlite struct contains the busy
6491 ** callback for the database handle. Each pager opened via the sqlite
6492 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6493 ** callback is currently invoked only from within pager.c.
6494 */
6495 typedef struct BusyHandler BusyHandler;
6496 struct BusyHandler {
6497   int (*xFunc)(void *,int);  /* The busy callback */
6498   void *pArg;                /* First arg to busy callback */
6499   int nBusy;                 /* Incremented with each busy call */
6500 };
6501
6502 /*
6503 ** Name of the master database table.  The master database table
6504 ** is a special table that holds the names and attributes of all
6505 ** user tables and indices.
6506 */
6507 #define MASTER_NAME       "sqlite_master"
6508 #define TEMP_MASTER_NAME  "sqlite_temp_master"
6509
6510 /*
6511 ** The root-page of the master database table.
6512 */
6513 #define MASTER_ROOT       1
6514
6515 /*
6516 ** The name of the schema table.
6517 */
6518 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6519
6520 /*
6521 ** A convenience macro that returns the number of elements in
6522 ** an array.
6523 */
6524 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
6525
6526 /*
6527 ** Forward references to structures
6528 */
6529 typedef struct AggInfo AggInfo;
6530 typedef struct AuthContext AuthContext;
6531 typedef struct Bitvec Bitvec;
6532 typedef struct CollSeq CollSeq;
6533 typedef struct Column Column;
6534 typedef struct Db Db;
6535 typedef struct Schema Schema;
6536 typedef struct Expr Expr;
6537 typedef struct ExprList ExprList;
6538 typedef struct FKey FKey;
6539 typedef struct FuncDef FuncDef;
6540 typedef struct IdList IdList;
6541 typedef struct Index Index;
6542 typedef struct KeyClass KeyClass;
6543 typedef struct KeyInfo KeyInfo;
6544 typedef struct Module Module;
6545 typedef struct NameContext NameContext;
6546 typedef struct Parse Parse;
6547 typedef struct Select Select;
6548 typedef struct SrcList SrcList;
6549 typedef struct StrAccum StrAccum;
6550 typedef struct Table Table;
6551 typedef struct TableLock TableLock;
6552 typedef struct Token Token;
6553 typedef struct TriggerStack TriggerStack;
6554 typedef struct TriggerStep TriggerStep;
6555 typedef struct Trigger Trigger;
6556 typedef struct WhereInfo WhereInfo;
6557 typedef struct WhereLevel WhereLevel;
6558
6559 /*
6560 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
6561 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
6562 ** pointer types (i.e. FuncDef) defined above.
6563 */
6564 /************** Include btree.h in the middle of sqliteInt.h *****************/
6565 /************** Begin file btree.h *******************************************/
6566 /*
6567 ** 2001 September 15
6568 **
6569 ** The author disclaims copyright to this source code.  In place of
6570 ** a legal notice, here is a blessing:
6571 **
6572 **    May you do good and not evil.
6573 **    May you find forgiveness for yourself and forgive others.
6574 **    May you share freely, never taking more than you give.
6575 **
6576 *************************************************************************
6577 ** This header file defines the interface that the sqlite B-Tree file
6578 ** subsystem.  See comments in the source code for a detailed description
6579 ** of what each interface routine does.
6580 **
6581 ** @(#) $Id: btree.h,v 1.98 2008/04/26 13:39:47 drh Exp $
6582 */
6583 #ifndef _BTREE_H_
6584 #define _BTREE_H_
6585
6586 /* TODO: This definition is just included so other modules compile. It
6587 ** needs to be revisited.
6588 */
6589 #define SQLITE_N_BTREE_META 10
6590
6591 /*
6592 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
6593 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
6594 */
6595 #ifndef SQLITE_DEFAULT_AUTOVACUUM
6596   #define SQLITE_DEFAULT_AUTOVACUUM 0
6597 #endif
6598
6599 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
6600 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
6601 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
6602
6603 /*
6604 ** Forward declarations of structure
6605 */
6606 typedef struct Btree Btree;
6607 typedef struct BtCursor BtCursor;
6608 typedef struct BtShared BtShared;
6609 typedef struct BtreeMutexArray BtreeMutexArray;
6610
6611 /*
6612 ** This structure records all of the Btrees that need to hold
6613 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
6614 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
6615 ** we can always lock and unlock them all quickly.
6616 */
6617 struct BtreeMutexArray {
6618   int nMutex;
6619   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
6620 };
6621
6622
6623 SQLITE_PRIVATE int sqlite3BtreeOpen(
6624   const char *zFilename,   /* Name of database file to open */
6625   sqlite3 *db,             /* Associated database connection */
6626   Btree **,                /* Return open Btree* here */
6627   int flags,               /* Flags */
6628   int vfsFlags             /* Flags passed through to VFS open */
6629 );
6630
6631 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
6632 ** following values.
6633 **
6634 ** NOTE:  These values must match the corresponding PAGER_ values in
6635 ** pager.h.
6636 */
6637 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
6638 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
6639 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
6640 #define BTREE_READONLY      8  /* Open the database in read-only mode */
6641 #define BTREE_READWRITE    16  /* Open for both reading and writing */
6642 #define BTREE_CREATE       32  /* Create the database if it does not exist */
6643
6644 /* Additional values for the 4th argument of sqlite3BtreeOpen that
6645 ** are not associated with PAGER_ values.
6646 */
6647 #define BTREE_PRIVATE      64  /* Never share with other connections */
6648
6649 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
6650 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
6651 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
6652 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
6653 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
6654 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6655 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
6656 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6657 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
6658 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
6659 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
6660 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
6661 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
6662 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
6663 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
6664 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
6665 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
6666 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
6667 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
6668 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
6669 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
6670 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
6671 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
6672 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
6673 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
6674
6675 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
6676 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
6677 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
6678 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
6679
6680 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
6681
6682 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
6683 ** of the following flags:
6684 */
6685 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
6686 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
6687 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
6688
6689 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
6690 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int);
6691 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
6692 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
6693 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
6694
6695 struct UnpackedRecord;  /* Forward declaration.  Definition in vdbeaux.c. */
6696
6697 SQLITE_PRIVATE int sqlite3BtreeCursor(
6698   Btree*,                              /* BTree containing table to open */
6699   int iTable,                          /* Index of root page */
6700   int wrFlag,                          /* 1 for writing.  0 for read-only */
6701   struct KeyInfo*,                     /* First argument to compare function */
6702   BtCursor *pCursor                    /* Space to write cursor structure */
6703 );
6704 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
6705
6706 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
6707 SQLITE_PRIVATE int sqlite3BtreeMoveto(
6708   BtCursor*,
6709   const void *pKey,
6710   struct UnpackedRecord *pUnKey,
6711   i64 nKey,
6712   int bias,
6713   int *pRes
6714 );
6715 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
6716 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
6717                                   const void *pData, int nData,
6718                                   int nZero, int bias);
6719 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
6720 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
6721 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
6722 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
6723 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
6724 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
6725 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
6726 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
6727 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
6728 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
6729 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
6730 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
6731 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
6732
6733 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
6734 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
6735
6736 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
6737 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
6738
6739 #ifdef SQLITE_TEST
6740 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
6741 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
6742 SQLITE_PRIVATE int sqlite3BtreePageDump(Btree*, int, int recursive);
6743 #endif
6744
6745 /*
6746 ** If we are not using shared cache, then there is no need to
6747 ** use mutexes to access the BtShared structures.  So make the
6748 ** Enter and Leave procedures no-ops.
6749 */
6750 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
6751 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
6752 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
6753 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
6754 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
6755 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
6756 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
6757 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
6758 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
6759 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
6760 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
6761 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
6762 #else
6763 # define sqlite3BtreeEnter(X)
6764 # define sqlite3BtreeLeave(X)
6765 # define sqlite3BtreeHoldsMutex(X) 1
6766 # define sqlite3BtreeEnterCursor(X)
6767 # define sqlite3BtreeLeaveCursor(X)
6768 # define sqlite3BtreeEnterAll(X)
6769 # define sqlite3BtreeLeaveAll(X)
6770 # define sqlite3BtreeHoldsAllMutexes(X) 1
6771 # define sqlite3BtreeMutexArrayEnter(X)
6772 # define sqlite3BtreeMutexArrayLeave(X)
6773 # define sqlite3BtreeMutexArrayInsert(X,Y)
6774 #endif
6775
6776
6777 #endif /* _BTREE_H_ */
6778
6779 /************** End of btree.h ***********************************************/
6780 /************** Continuing where we left off in sqliteInt.h ******************/
6781 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
6782 /************** Begin file vdbe.h ********************************************/
6783 /*
6784 ** 2001 September 15
6785 **
6786 ** The author disclaims copyright to this source code.  In place of
6787 ** a legal notice, here is a blessing:
6788 **
6789 **    May you do good and not evil.
6790 **    May you find forgiveness for yourself and forgive others.
6791 **    May you share freely, never taking more than you give.
6792 **
6793 *************************************************************************
6794 ** Header file for the Virtual DataBase Engine (VDBE)
6795 **
6796 ** This header defines the interface to the virtual database engine
6797 ** or VDBE.  The VDBE implements an abstract machine that runs a
6798 ** simple program to access and modify the underlying database.
6799 **
6800 ** $Id: vdbe.h,v 1.131 2008/05/01 17:03:49 drh Exp $
6801 */
6802 #ifndef _SQLITE_VDBE_H_
6803 #define _SQLITE_VDBE_H_
6804
6805 /*
6806 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
6807 ** in the source file sqliteVdbe.c are allowed to see the insides
6808 ** of this structure.
6809 */
6810 typedef struct Vdbe Vdbe;
6811
6812 /*
6813 ** The names of the following types declared in vdbeInt.h are required
6814 ** for the VdbeOp definition.
6815 */
6816 typedef struct VdbeFunc VdbeFunc;
6817 typedef struct Mem Mem;
6818 typedef struct UnpackedRecord UnpackedRecord;
6819
6820 /*
6821 ** A single instruction of the virtual machine has an opcode
6822 ** and as many as three operands.  The instruction is recorded
6823 ** as an instance of the following structure:
6824 */
6825 struct VdbeOp {
6826   u8 opcode;          /* What operation to perform */
6827   signed char p4type; /* One of the P4_xxx constants for p4 */
6828   u8 opflags;         /* Not currently used */
6829   u8 p5;              /* Fifth parameter is an unsigned character */
6830   int p1;             /* First operand */
6831   int p2;             /* Second parameter (often the jump destination) */
6832   int p3;             /* The third parameter */
6833   union {             /* forth parameter */
6834     int i;                 /* Integer value if p4type==P4_INT32 */
6835     void *p;               /* Generic pointer */
6836     char *z;               /* Pointer to data for string (char array) types */
6837     i64 *pI64;             /* Used when p4type is P4_INT64 */
6838     double *pReal;         /* Used when p4type is P4_REAL */
6839     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
6840     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
6841     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
6842     Mem *pMem;             /* Used when p4type is P4_MEM */
6843     sqlite3_vtab *pVtab;   /* Used when p4type is P4_VTAB */
6844     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
6845   } p4;
6846 #ifdef SQLITE_DEBUG
6847   char *zComment;     /* Comment to improve readability */
6848 #endif
6849 #ifdef VDBE_PROFILE
6850   int cnt;            /* Number of times this instruction was executed */
6851   long long cycles;   /* Total time spend executing this instruction */
6852 #endif
6853 };
6854 typedef struct VdbeOp VdbeOp;
6855
6856 /*
6857 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
6858 ** it takes up less space.
6859 */
6860 struct VdbeOpList {
6861   u8 opcode;          /* What operation to perform */
6862   signed char p1;     /* First operand */
6863   signed char p2;     /* Second parameter (often the jump destination) */
6864   signed char p3;     /* Third parameter */
6865 };
6866 typedef struct VdbeOpList VdbeOpList;
6867
6868 /*
6869 ** Allowed values of VdbeOp.p3type
6870 */
6871 #define P4_NOTUSED    0   /* The P4 parameter is not used */
6872 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
6873 #define P4_STATIC   (-2)  /* Pointer to a static string */
6874 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
6875 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
6876 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
6877 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
6878 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
6879 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
6880 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
6881 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
6882 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
6883 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
6884 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
6885
6886 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
6887 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
6888 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
6889 ** gets freed when the Vdbe is finalized so it still should be obtained
6890 ** from a single sqliteMalloc().  But no copy is made and the calling
6891 ** function should *not* try to free the KeyInfo.
6892 */
6893 #define P4_KEYINFO_HANDOFF (-9)
6894
6895 /*
6896 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
6897 ** number of columns of data returned by the statement.
6898 */
6899 #define COLNAME_NAME     0
6900 #define COLNAME_DECLTYPE 1
6901 #define COLNAME_DATABASE 2
6902 #define COLNAME_TABLE    3
6903 #define COLNAME_COLUMN   4
6904 #ifdef SQLITE_ENABLE_COLUMN_METADATA
6905 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
6906 #else
6907 # ifdef SQLITE_OMIT_DECLTYPE
6908 #   define COLNAME_N      1      /* Store only the name */
6909 # else
6910 #   define COLNAME_N      2      /* Store the name and decltype */
6911 # endif
6912 #endif
6913
6914 /*
6915 ** The following macro converts a relative address in the p2 field
6916 ** of a VdbeOp structure into a negative number so that 
6917 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
6918 ** the macro again restores the address.
6919 */
6920 #define ADDR(X)  (-1-(X))
6921
6922 /*
6923 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
6924 ** header file that defines a number for each opcode used by the VDBE.
6925 */
6926 /************** Include opcodes.h in the middle of vdbe.h ********************/
6927 /************** Begin file opcodes.h *****************************************/
6928 /* Automatically generated.  Do not edit */
6929 /* See the mkopcodeh.awk script for details */
6930 #define OP_VNext                                1
6931 #define OP_Affinity                             2
6932 #define OP_Column                               3
6933 #define OP_SetCookie                            4
6934 #define OP_Real                               125   /* same as TK_FLOAT    */
6935 #define OP_Sequence                             5
6936 #define OP_MoveGt                               6
6937 #define OP_Ge                                  72   /* same as TK_GE       */
6938 #define OP_RowKey                               7
6939 #define OP_SCopy                                8
6940 #define OP_Eq                                  68   /* same as TK_EQ       */
6941 #define OP_OpenWrite                            9
6942 #define OP_NotNull                             66   /* same as TK_NOTNULL  */
6943 #define OP_If                                  10
6944 #define OP_ToInt                              141   /* same as TK_TO_INT   */
6945 #define OP_String8                             88   /* same as TK_STRING   */
6946 #define OP_VRowid                              11
6947 #define OP_CollSeq                             12
6948 #define OP_OpenRead                            13
6949 #define OP_Expire                              14
6950 #define OP_AutoCommit                          15
6951 #define OP_Gt                                  69   /* same as TK_GT       */
6952 #define OP_IntegrityCk                         17
6953 #define OP_Sort                                18
6954 #define OP_Copy                                19
6955 #define OP_Trace                               20
6956 #define OP_Function                            21
6957 #define OP_IfNeg                               22
6958 #define OP_And                                 61   /* same as TK_AND      */
6959 #define OP_Subtract                            79   /* same as TK_MINUS    */
6960 #define OP_Noop                                23
6961 #define OP_Return                              24
6962 #define OP_Remainder                           82   /* same as TK_REM      */
6963 #define OP_NewRowid                            25
6964 #define OP_Multiply                            80   /* same as TK_STAR     */
6965 #define OP_Variable                            26
6966 #define OP_String                              27
6967 #define OP_RealAffinity                        28
6968 #define OP_VRename                             29
6969 #define OP_ParseSchema                         30
6970 #define OP_VOpen                               31
6971 #define OP_Close                               32
6972 #define OP_CreateIndex                         33
6973 #define OP_IsUnique                            34
6974 #define OP_NotFound                            35
6975 #define OP_Int64                               36
6976 #define OP_MustBeInt                           37
6977 #define OP_Halt                                38
6978 #define OP_Rowid                               39
6979 #define OP_IdxLT                               40
6980 #define OP_AddImm                              41
6981 #define OP_Statement                           42
6982 #define OP_RowData                             43
6983 #define OP_MemMax                              44
6984 #define OP_Or                                  60   /* same as TK_OR       */
6985 #define OP_NotExists                           45
6986 #define OP_Gosub                               46
6987 #define OP_Divide                              81   /* same as TK_SLASH    */
6988 #define OP_Integer                             47
6989 #define OP_ToNumeric                          140   /* same as TK_TO_NUMERIC*/
6990 #define OP_Prev                                48
6991 #define OP_Concat                              83   /* same as TK_CONCAT   */
6992 #define OP_BitAnd                              74   /* same as TK_BITAND   */
6993 #define OP_VColumn                             49
6994 #define OP_CreateTable                         50
6995 #define OP_Last                                51
6996 #define OP_IsNull                              65   /* same as TK_ISNULL   */
6997 #define OP_IncrVacuum                          52
6998 #define OP_IdxRowid                            53
6999 #define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
7000 #define OP_ResetCount                          54
7001 #define OP_FifoWrite                           55
7002 #define OP_ContextPush                         56
7003 #define OP_DropTrigger                         57
7004 #define OP_DropIndex                           58
7005 #define OP_IdxGE                               59
7006 #define OP_IdxDelete                           62
7007 #define OP_Vacuum                              63
7008 #define OP_MoveLe                              64
7009 #define OP_IfNot                               73
7010 #define OP_DropTable                           84
7011 #define OP_MakeRecord                          85
7012 #define OP_ToBlob                             139   /* same as TK_TO_BLOB  */
7013 #define OP_ResultRow                           86
7014 #define OP_Delete                              89
7015 #define OP_AggFinal                            90
7016 #define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
7017 #define OP_Goto                                91
7018 #define OP_TableLock                           92
7019 #define OP_FifoRead                            93
7020 #define OP_Clear                               94
7021 #define OP_MoveLt                              95
7022 #define OP_Le                                  70   /* same as TK_LE       */
7023 #define OP_VerifyCookie                        96
7024 #define OP_AggStep                             97
7025 #define OP_ToText                             138   /* same as TK_TO_TEXT  */
7026 #define OP_Not                                 16   /* same as TK_NOT      */
7027 #define OP_ToReal                             142   /* same as TK_TO_REAL  */
7028 #define OP_SetNumColumns                       98
7029 #define OP_Transaction                         99
7030 #define OP_VFilter                            100
7031 #define OP_Ne                                  67   /* same as TK_NE       */
7032 #define OP_VDestroy                           101
7033 #define OP_ContextPop                         102
7034 #define OP_BitOr                               75   /* same as TK_BITOR    */
7035 #define OP_Next                               103
7036 #define OP_IdxInsert                          104
7037 #define OP_Lt                                  71   /* same as TK_LT       */
7038 #define OP_Insert                             105
7039 #define OP_Destroy                            106
7040 #define OP_ReadCookie                         107
7041 #define OP_ForceInt                           108
7042 #define OP_LoadAnalysis                       109
7043 #define OP_Explain                            110
7044 #define OP_OpenPseudo                         111
7045 #define OP_OpenEphemeral                      112
7046 #define OP_Null                               113
7047 #define OP_Move                               114
7048 #define OP_Blob                               115
7049 #define OP_Add                                 78   /* same as TK_PLUS     */
7050 #define OP_Rewind                             116
7051 #define OP_MoveGe                             117
7052 #define OP_VBegin                             118
7053 #define OP_VUpdate                            119
7054 #define OP_IfZero                             120
7055 #define OP_BitNot                              87   /* same as TK_BITNOT   */
7056 #define OP_VCreate                            121
7057 #define OP_Found                              122
7058 #define OP_IfPos                              123
7059 #define OP_NullRow                            124
7060
7061 /* The following opcode values are never used */
7062 #define OP_NotUsed_126                        126
7063 #define OP_NotUsed_127                        127
7064 #define OP_NotUsed_128                        128
7065 #define OP_NotUsed_129                        129
7066 #define OP_NotUsed_130                        130
7067 #define OP_NotUsed_131                        131
7068 #define OP_NotUsed_132                        132
7069 #define OP_NotUsed_133                        133
7070 #define OP_NotUsed_134                        134
7071 #define OP_NotUsed_135                        135
7072 #define OP_NotUsed_136                        136
7073 #define OP_NotUsed_137                        137
7074
7075
7076 /* Properties such as "out2" or "jump" that are specified in
7077 ** comments following the "case" for each opcode in the vdbe.c
7078 ** are encoded into bitvectors as follows:
7079 */
7080 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7081 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7082 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7083 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7084 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7085 #define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
7086 #define OPFLG_INITIALIZER {\
7087 /*   0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x02, 0x11, 0x00,\
7088 /*   8 */ 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00,\
7089 /*  16 */ 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00,\
7090 /*  24 */ 0x00, 0x02, 0x02, 0x02, 0x04, 0x00, 0x00, 0x00,\
7091 /*  32 */ 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00, 0x02,\
7092 /*  40 */ 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01, 0x02,\
7093 /*  48 */ 0x01, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x04,\
7094 /*  56 */ 0x00, 0x00, 0x00, 0x11, 0x2c, 0x2c, 0x00, 0x00,\
7095 /*  64 */ 0x11, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7096 /*  72 */ 0x15, 0x05, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
7097 /*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04,\
7098 /*  88 */ 0x02, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x11,\
7099 /*  96 */ 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01,\
7100 /* 104 */ 0x08, 0x00, 0x02, 0x02, 0x05, 0x00, 0x00, 0x00,\
7101 /* 112 */ 0x00, 0x02, 0x00, 0x02, 0x01, 0x11, 0x00, 0x00,\
7102 /* 120 */ 0x05, 0x00, 0x11, 0x05, 0x00, 0x02, 0x00, 0x00,\
7103 /* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7104 /* 136 */ 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,}
7105
7106 /************** End of opcodes.h *********************************************/
7107 /************** Continuing where we left off in vdbe.h ***********************/
7108
7109 /*
7110 ** Prototypes for the VDBE interface.  See comments on the implementation
7111 ** for a description of what each of these routines does.
7112 */
7113 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7114 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7115 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7116 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7117 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7118 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7119 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7120 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7121 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7122 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7123 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7124 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7125 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7126 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7127 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7128 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7129 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7130 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7131 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
7132 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7133 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7134 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7135 #ifdef SQLITE_DEBUG
7136 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7137 #endif
7138 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7139 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*, int);
7140 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7141 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
7142 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7143 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7144 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
7145 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7146
7147 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7148 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int);
7149 #endif
7150 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,void*,int);
7151 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7152 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7153
7154
7155 #ifndef NDEBUG
7156 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7157 # define VdbeComment(X)  sqlite3VdbeComment X
7158 #else
7159 # define VdbeComment(X)
7160 #endif
7161
7162 #endif
7163
7164 /************** End of vdbe.h ************************************************/
7165 /************** Continuing where we left off in sqliteInt.h ******************/
7166 /************** Include pager.h in the middle of sqliteInt.h *****************/
7167 /************** Begin file pager.h *******************************************/
7168 /*
7169 ** 2001 September 15
7170 **
7171 ** The author disclaims copyright to this source code.  In place of
7172 ** a legal notice, here is a blessing:
7173 **
7174 **    May you do good and not evil.
7175 **    May you find forgiveness for yourself and forgive others.
7176 **    May you share freely, never taking more than you give.
7177 **
7178 *************************************************************************
7179 ** This header file defines the interface that the sqlite page cache
7180 ** subsystem.  The page cache subsystem reads and writes a file a page
7181 ** at a time and provides a journal for rollback.
7182 **
7183 ** @(#) $Id: pager.h,v 1.72 2008/05/01 17:03:49 drh Exp $
7184 */
7185
7186 #ifndef _PAGER_H_
7187 #define _PAGER_H_
7188
7189 /*
7190 ** The type used to represent a page number.  The first page in a file
7191 ** is called page 1.  0 is used to represent "not a page".
7192 */
7193 typedef unsigned int Pgno;
7194
7195 /*
7196 ** Each open file is managed by a separate instance of the "Pager" structure.
7197 */
7198 typedef struct Pager Pager;
7199
7200 /*
7201 ** Handle type for pages.
7202 */
7203 typedef struct PgHdr DbPage;
7204
7205 /*
7206 ** Allowed values for the flags parameter to sqlite3PagerOpen().
7207 **
7208 ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
7209 */
7210 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7211 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7212
7213 /*
7214 ** Valid values for the second argument to sqlite3PagerLockingMode().
7215 */
7216 #define PAGER_LOCKINGMODE_QUERY      -1
7217 #define PAGER_LOCKINGMODE_NORMAL      0
7218 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
7219
7220 /*
7221 ** Valid values for the second argument to sqlite3PagerJournalMode().
7222 */
7223 #define PAGER_JOURNALMODE_QUERY      -1
7224 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7225 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7226 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7227
7228 /*
7229 ** See source code comments for a detailed description of the following
7230 ** routines:
7231 */
7232 SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
7233 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
7234 SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
7235 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
7236 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
7237 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7238 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7239 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7240 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7241 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7242 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7243 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7244 SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
7245 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
7246 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7247 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*);
7248 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno);
7249 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
7250 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno, int);
7251 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7252 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7253 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*);
7254 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager*);
7255 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager*);
7256 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager*);
7257 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
7258 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7259 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7260 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7261 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7262 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7263 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7264 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
7265 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7266 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7267 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno);
7268 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
7269 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7270 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7271 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7272 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7273 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7274
7275 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
7276 SQLITE_PRIVATE   int sqlite3PagerReleaseMemory(int);
7277 #endif
7278
7279 #ifdef SQLITE_HAS_CODEC
7280 SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
7281 #endif
7282
7283 #if !defined(NDEBUG) || defined(SQLITE_TEST)
7284 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7285 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7286 #endif
7287
7288 #ifdef SQLITE_TEST
7289 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7290 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7291 #endif
7292
7293 #ifdef SQLITE_TEST
7294 void disable_simulated_io_errors(void);
7295 void enable_simulated_io_errors(void);
7296 #else
7297 # define disable_simulated_io_errors()
7298 # define enable_simulated_io_errors()
7299 #endif
7300
7301 #endif /* _PAGER_H_ */
7302
7303 /************** End of pager.h ***********************************************/
7304 /************** Continuing where we left off in sqliteInt.h ******************/
7305
7306 /************** Include os.h in the middle of sqliteInt.h ********************/
7307 /************** Begin file os.h **********************************************/
7308 /*
7309 ** 2001 September 16
7310 **
7311 ** The author disclaims copyright to this source code.  In place of
7312 ** a legal notice, here is a blessing:
7313 **
7314 **    May you do good and not evil.
7315 **    May you find forgiveness for yourself and forgive others.
7316 **    May you share freely, never taking more than you give.
7317 **
7318 ******************************************************************************
7319 **
7320 ** This header file (together with is companion C source-code file
7321 ** "os.c") attempt to abstract the underlying operating system so that
7322 ** the SQLite library will work on both POSIX and windows systems.
7323 **
7324 ** This header file is #include-ed by sqliteInt.h and thus ends up
7325 ** being included by every source file.
7326 */
7327 #ifndef _SQLITE_OS_H_
7328 #define _SQLITE_OS_H_
7329
7330 /*
7331 ** Figure out if we are dealing with Unix, Windows, or some other
7332 ** operating system.  After the following block of preprocess macros,
7333 ** all of OS_UNIX, OS_WIN, OS_OS2, and OS_OTHER will defined to either
7334 ** 1 or 0.  One of the four will be 1.  The other three will be 0.
7335 */
7336 #if defined(OS_OTHER)
7337 # if OS_OTHER==1
7338 #   undef OS_UNIX
7339 #   define OS_UNIX 0
7340 #   undef OS_WIN
7341 #   define OS_WIN 0
7342 #   undef OS_OS2
7343 #   define OS_OS2 0
7344 # else
7345 #   undef OS_OTHER
7346 # endif
7347 #endif
7348 #if !defined(OS_UNIX) && !defined(OS_OTHER)
7349 # define OS_OTHER 0
7350 # ifndef OS_WIN
7351 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
7352 #     define OS_WIN 1
7353 #     define OS_UNIX 0
7354 #     define OS_OS2 0
7355 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
7356 #     define OS_WIN 0
7357 #     define OS_UNIX 0
7358 #     define OS_OS2 1
7359 #   else
7360 #     define OS_WIN 0
7361 #     define OS_UNIX 1
7362 #     define OS_OS2 0
7363 #  endif
7364 # else
7365 #  define OS_UNIX 0
7366 #  define OS_OS2 0
7367 # endif
7368 #else
7369 # ifndef OS_WIN
7370 #  define OS_WIN 0
7371 # endif
7372 #endif
7373
7374
7375
7376 /*
7377 ** Define the maximum size of a temporary filename
7378 */
7379 #if OS_WIN
7380 # include <windows.h>
7381 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
7382 #elif OS_OS2
7383 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
7384 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
7385 # endif
7386 # define INCL_DOSDATETIME
7387 # define INCL_DOSFILEMGR
7388 # define INCL_DOSERRORS
7389 # define INCL_DOSMISC
7390 # define INCL_DOSPROCESS
7391 # define INCL_DOSMODULEMGR
7392 # define INCL_DOSSEMAPHORES
7393 # include <os2.h>
7394 # include <uconv.h>
7395 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
7396 #else
7397 # define SQLITE_TEMPNAME_SIZE 200
7398 #endif
7399
7400 /* If the SET_FULLSYNC macro is not defined above, then make it
7401 ** a no-op
7402 */
7403 #ifndef SET_FULLSYNC
7404 # define SET_FULLSYNC(x,y)
7405 #endif
7406
7407 /*
7408 ** The default size of a disk sector
7409 */
7410 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
7411 # define SQLITE_DEFAULT_SECTOR_SIZE 512
7412 #endif
7413
7414 /*
7415 ** Temporary files are named starting with this prefix followed by 16 random
7416 ** alphanumeric characters, and no file extension. They are stored in the
7417 ** OS's standard temporary file directory, and are deleted prior to exit.
7418 ** If sqlite is being embedded in another program, you may wish to change the
7419 ** prefix to reflect your program's name, so that if your program exits
7420 ** prematurely, old temporary files can be easily identified. This can be done
7421 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
7422 **
7423 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
7424 ** Mcafee started using SQLite in their anti-virus product and it
7425 ** started putting files with the "sqlite" name in the c:/temp folder.
7426 ** This annoyed many windows users.  Those users would then do a 
7427 ** Google search for "sqlite", find the telephone numbers of the
7428 ** developers and call to wake them up at night and complain.
7429 ** For this reason, the default name prefix is changed to be "sqlite" 
7430 ** spelled backwards.  So the temp files are still identified, but
7431 ** anybody smart enough to figure out the code is also likely smart
7432 ** enough to know that calling the developer will not help get rid
7433 ** of the file.
7434 */
7435 #ifndef SQLITE_TEMP_FILE_PREFIX
7436 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
7437 #endif
7438
7439 /*
7440 ** The following values may be passed as the second argument to
7441 ** sqlite3OsLock(). The various locks exhibit the following semantics:
7442 **
7443 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
7444 ** RESERVED:  A single process may hold a RESERVED lock on a file at
7445 **            any time. Other processes may hold and obtain new SHARED locks.
7446 ** PENDING:   A single process may hold a PENDING lock on a file at
7447 **            any one time. Existing SHARED locks may persist, but no new
7448 **            SHARED locks may be obtained by other processes.
7449 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
7450 **
7451 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
7452 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
7453 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
7454 ** sqlite3OsLock().
7455 */
7456 #define NO_LOCK         0
7457 #define SHARED_LOCK     1
7458 #define RESERVED_LOCK   2
7459 #define PENDING_LOCK    3
7460 #define EXCLUSIVE_LOCK  4
7461
7462 /*
7463 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
7464 **
7465 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
7466 ** those functions are not available.  So we use only LockFile() and
7467 ** UnlockFile().
7468 **
7469 ** LockFile() prevents not just writing but also reading by other processes.
7470 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
7471 ** byte out of a specific range of bytes. The lock byte is obtained at 
7472 ** random so two separate readers can probably access the file at the 
7473 ** same time, unless they are unlucky and choose the same lock byte.
7474 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
7475 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
7476 ** a single byte of the file that is designated as the reserved lock byte.
7477 ** A PENDING_LOCK is obtained by locking a designated byte different from
7478 ** the RESERVED_LOCK byte.
7479 **
7480 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
7481 ** which means we can use reader/writer locks.  When reader/writer locks
7482 ** are used, the lock is placed on the same range of bytes that is used
7483 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
7484 ** will support two or more Win95 readers or two or more WinNT readers.
7485 ** But a single Win95 reader will lock out all WinNT readers and a single
7486 ** WinNT reader will lock out all other Win95 readers.
7487 **
7488 ** The following #defines specify the range of bytes used for locking.
7489 ** SHARED_SIZE is the number of bytes available in the pool from which
7490 ** a random byte is selected for a shared lock.  The pool of bytes for
7491 ** shared locks begins at SHARED_FIRST. 
7492 **
7493 ** These #defines are available in sqlite_aux.h so that adaptors for
7494 ** connecting SQLite to other operating systems can use the same byte
7495 ** ranges for locking.  In particular, the same locking strategy and
7496 ** byte ranges are used for Unix.  This leaves open the possiblity of having
7497 ** clients on win95, winNT, and unix all talking to the same shared file
7498 ** and all locking correctly.  To do so would require that samba (or whatever
7499 ** tool is being used for file sharing) implements locks correctly between
7500 ** windows and unix.  I'm guessing that isn't likely to happen, but by
7501 ** using the same locking range we are at least open to the possibility.
7502 **
7503 ** Locking in windows is manditory.  For this reason, we cannot store
7504 ** actual data in the bytes used for locking.  The pager never allocates
7505 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
7506 ** that all locks will fit on a single page even at the minimum page size.
7507 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
7508 ** is set high so that we don't have to allocate an unused page except
7509 ** for very large databases.  But one should test the page skipping logic 
7510 ** by setting PENDING_BYTE low and running the entire regression suite.
7511 **
7512 ** Changing the value of PENDING_BYTE results in a subtly incompatible
7513 ** file format.  Depending on how it is changed, you might not notice
7514 ** the incompatibility right away, even running a full regression test.
7515 ** The default location of PENDING_BYTE is the first byte past the
7516 ** 1GB boundary.
7517 **
7518 */
7519 #ifndef SQLITE_TEST
7520 #define PENDING_BYTE      0x40000000  /* First byte past the 1GB boundary */
7521 #else
7522 SQLITE_API extern unsigned int sqlite3_pending_byte;
7523 #define PENDING_BYTE sqlite3_pending_byte
7524 #endif
7525
7526 #define RESERVED_BYTE     (PENDING_BYTE+1)
7527 #define SHARED_FIRST      (PENDING_BYTE+2)
7528 #define SHARED_SIZE       510
7529
7530 /* 
7531 ** Functions for accessing sqlite3_file methods 
7532 */
7533 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
7534 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
7535 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
7536 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
7537 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
7538 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
7539 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
7540 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
7541 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id);
7542 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
7543 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
7544 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
7545
7546 /* 
7547 ** Functions for accessing sqlite3_vfs methods 
7548 */
7549 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
7550 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
7551 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int);
7552 SQLITE_PRIVATE int sqlite3OsGetTempname(sqlite3_vfs *, int, char *);
7553 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
7554 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
7555 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
7556 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *, void *, const char *);
7557 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
7558 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
7559 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
7560 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
7561
7562 /*
7563 ** Convenience functions for opening and closing files using 
7564 ** sqlite3_malloc() to obtain space for the file-handle structure.
7565 */
7566 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
7567 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
7568
7569 /*
7570 ** Each OS-specific backend defines an instance of the following
7571 ** structure for returning a pointer to its sqlite3_vfs.  If OS_OTHER
7572 ** is defined (meaning that the application-defined OS interface layer
7573 ** is used) then there is no default VFS.   The application must
7574 ** register one or more VFS structures using sqlite3_vfs_register()
7575 ** before attempting to use SQLite.
7576 */
7577 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void);
7578
7579 #endif /* _SQLITE_OS_H_ */
7580
7581 /************** End of os.h **************************************************/
7582 /************** Continuing where we left off in sqliteInt.h ******************/
7583 /************** Include mutex.h in the middle of sqliteInt.h *****************/
7584 /************** Begin file mutex.h *******************************************/
7585 /*
7586 ** 2007 August 28
7587 **
7588 ** The author disclaims copyright to this source code.  In place of
7589 ** a legal notice, here is a blessing:
7590 **
7591 **    May you do good and not evil.
7592 **    May you find forgiveness for yourself and forgive others.
7593 **    May you share freely, never taking more than you give.
7594 **
7595 *************************************************************************
7596 **
7597 ** This file contains the common header for all mutex implementations.
7598 ** The sqliteInt.h header #includes this file so that it is available
7599 ** to all source files.  We break it out in an effort to keep the code
7600 ** better organized.
7601 **
7602 ** NOTE:  source files should *not* #include this header file directly.
7603 ** Source files should #include the sqliteInt.h file and let that file
7604 ** include this one indirectly.
7605 **
7606 ** $Id: mutex.h,v 1.2 2007/08/30 14:10:30 drh Exp $
7607 */
7608
7609
7610 #ifdef SQLITE_MUTEX_APPDEF
7611 /*
7612 ** If SQLITE_MUTEX_APPDEF is defined, then this whole module is
7613 ** omitted and equivalent functionality must be provided by the
7614 ** application that links against the SQLite library.
7615 */
7616 #else
7617 /*
7618 ** Figure out what version of the code to use.  The choices are
7619 **
7620 **   SQLITE_MUTEX_NOOP         For single-threaded applications that
7621 **                             do not desire error checking.
7622 **
7623 **   SQLITE_MUTEX_NOOP_DEBUG   For single-threaded applications with
7624 **                             error checking to help verify that mutexes
7625 **                             are being used correctly even though they
7626 **                             are not needed.  Used when SQLITE_DEBUG is
7627 **                             defined on single-threaded builds.
7628 **
7629 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
7630 **
7631 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
7632 **
7633 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
7634 */
7635 #define SQLITE_MUTEX_NOOP 1   /* The default */
7636 #if defined(SQLITE_DEBUG) && !SQLITE_THREADSAFE
7637 # undef SQLITE_MUTEX_NOOP
7638 # define SQLITE_MUTEX_NOOP_DEBUG
7639 #endif
7640 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_UNIX
7641 # undef SQLITE_MUTEX_NOOP
7642 # define SQLITE_MUTEX_PTHREADS
7643 #endif
7644 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_WIN
7645 # undef SQLITE_MUTEX_NOOP
7646 # define SQLITE_MUTEX_W32
7647 #endif
7648 #if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_OS2
7649 # undef SQLITE_MUTEX_NOOP
7650 # define SQLITE_MUTEX_OS2
7651 #endif
7652
7653 #ifdef SQLITE_MUTEX_NOOP
7654 /*
7655 ** If this is a no-op implementation, implement everything as macros.
7656 */
7657 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
7658 #define sqlite3_mutex_free(X)
7659 #define sqlite3_mutex_enter(X)
7660 #define sqlite3_mutex_try(X)      SQLITE_OK
7661 #define sqlite3_mutex_leave(X)
7662 #define sqlite3_mutex_held(X)     1
7663 #define sqlite3_mutex_notheld(X)  1
7664 #endif
7665
7666 #endif /* SQLITE_MUTEX_APPDEF */
7667
7668 /************** End of mutex.h ***********************************************/
7669 /************** Continuing where we left off in sqliteInt.h ******************/
7670
7671
7672 /*
7673 ** Each database file to be accessed by the system is an instance
7674 ** of the following structure.  There are normally two of these structures
7675 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
7676 ** aDb[1] is the database file used to hold temporary tables.  Additional
7677 ** databases may be attached.
7678 */
7679 struct Db {
7680   char *zName;         /* Name of this database */
7681   Btree *pBt;          /* The B*Tree structure for this database file */
7682   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
7683   u8 safety_level;     /* How aggressive at synching data to disk */
7684   void *pAux;               /* Auxiliary data.  Usually NULL */
7685   void (*xFreeAux)(void*);  /* Routine to free pAux */
7686   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
7687 };
7688
7689 /*
7690 ** An instance of the following structure stores a database schema.
7691 **
7692 ** If there are no virtual tables configured in this schema, the
7693 ** Schema.db variable is set to NULL. After the first virtual table
7694 ** has been added, it is set to point to the database connection 
7695 ** used to create the connection. Once a virtual table has been
7696 ** added to the Schema structure and the Schema.db variable populated, 
7697 ** only that database connection may use the Schema to prepare 
7698 ** statements.
7699 */
7700 struct Schema {
7701   int schema_cookie;   /* Database schema version number for this file */
7702   Hash tblHash;        /* All tables indexed by name */
7703   Hash idxHash;        /* All (named) indices indexed by name */
7704   Hash trigHash;       /* All triggers indexed by name */
7705   Hash aFKey;          /* Foreign keys indexed by to-table */
7706   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
7707   u8 file_format;      /* Schema format version for this file */
7708   u8 enc;              /* Text encoding used by this database */
7709   u16 flags;           /* Flags associated with this schema */
7710   int cache_size;      /* Number of pages to use in the cache */
7711 #ifndef SQLITE_OMIT_VIRTUALTABLE
7712   sqlite3 *db;         /* "Owner" connection. See comment above */
7713 #endif
7714 };
7715
7716 /*
7717 ** These macros can be used to test, set, or clear bits in the 
7718 ** Db.flags field.
7719 */
7720 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
7721 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
7722 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
7723 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
7724
7725 /*
7726 ** Allowed values for the DB.flags field.
7727 **
7728 ** The DB_SchemaLoaded flag is set after the database schema has been
7729 ** read into internal hash tables.
7730 **
7731 ** DB_UnresetViews means that one or more views have column names that
7732 ** have been filled out.  If the schema changes, these column names might
7733 ** changes and so the view will need to be reset.
7734 */
7735 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
7736 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
7737 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
7738
7739 /*
7740 ** The number of different kinds of things that can be limited
7741 ** using the sqlite3_limit() interface.
7742 */
7743 #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
7744
7745 /*
7746 ** Each database is an instance of the following structure.
7747 **
7748 ** The sqlite.lastRowid records the last insert rowid generated by an
7749 ** insert statement.  Inserts on views do not affect its value.  Each
7750 ** trigger has its own context, so that lastRowid can be updated inside
7751 ** triggers as usual.  The previous value will be restored once the trigger
7752 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
7753 ** longer (since after version 2.8.12) reset to -1.
7754 **
7755 ** The sqlite.nChange does not count changes within triggers and keeps no
7756 ** context.  It is reset at start of sqlite3_exec.
7757 ** The sqlite.lsChange represents the number of changes made by the last
7758 ** insert, update, or delete statement.  It remains constant throughout the
7759 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
7760 ** context stack just like lastRowid so that the count of changes
7761 ** within a trigger is not seen outside the trigger.  Changes to views do not
7762 ** affect the value of lsChange.
7763 ** The sqlite.csChange keeps track of the number of current changes (since
7764 ** the last statement) and is used to update sqlite_lsChange.
7765 **
7766 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
7767 ** store the most recent error code and, if applicable, string. The
7768 ** internal function sqlite3Error() is used to set these variables
7769 ** consistently.
7770 */
7771 struct sqlite3 {
7772   sqlite3_vfs *pVfs;            /* OS Interface */
7773   int nDb;                      /* Number of backends currently in use */
7774   Db *aDb;                      /* All backends */
7775   int flags;                    /* Miscellanous flags. See below */
7776   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
7777   int errCode;                  /* Most recent error code (SQLITE_*) */
7778   int errMask;                  /* & result codes with this before returning */
7779   u8 autoCommit;                /* The auto-commit flag. */
7780   u8 temp_store;                /* 1: file 2: memory 0: default */
7781   u8 mallocFailed;              /* True if we have seen a malloc failure */
7782   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
7783   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
7784   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
7785   int nextPagesize;             /* Pagesize after VACUUM if >0 */
7786   int nTable;                   /* Number of tables in the database */
7787   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
7788   i64 lastRowid;                /* ROWID of most recent insert (see above) */
7789   i64 priorNewRowid;            /* Last randomly generated ROWID */
7790   int magic;                    /* Magic number for detect library misuse */
7791   int nChange;                  /* Value returned by sqlite3_changes() */
7792   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
7793   sqlite3_mutex *mutex;         /* Connection mutex */
7794   int aLimit[SQLITE_N_LIMIT];   /* Limits */
7795   struct sqlite3InitInfo {      /* Information used during initialization */
7796     int iDb;                    /* When back is being initialized */
7797     int newTnum;                /* Rootpage of table being initialized */
7798     u8 busy;                    /* TRUE if currently initializing */
7799   } init;
7800   int nExtension;               /* Number of loaded extensions */
7801   void **aExtension;            /* Array of shared libraray handles */
7802   struct Vdbe *pVdbe;           /* List of active virtual machines */
7803   int activeVdbeCnt;            /* Number of vdbes currently executing */
7804   void (*xTrace)(void*,const char*);        /* Trace function */
7805   void *pTraceArg;                          /* Argument to the trace function */
7806   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
7807   void *pProfileArg;                        /* Argument to profile function */
7808   void *pCommitArg;                 /* Argument to xCommitCallback() */   
7809   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
7810   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
7811   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
7812   void *pUpdateArg;
7813   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
7814   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
7815   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
7816   void *pCollNeededArg;
7817   sqlite3_value *pErr;          /* Most recent error message */
7818   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
7819   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
7820   union {
7821     int isInterrupted;          /* True if sqlite3_interrupt has been called */
7822     double notUsed1;            /* Spacer */
7823   } u1;
7824 #ifndef SQLITE_OMIT_AUTHORIZATION
7825   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
7826                                 /* Access authorization function */
7827   void *pAuthArg;               /* 1st argument to the access auth function */
7828 #endif
7829 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
7830   int (*xProgress)(void *);     /* The progress callback */
7831   void *pProgressArg;           /* Argument to the progress callback */
7832   int nProgressOps;             /* Number of opcodes for progress callback */
7833 #endif
7834 #ifndef SQLITE_OMIT_VIRTUALTABLE
7835   Hash aModule;                 /* populated by sqlite3_create_module() */
7836   Table *pVTab;                 /* vtab with active Connect/Create method */
7837   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
7838   int nVTrans;                  /* Allocated size of aVTrans */
7839 #endif
7840   Hash aFunc;                   /* All functions that can be in SQL exprs */
7841   Hash aCollSeq;                /* All collating sequences */
7842   BusyHandler busyHandler;      /* Busy callback */
7843   int busyTimeout;              /* Busy handler timeout, in msec */
7844   Db aDbStatic[2];              /* Static space for the 2 default backends */
7845 #ifdef SQLITE_SSE
7846   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
7847 #endif
7848 };
7849
7850 /*
7851 ** A macro to discover the encoding of a database.
7852 */
7853 #define ENC(db) ((db)->aDb[0].pSchema->enc)
7854
7855 /*
7856 ** Possible values for the sqlite.flags and or Db.flags fields.
7857 **
7858 ** On sqlite.flags, the SQLITE_InTrans value means that we have
7859 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
7860 ** transaction is active on that particular database file.
7861 */
7862 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
7863 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
7864 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
7865 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
7866 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
7867 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
7868                                           /*   DELETE, or UPDATE and return */
7869                                           /*   the count using a callback. */
7870 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
7871                                           /*   result set is empty */
7872 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
7873 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
7874 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
7875 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
7876                                           ** accessing read-only databases */
7877 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
7878 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
7879 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
7880 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
7881 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
7882
7883 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
7884 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
7885 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
7886
7887 /*
7888 ** Possible values for the sqlite.magic field.
7889 ** The numbers are obtained at random and have no special meaning, other
7890 ** than being distinct from one another.
7891 */
7892 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
7893 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
7894 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
7895 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
7896 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
7897
7898 /*
7899 ** Each SQL function is defined by an instance of the following
7900 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
7901 ** hash table.  When multiple functions have the same name, the hash table
7902 ** points to a linked list of these structures.
7903 */
7904 struct FuncDef {
7905   i16 nArg;            /* Number of arguments.  -1 means unlimited */
7906   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
7907   u8 needCollSeq;      /* True if sqlite3GetFuncCollSeq() might be called */
7908   u8 flags;            /* Some combination of SQLITE_FUNC_* */
7909   void *pUserData;     /* User data parameter */
7910   FuncDef *pNext;      /* Next function with same name */
7911   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
7912   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
7913   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
7914   char zName[1];       /* SQL name of the function.  MUST BE LAST */
7915 };
7916
7917 /*
7918 ** Each SQLite module (virtual table definition) is defined by an
7919 ** instance of the following structure, stored in the sqlite3.aModule
7920 ** hash table.
7921 */
7922 struct Module {
7923   const sqlite3_module *pModule;       /* Callback pointers */
7924   const char *zName;                   /* Name passed to create_module() */
7925   void *pAux;                          /* pAux passed to create_module() */
7926   void (*xDestroy)(void *);            /* Module destructor function */
7927 };
7928
7929 /*
7930 ** Possible values for FuncDef.flags
7931 */
7932 #define SQLITE_FUNC_LIKE   0x01  /* Candidate for the LIKE optimization */
7933 #define SQLITE_FUNC_CASE   0x02  /* Case-sensitive LIKE-type function */
7934 #define SQLITE_FUNC_EPHEM  0x04  /* Ephermeral.  Delete with VDBE */
7935
7936 /*
7937 ** information about each column of an SQL table is held in an instance
7938 ** of this structure.
7939 */
7940 struct Column {
7941   char *zName;     /* Name of this column */
7942   Expr *pDflt;     /* Default value of this column */
7943   char *zType;     /* Data type for this column */
7944   char *zColl;     /* Collating sequence.  If NULL, use the default */
7945   u8 notNull;      /* True if there is a NOT NULL constraint */
7946   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
7947   char affinity;   /* One of the SQLITE_AFF_... values */
7948 #ifndef SQLITE_OMIT_VIRTUALTABLE
7949   u8 isHidden;     /* True if this column is 'hidden' */
7950 #endif
7951 };
7952
7953 /*
7954 ** A "Collating Sequence" is defined by an instance of the following
7955 ** structure. Conceptually, a collating sequence consists of a name and
7956 ** a comparison routine that defines the order of that sequence.
7957 **
7958 ** There may two seperate implementations of the collation function, one
7959 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
7960 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
7961 ** native byte order. When a collation sequence is invoked, SQLite selects
7962 ** the version that will require the least expensive encoding
7963 ** translations, if any.
7964 **
7965 ** The CollSeq.pUser member variable is an extra parameter that passed in
7966 ** as the first argument to the UTF-8 comparison function, xCmp.
7967 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
7968 ** xCmp16.
7969 **
7970 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
7971 ** collating sequence is undefined.  Indices built on an undefined
7972 ** collating sequence may not be read or written.
7973 */
7974 struct CollSeq {
7975   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
7976   u8 enc;               /* Text encoding handled by xCmp() */
7977   u8 type;              /* One of the SQLITE_COLL_... values below */
7978   void *pUser;          /* First argument to xCmp() */
7979   int (*xCmp)(void*,int, const void*, int, const void*);
7980   void (*xDel)(void*);  /* Destructor for pUser */
7981 };
7982
7983 /*
7984 ** Allowed values of CollSeq flags:
7985 */
7986 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
7987 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
7988 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
7989 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
7990
7991 /*
7992 ** A sort order can be either ASC or DESC.
7993 */
7994 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
7995 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
7996
7997 /*
7998 ** Column affinity types.
7999 **
8000 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8001 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8002 ** the speed a little by number the values consecutively.  
8003 **
8004 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
8005 ** when multiple affinity types are concatenated into a string and
8006 ** used as the P4 operand, they will be more readable.
8007 **
8008 ** Note also that the numeric types are grouped together so that testing
8009 ** for a numeric type is a single comparison.
8010 */
8011 #define SQLITE_AFF_TEXT     'a'
8012 #define SQLITE_AFF_NONE     'b'
8013 #define SQLITE_AFF_NUMERIC  'c'
8014 #define SQLITE_AFF_INTEGER  'd'
8015 #define SQLITE_AFF_REAL     'e'
8016
8017 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8018
8019 /*
8020 ** The SQLITE_AFF_MASK values masks off the significant bits of an
8021 ** affinity value. 
8022 */
8023 #define SQLITE_AFF_MASK     0x67
8024
8025 /*
8026 ** Additional bit values that can be ORed with an affinity without
8027 ** changing the affinity.
8028 */
8029 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8030 #define SQLITE_NULLEQUAL    0x10  /* compare NULLs equal */
8031 #define SQLITE_STOREP2      0x80  /* Store result in reg[P2] rather than jump */
8032
8033 /*
8034 ** Each SQL table is represented in memory by an instance of the
8035 ** following structure.
8036 **
8037 ** Table.zName is the name of the table.  The case of the original
8038 ** CREATE TABLE statement is stored, but case is not significant for
8039 ** comparisons.
8040 **
8041 ** Table.nCol is the number of columns in this table.  Table.aCol is a
8042 ** pointer to an array of Column structures, one for each column.
8043 **
8044 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8045 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8046 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8047 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8048 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8049 ** is generated for each row of the table.  Table.hasPrimKey is true if
8050 ** the table has any PRIMARY KEY, INTEGER or otherwise.
8051 **
8052 ** Table.tnum is the page number for the root BTree page of the table in the
8053 ** database file.  If Table.iDb is the index of the database table backend
8054 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8055 ** holds temporary tables and indices.  If Table.isEphem
8056 ** is true, then the table is stored in a file that is automatically deleted
8057 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
8058 ** refers VDBE cursor number that holds the table open, not to the root
8059 ** page number.  Transient tables are used to hold the results of a
8060 ** sub-query that appears instead of a real table name in the FROM clause 
8061 ** of a SELECT statement.
8062 */
8063 struct Table {
8064   char *zName;     /* Name of the table */
8065   int nCol;        /* Number of columns in this table */
8066   Column *aCol;    /* Information about each column */
8067   int iPKey;       /* If not less then 0, use aCol[iPKey] as the primary key */
8068   Index *pIndex;   /* List of SQL indexes on this table. */
8069   int tnum;        /* Root BTree node for this table (see note above) */
8070   Select *pSelect; /* NULL for tables.  Points to definition if a view. */
8071   int nRef;          /* Number of pointers to this Table */
8072   Trigger *pTrigger; /* List of SQL triggers on this table */
8073   FKey *pFKey;       /* Linked list of all foreign keys in this table */
8074   char *zColAff;     /* String defining the affinity of each column */
8075 #ifndef SQLITE_OMIT_CHECK
8076   Expr *pCheck;      /* The AND of all CHECK constraints */
8077 #endif
8078 #ifndef SQLITE_OMIT_ALTERTABLE
8079   int addColOffset;  /* Offset in CREATE TABLE statement to add a new column */
8080 #endif
8081   u8 readOnly;     /* True if this table should not be written by the user */
8082   u8 isEphem;      /* True if created using OP_OpenEphermeral */
8083   u8 hasPrimKey;   /* True if there exists a primary key */
8084   u8 keyConf;      /* What to do in case of uniqueness conflict on iPKey */
8085   u8 autoInc;      /* True if the integer primary key is autoincrement */
8086 #ifndef SQLITE_OMIT_VIRTUALTABLE
8087   u8 isVirtual;             /* True if this is a virtual table */
8088   u8 isCommit;              /* True once the CREATE TABLE has been committed */
8089   Module *pMod;             /* Pointer to the implementation of the module */
8090   sqlite3_vtab *pVtab;      /* Pointer to the module instance */
8091   int nModuleArg;           /* Number of arguments to the module */
8092   char **azModuleArg;       /* Text of all module args. [0] is module name */
8093 #endif
8094   Schema *pSchema;          /* Schema that contains this table */
8095 };
8096
8097 /*
8098 ** Test to see whether or not a table is a virtual table.  This is
8099 ** done as a macro so that it will be optimized out when virtual
8100 ** table support is omitted from the build.
8101 */
8102 #ifndef SQLITE_OMIT_VIRTUALTABLE
8103 #  define IsVirtual(X)      ((X)->isVirtual)
8104 #  define IsHiddenColumn(X) ((X)->isHidden)
8105 #else
8106 #  define IsVirtual(X)      0
8107 #  define IsHiddenColumn(X) 0
8108 #endif
8109
8110 /*
8111 ** Each foreign key constraint is an instance of the following structure.
8112 **
8113 ** A foreign key is associated with two tables.  The "from" table is
8114 ** the table that contains the REFERENCES clause that creates the foreign
8115 ** key.  The "to" table is the table that is named in the REFERENCES clause.
8116 ** Consider this example:
8117 **
8118 **     CREATE TABLE ex1(
8119 **       a INTEGER PRIMARY KEY,
8120 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
8121 **     );
8122 **
8123 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8124 **
8125 ** Each REFERENCES clause generates an instance of the following structure
8126 ** which is attached to the from-table.  The to-table need not exist when
8127 ** the from-table is created.  The existance of the to-table is not checked
8128 ** until an attempt is made to insert data into the from-table.
8129 **
8130 ** The sqlite.aFKey hash table stores pointers to this structure
8131 ** given the name of a to-table.  For each to-table, all foreign keys
8132 ** associated with that table are on a linked list using the FKey.pNextTo
8133 ** field.
8134 */
8135 struct FKey {
8136   Table *pFrom;     /* The table that constains the REFERENCES clause */
8137   FKey *pNextFrom;  /* Next foreign key in pFrom */
8138   char *zTo;        /* Name of table that the key points to */
8139   FKey *pNextTo;    /* Next foreign key that points to zTo */
8140   int nCol;         /* Number of columns in this key */
8141   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
8142     int iFrom;         /* Index of column in pFrom */
8143     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
8144   } *aCol;          /* One entry for each of nCol column s */
8145   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
8146   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
8147   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
8148   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
8149 };
8150
8151 /*
8152 ** SQLite supports many different ways to resolve a constraint
8153 ** error.  ROLLBACK processing means that a constraint violation
8154 ** causes the operation in process to fail and for the current transaction
8155 ** to be rolled back.  ABORT processing means the operation in process
8156 ** fails and any prior changes from that one operation are backed out,
8157 ** but the transaction is not rolled back.  FAIL processing means that
8158 ** the operation in progress stops and returns an error code.  But prior
8159 ** changes due to the same operation are not backed out and no rollback
8160 ** occurs.  IGNORE means that the particular row that caused the constraint
8161 ** error is not inserted or updated.  Processing continues and no error
8162 ** is returned.  REPLACE means that preexisting database rows that caused
8163 ** a UNIQUE constraint violation are removed so that the new insert or
8164 ** update can proceed.  Processing continues and no error is reported.
8165 **
8166 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
8167 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
8168 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
8169 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
8170 ** referenced table row is propagated into the row that holds the
8171 ** foreign key.
8172 ** 
8173 ** The following symbolic values are used to record which type
8174 ** of action to take.
8175 */
8176 #define OE_None     0   /* There is no constraint to check */
8177 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
8178 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
8179 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
8180 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
8181 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
8182
8183 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
8184 #define OE_SetNull  7   /* Set the foreign key value to NULL */
8185 #define OE_SetDflt  8   /* Set the foreign key value to its default */
8186 #define OE_Cascade  9   /* Cascade the changes */
8187
8188 #define OE_Default  99  /* Do whatever the default action is */
8189
8190
8191 /*
8192 ** An instance of the following structure is passed as the first
8193 ** argument to sqlite3VdbeKeyCompare and is used to control the 
8194 ** comparison of the two index keys.
8195 **
8196 ** If the KeyInfo.incrKey value is true and the comparison would
8197 ** otherwise be equal, then return a result as if the second key
8198 ** were larger.
8199 */
8200 struct KeyInfo {
8201   sqlite3 *db;        /* The database connection */
8202   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
8203   u8 incrKey;         /* Increase 2nd key by epsilon before comparison */
8204   u8 prefixIsEqual;   /* Treat a prefix as equal */
8205   int nField;         /* Number of entries in aColl[] */
8206   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
8207   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8208 };
8209
8210 /*
8211 ** Each SQL index is represented in memory by an
8212 ** instance of the following structure.
8213 **
8214 ** The columns of the table that are to be indexed are described
8215 ** by the aiColumn[] field of this structure.  For example, suppose
8216 ** we have the following table and index:
8217 **
8218 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
8219 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
8220 **
8221 ** In the Table structure describing Ex1, nCol==3 because there are
8222 ** three columns in the table.  In the Index structure describing
8223 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8224 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
8225 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8226 ** The second column to be indexed (c1) has an index of 0 in
8227 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8228 **
8229 ** The Index.onError field determines whether or not the indexed columns
8230 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
8231 ** it means this is not a unique index.  Otherwise it is a unique index
8232 ** and the value of Index.onError indicate the which conflict resolution 
8233 ** algorithm to employ whenever an attempt is made to insert a non-unique
8234 ** element.
8235 */
8236 struct Index {
8237   char *zName;     /* Name of this index */
8238   int nColumn;     /* Number of columns in the table used by this index */
8239   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
8240   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
8241   Table *pTable;   /* The SQL table being indexed */
8242   int tnum;        /* Page containing root of this index in database file */
8243   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
8244   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
8245   char *zColAff;   /* String defining the affinity of each column */
8246   Index *pNext;    /* The next index associated with the same table */
8247   Schema *pSchema; /* Schema containing this index */
8248   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
8249   char **azColl;   /* Array of collation sequence names for index */
8250 };
8251
8252 /*
8253 ** Each token coming out of the lexer is an instance of
8254 ** this structure.  Tokens are also used as part of an expression.
8255 **
8256 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
8257 ** may contain random values.  Do not make any assuptions about Token.dyn
8258 ** and Token.n when Token.z==0.
8259 */
8260 struct Token {
8261   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
8262   unsigned dyn  : 1;      /* True for malloced memory, false for static */
8263   unsigned n    : 31;     /* Number of characters in this token */
8264 };
8265
8266 /*
8267 ** An instance of this structure contains information needed to generate
8268 ** code for a SELECT that contains aggregate functions.
8269 **
8270 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
8271 ** pointer to this structure.  The Expr.iColumn field is the index in
8272 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
8273 ** code for that node.
8274 **
8275 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
8276 ** original Select structure that describes the SELECT statement.  These
8277 ** fields do not need to be freed when deallocating the AggInfo structure.
8278 */
8279 struct AggInfo {
8280   u8 directMode;          /* Direct rendering mode means take data directly
8281                           ** from source tables rather than from accumulators */
8282   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
8283                           ** than the source table */
8284   int sortingIdx;         /* Cursor number of the sorting index */
8285   ExprList *pGroupBy;     /* The group by clause */
8286   int nSortingColumn;     /* Number of columns in the sorting index */
8287   struct AggInfo_col {    /* For each column used in source tables */
8288     Table *pTab;             /* Source table */
8289     int iTable;              /* Cursor number of the source table */
8290     int iColumn;             /* Column number within the source table */
8291     int iSorterColumn;       /* Column number in the sorting index */
8292     int iMem;                /* Memory location that acts as accumulator */
8293     Expr *pExpr;             /* The original expression */
8294   } *aCol;
8295   int nColumn;            /* Number of used entries in aCol[] */
8296   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
8297   int nAccumulator;       /* Number of columns that show through to the output.
8298                           ** Additional columns are used only as parameters to
8299                           ** aggregate functions */
8300   struct AggInfo_func {   /* For each aggregate function */
8301     Expr *pExpr;             /* Expression encoding the function */
8302     FuncDef *pFunc;          /* The aggregate function implementation */
8303     int iMem;                /* Memory location that acts as accumulator */
8304     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
8305   } *aFunc;
8306   int nFunc;              /* Number of entries in aFunc[] */
8307   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
8308 };
8309
8310 /*
8311 ** Each node of an expression in the parse tree is an instance
8312 ** of this structure.
8313 **
8314 ** Expr.op is the opcode.  The integer parser token codes are reused
8315 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
8316 ** code representing the ">=" operator.  This same integer code is reused
8317 ** to represent the greater-than-or-equal-to operator in the expression
8318 ** tree.
8319 **
8320 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
8321 ** of argument if the expression is a function.
8322 **
8323 ** Expr.token is the operator token for this node.  For some expressions
8324 ** that have subexpressions, Expr.token can be the complete text that gave
8325 ** rise to the Expr.  In the latter case, the token is marked as being
8326 ** a compound token.
8327 **
8328 ** An expression of the form ID or ID.ID refers to a column in a table.
8329 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
8330 ** the integer cursor number of a VDBE cursor pointing to that table and
8331 ** Expr.iColumn is the column number for the specific column.  If the
8332 ** expression is used as a result in an aggregate SELECT, then the
8333 ** value is also stored in the Expr.iAgg column in the aggregate so that
8334 ** it can be accessed after all aggregates are computed.
8335 **
8336 ** If the expression is a function, the Expr.iTable is an integer code
8337 ** representing which function.  If the expression is an unbound variable
8338 ** marker (a question mark character '?' in the original SQL) then the
8339 ** Expr.iTable holds the index number for that variable.
8340 **
8341 ** If the expression is a subquery then Expr.iColumn holds an integer
8342 ** register number containing the result of the subquery.  If the
8343 ** subquery gives a constant result, then iTable is -1.  If the subquery
8344 ** gives a different answer at different times during statement processing
8345 ** then iTable is the address of a subroutine that computes the subquery.
8346 **
8347 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
8348 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
8349 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
8350 ** operand.
8351 **
8352 ** If the Expr is of type OP_Column, and the table it is selecting from
8353 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
8354 ** corresponding table definition.
8355 */
8356 struct Expr {
8357   u8 op;                 /* Operation performed by this node */
8358   char affinity;         /* The affinity of the column or 0 if not a column */
8359   u16 flags;             /* Various flags.  See below */
8360   CollSeq *pColl;        /* The collation type of the column or 0 */
8361   Expr *pLeft, *pRight;  /* Left and right subnodes */
8362   ExprList *pList;       /* A list of expressions used as function arguments
8363                          ** or in "<expr> IN (<expr-list)" */
8364   Token token;           /* An operand token */
8365   Token span;            /* Complete text of the expression */
8366   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
8367                          ** iColumn-th field of the iTable-th table. */
8368   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
8369   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
8370   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
8371   Select *pSelect;       /* When the expression is a sub-select.  Also the
8372                          ** right side of "<expr> IN (<select>)" */
8373   Table *pTab;           /* Table for OP_Column expressions. */
8374 /*  Schema *pSchema; */
8375 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
8376   int nHeight;           /* Height of the tree headed by this node */
8377 #endif
8378 };
8379
8380 /*
8381 ** The following are the meanings of bits in the Expr.flags field.
8382 */
8383 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
8384 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
8385 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
8386 #define EP_Error      0x0008  /* Expression contains one or more errors */
8387 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
8388 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
8389 #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
8390 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
8391 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
8392 #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
8393 #define EP_FixedDest  0x0400  /* Result needed in a specific register */
8394
8395 /*
8396 ** These macros can be used to test, set, or clear bits in the 
8397 ** Expr.flags field.
8398 */
8399 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
8400 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
8401 #define ExprSetProperty(E,P)     (E)->flags|=(P)
8402 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
8403
8404 /*
8405 ** A list of expressions.  Each expression may optionally have a
8406 ** name.  An expr/name combination can be used in several ways, such
8407 ** as the list of "expr AS ID" fields following a "SELECT" or in the
8408 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
8409 ** also be used as the argument to a function, in which case the a.zName
8410 ** field is not used.
8411 */
8412 struct ExprList {
8413   int nExpr;             /* Number of expressions on the list */
8414   int nAlloc;            /* Number of entries allocated below */
8415   int iECursor;          /* VDBE Cursor associated with this ExprList */
8416   struct ExprList_item {
8417     Expr *pExpr;           /* The list of expressions */
8418     char *zName;           /* Token associated with this expression */
8419     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
8420     u8 isAgg;              /* True if this is an aggregate like count(*) */
8421     u8 done;               /* A flag to indicate when processing is finished */
8422   } *a;                  /* One entry for each expression */
8423 };
8424
8425 /*
8426 ** An instance of this structure can hold a simple list of identifiers,
8427 ** such as the list "a,b,c" in the following statements:
8428 **
8429 **      INSERT INTO t(a,b,c) VALUES ...;
8430 **      CREATE INDEX idx ON t(a,b,c);
8431 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
8432 **
8433 ** The IdList.a.idx field is used when the IdList represents the list of
8434 ** column names after a table name in an INSERT statement.  In the statement
8435 **
8436 **     INSERT INTO t(a,b,c) ...
8437 **
8438 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
8439 */
8440 struct IdList {
8441   struct IdList_item {
8442     char *zName;      /* Name of the identifier */
8443     int idx;          /* Index in some Table.aCol[] of a column named zName */
8444   } *a;
8445   int nId;         /* Number of identifiers on the list */
8446   int nAlloc;      /* Number of entries allocated for a[] below */
8447 };
8448
8449 /*
8450 ** The bitmask datatype defined below is used for various optimizations.
8451 **
8452 ** Changing this from a 64-bit to a 32-bit type limits the number of
8453 ** tables in a join to 32 instead of 64.  But it also reduces the size
8454 ** of the library by 738 bytes on ix86.
8455 */
8456 typedef u64 Bitmask;
8457
8458 /*
8459 ** The following structure describes the FROM clause of a SELECT statement.
8460 ** Each table or subquery in the FROM clause is a separate element of
8461 ** the SrcList.a[] array.
8462 **
8463 ** With the addition of multiple database support, the following structure
8464 ** can also be used to describe a particular table such as the table that
8465 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
8466 ** such a table must be a simple name: ID.  But in SQLite, the table can
8467 ** now be identified by a database name, a dot, then the table name: ID.ID.
8468 **
8469 ** The jointype starts out showing the join type between the current table
8470 ** and the next table on the list.  The parser builds the list this way.
8471 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
8472 ** jointype expresses the join between the table and the previous table.
8473 */
8474 struct SrcList {
8475   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
8476   i16 nAlloc;      /* Number of entries allocated in a[] below */
8477   struct SrcList_item {
8478     char *zDatabase;  /* Name of database holding this table */
8479     char *zName;      /* Name of the table */
8480     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
8481     Table *pTab;      /* An SQL table corresponding to zName */
8482     Select *pSelect;  /* A SELECT statement used in place of a table name */
8483     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
8484     u8 jointype;      /* Type of join between this able and the previous */
8485     int iCursor;      /* The VDBE cursor number used to access this table */
8486     Expr *pOn;        /* The ON clause of a join */
8487     IdList *pUsing;   /* The USING clause of a join */
8488     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
8489   } a[1];             /* One entry for each identifier on the list */
8490 };
8491
8492 /*
8493 ** Permitted values of the SrcList.a.jointype field
8494 */
8495 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
8496 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
8497 #define JT_NATURAL   0x0004    /* True for a "natural" join */
8498 #define JT_LEFT      0x0008    /* Left outer join */
8499 #define JT_RIGHT     0x0010    /* Right outer join */
8500 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
8501 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
8502
8503 /*
8504 ** For each nested loop in a WHERE clause implementation, the WhereInfo
8505 ** structure contains a single instance of this structure.  This structure
8506 ** is intended to be private the the where.c module and should not be
8507 ** access or modified by other modules.
8508 **
8509 ** The pIdxInfo and pBestIdx fields are used to help pick the best
8510 ** index on a virtual table.  The pIdxInfo pointer contains indexing
8511 ** information for the i-th table in the FROM clause before reordering.
8512 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
8513 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
8514 ** FROM clause ordering.  This is a little confusing so I will repeat
8515 ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
8516 ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
8517 ** index information for the i-th loop of the join.  pBestInfo is always
8518 ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
8519 ** sufficient to free all of the pIdxInfo pointers.
8520 ** 
8521 */
8522 struct WhereLevel {
8523   int iFrom;            /* Which entry in the FROM clause */
8524   int flags;            /* Flags associated with this level */
8525   int iMem;             /* First memory cell used by this level */
8526   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
8527   Index *pIdx;          /* Index used.  NULL if no index */
8528   int iTabCur;          /* The VDBE cursor used to access the table */
8529   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
8530   int brk;              /* Jump here to break out of the loop */
8531   int nxt;              /* Jump here to start the next IN combination */
8532   int cont;             /* Jump here to continue with the next loop cycle */
8533   int top;              /* First instruction of interior of the loop */
8534   int op, p1, p2;       /* Opcode used to terminate the loop */
8535   int nEq;              /* Number of == or IN constraints on this loop */
8536   int nIn;              /* Number of IN operators constraining this loop */
8537   struct InLoop {
8538     int iCur;              /* The VDBE cursor used by this IN operator */
8539     int topAddr;           /* Top of the IN loop */
8540   } *aInLoop;           /* Information about each nested IN operator */
8541   sqlite3_index_info *pBestIdx;  /* Index information for this level */
8542
8543   /* The following field is really not part of the current level.  But
8544   ** we need a place to cache index information for each table in the
8545   ** FROM clause and the WhereLevel structure is a convenient place.
8546   */
8547   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
8548 };
8549
8550 /*
8551 ** Flags appropriate for the wflags parameter of sqlite3WhereBegin().
8552 */
8553 #define WHERE_ORDERBY_NORMAL     0   /* No-op */
8554 #define WHERE_ORDERBY_MIN        1   /* ORDER BY processing for min() func */
8555 #define WHERE_ORDERBY_MAX        2   /* ORDER BY processing for max() func */
8556 #define WHERE_ONEPASS_DESIRED    4   /* Want to do one-pass UPDATE/DELETE */
8557
8558 /*
8559 ** The WHERE clause processing routine has two halves.  The
8560 ** first part does the start of the WHERE loop and the second
8561 ** half does the tail of the WHERE loop.  An instance of
8562 ** this structure is returned by the first half and passed
8563 ** into the second half to give some continuity.
8564 */
8565 struct WhereInfo {
8566   Parse *pParse;       /* Parsing and code generating context */
8567   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
8568   SrcList *pTabList;   /* List of tables in the join */
8569   int iTop;            /* The very beginning of the WHERE loop */
8570   int iContinue;       /* Jump here to continue with next record */
8571   int iBreak;          /* Jump here to break out of the loop */
8572   int nLevel;          /* Number of nested loop */
8573   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
8574   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
8575 };
8576
8577 /*
8578 ** A NameContext defines a context in which to resolve table and column
8579 ** names.  The context consists of a list of tables (the pSrcList) field and
8580 ** a list of named expression (pEList).  The named expression list may
8581 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
8582 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
8583 ** pEList corresponds to the result set of a SELECT and is NULL for
8584 ** other statements.
8585 **
8586 ** NameContexts can be nested.  When resolving names, the inner-most 
8587 ** context is searched first.  If no match is found, the next outer
8588 ** context is checked.  If there is still no match, the next context
8589 ** is checked.  This process continues until either a match is found
8590 ** or all contexts are check.  When a match is found, the nRef member of
8591 ** the context containing the match is incremented. 
8592 **
8593 ** Each subquery gets a new NameContext.  The pNext field points to the
8594 ** NameContext in the parent query.  Thus the process of scanning the
8595 ** NameContext list corresponds to searching through successively outer
8596 ** subqueries looking for a match.
8597 */
8598 struct NameContext {
8599   Parse *pParse;       /* The parser */
8600   SrcList *pSrcList;   /* One or more tables used to resolve names */
8601   ExprList *pEList;    /* Optional list of named expressions */
8602   int nRef;            /* Number of names resolved by this context */
8603   int nErr;            /* Number of errors encountered while resolving names */
8604   u8 allowAgg;         /* Aggregate functions allowed here */
8605   u8 hasAgg;           /* True if aggregates are seen */
8606   u8 isCheck;          /* True if resolving names in a CHECK constraint */
8607   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
8608   AggInfo *pAggInfo;   /* Information about aggregates at this level */
8609   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
8610 };
8611
8612 /*
8613 ** An instance of the following structure contains all information
8614 ** needed to generate code for a single SELECT statement.
8615 **
8616 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
8617 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
8618 ** limit and nOffset to the value of the offset (or 0 if there is not
8619 ** offset).  But later on, nLimit and nOffset become the memory locations
8620 ** in the VDBE that record the limit and offset counters.
8621 **
8622 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
8623 ** These addresses must be stored so that we can go back and fill in
8624 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
8625 ** the number of columns in P2 can be computed at the same time
8626 ** as the OP_OpenEphm instruction is coded because not
8627 ** enough information about the compound query is known at that point.
8628 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
8629 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
8630 ** sequences for the ORDER BY clause.
8631 */
8632 struct Select {
8633   ExprList *pEList;      /* The fields of the result */
8634   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
8635   u8 isDistinct;         /* True if the DISTINCT keyword is present */
8636   u8 isResolved;         /* True once sqlite3SelectResolve() has run. */
8637   u8 isAgg;              /* True if this is an aggregate query */
8638   u8 usesEphm;           /* True if uses an OpenEphemeral opcode */
8639   u8 disallowOrderBy;    /* Do not allow an ORDER BY to be attached if TRUE */
8640   char affinity;         /* MakeRecord with this affinity for SRT_Set */
8641   SrcList *pSrc;         /* The FROM clause */
8642   Expr *pWhere;          /* The WHERE clause */
8643   ExprList *pGroupBy;    /* The GROUP BY clause */
8644   Expr *pHaving;         /* The HAVING clause */
8645   ExprList *pOrderBy;    /* The ORDER BY clause */
8646   Select *pPrior;        /* Prior select in a compound select statement */
8647   Select *pNext;         /* Next select to the left in a compound */
8648   Select *pRightmost;    /* Right-most select in a compound select statement */
8649   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
8650   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
8651   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
8652   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
8653 };
8654
8655 /*
8656 ** The results of a select can be distributed in several ways.
8657 */
8658 #define SRT_Union        1  /* Store result as keys in an index */
8659 #define SRT_Except       2  /* Remove result from a UNION index */
8660 #define SRT_Exists       3  /* Store 1 if the result is not empty */
8661 #define SRT_Discard      4  /* Do not save the results anywhere */
8662
8663 /* The ORDER BY clause is ignored for all of the above */
8664 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
8665
8666 #define SRT_Callback     5  /* Invoke a callback with each row of result */
8667 #define SRT_Mem          6  /* Store result in a memory cell */
8668 #define SRT_Set          7  /* Store non-null results as keys in an index */
8669 #define SRT_Table        8  /* Store result as data with an automatic rowid */
8670 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
8671 #define SRT_Subroutine  10  /* Call a subroutine to handle results */
8672
8673 /*
8674 ** A structure used to customize the behaviour of sqlite3Select(). See
8675 ** comments above sqlite3Select() for details.
8676 */
8677 typedef struct SelectDest SelectDest;
8678 struct SelectDest {
8679   u8 eDest;         /* How to dispose of the results */
8680   u8 affinity;      /* Affinity used when eDest==SRT_Set */
8681   int iParm;        /* A parameter used by the eDest disposal method */
8682   int iMem;         /* Base register where results are written */
8683   int nMem;         /* Number of registers allocated */
8684 };
8685
8686 /*
8687 ** An SQL parser context.  A copy of this structure is passed through
8688 ** the parser and down into all the parser action routine in order to
8689 ** carry around information that is global to the entire parse.
8690 **
8691 ** The structure is divided into two parts.  When the parser and code
8692 ** generate call themselves recursively, the first part of the structure
8693 ** is constant but the second part is reset at the beginning and end of
8694 ** each recursion.
8695 **
8696 ** The nTableLock and aTableLock variables are only used if the shared-cache 
8697 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
8698 ** used to store the set of table-locks required by the statement being
8699 ** compiled. Function sqlite3TableLock() is used to add entries to the
8700 ** list.
8701 */
8702 struct Parse {
8703   sqlite3 *db;         /* The main database structure */
8704   int rc;              /* Return code from execution */
8705   char *zErrMsg;       /* An error message */
8706   Vdbe *pVdbe;         /* An engine for executing database bytecode */
8707   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
8708   u8 nameClash;        /* A permanent table name clashes with temp table name */
8709   u8 checkSchema;      /* Causes schema cookie check after an error */
8710   u8 nested;           /* Number of nested calls to the parser/code generator */
8711   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
8712   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
8713   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
8714   int aTempReg[8];     /* Holding area for temporary registers */
8715   int nRangeReg;       /* Size of the temporary register block */
8716   int iRangeReg;       /* First register in temporary register block */
8717   int nErr;            /* Number of errors seen */
8718   int nTab;            /* Number of previously allocated VDBE cursors */
8719   int nMem;            /* Number of memory cells used so far */
8720   int nSet;            /* Number of sets used so far */
8721   int ckBase;          /* Base register of data during check constraints */
8722   int disableColCache; /* True to disable adding to column cache */
8723   int nColCache;       /* Number of entries in the column cache */
8724   int iColCache;       /* Next entry of the cache to replace */
8725   struct yColCache {
8726     int iTable;           /* Table cursor number */
8727     int iColumn;          /* Table column number */
8728     char affChange;       /* True if this register has had an affinity change */
8729     int iReg;             /* Register holding value of this column */
8730   } aColCache[10];     /* One for each valid column cache entry */
8731   u32 writeMask;       /* Start a write transaction on these databases */
8732   u32 cookieMask;      /* Bitmask of schema verified databases */
8733   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
8734   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
8735 #ifndef SQLITE_OMIT_SHARED_CACHE
8736   int nTableLock;        /* Number of locks in aTableLock */
8737   TableLock *aTableLock; /* Required table locks for shared-cache mode */
8738 #endif
8739   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
8740   int regRoot;         /* Register holding root page number for new objects */
8741
8742   /* Above is constant between recursions.  Below is reset before and after
8743   ** each recursion */
8744
8745   int nVar;            /* Number of '?' variables seen in the SQL so far */
8746   int nVarExpr;        /* Number of used slots in apVarExpr[] */
8747   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
8748   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
8749   u8 explain;          /* True if the EXPLAIN flag is found on the query */
8750   Token sErrToken;     /* The token at which the error occurred */
8751   Token sNameToken;    /* Token with unqualified schema object name */
8752   Token sLastToken;    /* The last token parsed */
8753   const char *zSql;    /* All SQL text */
8754   const char *zTail;   /* All SQL text past the last semicolon parsed */
8755   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
8756   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
8757   TriggerStack *trigStack;  /* Trigger actions being coded */
8758   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
8759 #ifndef SQLITE_OMIT_VIRTUALTABLE
8760   Token sArg;                /* Complete text of a module argument */
8761   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
8762   int nVtabLock;             /* Number of virtual tables to lock */
8763   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
8764 #endif
8765 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
8766   int nHeight;            /* Expression tree height of current sub-select */
8767 #endif
8768 };
8769
8770 #ifdef SQLITE_OMIT_VIRTUALTABLE
8771   #define IN_DECLARE_VTAB 0
8772 #else
8773   #define IN_DECLARE_VTAB (pParse->declareVtab)
8774 #endif
8775
8776 /*
8777 ** An instance of the following structure can be declared on a stack and used
8778 ** to save the Parse.zAuthContext value so that it can be restored later.
8779 */
8780 struct AuthContext {
8781   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
8782   Parse *pParse;              /* The Parse structure */
8783 };
8784
8785 /*
8786 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
8787 */
8788 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
8789 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
8790 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
8791 #define OPFLAG_APPEND    8    /* This is likely to be an append */
8792
8793 /*
8794  * Each trigger present in the database schema is stored as an instance of
8795  * struct Trigger. 
8796  *
8797  * Pointers to instances of struct Trigger are stored in two ways.
8798  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
8799  *    database). This allows Trigger structures to be retrieved by name.
8800  * 2. All triggers associated with a single table form a linked list, using the
8801  *    pNext member of struct Trigger. A pointer to the first element of the
8802  *    linked list is stored as the "pTrigger" member of the associated
8803  *    struct Table.
8804  *
8805  * The "step_list" member points to the first element of a linked list
8806  * containing the SQL statements specified as the trigger program.
8807  */
8808 struct Trigger {
8809   char *name;             /* The name of the trigger                        */
8810   char *table;            /* The table or view to which the trigger applies */
8811   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
8812   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
8813   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
8814   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
8815                              the <column-list> is stored here */
8816   Token nameToken;        /* Token containing zName. Use during parsing only */
8817   Schema *pSchema;        /* Schema containing the trigger */
8818   Schema *pTabSchema;     /* Schema containing the table */
8819   TriggerStep *step_list; /* Link list of trigger program steps             */
8820   Trigger *pNext;         /* Next trigger associated with the table */
8821 };
8822
8823 /*
8824 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
8825 ** determine which. 
8826 **
8827 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
8828 ** In that cases, the constants below can be ORed together.
8829 */
8830 #define TRIGGER_BEFORE  1
8831 #define TRIGGER_AFTER   2
8832
8833 /*
8834  * An instance of struct TriggerStep is used to store a single SQL statement
8835  * that is a part of a trigger-program. 
8836  *
8837  * Instances of struct TriggerStep are stored in a singly linked list (linked
8838  * using the "pNext" member) referenced by the "step_list" member of the 
8839  * associated struct Trigger instance. The first element of the linked list is
8840  * the first step of the trigger-program.
8841  * 
8842  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
8843  * "SELECT" statement. The meanings of the other members is determined by the 
8844  * value of "op" as follows:
8845  *
8846  * (op == TK_INSERT)
8847  * orconf    -> stores the ON CONFLICT algorithm
8848  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
8849  *              this stores a pointer to the SELECT statement. Otherwise NULL.
8850  * target    -> A token holding the name of the table to insert into.
8851  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
8852  *              this stores values to be inserted. Otherwise NULL.
8853  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
8854  *              statement, then this stores the column-names to be
8855  *              inserted into.
8856  *
8857  * (op == TK_DELETE)
8858  * target    -> A token holding the name of the table to delete from.
8859  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
8860  *              Otherwise NULL.
8861  * 
8862  * (op == TK_UPDATE)
8863  * target    -> A token holding the name of the table to update rows of.
8864  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
8865  *              Otherwise NULL.
8866  * pExprList -> A list of the columns to update and the expressions to update
8867  *              them to. See sqlite3Update() documentation of "pChanges"
8868  *              argument.
8869  * 
8870  */
8871 struct TriggerStep {
8872   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
8873   int orconf;          /* OE_Rollback etc. */
8874   Trigger *pTrig;      /* The trigger that this step is a part of */
8875
8876   Select *pSelect;     /* Valid for SELECT and sometimes 
8877                           INSERT steps (when pExprList == 0) */
8878   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
8879   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
8880   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
8881                            INSERT steps (when pSelect == 0)         */
8882   IdList *pIdList;     /* Valid for INSERT statements only */
8883   TriggerStep *pNext;  /* Next in the link-list */
8884   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
8885 };
8886
8887 /*
8888  * An instance of struct TriggerStack stores information required during code
8889  * generation of a single trigger program. While the trigger program is being
8890  * coded, its associated TriggerStack instance is pointed to by the
8891  * "pTriggerStack" member of the Parse structure.
8892  *
8893  * The pTab member points to the table that triggers are being coded on. The 
8894  * newIdx member contains the index of the vdbe cursor that points at the temp
8895  * table that stores the new.* references. If new.* references are not valid
8896  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
8897  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
8898  *
8899  * The ON CONFLICT policy to be used for the trigger program steps is stored 
8900  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
8901  * specified for individual triggers steps is used.
8902  *
8903  * struct TriggerStack has a "pNext" member, to allow linked lists to be
8904  * constructed. When coding nested triggers (triggers fired by other triggers)
8905  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
8906  * pointer. Once the nested trigger has been coded, the pNext value is restored
8907  * to the pTriggerStack member of the Parse stucture and coding of the parent
8908  * trigger continues.
8909  *
8910  * Before a nested trigger is coded, the linked list pointed to by the 
8911  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
8912  * recursively. If this condition is detected, the nested trigger is not coded.
8913  */
8914 struct TriggerStack {
8915   Table *pTab;         /* Table that triggers are currently being coded on */
8916   int newIdx;          /* Index of vdbe cursor to "new" temp table */
8917   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
8918   u32 newColMask;
8919   u32 oldColMask;
8920   int orconf;          /* Current orconf policy */
8921   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
8922   Trigger *pTrigger;   /* The trigger currently being coded */
8923   TriggerStack *pNext; /* Next trigger down on the trigger stack */
8924 };
8925
8926 /*
8927 ** The following structure contains information used by the sqliteFix...
8928 ** routines as they walk the parse tree to make database references
8929 ** explicit.  
8930 */
8931 typedef struct DbFixer DbFixer;
8932 struct DbFixer {
8933   Parse *pParse;      /* The parsing context.  Error messages written here */
8934   const char *zDb;    /* Make sure all objects are contained in this database */
8935   const char *zType;  /* Type of the container - used for error messages */
8936   const Token *pName; /* Name of the container - used for error messages */
8937 };
8938
8939 /*
8940 ** An objected used to accumulate the text of a string where we
8941 ** do not necessarily know how big the string will be in the end.
8942 */
8943 struct StrAccum {
8944   char *zBase;     /* A base allocation.  Not from malloc. */
8945   char *zText;     /* The string collected so far */
8946   int  nChar;      /* Length of the string so far */
8947   int  nAlloc;     /* Amount of space allocated in zText */
8948   int  mxAlloc;        /* Maximum allowed string length */
8949   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
8950   u8   useMalloc;      /* True if zText is enlargable using realloc */
8951   u8   tooBig;         /* Becomes true if string size exceeds limits */
8952 };
8953
8954 /*
8955 ** A pointer to this structure is used to communicate information
8956 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
8957 */
8958 typedef struct {
8959   sqlite3 *db;        /* The database being initialized */
8960   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
8961   char **pzErrMsg;    /* Error message stored here */
8962   int rc;             /* Result code stored here */
8963 } InitData;
8964
8965 /*
8966 ** Assuming zIn points to the first byte of a UTF-8 character,
8967 ** advance zIn to point to the first byte of the next UTF-8 character.
8968 */
8969 #define SQLITE_SKIP_UTF8(zIn) {                        \
8970   if( (*(zIn++))>=0xc0 ){                              \
8971     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
8972   }                                                    \
8973 }
8974
8975 /*
8976 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
8977 ** builds) or a function call (for debugging).  If it is a function call,
8978 ** it allows the operator to set a breakpoint at the spot where database
8979 ** corruption is first detected.
8980 */
8981 #ifdef SQLITE_DEBUG
8982 SQLITE_PRIVATE   int sqlite3Corrupt(void);
8983 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
8984 # define DEBUGONLY(X)        X
8985 #else
8986 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
8987 # define DEBUGONLY(X)
8988 #endif
8989
8990 /*
8991 ** Internal function prototypes
8992 */
8993 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
8994 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
8995 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
8996
8997 SQLITE_PRIVATE void *sqlite3MallocZero(unsigned);
8998 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, unsigned);
8999 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, unsigned);
9000 SQLITE_PRIVATE char *sqlite3StrDup(const char*);
9001 SQLITE_PRIVATE char *sqlite3StrNDup(const char*, int);
9002 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
9003 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
9004 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
9005 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
9006 SQLITE_PRIVATE int sqlite3MallocSize(void *);
9007
9008 SQLITE_PRIVATE int sqlite3IsNaN(double);
9009
9010 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
9011 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
9012 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
9013 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
9014 #endif
9015 #if defined(SQLITE_TEST)
9016 SQLITE_PRIVATE   void *sqlite3TextToPtr(const char*);
9017 #endif
9018 SQLITE_PRIVATE void sqlite3SetString(char **, ...);
9019 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
9020 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
9021 SQLITE_PRIVATE void sqlite3Dequote(char*);
9022 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
9023 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
9024 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
9025 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
9026 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
9027 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
9028 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
9029 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
9030 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
9031 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
9032 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
9033 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
9034 SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
9035 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
9036 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
9037 SQLITE_PRIVATE void sqlite3ExprDelete(Expr*);
9038 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
9039 SQLITE_PRIVATE void sqlite3ExprListDelete(ExprList*);
9040 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
9041 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
9042 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
9043 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
9044 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
9045 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
9046 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
9047 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
9048 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
9049 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
9050 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
9051 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
9052 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
9053 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
9054 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
9055 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
9056 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
9057
9058 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
9059 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
9060 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
9061 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
9062 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
9063 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
9064
9065 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
9066
9067 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
9068 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
9069 #else
9070 # define sqlite3ViewGetColumnNames(A,B) 0
9071 #endif
9072
9073 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
9074 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
9075 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
9076 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
9077 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
9078 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
9079 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
9080 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*,
9081                                       Select*, Expr*, IdList*);
9082 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
9083 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
9084 SQLITE_PRIVATE void sqlite3IdListDelete(IdList*);
9085 SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList*);
9086 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
9087                         Token*, int, int);
9088 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
9089 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*, Select*, int, int*, char *aff);
9090 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
9091                          Expr*,ExprList*,int,Expr*,Expr*);
9092 SQLITE_PRIVATE void sqlite3SelectDelete(Select*);
9093 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
9094 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
9095 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
9096 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
9097 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
9098 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8);
9099 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
9100 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
9101 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int);
9102 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
9103 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
9104 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse*,int,int);
9105 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
9106 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
9107 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
9108 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
9109 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
9110 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
9111 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
9112 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
9113 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
9114 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
9115 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
9116 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
9117 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
9118 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
9119 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
9120 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
9121 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
9122 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
9123 SQLITE_PRIVATE int sqlite3ExprResolveNames(NameContext *, Expr *);
9124 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
9125 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
9126 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
9127 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
9128 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
9129 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
9130 SQLITE_PRIVATE void sqlite3PrngResetState(void);
9131 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
9132 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
9133 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
9134 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
9135 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
9136 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
9137 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
9138 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
9139 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
9140 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
9141 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
9142 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
9143 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
9144 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
9145                                      int*,int,int,int,int);
9146 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*,int,int,int,int);
9147 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
9148 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
9149 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
9150 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
9151 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
9152 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
9153 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
9154 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
9155 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
9156 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
9157 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3*);
9158 #ifdef SQLITE_DEBUG
9159 SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
9160 SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
9161 #else
9162 # define sqlite3SafetyOn(A) 0
9163 # define sqlite3SafetyOff(A) 0
9164 #endif
9165 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
9166 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
9167 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
9168 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Select*, Expr*, int);
9169
9170 #ifndef SQLITE_OMIT_TRIGGER
9171 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
9172                            Expr*,int, int);
9173 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
9174 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
9175 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
9176 SQLITE_PRIVATE   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
9177 SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
9178                            int, int, u32*, u32*);
9179   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
9180 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(TriggerStep*);
9181 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
9182 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
9183                                         ExprList*,Select*,int);
9184 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
9185 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
9186 SQLITE_PRIVATE   void sqlite3DeleteTrigger(Trigger*);
9187 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
9188 #else
9189 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
9190 # define sqlite3DeleteTrigger(A)
9191 # define sqlite3DropTriggerPtr(A,B)
9192 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
9193 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
9194 #endif
9195
9196 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
9197 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
9198 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
9199 #ifndef SQLITE_OMIT_AUTHORIZATION
9200 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
9201 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
9202 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
9203 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
9204 #else
9205 # define sqlite3AuthRead(a,b,c,d)
9206 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
9207 # define sqlite3AuthContextPush(a,b,c)
9208 # define sqlite3AuthContextPop(a)  ((void)(a))
9209 #endif
9210 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
9211 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
9212 SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
9213                        int omitJournal, int nCache, int flags, Btree **ppBtree);
9214 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
9215 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
9216 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
9217 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
9218 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
9219 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
9220 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
9221 SQLITE_API char *sqlite3_snprintf(int,char*,const char*,...);
9222 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
9223 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
9224 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
9225 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
9226 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
9227
9228 /*
9229 ** Routines to read and write variable-length integers.  These used to
9230 ** be defined locally, but now we use the varint routines in the util.c
9231 ** file.  Code should use the MACRO forms below, as the Varint32 versions
9232 ** are coded to assume the single byte case is already handled (which 
9233 ** the MACRO form does).
9234 */
9235 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
9236 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
9237 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *, u64 *);
9238 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *, u32 *);
9239 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
9240
9241 /*
9242 ** The header of a record consists of a sequence variable-length integers.
9243 ** These integers are almost always small and are encoded as a single byte.
9244 ** The following macros take advantage this fact to provide a fast encode
9245 ** and decode of the integers in a record header.  It is faster for the common
9246 ** case where the integer is a single byte.  It is a little slower when the
9247 ** integer is two or more bytes.  But overall it is faster.
9248 **
9249 ** The following expressions are equivalent:
9250 **
9251 **     x = sqlite3GetVarint32( A, &B );
9252 **     x = sqlite3PutVarint32( A, B );
9253 **
9254 **     x = getVarint32( A, B );
9255 **     x = putVarint32( A, B );
9256 **
9257 */
9258 #define getVarint32(A,B)  ((*(A)<(unsigned char)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), &(B)))
9259 #define putVarint32(A,B)  (((B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
9260 #define getVarint    sqlite3GetVarint
9261 #define putVarint    sqlite3PutVarint
9262
9263
9264 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
9265 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
9266 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
9267 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
9268 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
9269 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
9270 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
9271 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
9272 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
9273 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
9274 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
9275 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
9276 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
9277 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
9278 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
9279 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
9280 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
9281 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
9282
9283 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
9284 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
9285 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
9286                         void(*)(void*));
9287 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
9288 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
9289 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
9290 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
9291 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
9292 #ifndef SQLITE_AMALGAMATION
9293 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
9294 #endif
9295 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
9296 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
9297 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
9298 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
9299 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
9300 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
9301 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
9302 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *);
9303 SQLITE_PRIVATE int sqlite3SelectResolve(Parse *, Select *, NameContext *);
9304 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
9305 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
9306 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
9307 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
9308 SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
9309 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
9310 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
9311 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
9312 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
9313 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
9314 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
9315 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
9316 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *);
9317 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
9318 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
9319 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
9320 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
9321 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
9322 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
9323   void (*)(sqlite3_context*,int,sqlite3_value **),
9324   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
9325 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
9326 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
9327
9328 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
9329 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
9330 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
9331 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
9332
9333 /*
9334 ** The interface to the LEMON-generated parser
9335 */
9336 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
9337 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
9338 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
9339
9340 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3*);
9341 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9342 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
9343 #else
9344 # define sqlite3CloseExtensions(X)
9345 #endif
9346
9347 #ifndef SQLITE_OMIT_SHARED_CACHE
9348 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
9349 #else
9350   #define sqlite3TableLock(v,w,x,y,z)
9351 #endif
9352
9353 #ifdef SQLITE_TEST
9354 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
9355 #endif
9356
9357 #ifdef SQLITE_OMIT_VIRTUALTABLE
9358 #  define sqlite3VtabClear(X)
9359 #  define sqlite3VtabSync(X,Y) (Y)
9360 #  define sqlite3VtabRollback(X)
9361 #  define sqlite3VtabCommit(X)
9362 #else
9363 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
9364 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, int rc);
9365 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
9366 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
9367 #endif
9368 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
9369 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
9370 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
9371 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
9372 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
9373 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
9374 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
9375 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
9376 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
9377 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
9378 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
9379 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
9380 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
9381 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
9382 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
9383 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
9384
9385
9386 /*
9387 ** Available fault injectors.  Should be numbered beginning with 0.
9388 */
9389 #define SQLITE_FAULTINJECTOR_MALLOC     0
9390 #define SQLITE_FAULTINJECTOR_COUNT      1
9391
9392 /*
9393 ** The interface to the fault injector subsystem.  If the fault injector
9394 ** mechanism is disabled at compile-time then set up macros so that no
9395 ** unnecessary code is generated.
9396 */
9397 #ifndef SQLITE_OMIT_BUILTIN_TEST
9398 SQLITE_PRIVATE   void sqlite3FaultConfig(int,int,int);
9399 SQLITE_PRIVATE   int sqlite3FaultFailures(int);
9400 SQLITE_PRIVATE   int sqlite3FaultBenignFailures(int);
9401 SQLITE_PRIVATE   int sqlite3FaultPending(int);
9402 SQLITE_PRIVATE   void sqlite3FaultBeginBenign(int);
9403 SQLITE_PRIVATE   void sqlite3FaultEndBenign(int);
9404 SQLITE_PRIVATE   int sqlite3FaultStep(int);
9405 #else
9406 # define sqlite3FaultConfig(A,B,C)
9407 # define sqlite3FaultFailures(A)         0
9408 # define sqlite3FaultBenignFailures(A)   0
9409 # define sqlite3FaultPending(A)          (-1)
9410 # define sqlite3FaultBeginBenign(A)
9411 # define sqlite3FaultEndBenign(A)
9412 # define sqlite3FaultStep(A)             0
9413 #endif
9414   
9415   
9416
9417 #define IN_INDEX_ROWID           1
9418 #define IN_INDEX_EPH             2
9419 #define IN_INDEX_INDEX           3
9420 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int);
9421
9422 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
9423 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
9424 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
9425 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
9426 #else
9427   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
9428 #endif
9429
9430 #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
9431 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Expr *);
9432 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
9433 #else
9434   #define sqlite3ExprSetHeight(x)
9435 #endif
9436
9437 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
9438 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
9439
9440 #ifdef SQLITE_SSE
9441 #include "sseInt.h"
9442 #endif
9443
9444 #ifdef SQLITE_DEBUG
9445 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
9446 #endif
9447
9448 /*
9449 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
9450 ** sqlite3IoTrace is a pointer to a printf-like routine used to
9451 ** print I/O tracing messages. 
9452 */
9453 #ifdef SQLITE_ENABLE_IOTRACE
9454 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
9455 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
9456 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
9457 #else
9458 # define IOTRACE(A)
9459 # define sqlite3VdbeIOTraceSql(X)
9460 #endif
9461
9462 #endif
9463
9464 /************** End of sqliteInt.h *******************************************/
9465 /************** Begin file date.c ********************************************/
9466 /*
9467 ** 2003 October 31
9468 **
9469 ** The author disclaims copyright to this source code.  In place of
9470 ** a legal notice, here is a blessing:
9471 **
9472 **    May you do good and not evil.
9473 **    May you find forgiveness for yourself and forgive others.
9474 **    May you share freely, never taking more than you give.
9475 **
9476 *************************************************************************
9477 ** This file contains the C functions that implement date and time
9478 ** functions for SQLite.  
9479 **
9480 ** There is only one exported symbol in this file - the function
9481 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
9482 ** All other code has file scope.
9483 **
9484 ** $Id: date.c,v 1.79 2008/03/20 14:03:29 drh Exp $
9485 **
9486 ** SQLite processes all times and dates as Julian Day numbers.  The
9487 ** dates and times are stored as the number of days since noon
9488 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
9489 ** calendar system. 
9490 **
9491 ** 1970-01-01 00:00:00 is JD 2440587.5
9492 ** 2000-01-01 00:00:00 is JD 2451544.5
9493 **
9494 ** This implemention requires years to be expressed as a 4-digit number
9495 ** which means that only dates between 0000-01-01 and 9999-12-31 can
9496 ** be represented, even though julian day numbers allow a much wider
9497 ** range of dates.
9498 **
9499 ** The Gregorian calendar system is used for all dates and times,
9500 ** even those that predate the Gregorian calendar.  Historians usually
9501 ** use the Julian calendar for dates prior to 1582-10-15 and for some
9502 ** dates afterwards, depending on locale.  Beware of this difference.
9503 **
9504 ** The conversion algorithms are implemented based on descriptions
9505 ** in the following text:
9506 **
9507 **      Jean Meeus
9508 **      Astronomical Algorithms, 2nd Edition, 1998
9509 **      ISBM 0-943396-61-1
9510 **      Willmann-Bell, Inc
9511 **      Richmond, Virginia (USA)
9512 */
9513 #include <ctype.h>
9514 #include <time.h>
9515
9516 #ifndef SQLITE_OMIT_DATETIME_FUNCS
9517
9518 /*
9519 ** A structure for holding a single date and time.
9520 */
9521 typedef struct DateTime DateTime;
9522 struct DateTime {
9523   double rJD;      /* The julian day number */
9524   int Y, M, D;     /* Year, month, and day */
9525   int h, m;        /* Hour and minutes */
9526   int tz;          /* Timezone offset in minutes */
9527   double s;        /* Seconds */
9528   char validYMD;   /* True if Y,M,D are valid */
9529   char validHMS;   /* True if h,m,s are valid */
9530   char validJD;    /* True if rJD is valid */
9531   char validTZ;    /* True if tz is valid */
9532 };
9533
9534
9535 /*
9536 ** Convert zDate into one or more integers.  Additional arguments
9537 ** come in groups of 5 as follows:
9538 **
9539 **       N       number of digits in the integer
9540 **       min     minimum allowed value of the integer
9541 **       max     maximum allowed value of the integer
9542 **       nextC   first character after the integer
9543 **       pVal    where to write the integers value.
9544 **
9545 ** Conversions continue until one with nextC==0 is encountered.
9546 ** The function returns the number of successful conversions.
9547 */
9548 static int getDigits(const char *zDate, ...){
9549   va_list ap;
9550   int val;
9551   int N;
9552   int min;
9553   int max;
9554   int nextC;
9555   int *pVal;
9556   int cnt = 0;
9557   va_start(ap, zDate);
9558   do{
9559     N = va_arg(ap, int);
9560     min = va_arg(ap, int);
9561     max = va_arg(ap, int);
9562     nextC = va_arg(ap, int);
9563     pVal = va_arg(ap, int*);
9564     val = 0;
9565     while( N-- ){
9566       if( !isdigit(*(u8*)zDate) ){
9567         goto end_getDigits;
9568       }
9569       val = val*10 + *zDate - '0';
9570       zDate++;
9571     }
9572     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
9573       goto end_getDigits;
9574     }
9575     *pVal = val;
9576     zDate++;
9577     cnt++;
9578   }while( nextC );
9579 end_getDigits:
9580   va_end(ap);
9581   return cnt;
9582 }
9583
9584 /*
9585 ** Read text from z[] and convert into a floating point number.  Return
9586 ** the number of digits converted.
9587 */
9588 #define getValue sqlite3AtoF
9589
9590 /*
9591 ** Parse a timezone extension on the end of a date-time.
9592 ** The extension is of the form:
9593 **
9594 **        (+/-)HH:MM
9595 **
9596 ** Or the "zulu" notation:
9597 **
9598 **        Z
9599 **
9600 ** If the parse is successful, write the number of minutes
9601 ** of change in p->tz and return 0.  If a parser error occurs,
9602 ** return non-zero.
9603 **
9604 ** A missing specifier is not considered an error.
9605 */
9606 static int parseTimezone(const char *zDate, DateTime *p){
9607   int sgn = 0;
9608   int nHr, nMn;
9609   int c;
9610   while( isspace(*(u8*)zDate) ){ zDate++; }
9611   p->tz = 0;
9612   c = *zDate;
9613   if( c=='-' ){
9614     sgn = -1;
9615   }else if( c=='+' ){
9616     sgn = +1;
9617   }else if( c=='Z' || c=='z' ){
9618     zDate++;
9619     goto zulu_time;
9620   }else{
9621     return c!=0;
9622   }
9623   zDate++;
9624   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
9625     return 1;
9626   }
9627   zDate += 5;
9628   p->tz = sgn*(nMn + nHr*60);
9629 zulu_time:
9630   while( isspace(*(u8*)zDate) ){ zDate++; }
9631   return *zDate!=0;
9632 }
9633
9634 /*
9635 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
9636 ** The HH, MM, and SS must each be exactly 2 digits.  The
9637 ** fractional seconds FFFF can be one or more digits.
9638 **
9639 ** Return 1 if there is a parsing error and 0 on success.
9640 */
9641 static int parseHhMmSs(const char *zDate, DateTime *p){
9642   int h, m, s;
9643   double ms = 0.0;
9644   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
9645     return 1;
9646   }
9647   zDate += 5;
9648   if( *zDate==':' ){
9649     zDate++;
9650     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
9651       return 1;
9652     }
9653     zDate += 2;
9654     if( *zDate=='.' && isdigit((u8)zDate[1]) ){
9655       double rScale = 1.0;
9656       zDate++;
9657       while( isdigit(*(u8*)zDate) ){
9658         ms = ms*10.0 + *zDate - '0';
9659         rScale *= 10.0;
9660         zDate++;
9661       }
9662       ms /= rScale;
9663     }
9664   }else{
9665     s = 0;
9666   }
9667   p->validJD = 0;
9668   p->validHMS = 1;
9669   p->h = h;
9670   p->m = m;
9671   p->s = s + ms;
9672   if( parseTimezone(zDate, p) ) return 1;
9673   p->validTZ = p->tz!=0;
9674   return 0;
9675 }
9676
9677 /*
9678 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
9679 ** that the YYYY-MM-DD is according to the Gregorian calendar.
9680 **
9681 ** Reference:  Meeus page 61
9682 */
9683 static void computeJD(DateTime *p){
9684   int Y, M, D, A, B, X1, X2;
9685
9686   if( p->validJD ) return;
9687   if( p->validYMD ){
9688     Y = p->Y;
9689     M = p->M;
9690     D = p->D;
9691   }else{
9692     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
9693     M = 1;
9694     D = 1;
9695   }
9696   if( M<=2 ){
9697     Y--;
9698     M += 12;
9699   }
9700   A = Y/100;
9701   B = 2 - A + (A/4);
9702   X1 = 365.25*(Y+4716);
9703   X2 = 30.6001*(M+1);
9704   p->rJD = X1 + X2 + D + B - 1524.5;
9705   p->validJD = 1;
9706   if( p->validHMS ){
9707     p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
9708     if( p->validTZ ){
9709       p->rJD -= p->tz*60/86400.0;
9710       p->validYMD = 0;
9711       p->validHMS = 0;
9712       p->validTZ = 0;
9713     }
9714   }
9715 }
9716
9717 /*
9718 ** Parse dates of the form
9719 **
9720 **     YYYY-MM-DD HH:MM:SS.FFF
9721 **     YYYY-MM-DD HH:MM:SS
9722 **     YYYY-MM-DD HH:MM
9723 **     YYYY-MM-DD
9724 **
9725 ** Write the result into the DateTime structure and return 0
9726 ** on success and 1 if the input string is not a well-formed
9727 ** date.
9728 */
9729 static int parseYyyyMmDd(const char *zDate, DateTime *p){
9730   int Y, M, D, neg;
9731
9732   if( zDate[0]=='-' ){
9733     zDate++;
9734     neg = 1;
9735   }else{
9736     neg = 0;
9737   }
9738   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
9739     return 1;
9740   }
9741   zDate += 10;
9742   while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
9743   if( parseHhMmSs(zDate, p)==0 ){
9744     /* We got the time */
9745   }else if( *zDate==0 ){
9746     p->validHMS = 0;
9747   }else{
9748     return 1;
9749   }
9750   p->validJD = 0;
9751   p->validYMD = 1;
9752   p->Y = neg ? -Y : Y;
9753   p->M = M;
9754   p->D = D;
9755   if( p->validTZ ){
9756     computeJD(p);
9757   }
9758   return 0;
9759 }
9760
9761 /*
9762 ** Attempt to parse the given string into a Julian Day Number.  Return
9763 ** the number of errors.
9764 **
9765 ** The following are acceptable forms for the input string:
9766 **
9767 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
9768 **      DDDD.DD 
9769 **      now
9770 **
9771 ** In the first form, the +/-HH:MM is always optional.  The fractional
9772 ** seconds extension (the ".FFF") is optional.  The seconds portion
9773 ** (":SS.FFF") is option.  The year and date can be omitted as long
9774 ** as there is a time string.  The time string can be omitted as long
9775 ** as there is a year and date.
9776 */
9777 static int parseDateOrTime(
9778   sqlite3_context *context, 
9779   const char *zDate, 
9780   DateTime *p
9781 ){
9782   memset(p, 0, sizeof(*p));
9783   if( parseYyyyMmDd(zDate,p)==0 ){
9784     return 0;
9785   }else if( parseHhMmSs(zDate, p)==0 ){
9786     return 0;
9787   }else if( sqlite3StrICmp(zDate,"now")==0){
9788     double r;
9789     sqlite3 *db = sqlite3_context_db_handle(context);
9790     sqlite3OsCurrentTime(db->pVfs, &r);
9791     p->rJD = r;
9792     p->validJD = 1;
9793     return 0;
9794   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
9795     getValue(zDate, &p->rJD);
9796     p->validJD = 1;
9797     return 0;
9798   }
9799   return 1;
9800 }
9801
9802 /*
9803 ** Compute the Year, Month, and Day from the julian day number.
9804 */
9805 static void computeYMD(DateTime *p){
9806   int Z, A, B, C, D, E, X1;
9807   if( p->validYMD ) return;
9808   if( !p->validJD ){
9809     p->Y = 2000;
9810     p->M = 1;
9811     p->D = 1;
9812   }else{
9813     Z = p->rJD + 0.5;
9814     A = (Z - 1867216.25)/36524.25;
9815     A = Z + 1 + A - (A/4);
9816     B = A + 1524;
9817     C = (B - 122.1)/365.25;
9818     D = 365.25*C;
9819     E = (B-D)/30.6001;
9820     X1 = 30.6001*E;
9821     p->D = B - D - X1;
9822     p->M = E<14 ? E-1 : E-13;
9823     p->Y = p->M>2 ? C - 4716 : C - 4715;
9824   }
9825   p->validYMD = 1;
9826 }
9827
9828 /*
9829 ** Compute the Hour, Minute, and Seconds from the julian day number.
9830 */
9831 static void computeHMS(DateTime *p){
9832   int Z, s;
9833   if( p->validHMS ) return;
9834   computeJD(p);
9835   Z = p->rJD + 0.5;
9836   s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
9837   p->s = 0.001*s;
9838   s = p->s;
9839   p->s -= s;
9840   p->h = s/3600;
9841   s -= p->h*3600;
9842   p->m = s/60;
9843   p->s += s - p->m*60;
9844   p->validHMS = 1;
9845 }
9846
9847 /*
9848 ** Compute both YMD and HMS
9849 */
9850 static void computeYMD_HMS(DateTime *p){
9851   computeYMD(p);
9852   computeHMS(p);
9853 }
9854
9855 /*
9856 ** Clear the YMD and HMS and the TZ
9857 */
9858 static void clearYMD_HMS_TZ(DateTime *p){
9859   p->validYMD = 0;
9860   p->validHMS = 0;
9861   p->validTZ = 0;
9862 }
9863
9864 /*
9865 ** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
9866 ** for the time value p where p is in UTC.
9867 */
9868 static double localtimeOffset(DateTime *p){
9869   DateTime x, y;
9870   time_t t;
9871   x = *p;
9872   computeYMD_HMS(&x);
9873   if( x.Y<1971 || x.Y>=2038 ){
9874     x.Y = 2000;
9875     x.M = 1;
9876     x.D = 1;
9877     x.h = 0;
9878     x.m = 0;
9879     x.s = 0.0;
9880   } else {
9881     int s = x.s + 0.5;
9882     x.s = s;
9883   }
9884   x.tz = 0;
9885   x.validJD = 0;
9886   computeJD(&x);
9887   t = (x.rJD-2440587.5)*86400.0 + 0.5;
9888 #ifdef HAVE_LOCALTIME_R
9889   {
9890     struct tm sLocal;
9891     localtime_r(&t, &sLocal);
9892     y.Y = sLocal.tm_year + 1900;
9893     y.M = sLocal.tm_mon + 1;
9894     y.D = sLocal.tm_mday;
9895     y.h = sLocal.tm_hour;
9896     y.m = sLocal.tm_min;
9897     y.s = sLocal.tm_sec;
9898   }
9899 #else
9900   {
9901     struct tm *pTm;
9902     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
9903     pTm = localtime(&t);
9904     y.Y = pTm->tm_year + 1900;
9905     y.M = pTm->tm_mon + 1;
9906     y.D = pTm->tm_mday;
9907     y.h = pTm->tm_hour;
9908     y.m = pTm->tm_min;
9909     y.s = pTm->tm_sec;
9910     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
9911   }
9912 #endif
9913   y.validYMD = 1;
9914   y.validHMS = 1;
9915   y.validJD = 0;
9916   y.validTZ = 0;
9917   computeJD(&y);
9918   return y.rJD - x.rJD;
9919 }
9920
9921 /*
9922 ** Process a modifier to a date-time stamp.  The modifiers are
9923 ** as follows:
9924 **
9925 **     NNN days
9926 **     NNN hours
9927 **     NNN minutes
9928 **     NNN.NNNN seconds
9929 **     NNN months
9930 **     NNN years
9931 **     start of month
9932 **     start of year
9933 **     start of week
9934 **     start of day
9935 **     weekday N
9936 **     unixepoch
9937 **     localtime
9938 **     utc
9939 **
9940 ** Return 0 on success and 1 if there is any kind of error.
9941 */
9942 static int parseModifier(const char *zMod, DateTime *p){
9943   int rc = 1;
9944   int n;
9945   double r;
9946   char *z, zBuf[30];
9947   z = zBuf;
9948   for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
9949     z[n] = tolower(zMod[n]);
9950   }
9951   z[n] = 0;
9952   switch( z[0] ){
9953     case 'l': {
9954       /*    localtime
9955       **
9956       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
9957       ** show local time.
9958       */
9959       if( strcmp(z, "localtime")==0 ){
9960         computeJD(p);
9961         p->rJD += localtimeOffset(p);
9962         clearYMD_HMS_TZ(p);
9963         rc = 0;
9964       }
9965       break;
9966     }
9967     case 'u': {
9968       /*
9969       **    unixepoch
9970       **
9971       ** Treat the current value of p->rJD as the number of
9972       ** seconds since 1970.  Convert to a real julian day number.
9973       */
9974       if( strcmp(z, "unixepoch")==0 && p->validJD ){
9975         p->rJD = p->rJD/86400.0 + 2440587.5;
9976         clearYMD_HMS_TZ(p);
9977         rc = 0;
9978       }else if( strcmp(z, "utc")==0 ){
9979         double c1;
9980         computeJD(p);
9981         c1 = localtimeOffset(p);
9982         p->rJD -= c1;
9983         clearYMD_HMS_TZ(p);
9984         p->rJD += c1 - localtimeOffset(p);
9985         rc = 0;
9986       }
9987       break;
9988     }
9989     case 'w': {
9990       /*
9991       **    weekday N
9992       **
9993       ** Move the date to the same time on the next occurrence of
9994       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
9995       ** date is already on the appropriate weekday, this is a no-op.
9996       */
9997       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
9998                  && (n=r)==r && n>=0 && r<7 ){
9999         int Z;
10000         computeYMD_HMS(p);
10001         p->validTZ = 0;
10002         p->validJD = 0;
10003         computeJD(p);
10004         Z = p->rJD + 1.5;
10005         Z %= 7;
10006         if( Z>n ) Z -= 7;
10007         p->rJD += n - Z;
10008         clearYMD_HMS_TZ(p);
10009         rc = 0;
10010       }
10011       break;
10012     }
10013     case 's': {
10014       /*
10015       **    start of TTTTT
10016       **
10017       ** Move the date backwards to the beginning of the current day,
10018       ** or month or year.
10019       */
10020       if( strncmp(z, "start of ", 9)!=0 ) break;
10021       z += 9;
10022       computeYMD(p);
10023       p->validHMS = 1;
10024       p->h = p->m = 0;
10025       p->s = 0.0;
10026       p->validTZ = 0;
10027       p->validJD = 0;
10028       if( strcmp(z,"month")==0 ){
10029         p->D = 1;
10030         rc = 0;
10031       }else if( strcmp(z,"year")==0 ){
10032         computeYMD(p);
10033         p->M = 1;
10034         p->D = 1;
10035         rc = 0;
10036       }else if( strcmp(z,"day")==0 ){
10037         rc = 0;
10038       }
10039       break;
10040     }
10041     case '+':
10042     case '-':
10043     case '0':
10044     case '1':
10045     case '2':
10046     case '3':
10047     case '4':
10048     case '5':
10049     case '6':
10050     case '7':
10051     case '8':
10052     case '9': {
10053       n = getValue(z, &r);
10054       assert( n>=1 );
10055       if( z[n]==':' ){
10056         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
10057         ** specified number of hours, minutes, seconds, and fractional seconds
10058         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
10059         ** omitted.
10060         */
10061         const char *z2 = z;
10062         DateTime tx;
10063         int day;
10064         if( !isdigit(*(u8*)z2) ) z2++;
10065         memset(&tx, 0, sizeof(tx));
10066         if( parseHhMmSs(z2, &tx) ) break;
10067         computeJD(&tx);
10068         tx.rJD -= 0.5;
10069         day = (int)tx.rJD;
10070         tx.rJD -= day;
10071         if( z[0]=='-' ) tx.rJD = -tx.rJD;
10072         computeJD(p);
10073         clearYMD_HMS_TZ(p);
10074         p->rJD += tx.rJD;
10075         rc = 0;
10076         break;
10077       }
10078       z += n;
10079       while( isspace(*(u8*)z) ) z++;
10080       n = strlen(z);
10081       if( n>10 || n<3 ) break;
10082       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
10083       computeJD(p);
10084       rc = 0;
10085       if( n==3 && strcmp(z,"day")==0 ){
10086         p->rJD += r;
10087       }else if( n==4 && strcmp(z,"hour")==0 ){
10088         p->rJD += r/24.0;
10089       }else if( n==6 && strcmp(z,"minute")==0 ){
10090         p->rJD += r/(24.0*60.0);
10091       }else if( n==6 && strcmp(z,"second")==0 ){
10092         p->rJD += r/(24.0*60.0*60.0);
10093       }else if( n==5 && strcmp(z,"month")==0 ){
10094         int x, y;
10095         computeYMD_HMS(p);
10096         p->M += r;
10097         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
10098         p->Y += x;
10099         p->M -= x*12;
10100         p->validJD = 0;
10101         computeJD(p);
10102         y = r;
10103         if( y!=r ){
10104           p->rJD += (r - y)*30.0;
10105         }
10106       }else if( n==4 && strcmp(z,"year")==0 ){
10107         computeYMD_HMS(p);
10108         p->Y += r;
10109         p->validJD = 0;
10110         computeJD(p);
10111       }else{
10112         rc = 1;
10113       }
10114       clearYMD_HMS_TZ(p);
10115       break;
10116     }
10117     default: {
10118       break;
10119     }
10120   }
10121   return rc;
10122 }
10123
10124 /*
10125 ** Process time function arguments.  argv[0] is a date-time stamp.
10126 ** argv[1] and following are modifiers.  Parse them all and write
10127 ** the resulting time into the DateTime structure p.  Return 0
10128 ** on success and 1 if there are any errors.
10129 **
10130 ** If there are zero parameters (if even argv[0] is undefined)
10131 ** then assume a default value of "now" for argv[0].
10132 */
10133 static int isDate(
10134   sqlite3_context *context, 
10135   int argc, 
10136   sqlite3_value **argv, 
10137   DateTime *p
10138 ){
10139   int i;
10140   const unsigned char *z;
10141   static const unsigned char zDflt[] = "now";
10142   if( argc==0 ){
10143     z = zDflt;
10144   }else{
10145     z = sqlite3_value_text(argv[0]);
10146   }
10147   if( !z || parseDateOrTime(context, (char*)z, p) ){
10148     return 1;
10149   }
10150   for(i=1; i<argc; i++){
10151     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
10152       return 1;
10153     }
10154   }
10155   return 0;
10156 }
10157
10158
10159 /*
10160 ** The following routines implement the various date and time functions
10161 ** of SQLite.
10162 */
10163
10164 /*
10165 **    julianday( TIMESTRING, MOD, MOD, ...)
10166 **
10167 ** Return the julian day number of the date specified in the arguments
10168 */
10169 static void juliandayFunc(
10170   sqlite3_context *context,
10171   int argc,
10172   sqlite3_value **argv
10173 ){
10174   DateTime x;
10175   if( isDate(context, argc, argv, &x)==0 ){
10176     computeJD(&x);
10177     sqlite3_result_double(context, x.rJD);
10178   }
10179 }
10180
10181 /*
10182 **    datetime( TIMESTRING, MOD, MOD, ...)
10183 **
10184 ** Return YYYY-MM-DD HH:MM:SS
10185 */
10186 static void datetimeFunc(
10187   sqlite3_context *context,
10188   int argc,
10189   sqlite3_value **argv
10190 ){
10191   DateTime x;
10192   if( isDate(context, argc, argv, &x)==0 ){
10193     char zBuf[100];
10194     computeYMD_HMS(&x);
10195     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
10196                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
10197     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
10198   }
10199 }
10200
10201 /*
10202 **    time( TIMESTRING, MOD, MOD, ...)
10203 **
10204 ** Return HH:MM:SS
10205 */
10206 static void timeFunc(
10207   sqlite3_context *context,
10208   int argc,
10209   sqlite3_value **argv
10210 ){
10211   DateTime x;
10212   if( isDate(context, argc, argv, &x)==0 ){
10213     char zBuf[100];
10214     computeHMS(&x);
10215     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
10216     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
10217   }
10218 }
10219
10220 /*
10221 **    date( TIMESTRING, MOD, MOD, ...)
10222 **
10223 ** Return YYYY-MM-DD
10224 */
10225 static void dateFunc(
10226   sqlite3_context *context,
10227   int argc,
10228   sqlite3_value **argv
10229 ){
10230   DateTime x;
10231   if( isDate(context, argc, argv, &x)==0 ){
10232     char zBuf[100];
10233     computeYMD(&x);
10234     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
10235     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
10236   }
10237 }
10238
10239 /*
10240 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
10241 **
10242 ** Return a string described by FORMAT.  Conversions as follows:
10243 **
10244 **   %d  day of month
10245 **   %f  ** fractional seconds  SS.SSS
10246 **   %H  hour 00-24
10247 **   %j  day of year 000-366
10248 **   %J  ** Julian day number
10249 **   %m  month 01-12
10250 **   %M  minute 00-59
10251 **   %s  seconds since 1970-01-01
10252 **   %S  seconds 00-59
10253 **   %w  day of week 0-6  sunday==0
10254 **   %W  week of year 00-53
10255 **   %Y  year 0000-9999
10256 **   %%  %
10257 */
10258 static void strftimeFunc(
10259   sqlite3_context *context,
10260   int argc,
10261   sqlite3_value **argv
10262 ){
10263   DateTime x;
10264   u64 n;
10265   int i, j;
10266   char *z;
10267   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
10268   char zBuf[100];
10269   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
10270   for(i=0, n=1; zFmt[i]; i++, n++){
10271     if( zFmt[i]=='%' ){
10272       switch( zFmt[i+1] ){
10273         case 'd':
10274         case 'H':
10275         case 'm':
10276         case 'M':
10277         case 'S':
10278         case 'W':
10279           n++;
10280           /* fall thru */
10281         case 'w':
10282         case '%':
10283           break;
10284         case 'f':
10285           n += 8;
10286           break;
10287         case 'j':
10288           n += 3;
10289           break;
10290         case 'Y':
10291           n += 8;
10292           break;
10293         case 's':
10294         case 'J':
10295           n += 50;
10296           break;
10297         default:
10298           return;  /* ERROR.  return a NULL */
10299       }
10300       i++;
10301     }
10302   }
10303   if( n<sizeof(zBuf) ){
10304     z = zBuf;
10305   }else if( n>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
10306     sqlite3_result_error_toobig(context);
10307     return;
10308   }else{
10309     z = sqlite3_malloc( n );
10310     if( z==0 ){
10311       sqlite3_result_error_nomem(context);
10312       return;
10313     }
10314   }
10315   computeJD(&x);
10316   computeYMD_HMS(&x);
10317   for(i=j=0; zFmt[i]; i++){
10318     if( zFmt[i]!='%' ){
10319       z[j++] = zFmt[i];
10320     }else{
10321       i++;
10322       switch( zFmt[i] ){
10323         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
10324         case 'f': {
10325           double s = x.s;
10326           if( s>59.999 ) s = 59.999;
10327           sqlite3_snprintf(7, &z[j],"%06.3f", s);
10328           j += strlen(&z[j]);
10329           break;
10330         }
10331         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
10332         case 'W': /* Fall thru */
10333         case 'j': {
10334           int nDay;             /* Number of days since 1st day of year */
10335           DateTime y = x;
10336           y.validJD = 0;
10337           y.M = 1;
10338           y.D = 1;
10339           computeJD(&y);
10340           nDay = x.rJD - y.rJD + 0.5;
10341           if( zFmt[i]=='W' ){
10342             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
10343             wd = ((int)(x.rJD+0.5)) % 7;
10344             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
10345             j += 2;
10346           }else{
10347             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
10348             j += 3;
10349           }
10350           break;
10351         }
10352         case 'J': {
10353           sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
10354           j+=strlen(&z[j]);
10355           break;
10356         }
10357         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
10358         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
10359         case 's': {
10360           sqlite3_snprintf(30,&z[j],"%d",
10361                            (int)((x.rJD-2440587.5)*86400.0 + 0.5));
10362           j += strlen(&z[j]);
10363           break;
10364         }
10365         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
10366         case 'w':  z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
10367         case 'Y':  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
10368         default:   z[j++] = '%'; break;
10369       }
10370     }
10371   }
10372   z[j] = 0;
10373   sqlite3_result_text(context, z, -1,
10374                       z==zBuf ? SQLITE_TRANSIENT : sqlite3_free);
10375 }
10376
10377 /*
10378 ** current_time()
10379 **
10380 ** This function returns the same value as time('now').
10381 */
10382 static void ctimeFunc(
10383   sqlite3_context *context,
10384   int argc,
10385   sqlite3_value **argv
10386 ){
10387   timeFunc(context, 0, 0);
10388 }
10389
10390 /*
10391 ** current_date()
10392 **
10393 ** This function returns the same value as date('now').
10394 */
10395 static void cdateFunc(
10396   sqlite3_context *context,
10397   int argc,
10398   sqlite3_value **argv
10399 ){
10400   dateFunc(context, 0, 0);
10401 }
10402
10403 /*
10404 ** current_timestamp()
10405 **
10406 ** This function returns the same value as datetime('now').
10407 */
10408 static void ctimestampFunc(
10409   sqlite3_context *context,
10410   int argc,
10411   sqlite3_value **argv
10412 ){
10413   datetimeFunc(context, 0, 0);
10414 }
10415 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
10416
10417 #ifdef SQLITE_OMIT_DATETIME_FUNCS
10418 /*
10419 ** If the library is compiled to omit the full-scale date and time
10420 ** handling (to get a smaller binary), the following minimal version
10421 ** of the functions current_time(), current_date() and current_timestamp()
10422 ** are included instead. This is to support column declarations that
10423 ** include "DEFAULT CURRENT_TIME" etc.
10424 **
10425 ** This function uses the C-library functions time(), gmtime()
10426 ** and strftime(). The format string to pass to strftime() is supplied
10427 ** as the user-data for the function.
10428 */
10429 static void currentTimeFunc(
10430   sqlite3_context *context,
10431   int argc,
10432   sqlite3_value **argv
10433 ){
10434   time_t t;
10435   char *zFormat = (char *)sqlite3_user_data(context);
10436   sqlite3 *db;
10437   double rT;
10438   char zBuf[20];
10439
10440   db = sqlite3_context_db_handle(context);
10441   sqlite3OsCurrentTime(db->pVfs, &rT);
10442   t = 86400.0*(rT - 2440587.5) + 0.5;
10443 #ifdef HAVE_GMTIME_R
10444   {
10445     struct tm sNow;
10446     gmtime_r(&t, &sNow);
10447     strftime(zBuf, 20, zFormat, &sNow);
10448   }
10449 #else
10450   {
10451     struct tm *pTm;
10452     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
10453     pTm = gmtime(&t);
10454     strftime(zBuf, 20, zFormat, pTm);
10455     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
10456   }
10457 #endif
10458
10459   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
10460 }
10461 #endif
10462
10463 /*
10464 ** This function registered all of the above C functions as SQL
10465 ** functions.  This should be the only routine in this file with
10466 ** external linkage.
10467 */
10468 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
10469 #ifndef SQLITE_OMIT_DATETIME_FUNCS
10470   static const struct {
10471      char *zName;
10472      int nArg;
10473      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
10474   } aFuncs[] = {
10475     { "julianday", -1, juliandayFunc   },
10476     { "date",      -1, dateFunc        },
10477     { "time",      -1, timeFunc        },
10478     { "datetime",  -1, datetimeFunc    },
10479     { "strftime",  -1, strftimeFunc    },
10480     { "current_time",       0, ctimeFunc      },
10481     { "current_timestamp",  0, ctimestampFunc },
10482     { "current_date",       0, cdateFunc      },
10483   };
10484   int i;
10485
10486   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
10487     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
10488         SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
10489   }
10490 #else
10491   static const struct {
10492      char *zName;
10493      char *zFormat;
10494   } aFuncs[] = {
10495     { "current_time", "%H:%M:%S" },
10496     { "current_date", "%Y-%m-%d" },
10497     { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
10498   };
10499   int i;
10500
10501   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
10502     sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8, 
10503         aFuncs[i].zFormat, currentTimeFunc, 0, 0);
10504   }
10505 #endif
10506 }
10507
10508 /************** End of date.c ************************************************/
10509 /************** Begin file os.c **********************************************/
10510 /*
10511 ** 2005 November 29
10512 **
10513 ** The author disclaims copyright to this source code.  In place of
10514 ** a legal notice, here is a blessing:
10515 **
10516 **    May you do good and not evil.
10517 **    May you find forgiveness for yourself and forgive others.
10518 **    May you share freely, never taking more than you give.
10519 **
10520 ******************************************************************************
10521 **
10522 ** This file contains OS interface code that is common to all
10523 ** architectures.
10524 */
10525 #define _SQLITE_OS_C_ 1
10526 #undef _SQLITE_OS_C_
10527
10528 /*
10529 ** The default SQLite sqlite3_vfs implementations do not allocate
10530 ** memory (actually, os_unix.c allocates a small amount of memory
10531 ** from within OsOpen()), but some third-party implementations may.
10532 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
10533 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
10534 **
10535 ** The following functions are instrumented for malloc() failure 
10536 ** testing:
10537 **
10538 **     sqlite3OsOpen()
10539 **     sqlite3OsRead()
10540 **     sqlite3OsWrite()
10541 **     sqlite3OsSync()
10542 **     sqlite3OsLock()
10543 **
10544 */
10545 #if defined(SQLITE_TEST) && (OS_WIN==0)
10546   #define DO_OS_MALLOC_TEST if (1) {            \
10547     void *pTstAlloc = sqlite3_malloc(10);       \
10548     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;  \
10549     sqlite3_free(pTstAlloc);                    \
10550   }
10551 #else
10552   #define DO_OS_MALLOC_TEST
10553 #endif
10554
10555 /*
10556 ** The following routines are convenience wrappers around methods
10557 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
10558 ** of this would be completely automatic if SQLite were coded using
10559 ** C++ instead of plain old C.
10560 */
10561 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
10562   int rc = SQLITE_OK;
10563   if( pId->pMethods ){
10564     rc = pId->pMethods->xClose(pId);
10565     pId->pMethods = 0;
10566   }
10567   return rc;
10568 }
10569 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
10570   DO_OS_MALLOC_TEST;
10571   return id->pMethods->xRead(id, pBuf, amt, offset);
10572 }
10573 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
10574   DO_OS_MALLOC_TEST;
10575   return id->pMethods->xWrite(id, pBuf, amt, offset);
10576 }
10577 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
10578   return id->pMethods->xTruncate(id, size);
10579 }
10580 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
10581   DO_OS_MALLOC_TEST;
10582   return id->pMethods->xSync(id, flags);
10583 }
10584 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
10585   return id->pMethods->xFileSize(id, pSize);
10586 }
10587 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
10588   DO_OS_MALLOC_TEST;
10589   return id->pMethods->xLock(id, lockType);
10590 }
10591 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
10592   return id->pMethods->xUnlock(id, lockType);
10593 }
10594 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id){
10595   return id->pMethods->xCheckReservedLock(id);
10596 }
10597 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
10598   return id->pMethods->xFileControl(id,op,pArg);
10599 }
10600 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
10601   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
10602   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
10603 }
10604 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
10605   return id->pMethods->xDeviceCharacteristics(id);
10606 }
10607
10608 /*
10609 ** The next group of routines are convenience wrappers around the
10610 ** VFS methods.
10611 */
10612 SQLITE_PRIVATE int sqlite3OsOpen(
10613   sqlite3_vfs *pVfs, 
10614   const char *zPath, 
10615   sqlite3_file *pFile, 
10616   int flags, 
10617   int *pFlagsOut
10618 ){
10619   DO_OS_MALLOC_TEST;
10620   return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
10621 }
10622 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
10623   return pVfs->xDelete(pVfs, zPath, dirSync);
10624 }
10625 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
10626   int rc;
10627 #ifdef SQLITE_TEST
10628   void *pTstAlloc = sqlite3_malloc(10);
10629   if (!pTstAlloc) return -1;
10630   sqlite3_free(pTstAlloc);
10631 #endif
10632   rc = pVfs->xAccess(pVfs, zPath, flags);
10633   return rc;
10634 }
10635 SQLITE_PRIVATE int sqlite3OsGetTempname(sqlite3_vfs *pVfs, int nBufOut, char *zBufOut){
10636   return pVfs->xGetTempname(pVfs, nBufOut, zBufOut);
10637 }
10638 SQLITE_PRIVATE int sqlite3OsFullPathname(
10639   sqlite3_vfs *pVfs, 
10640   const char *zPath, 
10641   int nPathOut, 
10642   char *zPathOut
10643 ){
10644   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
10645 }
10646 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
10647   return pVfs->xDlOpen(pVfs, zPath);
10648 }
10649 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
10650   pVfs->xDlError(pVfs, nByte, zBufOut);
10651 }
10652 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
10653   return pVfs->xDlSym(pVfs, pHandle, zSymbol);
10654 }
10655 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
10656   pVfs->xDlClose(pVfs, pHandle);
10657 }
10658 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
10659   return pVfs->xRandomness(pVfs, nByte, zBufOut);
10660 }
10661 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
10662   return pVfs->xSleep(pVfs, nMicro);
10663 }
10664 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
10665   return pVfs->xCurrentTime(pVfs, pTimeOut);
10666 }
10667
10668 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
10669   sqlite3_vfs *pVfs, 
10670   const char *zFile, 
10671   sqlite3_file **ppFile, 
10672   int flags,
10673   int *pOutFlags
10674 ){
10675   int rc = SQLITE_NOMEM;
10676   sqlite3_file *pFile;
10677   pFile = (sqlite3_file *)sqlite3_malloc(pVfs->szOsFile);
10678   if( pFile ){
10679     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
10680     if( rc!=SQLITE_OK ){
10681       sqlite3_free(pFile);
10682     }else{
10683       *ppFile = pFile;
10684     }
10685   }
10686   return rc;
10687 }
10688 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
10689   int rc = SQLITE_OK;
10690   assert( pFile );
10691   rc = sqlite3OsClose(pFile);
10692   sqlite3_free(pFile);
10693   return rc;
10694 }
10695
10696 /*
10697 ** The list of all registered VFS implementations.  This list is
10698 ** initialized to the single VFS returned by sqlite3OsDefaultVfs()
10699 ** upon the first call to sqlite3_vfs_find().
10700 */
10701 static sqlite3_vfs *vfsList = 0;
10702
10703 /*
10704 ** Locate a VFS by name.  If no name is given, simply return the
10705 ** first VFS on the list.
10706 */
10707 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
10708 #ifndef SQLITE_MUTEX_NOOP
10709   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
10710 #endif
10711   sqlite3_vfs *pVfs = 0;
10712   static int isInit = 0;
10713   sqlite3_mutex_enter(mutex);
10714   if( !isInit ){
10715     vfsList = sqlite3OsDefaultVfs();
10716     isInit = 1;
10717   }
10718   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
10719     if( zVfs==0 ) break;
10720     if( strcmp(zVfs, pVfs->zName)==0 ) break;
10721   }
10722   sqlite3_mutex_leave(mutex);
10723   return pVfs;
10724 }
10725
10726 /*
10727 ** Unlink a VFS from the linked list
10728 */
10729 static void vfsUnlink(sqlite3_vfs *pVfs){
10730   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)) );
10731   if( pVfs==0 ){
10732     /* No-op */
10733   }else if( vfsList==pVfs ){
10734     vfsList = pVfs->pNext;
10735   }else if( vfsList ){
10736     sqlite3_vfs *p = vfsList;
10737     while( p->pNext && p->pNext!=pVfs ){
10738       p = p->pNext;
10739     }
10740     if( p->pNext==pVfs ){
10741       p->pNext = pVfs->pNext;
10742     }
10743   }
10744 }
10745
10746 /*
10747 ** Register a VFS with the system.  It is harmless to register the same
10748 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
10749 ** true.
10750 */
10751 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
10752 #ifndef SQLITE_MUTEX_NOOP
10753   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
10754 #endif
10755   sqlite3_vfs_find(0);  /* Make sure we are initialized */
10756   sqlite3_mutex_enter(mutex);
10757   vfsUnlink(pVfs);
10758   if( makeDflt || vfsList==0 ){
10759     pVfs->pNext = vfsList;
10760     vfsList = pVfs;
10761   }else{
10762     pVfs->pNext = vfsList->pNext;
10763     vfsList->pNext = pVfs;
10764   }
10765   assert(vfsList);
10766   sqlite3_mutex_leave(mutex);
10767   return SQLITE_OK;
10768 }
10769
10770 /*
10771 ** Unregister a VFS so that it is no longer accessible.
10772 */
10773 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
10774 #ifndef SQLITE_MUTEX_NOOP
10775   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
10776 #endif
10777   sqlite3_mutex_enter(mutex);
10778   vfsUnlink(pVfs);
10779   sqlite3_mutex_leave(mutex);
10780   return SQLITE_OK;
10781 }
10782
10783 /*
10784 ** Provide a default sqlite3OsDefaultVfs() implementation in the
10785 ** cases where none of the standard backends are used.
10786 */
10787 #if !OS_UNIX && !OS_WIN && !OS_OS2
10788 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){ return 0; }
10789 #endif
10790
10791 /************** End of os.c **************************************************/
10792 /************** Begin file fault.c *******************************************/
10793 /*
10794 ** 2008 Jan 22
10795 **
10796 ** The author disclaims copyright to this source code.  In place of
10797 ** a legal notice, here is a blessing:
10798 **
10799 **    May you do good and not evil.
10800 **    May you find forgiveness for yourself and forgive others.
10801 **    May you share freely, never taking more than you give.
10802 **
10803 *************************************************************************
10804 ** This file contains code to implement a fault-injector used for
10805 ** testing and verification of SQLite.
10806 **
10807 ** Subsystems within SQLite can call sqlite3FaultStep() to see if
10808 ** they should simulate a fault.  sqlite3FaultStep() normally returns
10809 ** zero but will return non-zero if a fault should be simulated.
10810 ** Fault injectors can be used, for example, to simulate memory
10811 ** allocation failures or I/O errors.
10812 **
10813 ** The fault injector is omitted from the code if SQLite is
10814 ** compiled with -DSQLITE_OMIT_BUILTIN_TEST=1.  There is a very
10815 ** small performance hit for leaving the fault injector in the code.
10816 ** Commerical products will probably want to omit the fault injector
10817 ** from production builds.  But safety-critical systems who work
10818 ** under the motto "fly what you test and test what you fly" may
10819 ** choose to leave the fault injector enabled even in production.
10820 */
10821
10822 #ifndef SQLITE_OMIT_BUILTIN_TEST
10823
10824 /*
10825 ** There can be various kinds of faults.  For example, there can be
10826 ** a memory allocation failure.  Or an I/O failure.  For each different
10827 ** fault type, there is a separate FaultInjector structure to keep track
10828 ** of the status of that fault.
10829 */
10830 static struct FaultInjector {
10831   int iCountdown;   /* Number of pending successes before we hit a failure */
10832   int nRepeat;      /* Number of times to repeat the failure */
10833   int nBenign;      /* Number of benign failures seen since last config */
10834   int nFail;        /* Number of failures seen since last config */
10835   u8 enable;        /* True if enabled */
10836   i16 benign;       /* Positive if next failure will be benign */
10837 } aFault[SQLITE_FAULTINJECTOR_COUNT];
10838
10839 /*
10840 ** This routine configures and enables a fault injector.  After
10841 ** calling this routine, aFaultStep() will return false (zero)
10842 ** nDelay times, then it will return true nRepeat times,
10843 ** then it will again begin returning false.
10844 */
10845 SQLITE_PRIVATE void sqlite3FaultConfig(int id, int nDelay, int nRepeat){
10846   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10847   aFault[id].iCountdown = nDelay;
10848   aFault[id].nRepeat = nRepeat;
10849   aFault[id].nBenign = 0;
10850   aFault[id].nFail = 0;
10851   aFault[id].enable = nDelay>=0;
10852   aFault[id].benign = 0;
10853 }
10854
10855 /*
10856 ** Return the number of faults (both hard and benign faults) that have
10857 ** occurred since the injector was last configured.
10858 */
10859 SQLITE_PRIVATE int sqlite3FaultFailures(int id){
10860   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10861   return aFault[id].nFail;
10862 }
10863
10864 /*
10865 ** Return the number of benign faults that have occurred since the
10866 ** injector was last configured.
10867 */
10868 SQLITE_PRIVATE int sqlite3FaultBenignFailures(int id){
10869   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10870   return aFault[id].nBenign;
10871 }
10872
10873 /*
10874 ** Return the number of successes that will occur before the next failure.
10875 ** If no failures are scheduled, return -1.
10876 */
10877 SQLITE_PRIVATE int sqlite3FaultPending(int id){
10878   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10879   if( aFault[id].enable ){
10880     return aFault[id].iCountdown;
10881   }else{
10882     return -1;
10883   }
10884 }
10885
10886 /* 
10887 ** After this routine causes subsequent faults to be either benign
10888 ** or hard (not benign), according to the "enable" parameter.
10889 **
10890 ** Most faults are hard.  In other words, most faults cause
10891 ** an error to be propagated back up to the application interface.
10892 ** However, sometimes a fault is easily recoverable.  For example,
10893 ** if a malloc fails while resizing a hash table, this is completely
10894 ** recoverable simply by not carrying out the resize.  The hash table
10895 ** will continue to function normally.  So a malloc failure during
10896 ** a hash table resize is a benign fault.  
10897 */
10898 SQLITE_PRIVATE void sqlite3FaultBeginBenign(int id){
10899   if( id<0 ){
10900     for(id=0; id<SQLITE_FAULTINJECTOR_COUNT; id++){
10901       aFault[id].benign++;
10902     }
10903   }else{
10904     assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10905     aFault[id].benign++;
10906   }
10907 }
10908 SQLITE_PRIVATE void sqlite3FaultEndBenign(int id){
10909   if( id<0 ){
10910     for(id=0; id<SQLITE_FAULTINJECTOR_COUNT; id++){
10911       assert( aFault[id].benign>0 );
10912       aFault[id].benign--;
10913     }
10914   }else{
10915     assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10916     assert( aFault[id].benign>0 );
10917     aFault[id].benign--;
10918   }
10919 }
10920
10921 /*
10922 ** This routine exists as a place to set a breakpoint that will
10923 ** fire on any simulated fault.
10924 */
10925 static void sqlite3Fault(void){
10926   static int cnt = 0;
10927   cnt++;
10928 }
10929
10930
10931 /*
10932 ** Check to see if a fault should be simulated.  Return true to simulate
10933 ** the fault.  Return false if the fault should not be simulated.
10934 */
10935 SQLITE_PRIVATE int sqlite3FaultStep(int id){
10936   assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT );
10937   if( likely(!aFault[id].enable) ){
10938     return 0;
10939   }
10940   if( aFault[id].iCountdown>0 ){
10941     aFault[id].iCountdown--;
10942     return 0;
10943   }
10944   sqlite3Fault();
10945   aFault[id].nFail++;
10946   if( aFault[id].benign>0 ){
10947     aFault[id].nBenign++;
10948   }
10949   aFault[id].nRepeat--;
10950   if( aFault[id].nRepeat<=0 ){
10951     aFault[id].enable = 0;
10952   }
10953   return 1;  
10954 }
10955
10956 #endif /* SQLITE_OMIT_BUILTIN_TEST */
10957
10958 /************** End of fault.c ***********************************************/
10959 /************** Begin file mem1.c ********************************************/
10960 /*
10961 ** 2007 August 14
10962 **
10963 ** The author disclaims copyright to this source code.  In place of
10964 ** a legal notice, here is a blessing:
10965 **
10966 **    May you do good and not evil.
10967 **    May you find forgiveness for yourself and forgive others.
10968 **    May you share freely, never taking more than you give.
10969 **
10970 *************************************************************************
10971 ** This file contains the C functions that implement a memory
10972 ** allocation subsystem for use by SQLite.  
10973 **
10974 ** $Id: mem1.c,v 1.17 2008/03/18 00:07:11 drh Exp $
10975 */
10976
10977 /*
10978 ** This version of the memory allocator is the default.  It is
10979 ** used when no other memory allocator is specified using compile-time
10980 ** macros.
10981 */
10982 #ifdef SQLITE_SYSTEM_MALLOC
10983
10984 /*
10985 ** All of the static variables used by this module are collected
10986 ** into a single structure named "mem".  This is to keep the
10987 ** static variables organized and to reduce namespace pollution
10988 ** when this module is combined with other in the amalgamation.
10989 */
10990 static struct {
10991   /*
10992   ** The alarm callback and its arguments.  The mem.mutex lock will
10993   ** be held while the callback is running.  Recursive calls into
10994   ** the memory subsystem are allowed, but no new callbacks will be
10995   ** issued.  The alarmBusy variable is set to prevent recursive
10996   ** callbacks.
10997   */
10998   sqlite3_int64 alarmThreshold;
10999   void (*alarmCallback)(void*, sqlite3_int64,int);
11000   void *alarmArg;
11001   int alarmBusy;
11002   
11003   /*
11004   ** Mutex to control access to the memory allocation subsystem.
11005   */
11006   sqlite3_mutex *mutex;
11007   
11008   /*
11009   ** Current allocation and high-water mark.
11010   */
11011   sqlite3_int64 nowUsed;
11012   sqlite3_int64 mxUsed;
11013   
11014  
11015 } mem;
11016
11017 /*
11018 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
11019 */
11020 static void enterMem(void){
11021   if( mem.mutex==0 ){
11022     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
11023   }
11024   sqlite3_mutex_enter(mem.mutex);
11025 }
11026
11027 /*
11028 ** Return the amount of memory currently checked out.
11029 */
11030 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
11031   sqlite3_int64 n;
11032   enterMem();
11033   n = mem.nowUsed;
11034   sqlite3_mutex_leave(mem.mutex);  
11035   return n;
11036 }
11037
11038 /*
11039 ** Return the maximum amount of memory that has ever been
11040 ** checked out since either the beginning of this process
11041 ** or since the most recent reset.
11042 */
11043 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
11044   sqlite3_int64 n;
11045   enterMem();
11046   n = mem.mxUsed;
11047   if( resetFlag ){
11048     mem.mxUsed = mem.nowUsed;
11049   }
11050   sqlite3_mutex_leave(mem.mutex);  
11051   return n;
11052 }
11053
11054 /*
11055 ** Change the alarm callback
11056 */
11057 SQLITE_API int sqlite3_memory_alarm(
11058   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
11059   void *pArg,
11060   sqlite3_int64 iThreshold
11061 ){
11062   enterMem();
11063   mem.alarmCallback = xCallback;
11064   mem.alarmArg = pArg;
11065   mem.alarmThreshold = iThreshold;
11066   sqlite3_mutex_leave(mem.mutex);
11067   return SQLITE_OK;
11068 }
11069
11070 /*
11071 ** Trigger the alarm 
11072 */
11073 static void sqlite3MemsysAlarm(int nByte){
11074   void (*xCallback)(void*,sqlite3_int64,int);
11075   sqlite3_int64 nowUsed;
11076   void *pArg;
11077   if( mem.alarmCallback==0 || mem.alarmBusy  ) return;
11078   mem.alarmBusy = 1;
11079   xCallback = mem.alarmCallback;
11080   nowUsed = mem.nowUsed;
11081   pArg = mem.alarmArg;
11082   sqlite3_mutex_leave(mem.mutex);
11083   xCallback(pArg, nowUsed, nByte);
11084   sqlite3_mutex_enter(mem.mutex);
11085   mem.alarmBusy = 0;
11086 }
11087
11088 /*
11089 ** Allocate nBytes of memory
11090 */
11091 SQLITE_API void *sqlite3_malloc(int nBytes){
11092   sqlite3_int64 *p = 0;
11093   if( nBytes>0 ){
11094     enterMem();
11095     if( mem.alarmCallback!=0 && mem.nowUsed+nBytes>=mem.alarmThreshold ){
11096       sqlite3MemsysAlarm(nBytes);
11097     }
11098     if( sqlite3FaultStep(SQLITE_FAULTINJECTOR_MALLOC) ){
11099       p = 0;
11100     }else{
11101       p = malloc(nBytes+8);
11102       if( p==0 ){
11103         sqlite3MemsysAlarm(nBytes);
11104         p = malloc(nBytes+8);
11105       }
11106     }
11107     if( p ){
11108       p[0] = nBytes;
11109       p++;
11110       mem.nowUsed += nBytes;
11111       if( mem.nowUsed>mem.mxUsed ){
11112         mem.mxUsed = mem.nowUsed;
11113       }
11114     }
11115     sqlite3_mutex_leave(mem.mutex);
11116   }
11117   return (void*)p; 
11118 }
11119
11120 /*
11121 ** Free memory.
11122 */
11123 SQLITE_API void sqlite3_free(void *pPrior){
11124   sqlite3_int64 *p;
11125   int nByte;
11126   if( pPrior==0 ){
11127     return;
11128   }
11129   assert( mem.mutex!=0 );
11130   p = pPrior;
11131   p--;
11132   nByte = (int)*p;
11133   sqlite3_mutex_enter(mem.mutex);
11134   mem.nowUsed -= nByte;
11135   free(p);
11136   sqlite3_mutex_leave(mem.mutex);  
11137 }
11138
11139 /*
11140 ** Return the number of bytes allocated at p.
11141 */
11142 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
11143   sqlite3_int64 *pInt;
11144   if( !p ) return 0;
11145   pInt = p;
11146   return pInt[-1];
11147 }
11148
11149 /*
11150 ** Change the size of an existing memory allocation
11151 */
11152 SQLITE_API void *sqlite3_realloc(void *pPrior, int nBytes){
11153   int nOld;
11154   sqlite3_int64 *p;
11155   if( pPrior==0 ){
11156     return sqlite3_malloc(nBytes);
11157   }
11158   if( nBytes<=0 ){
11159     sqlite3_free(pPrior);
11160     return 0;
11161   }
11162   p = pPrior;
11163   p--;
11164   nOld = (int)p[0];
11165   assert( mem.mutex!=0 );
11166   sqlite3_mutex_enter(mem.mutex);
11167   if( mem.nowUsed+nBytes-nOld>=mem.alarmThreshold ){
11168     sqlite3MemsysAlarm(nBytes-nOld);
11169   }
11170   if( sqlite3FaultStep(SQLITE_FAULTINJECTOR_MALLOC) ){
11171     p = 0;
11172   }else{
11173     p = realloc(p, nBytes+8);
11174     if( p==0 ){
11175       sqlite3MemsysAlarm(nBytes);
11176       p = pPrior;
11177       p--;
11178       p = realloc(p, nBytes+8);
11179     }
11180   }
11181   if( p ){
11182     p[0] = nBytes;
11183     p++;
11184     mem.nowUsed += nBytes-nOld;
11185     if( mem.nowUsed>mem.mxUsed ){
11186       mem.mxUsed = mem.nowUsed;
11187     }
11188   }
11189   sqlite3_mutex_leave(mem.mutex);
11190   return (void*)p;
11191 }
11192
11193 #endif /* SQLITE_SYSTEM_MALLOC */
11194
11195 /************** End of mem1.c ************************************************/
11196 /************** Begin file mem2.c ********************************************/
11197 /*
11198 ** 2007 August 15
11199 **
11200 ** The author disclaims copyright to this source code.  In place of
11201 ** a legal notice, here is a blessing:
11202 **
11203 **    May you do good and not evil.
11204 **    May you find forgiveness for yourself and forgive others.
11205 **    May you share freely, never taking more than you give.
11206 **
11207 *************************************************************************
11208 ** This file contains the C functions that implement a memory
11209 ** allocation subsystem for use by SQLite.  
11210 **
11211 ** $Id: mem2.c,v 1.26 2008/04/10 14:57:25 drh Exp $
11212 */
11213
11214 /*
11215 ** This version of the memory allocator is used only if the
11216 ** SQLITE_MEMDEBUG macro is defined
11217 */
11218 #ifdef SQLITE_MEMDEBUG
11219
11220 /*
11221 ** The backtrace functionality is only available with GLIBC
11222 */
11223 #ifdef __GLIBC__
11224   extern int backtrace(void**,int);
11225   extern void backtrace_symbols_fd(void*const*,int,int);
11226 #else
11227 # define backtrace(A,B) 0
11228 # define backtrace_symbols_fd(A,B,C)
11229 #endif
11230
11231 /*
11232 ** Each memory allocation looks like this:
11233 **
11234 **  ------------------------------------------------------------------------
11235 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
11236 **  ------------------------------------------------------------------------
11237 **
11238 ** The application code sees only a pointer to the allocation.  We have
11239 ** to back up from the allocation pointer to find the MemBlockHdr.  The
11240 ** MemBlockHdr tells us the size of the allocation and the number of
11241 ** backtrace pointers.  There is also a guard word at the end of the
11242 ** MemBlockHdr.
11243 */
11244 struct MemBlockHdr {
11245   i64 iSize;                          /* Size of this allocation */
11246   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
11247   char nBacktrace;                    /* Number of backtraces on this alloc */
11248   char nBacktraceSlots;               /* Available backtrace slots */
11249   short nTitle;                       /* Bytes of title; includes '\0' */
11250   int iForeGuard;                     /* Guard word for sanity */
11251 };
11252
11253 /*
11254 ** Guard words
11255 */
11256 #define FOREGUARD 0x80F5E153
11257 #define REARGUARD 0xE4676B53
11258
11259 /*
11260 ** Number of malloc size increments to track.
11261 */
11262 #define NCSIZE  1000
11263
11264 /*
11265 ** All of the static variables used by this module are collected
11266 ** into a single structure named "mem".  This is to keep the
11267 ** static variables organized and to reduce namespace pollution
11268 ** when this module is combined with other in the amalgamation.
11269 */
11270 static struct {
11271   /*
11272   ** The alarm callback and its arguments.  The mem.mutex lock will
11273   ** be held while the callback is running.  Recursive calls into
11274   ** the memory subsystem are allowed, but no new callbacks will be
11275   ** issued.  The alarmBusy variable is set to prevent recursive
11276   ** callbacks.
11277   */
11278   sqlite3_int64 alarmThreshold;
11279   void (*alarmCallback)(void*, sqlite3_int64, int);
11280   void *alarmArg;
11281   int alarmBusy;
11282   
11283   /*
11284   ** Mutex to control access to the memory allocation subsystem.
11285   */
11286   sqlite3_mutex *mutex;
11287   
11288   /*
11289   ** Current allocation and high-water mark.
11290   */
11291   sqlite3_int64 nowUsed;
11292   sqlite3_int64 mxUsed;
11293   
11294   /*
11295   ** Head and tail of a linked list of all outstanding allocations
11296   */
11297   struct MemBlockHdr *pFirst;
11298   struct MemBlockHdr *pLast;
11299   
11300   /*
11301   ** The number of levels of backtrace to save in new allocations.
11302   */
11303   int nBacktrace;
11304   void (*xBacktrace)(int, int, void **);
11305
11306   /*
11307   ** Title text to insert in front of each block
11308   */
11309   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
11310   char zTitle[100];  /* The title text */
11311
11312   /* 
11313   ** sqlite3MallocDisallow() increments the following counter.
11314   ** sqlite3MallocAllow() decrements it.
11315   */
11316   int disallow; /* Do not allow memory allocation */
11317
11318   /*
11319   ** Gather statistics on the sizes of memory allocations.
11320   ** sizeCnt[i] is the number of allocation attempts of i*8
11321   ** bytes.  i==NCSIZE is the number of allocation attempts for
11322   ** sizes more than NCSIZE*8 bytes.
11323   */
11324   int sizeCnt[NCSIZE];
11325
11326 } mem;
11327
11328
11329 /*
11330 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
11331 */
11332 static void enterMem(void){
11333   if( mem.mutex==0 ){
11334     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
11335   }
11336   sqlite3_mutex_enter(mem.mutex);
11337 }
11338
11339 /*
11340 ** Return the amount of memory currently checked out.
11341 */
11342 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
11343   sqlite3_int64 n;
11344   enterMem();
11345   n = mem.nowUsed;
11346   sqlite3_mutex_leave(mem.mutex);  
11347   return n;
11348 }
11349
11350 /*
11351 ** Return the maximum amount of memory that has ever been
11352 ** checked out since either the beginning of this process
11353 ** or since the most recent reset.
11354 */
11355 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
11356   sqlite3_int64 n;
11357   enterMem();
11358   n = mem.mxUsed;
11359   if( resetFlag ){
11360     mem.mxUsed = mem.nowUsed;
11361   }
11362   sqlite3_mutex_leave(mem.mutex);  
11363   return n;
11364 }
11365
11366 /*
11367 ** Change the alarm callback
11368 */
11369 SQLITE_API int sqlite3_memory_alarm(
11370   void(*xCallback)(void *pArg, sqlite3_int64 used, int N),
11371   void *pArg,
11372   sqlite3_int64 iThreshold
11373 ){
11374   enterMem();
11375   mem.alarmCallback = xCallback;
11376   mem.alarmArg = pArg;
11377   mem.alarmThreshold = iThreshold;
11378   sqlite3_mutex_leave(mem.mutex);
11379   return SQLITE_OK;
11380 }
11381
11382 /*
11383 ** Trigger the alarm 
11384 */
11385 static void sqlite3MemsysAlarm(int nByte){
11386   void (*xCallback)(void*,sqlite3_int64,int);
11387   sqlite3_int64 nowUsed;
11388   void *pArg;
11389   if( mem.alarmCallback==0 || mem.alarmBusy  ) return;
11390   mem.alarmBusy = 1;
11391   xCallback = mem.alarmCallback;
11392   nowUsed = mem.nowUsed;
11393   pArg = mem.alarmArg;
11394   sqlite3_mutex_leave(mem.mutex);
11395   xCallback(pArg, nowUsed, nByte);
11396   sqlite3_mutex_enter(mem.mutex);
11397   mem.alarmBusy = 0;
11398 }
11399
11400 /*
11401 ** Given an allocation, find the MemBlockHdr for that allocation.
11402 **
11403 ** This routine checks the guards at either end of the allocation and
11404 ** if they are incorrect it asserts.
11405 */
11406 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
11407   struct MemBlockHdr *p;
11408   int *pInt;
11409   u8 *pU8;
11410   int nReserve;
11411
11412   p = (struct MemBlockHdr*)pAllocation;
11413   p--;
11414   assert( p->iForeGuard==FOREGUARD );
11415   nReserve = (p->iSize+7)&~7;
11416   pInt = (int*)pAllocation;
11417   pU8 = (u8*)pAllocation;
11418   assert( pInt[nReserve/sizeof(int)]==REARGUARD );
11419   assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 );
11420   assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 );
11421   assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 );
11422   return p;
11423 }
11424
11425 /*
11426 ** Return the number of bytes currently allocated at address p.
11427 */
11428 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
11429   struct MemBlockHdr *pHdr;
11430   if( !p ){
11431     return 0;
11432   }
11433   pHdr = sqlite3MemsysGetHeader(p);
11434   return pHdr->iSize;
11435 }
11436
11437 /*
11438 ** Allocate nByte bytes of memory.
11439 */
11440 SQLITE_API void *sqlite3_malloc(int nByte){
11441   struct MemBlockHdr *pHdr;
11442   void **pBt;
11443   char *z;
11444   int *pInt;
11445   void *p = 0;
11446   int totalSize;
11447
11448   if( nByte>0 ){
11449     int nReserve;
11450     enterMem();
11451     assert( mem.disallow==0 );
11452     if( mem.alarmCallback!=0 && mem.nowUsed+nByte>=mem.alarmThreshold ){
11453       sqlite3MemsysAlarm(nByte);
11454     }
11455     nReserve = (nByte+7)&~7;
11456     if( nReserve/8>NCSIZE-1 ){
11457       mem.sizeCnt[NCSIZE-1]++;
11458     }else{
11459       mem.sizeCnt[nReserve/8]++;
11460     }
11461     totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
11462                  mem.nBacktrace*sizeof(void*) + mem.nTitle;
11463     if( sqlite3FaultStep(SQLITE_FAULTINJECTOR_MALLOC) ){
11464       p = 0;
11465     }else{
11466       p = malloc(totalSize);
11467       if( p==0 ){
11468         sqlite3MemsysAlarm(nByte);
11469         p = malloc(totalSize);
11470       }
11471     }
11472     if( p ){
11473       z = p;
11474       pBt = (void**)&z[mem.nTitle];
11475       pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
11476       pHdr->pNext = 0;
11477       pHdr->pPrev = mem.pLast;
11478       if( mem.pLast ){
11479         mem.pLast->pNext = pHdr;
11480       }else{
11481         mem.pFirst = pHdr;
11482       }
11483       mem.pLast = pHdr;
11484       pHdr->iForeGuard = FOREGUARD;
11485       pHdr->nBacktraceSlots = mem.nBacktrace;
11486       pHdr->nTitle = mem.nTitle;
11487       if( mem.nBacktrace ){
11488         void *aAddr[40];
11489         pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
11490         memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
11491         if( mem.xBacktrace ){
11492           mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
11493         }
11494       }else{
11495         pHdr->nBacktrace = 0;
11496       }
11497       if( mem.nTitle ){
11498         memcpy(z, mem.zTitle, mem.nTitle);
11499       }
11500       pHdr->iSize = nByte;
11501       pInt = (int*)&pHdr[1];
11502       pInt[nReserve/sizeof(int)] = REARGUARD;
11503       memset(pInt, 0x65, nReserve);
11504       mem.nowUsed += nByte;
11505       if( mem.nowUsed>mem.mxUsed ){
11506         mem.mxUsed = mem.nowUsed;
11507       }
11508       p = (void*)pInt;
11509     }
11510     sqlite3_mutex_leave(mem.mutex);
11511   }
11512   return p; 
11513 }
11514
11515 /*
11516 ** Free memory.
11517 */
11518 SQLITE_API void sqlite3_free(void *pPrior){
11519   struct MemBlockHdr *pHdr;
11520   void **pBt;
11521   char *z;
11522   if( pPrior==0 ){
11523     return;
11524   }
11525   assert( mem.mutex!=0 );
11526   pHdr = sqlite3MemsysGetHeader(pPrior);
11527   pBt = (void**)pHdr;
11528   pBt -= pHdr->nBacktraceSlots;
11529   sqlite3_mutex_enter(mem.mutex);
11530   mem.nowUsed -= pHdr->iSize;
11531   if( pHdr->pPrev ){
11532     assert( pHdr->pPrev->pNext==pHdr );
11533     pHdr->pPrev->pNext = pHdr->pNext;
11534   }else{
11535     assert( mem.pFirst==pHdr );
11536     mem.pFirst = pHdr->pNext;
11537   }
11538   if( pHdr->pNext ){
11539     assert( pHdr->pNext->pPrev==pHdr );
11540     pHdr->pNext->pPrev = pHdr->pPrev;
11541   }else{
11542     assert( mem.pLast==pHdr );
11543     mem.pLast = pHdr->pPrev;
11544   }
11545   z = (char*)pBt;
11546   z -= pHdr->nTitle;
11547   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
11548                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
11549   free(z);
11550   sqlite3_mutex_leave(mem.mutex);  
11551 }
11552
11553 /*
11554 ** Change the size of an existing memory allocation.
11555 **
11556 ** For this debugging implementation, we *always* make a copy of the
11557 ** allocation into a new place in memory.  In this way, if the 
11558 ** higher level code is using pointer to the old allocation, it is 
11559 ** much more likely to break and we are much more liking to find
11560 ** the error.
11561 */
11562 SQLITE_API void *sqlite3_realloc(void *pPrior, int nByte){
11563   struct MemBlockHdr *pOldHdr;
11564   void *pNew;
11565   if( pPrior==0 ){
11566     return sqlite3_malloc(nByte);
11567   }
11568   if( nByte<=0 ){
11569     sqlite3_free(pPrior);
11570     return 0;
11571   }
11572   assert( mem.disallow==0 );
11573   pOldHdr = sqlite3MemsysGetHeader(pPrior);
11574   pNew = sqlite3_malloc(nByte);
11575   if( pNew ){
11576     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
11577     if( nByte>pOldHdr->iSize ){
11578       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
11579     }
11580     sqlite3_free(pPrior);
11581   }
11582   return pNew;
11583 }
11584
11585 /*
11586 ** Set the number of backtrace levels kept for each allocation.
11587 ** A value of zero turns of backtracing.  The number is always rounded
11588 ** up to a multiple of 2.
11589 */
11590 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
11591   if( depth<0 ){ depth = 0; }
11592   if( depth>20 ){ depth = 20; }
11593   depth = (depth+1)&0xfe;
11594   mem.nBacktrace = depth;
11595 }
11596
11597 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
11598   mem.xBacktrace = xBacktrace;
11599 }
11600
11601 /*
11602 ** Set the title string for subsequent allocations.
11603 */
11604 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
11605   int n = strlen(zTitle) + 1;
11606   enterMem();
11607   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
11608   memcpy(mem.zTitle, zTitle, n);
11609   mem.zTitle[n] = 0;
11610   mem.nTitle = (n+7)&~7;
11611   sqlite3_mutex_leave(mem.mutex);
11612 }
11613
11614 SQLITE_PRIVATE void sqlite3MemdebugSync(){
11615   struct MemBlockHdr *pHdr;
11616   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
11617     void **pBt = (void**)pHdr;
11618     pBt -= pHdr->nBacktraceSlots;
11619     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
11620   }
11621 }
11622
11623 /*
11624 ** Open the file indicated and write a log of all unfreed memory 
11625 ** allocations into that log.
11626 */
11627 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
11628   FILE *out;
11629   struct MemBlockHdr *pHdr;
11630   void **pBt;
11631   int i;
11632   out = fopen(zFilename, "w");
11633   if( out==0 ){
11634     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
11635                     zFilename);
11636     return;
11637   }
11638   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
11639     char *z = (char*)pHdr;
11640     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
11641     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
11642             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
11643     if( pHdr->nBacktrace ){
11644       fflush(out);
11645       pBt = (void**)pHdr;
11646       pBt -= pHdr->nBacktraceSlots;
11647       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
11648       fprintf(out, "\n");
11649     }
11650   }
11651   fprintf(out, "COUNTS:\n");
11652   for(i=0; i<NCSIZE-1; i++){
11653     if( mem.sizeCnt[i] ){
11654       fprintf(out, "   %3d: %d\n", i*8+8, mem.sizeCnt[i]);
11655     }
11656   }
11657   if( mem.sizeCnt[NCSIZE-1] ){
11658     fprintf(out, "  >%3d: %d\n", NCSIZE*8, mem.sizeCnt[NCSIZE-1]);
11659   }
11660   fclose(out);
11661 }
11662
11663 /*
11664 ** Return the number of times sqlite3_malloc() has been called.
11665 */
11666 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
11667   int i;
11668   int nTotal = 0;
11669   for(i=0; i<NCSIZE; i++){
11670     nTotal += mem.sizeCnt[i];
11671   }
11672   return nTotal;
11673 }
11674
11675
11676 #endif /* SQLITE_MEMDEBUG */
11677
11678 /************** End of mem2.c ************************************************/
11679 /************** Begin file mem3.c ********************************************/
11680 /*
11681 ** 2007 October 14
11682 **
11683 ** The author disclaims copyright to this source code.  In place of
11684 ** a legal notice, here is a blessing:
11685 **
11686 **    May you do good and not evil.
11687 **    May you find forgiveness for yourself and forgive others.
11688 **    May you share freely, never taking more than you give.
11689 **
11690 *************************************************************************
11691 ** This file contains the C functions that implement a memory
11692 ** allocation subsystem for use by SQLite. 
11693 **
11694 ** This version of the memory allocation subsystem omits all
11695 ** use of malloc().  All dynamically allocatable memory is
11696 ** contained in a static array, mem.aPool[].  The size of this
11697 ** fixed memory pool is SQLITE_MEMORY_SIZE bytes.
11698 **
11699 ** This version of the memory allocation subsystem is used if
11700 ** and only if SQLITE_MEMORY_SIZE is defined.
11701 **
11702 ** $Id: mem3.c,v 1.12 2008/02/19 15:15:16 drh Exp $
11703 */
11704
11705 /*
11706 ** This version of the memory allocator is used only when 
11707 ** SQLITE_MEMORY_SIZE is defined.
11708 */
11709 #ifdef SQLITE_MEMORY_SIZE
11710
11711 /*
11712 ** Maximum size (in Mem3Blocks) of a "small" chunk.
11713 */
11714 #define MX_SMALL 10
11715
11716
11717 /*
11718 ** Number of freelist hash slots
11719 */
11720 #define N_HASH  61
11721
11722 /*
11723 ** A memory allocation (also called a "chunk") consists of two or 
11724 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
11725 ** a header that is not returned to the user.
11726 **
11727 ** A chunk is two or more blocks that is either checked out or
11728 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
11729 ** size of the allocation in blocks if the allocation is free.
11730 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
11731 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
11732 ** is true if the previous chunk is checked out and false if the
11733 ** previous chunk is free.  The u.hdr.prevSize field is the size of
11734 ** the previous chunk in blocks if the previous chunk is on the
11735 ** freelist. If the previous chunk is checked out, then
11736 ** u.hdr.prevSize can be part of the data for that chunk and should
11737 ** not be read or written.
11738 **
11739 ** We often identify a chunk by its index in mem.aPool[].  When
11740 ** this is done, the chunk index refers to the second block of
11741 ** the chunk.  In this way, the first chunk has an index of 1.
11742 ** A chunk index of 0 means "no such chunk" and is the equivalent
11743 ** of a NULL pointer.
11744 **
11745 ** The second block of free chunks is of the form u.list.  The
11746 ** two fields form a double-linked list of chunks of related sizes.
11747 ** Pointers to the head of the list are stored in mem.aiSmall[] 
11748 ** for smaller chunks and mem.aiHash[] for larger chunks.
11749 **
11750 ** The second block of a chunk is user data if the chunk is checked 
11751 ** out.  If a chunk is checked out, the user data may extend into
11752 ** the u.hdr.prevSize value of the following chunk.
11753 */
11754 typedef struct Mem3Block Mem3Block;
11755 struct Mem3Block {
11756   union {
11757     struct {
11758       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
11759       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
11760     } hdr;
11761     struct {
11762       u32 next;       /* Index in mem.aPool[] of next free chunk */
11763       u32 prev;       /* Index in mem.aPool[] of previous free chunk */
11764     } list;
11765   } u;
11766 };
11767
11768 /*
11769 ** All of the static variables used by this module are collected
11770 ** into a single structure named "mem".  This is to keep the
11771 ** static variables organized and to reduce namespace pollution
11772 ** when this module is combined with other in the amalgamation.
11773 */
11774 static struct {
11775   /*
11776   ** True if we are evaluating an out-of-memory callback.
11777   */
11778   int alarmBusy;
11779   
11780   /*
11781   ** Mutex to control access to the memory allocation subsystem.
11782   */
11783   sqlite3_mutex *mutex;
11784   
11785   /*
11786   ** The minimum amount of free space that we have seen.
11787   */
11788   u32 mnMaster;
11789
11790   /*
11791   ** iMaster is the index of the master chunk.  Most new allocations
11792   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
11793   ** of the current master.  iMaster is 0 if there is not master chunk.
11794   ** The master chunk is not in either the aiHash[] or aiSmall[].
11795   */
11796   u32 iMaster;
11797   u32 szMaster;
11798
11799   /*
11800   ** Array of lists of free blocks according to the block size 
11801   ** for smaller chunks, or a hash on the block size for larger
11802   ** chunks.
11803   */
11804   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
11805   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
11806
11807   /*
11808   ** Memory available for allocation
11809   */
11810   Mem3Block aPool[SQLITE_MEMORY_SIZE/sizeof(Mem3Block)+2];
11811 } mem;
11812
11813 /*
11814 ** Unlink the chunk at mem.aPool[i] from list it is currently
11815 ** on.  *pRoot is the list that i is a member of.
11816 */
11817 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
11818   u32 next = mem.aPool[i].u.list.next;
11819   u32 prev = mem.aPool[i].u.list.prev;
11820   assert( sqlite3_mutex_held(mem.mutex) );
11821   if( prev==0 ){
11822     *pRoot = next;
11823   }else{
11824     mem.aPool[prev].u.list.next = next;
11825   }
11826   if( next ){
11827     mem.aPool[next].u.list.prev = prev;
11828   }
11829   mem.aPool[i].u.list.next = 0;
11830   mem.aPool[i].u.list.prev = 0;
11831 }
11832
11833 /*
11834 ** Unlink the chunk at index i from 
11835 ** whatever list is currently a member of.
11836 */
11837 static void memsys3Unlink(u32 i){
11838   u32 size, hash;
11839   assert( sqlite3_mutex_held(mem.mutex) );
11840   assert( (mem.aPool[i-1].u.hdr.size4x & 1)==0 );
11841   assert( i>=1 );
11842   size = mem.aPool[i-1].u.hdr.size4x/4;
11843   assert( size==mem.aPool[i+size-1].u.hdr.prevSize );
11844   assert( size>=2 );
11845   if( size <= MX_SMALL ){
11846     memsys3UnlinkFromList(i, &mem.aiSmall[size-2]);
11847   }else{
11848     hash = size % N_HASH;
11849     memsys3UnlinkFromList(i, &mem.aiHash[hash]);
11850   }
11851 }
11852
11853 /*
11854 ** Link the chunk at mem.aPool[i] so that is on the list rooted
11855 ** at *pRoot.
11856 */
11857 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
11858   assert( sqlite3_mutex_held(mem.mutex) );
11859   mem.aPool[i].u.list.next = *pRoot;
11860   mem.aPool[i].u.list.prev = 0;
11861   if( *pRoot ){
11862     mem.aPool[*pRoot].u.list.prev = i;
11863   }
11864   *pRoot = i;
11865 }
11866
11867 /*
11868 ** Link the chunk at index i into either the appropriate
11869 ** small chunk list, or into the large chunk hash table.
11870 */
11871 static void memsys3Link(u32 i){
11872   u32 size, hash;
11873   assert( sqlite3_mutex_held(mem.mutex) );
11874   assert( i>=1 );
11875   assert( (mem.aPool[i-1].u.hdr.size4x & 1)==0 );
11876   size = mem.aPool[i-1].u.hdr.size4x/4;
11877   assert( size==mem.aPool[i+size-1].u.hdr.prevSize );
11878   assert( size>=2 );
11879   if( size <= MX_SMALL ){
11880     memsys3LinkIntoList(i, &mem.aiSmall[size-2]);
11881   }else{
11882     hash = size % N_HASH;
11883     memsys3LinkIntoList(i, &mem.aiHash[hash]);
11884   }
11885 }
11886
11887 /*
11888 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
11889 **
11890 ** Also:  Initialize the memory allocation subsystem the first time
11891 ** this routine is called.
11892 */
11893 static void memsys3Enter(void){
11894   if( mem.mutex==0 ){
11895     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
11896     mem.aPool[0].u.hdr.size4x = SQLITE_MEMORY_SIZE/2 + 2;
11897     mem.aPool[SQLITE_MEMORY_SIZE/8].u.hdr.prevSize = SQLITE_MEMORY_SIZE/8;
11898     mem.aPool[SQLITE_MEMORY_SIZE/8].u.hdr.size4x = 1;
11899     mem.iMaster = 1;
11900     mem.szMaster = SQLITE_MEMORY_SIZE/8;
11901     mem.mnMaster = mem.szMaster;
11902   }
11903   sqlite3_mutex_enter(mem.mutex);
11904 }
11905
11906 /*
11907 ** Return the amount of memory currently checked out.
11908 */
11909 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
11910   sqlite3_int64 n;
11911   memsys3Enter();
11912   n = SQLITE_MEMORY_SIZE - mem.szMaster*8;
11913   sqlite3_mutex_leave(mem.mutex);  
11914   return n;
11915 }
11916
11917 /*
11918 ** Return the maximum amount of memory that has ever been
11919 ** checked out since either the beginning of this process
11920 ** or since the most recent reset.
11921 */
11922 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
11923   sqlite3_int64 n;
11924   memsys3Enter();
11925   n = SQLITE_MEMORY_SIZE - mem.mnMaster*8;
11926   if( resetFlag ){
11927     mem.mnMaster = mem.szMaster;
11928   }
11929   sqlite3_mutex_leave(mem.mutex);  
11930   return n;
11931 }
11932
11933 /*
11934 ** Change the alarm callback.
11935 **
11936 ** This is a no-op for the static memory allocator.  The purpose
11937 ** of the memory alarm is to support sqlite3_soft_heap_limit().
11938 ** But with this memory allocator, the soft_heap_limit is really
11939 ** a hard limit that is fixed at SQLITE_MEMORY_SIZE.
11940 */
11941 SQLITE_API int sqlite3_memory_alarm(
11942   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
11943   void *pArg,
11944   sqlite3_int64 iThreshold
11945 ){
11946   return SQLITE_OK;
11947 }
11948
11949 /*
11950 ** Called when we are unable to satisfy an allocation of nBytes.
11951 */
11952 static void memsys3OutOfMemory(int nByte){
11953   if( !mem.alarmBusy ){
11954     mem.alarmBusy = 1;
11955     assert( sqlite3_mutex_held(mem.mutex) );
11956     sqlite3_mutex_leave(mem.mutex);
11957     sqlite3_release_memory(nByte);
11958     sqlite3_mutex_enter(mem.mutex);
11959     mem.alarmBusy = 0;
11960   }
11961 }
11962
11963 /*
11964 ** Return the size of an outstanding allocation, in bytes.  The
11965 ** size returned omits the 8-byte header overhead.  This only
11966 ** works for chunks that are currently checked out.
11967 */
11968 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
11969   int iSize = 0;
11970   if( p ){
11971     Mem3Block *pBlock = (Mem3Block*)p;
11972     assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
11973     iSize = (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
11974   }
11975   return iSize;
11976 }
11977
11978 /*
11979 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
11980 ** size parameters for check-out and return a pointer to the 
11981 ** user portion of the chunk.
11982 */
11983 static void *memsys3Checkout(u32 i, int nBlock){
11984   u32 x;
11985   assert( sqlite3_mutex_held(mem.mutex) );
11986   assert( i>=1 );
11987   assert( mem.aPool[i-1].u.hdr.size4x/4==nBlock );
11988   assert( mem.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
11989   x = mem.aPool[i-1].u.hdr.size4x;
11990   mem.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
11991   mem.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
11992   mem.aPool[i+nBlock-1].u.hdr.size4x |= 2;
11993   return &mem.aPool[i];
11994 }
11995
11996 /*
11997 ** Carve a piece off of the end of the mem.iMaster free chunk.
11998 ** Return a pointer to the new allocation.  Or, if the master chunk
11999 ** is not large enough, return 0.
12000 */
12001 static void *memsys3FromMaster(int nBlock){
12002   assert( sqlite3_mutex_held(mem.mutex) );
12003   assert( mem.szMaster>=nBlock );
12004   if( nBlock>=mem.szMaster-1 ){
12005     /* Use the entire master */
12006     void *p = memsys3Checkout(mem.iMaster, mem.szMaster);
12007     mem.iMaster = 0;
12008     mem.szMaster = 0;
12009     mem.mnMaster = 0;
12010     return p;
12011   }else{
12012     /* Split the master block.  Return the tail. */
12013     u32 newi, x;
12014     newi = mem.iMaster + mem.szMaster - nBlock;
12015     assert( newi > mem.iMaster+1 );
12016     mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = nBlock;
12017     mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x |= 2;
12018     mem.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
12019     mem.szMaster -= nBlock;
12020     mem.aPool[newi-1].u.hdr.prevSize = mem.szMaster;
12021     x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2;
12022     mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x;
12023     if( mem.szMaster < mem.mnMaster ){
12024       mem.mnMaster = mem.szMaster;
12025     }
12026     return (void*)&mem.aPool[newi];
12027   }
12028 }
12029
12030 /*
12031 ** *pRoot is the head of a list of free chunks of the same size
12032 ** or same size hash.  In other words, *pRoot is an entry in either
12033 ** mem.aiSmall[] or mem.aiHash[].  
12034 **
12035 ** This routine examines all entries on the given list and tries
12036 ** to coalesce each entries with adjacent free chunks.  
12037 **
12038 ** If it sees a chunk that is larger than mem.iMaster, it replaces 
12039 ** the current mem.iMaster with the new larger chunk.  In order for
12040 ** this mem.iMaster replacement to work, the master chunk must be
12041 ** linked into the hash tables.  That is not the normal state of
12042 ** affairs, of course.  The calling routine must link the master
12043 ** chunk before invoking this routine, then must unlink the (possibly
12044 ** changed) master chunk once this routine has finished.
12045 */
12046 static void memsys3Merge(u32 *pRoot){
12047   u32 iNext, prev, size, i, x;
12048
12049   assert( sqlite3_mutex_held(mem.mutex) );
12050   for(i=*pRoot; i>0; i=iNext){
12051     iNext = mem.aPool[i].u.list.next;
12052     size = mem.aPool[i-1].u.hdr.size4x;
12053     assert( (size&1)==0 );
12054     if( (size&2)==0 ){
12055       memsys3UnlinkFromList(i, pRoot);
12056       assert( i > mem.aPool[i-1].u.hdr.prevSize );
12057       prev = i - mem.aPool[i-1].u.hdr.prevSize;
12058       if( prev==iNext ){
12059         iNext = mem.aPool[prev].u.list.next;
12060       }
12061       memsys3Unlink(prev);
12062       size = i + size/4 - prev;
12063       x = mem.aPool[prev-1].u.hdr.size4x & 2;
12064       mem.aPool[prev-1].u.hdr.size4x = size*4 | x;
12065       mem.aPool[prev+size-1].u.hdr.prevSize = size;
12066       memsys3Link(prev);
12067       i = prev;
12068     }else{
12069       size /= 4;
12070     }
12071     if( size>mem.szMaster ){
12072       mem.iMaster = i;
12073       mem.szMaster = size;
12074     }
12075   }
12076 }
12077
12078 /*
12079 ** Return a block of memory of at least nBytes in size.
12080 ** Return NULL if unable.
12081 */
12082 static void *memsys3Malloc(int nByte){
12083   u32 i;
12084   int nBlock;
12085   int toFree;
12086
12087   assert( sqlite3_mutex_held(mem.mutex) );
12088   assert( sizeof(Mem3Block)==8 );
12089   if( nByte<=12 ){
12090     nBlock = 2;
12091   }else{
12092     nBlock = (nByte + 11)/8;
12093   }
12094   assert( nBlock >= 2 );
12095
12096   /* STEP 1:
12097   ** Look for an entry of the correct size in either the small
12098   ** chunk table or in the large chunk hash table.  This is
12099   ** successful most of the time (about 9 times out of 10).
12100   */
12101   if( nBlock <= MX_SMALL ){
12102     i = mem.aiSmall[nBlock-2];
12103     if( i>0 ){
12104       memsys3UnlinkFromList(i, &mem.aiSmall[nBlock-2]);
12105       return memsys3Checkout(i, nBlock);
12106     }
12107   }else{
12108     int hash = nBlock % N_HASH;
12109     for(i=mem.aiHash[hash]; i>0; i=mem.aPool[i].u.list.next){
12110       if( mem.aPool[i-1].u.hdr.size4x/4==nBlock ){
12111         memsys3UnlinkFromList(i, &mem.aiHash[hash]);
12112         return memsys3Checkout(i, nBlock);
12113       }
12114     }
12115   }
12116
12117   /* STEP 2:
12118   ** Try to satisfy the allocation by carving a piece off of the end
12119   ** of the master chunk.  This step usually works if step 1 fails.
12120   */
12121   if( mem.szMaster>=nBlock ){
12122     return memsys3FromMaster(nBlock);
12123   }
12124
12125
12126   /* STEP 3:  
12127   ** Loop through the entire memory pool.  Coalesce adjacent free
12128   ** chunks.  Recompute the master chunk as the largest free chunk.
12129   ** Then try again to satisfy the allocation by carving a piece off
12130   ** of the end of the master chunk.  This step happens very
12131   ** rarely (we hope!)
12132   */
12133   for(toFree=nBlock*16; toFree<SQLITE_MEMORY_SIZE*2; toFree *= 2){
12134     memsys3OutOfMemory(toFree);
12135     if( mem.iMaster ){
12136       memsys3Link(mem.iMaster);
12137       mem.iMaster = 0;
12138       mem.szMaster = 0;
12139     }
12140     for(i=0; i<N_HASH; i++){
12141       memsys3Merge(&mem.aiHash[i]);
12142     }
12143     for(i=0; i<MX_SMALL-1; i++){
12144       memsys3Merge(&mem.aiSmall[i]);
12145     }
12146     if( mem.szMaster ){
12147       memsys3Unlink(mem.iMaster);
12148       if( mem.szMaster>=nBlock ){
12149         return memsys3FromMaster(nBlock);
12150       }
12151     }
12152   }
12153
12154   /* If none of the above worked, then we fail. */
12155   return 0;
12156 }
12157
12158 /*
12159 ** Free an outstanding memory allocation.
12160 */
12161 void memsys3Free(void *pOld){
12162   Mem3Block *p = (Mem3Block*)pOld;
12163   int i;
12164   u32 size, x;
12165   assert( sqlite3_mutex_held(mem.mutex) );
12166   assert( p>mem.aPool && p<&mem.aPool[SQLITE_MEMORY_SIZE/8] );
12167   i = p - mem.aPool;
12168   assert( (mem.aPool[i-1].u.hdr.size4x&1)==1 );
12169   size = mem.aPool[i-1].u.hdr.size4x/4;
12170   assert( i+size<=SQLITE_MEMORY_SIZE/8+1 );
12171   mem.aPool[i-1].u.hdr.size4x &= ~1;
12172   mem.aPool[i+size-1].u.hdr.prevSize = size;
12173   mem.aPool[i+size-1].u.hdr.size4x &= ~2;
12174   memsys3Link(i);
12175
12176   /* Try to expand the master using the newly freed chunk */
12177   if( mem.iMaster ){
12178     while( (mem.aPool[mem.iMaster-1].u.hdr.size4x&2)==0 ){
12179       size = mem.aPool[mem.iMaster-1].u.hdr.prevSize;
12180       mem.iMaster -= size;
12181       mem.szMaster += size;
12182       memsys3Unlink(mem.iMaster);
12183       x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2;
12184       mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x;
12185       mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster;
12186     }
12187     x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2;
12188     while( (mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x&1)==0 ){
12189       memsys3Unlink(mem.iMaster+mem.szMaster);
12190       mem.szMaster += mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x/4;
12191       mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x;
12192       mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster;
12193     }
12194   }
12195 }
12196
12197 /*
12198 ** Allocate nBytes of memory
12199 */
12200 SQLITE_API void *sqlite3_malloc(int nBytes){
12201   sqlite3_int64 *p = 0;
12202   if( nBytes>0 ){
12203     memsys3Enter();
12204     p = memsys3Malloc(nBytes);
12205     sqlite3_mutex_leave(mem.mutex);
12206   }
12207   return (void*)p; 
12208 }
12209
12210 /*
12211 ** Free memory.
12212 */
12213 SQLITE_API void sqlite3_free(void *pPrior){
12214   if( pPrior==0 ){
12215     return;
12216   }
12217   assert( mem.mutex!=0 );
12218   sqlite3_mutex_enter(mem.mutex);
12219   memsys3Free(pPrior);
12220   sqlite3_mutex_leave(mem.mutex);  
12221 }
12222
12223 /*
12224 ** Change the size of an existing memory allocation
12225 */
12226 SQLITE_API void *sqlite3_realloc(void *pPrior, int nBytes){
12227   int nOld;
12228   void *p;
12229   if( pPrior==0 ){
12230     return sqlite3_malloc(nBytes);
12231   }
12232   if( nBytes<=0 ){
12233     sqlite3_free(pPrior);
12234     return 0;
12235   }
12236   assert( mem.mutex!=0 );
12237   nOld = sqlite3MallocSize(pPrior);
12238   if( nBytes<=nOld && nBytes>=nOld-128 ){
12239     return pPrior;
12240   }
12241   sqlite3_mutex_enter(mem.mutex);
12242   p = memsys3Malloc(nBytes);
12243   if( p ){
12244     if( nOld<nBytes ){
12245       memcpy(p, pPrior, nOld);
12246     }else{
12247       memcpy(p, pPrior, nBytes);
12248     }
12249     memsys3Free(pPrior);
12250   }
12251   sqlite3_mutex_leave(mem.mutex);
12252   return p;
12253 }
12254
12255 /*
12256 ** Open the file indicated and write a log of all unfreed memory 
12257 ** allocations into that log.
12258 */
12259 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
12260 #ifdef SQLITE_DEBUG
12261   FILE *out;
12262   int i, j;
12263   u32 size;
12264   if( zFilename==0 || zFilename[0]==0 ){
12265     out = stdout;
12266   }else{
12267     out = fopen(zFilename, "w");
12268     if( out==0 ){
12269       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
12270                       zFilename);
12271       return;
12272     }
12273   }
12274   memsys3Enter();
12275   fprintf(out, "CHUNKS:\n");
12276   for(i=1; i<=SQLITE_MEMORY_SIZE/8; i+=size/4){
12277     size = mem.aPool[i-1].u.hdr.size4x;
12278     if( size/4<=1 ){
12279       fprintf(out, "%p size error\n", &mem.aPool[i]);
12280       assert( 0 );
12281       break;
12282     }
12283     if( (size&1)==0 && mem.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
12284       fprintf(out, "%p tail size does not match\n", &mem.aPool[i]);
12285       assert( 0 );
12286       break;
12287     }
12288     if( ((mem.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
12289       fprintf(out, "%p tail checkout bit is incorrect\n", &mem.aPool[i]);
12290       assert( 0 );
12291       break;
12292     }
12293     if( size&1 ){
12294       fprintf(out, "%p %6d bytes checked out\n", &mem.aPool[i], (size/4)*8-8);
12295     }else{
12296       fprintf(out, "%p %6d bytes free%s\n", &mem.aPool[i], (size/4)*8-8,
12297                   i==mem.iMaster ? " **master**" : "");
12298     }
12299   }
12300   for(i=0; i<MX_SMALL-1; i++){
12301     if( mem.aiSmall[i]==0 ) continue;
12302     fprintf(out, "small(%2d):", i);
12303     for(j = mem.aiSmall[i]; j>0; j=mem.aPool[j].u.list.next){
12304       fprintf(out, " %p(%d)", &mem.aPool[j],
12305               (mem.aPool[j-1].u.hdr.size4x/4)*8-8);
12306     }
12307     fprintf(out, "\n"); 
12308   }
12309   for(i=0; i<N_HASH; i++){
12310     if( mem.aiHash[i]==0 ) continue;
12311     fprintf(out, "hash(%2d):", i);
12312     for(j = mem.aiHash[i]; j>0; j=mem.aPool[j].u.list.next){
12313       fprintf(out, " %p(%d)", &mem.aPool[j],
12314               (mem.aPool[j-1].u.hdr.size4x/4)*8-8);
12315     }
12316     fprintf(out, "\n"); 
12317   }
12318   fprintf(out, "master=%d\n", mem.iMaster);
12319   fprintf(out, "nowUsed=%d\n", SQLITE_MEMORY_SIZE - mem.szMaster*8);
12320   fprintf(out, "mxUsed=%d\n", SQLITE_MEMORY_SIZE - mem.mnMaster*8);
12321   sqlite3_mutex_leave(mem.mutex);
12322   if( out==stdout ){
12323     fflush(stdout);
12324   }else{
12325     fclose(out);
12326   }
12327 #endif
12328 }
12329
12330
12331 #endif /* !SQLITE_MEMORY_SIZE */
12332
12333 /************** End of mem3.c ************************************************/
12334 /************** Begin file mem5.c ********************************************/
12335 /*
12336 ** 2007 October 14
12337 **
12338 ** The author disclaims copyright to this source code.  In place of
12339 ** a legal notice, here is a blessing:
12340 **
12341 **    May you do good and not evil.
12342 **    May you find forgiveness for yourself and forgive others.
12343 **    May you share freely, never taking more than you give.
12344 **
12345 *************************************************************************
12346 ** This file contains the C functions that implement a memory
12347 ** allocation subsystem for use by SQLite. 
12348 **
12349 ** This version of the memory allocation subsystem omits all
12350 ** use of malloc().  All dynamically allocatable memory is
12351 ** contained in a static array, mem.aPool[].  The size of this
12352 ** fixed memory pool is SQLITE_POW2_MEMORY_SIZE bytes.
12353 **
12354 ** This version of the memory allocation subsystem is used if
12355 ** and only if SQLITE_POW2_MEMORY_SIZE is defined.
12356 **
12357 ** $Id: mem5.c,v 1.4 2008/02/19 15:15:16 drh Exp $
12358 */
12359
12360 /*
12361 ** This version of the memory allocator is used only when 
12362 ** SQLITE_POW2_MEMORY_SIZE is defined.
12363 */
12364 #ifdef SQLITE_POW2_MEMORY_SIZE
12365
12366 /*
12367 ** Log2 of the minimum size of an allocation.  For example, if
12368 ** 4 then all allocations will be rounded up to at least 16 bytes.
12369 ** If 5 then all allocations will be rounded up to at least 32 bytes.
12370 */
12371 #ifndef SQLITE_POW2_LOGMIN
12372 # define SQLITE_POW2_LOGMIN 6
12373 #endif
12374 #define POW2_MIN (1<<SQLITE_POW2_LOGMIN)
12375
12376 /*
12377 ** Log2 of the maximum size of an allocation.
12378 */
12379 #ifndef SQLITE_POW2_LOGMAX
12380 # define SQLITE_POW2_LOGMAX 18
12381 #endif
12382 #define POW2_MAX (((unsigned int)1)<<SQLITE_POW2_LOGMAX)
12383
12384 /*
12385 ** Number of distinct allocation sizes.
12386 */
12387 #define NSIZE (SQLITE_POW2_LOGMAX - SQLITE_POW2_LOGMIN + 1)
12388
12389 /*
12390 ** A minimum allocation is an instance of the following structure.
12391 ** Larger allocations are an array of these structures where the
12392 ** size of the array is a power of 2.
12393 */
12394 typedef struct Mem5Block Mem5Block;
12395 struct Mem5Block {
12396   union {
12397     char aData[POW2_MIN];
12398     struct {
12399       int next;       /* Index in mem.aPool[] of next free chunk */
12400       int prev;       /* Index in mem.aPool[] of previous free chunk */
12401     } list;
12402   } u;
12403 };
12404
12405 /*
12406 ** Number of blocks of memory available for allocation.
12407 */
12408 #define NBLOCK (SQLITE_POW2_MEMORY_SIZE/POW2_MIN)
12409
12410 /*
12411 ** The size in blocks of an POW2_MAX allocation
12412 */
12413 #define SZ_MAX (1<<(NSIZE-1))
12414
12415 /*
12416 ** Masks used for mem.aCtrl[] elements.
12417 */
12418 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
12419 #define CTRL_FREE     0x20    /* True if not checked out */
12420
12421 /*
12422 ** All of the static variables used by this module are collected
12423 ** into a single structure named "mem".  This is to keep the
12424 ** static variables organized and to reduce namespace pollution
12425 ** when this module is combined with other in the amalgamation.
12426 */
12427 static struct {
12428   /*
12429   ** The alarm callback and its arguments.  The mem.mutex lock will
12430   ** be held while the callback is running.  Recursive calls into
12431   ** the memory subsystem are allowed, but no new callbacks will be
12432   ** issued.  The alarmBusy variable is set to prevent recursive
12433   ** callbacks.
12434   */
12435   sqlite3_int64 alarmThreshold;
12436   void (*alarmCallback)(void*, sqlite3_int64,int);
12437   void *alarmArg;
12438   int alarmBusy;
12439   
12440   /*
12441   ** Mutex to control access to the memory allocation subsystem.
12442   */
12443   sqlite3_mutex *mutex;
12444
12445   /*
12446   ** Performance statistics
12447   */
12448   u64 nAlloc;         /* Total number of calls to malloc */
12449   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
12450   u64 totalExcess;    /* Total internal fragmentation */
12451   u32 currentOut;     /* Current checkout, including internal fragmentation */
12452   u32 currentCount;   /* Current number of distinct checkouts */
12453   u32 maxOut;         /* Maximum instantaneous currentOut */
12454   u32 maxCount;       /* Maximum instantaneous currentCount */
12455   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
12456   
12457   /*
12458   ** Lists of free blocks of various sizes.
12459   */
12460   int aiFreelist[NSIZE];
12461
12462   /*
12463   ** Space for tracking which blocks are checked out and the size
12464   ** of each block.  One byte per block.
12465   */
12466   u8 aCtrl[NBLOCK];
12467
12468   /*
12469   ** Memory available for allocation
12470   */
12471   Mem5Block aPool[NBLOCK];
12472 } mem;
12473
12474 /*
12475 ** Unlink the chunk at mem.aPool[i] from list it is currently
12476 ** on.  It should be found on mem.aiFreelist[iLogsize].
12477 */
12478 static void memsys5Unlink(int i, int iLogsize){
12479   int next, prev;
12480   assert( i>=0 && i<NBLOCK );
12481   assert( iLogsize>=0 && iLogsize<NSIZE );
12482   assert( (mem.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
12483   assert( sqlite3_mutex_held(mem.mutex) );
12484
12485   next = mem.aPool[i].u.list.next;
12486   prev = mem.aPool[i].u.list.prev;
12487   if( prev<0 ){
12488     mem.aiFreelist[iLogsize] = next;
12489   }else{
12490     mem.aPool[prev].u.list.next = next;
12491   }
12492   if( next>=0 ){
12493     mem.aPool[next].u.list.prev = prev;
12494   }
12495 }
12496
12497 /*
12498 ** Link the chunk at mem.aPool[i] so that is on the iLogsize
12499 ** free list.
12500 */
12501 static void memsys5Link(int i, int iLogsize){
12502   int x;
12503   assert( sqlite3_mutex_held(mem.mutex) );
12504   assert( i>=0 && i<NBLOCK );
12505   assert( iLogsize>=0 && iLogsize<NSIZE );
12506   assert( (mem.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
12507
12508   mem.aPool[i].u.list.next = x = mem.aiFreelist[iLogsize];
12509   mem.aPool[i].u.list.prev = -1;
12510   if( x>=0 ){
12511     assert( x<NBLOCK );
12512     mem.aPool[x].u.list.prev = i;
12513   }
12514   mem.aiFreelist[iLogsize] = i;
12515 }
12516
12517 /*
12518 ** Enter the mutex mem.mutex. Allocate it if it is not already allocated.
12519 **
12520 ** Also:  Initialize the memory allocation subsystem the first time
12521 ** this routine is called.
12522 */
12523 static void memsys5Enter(void){
12524   if( mem.mutex==0 ){
12525     int i;
12526     assert( sizeof(Mem5Block)==POW2_MIN );
12527     assert( (SQLITE_POW2_MEMORY_SIZE % POW2_MAX)==0 );
12528     assert( SQLITE_POW2_MEMORY_SIZE>=POW2_MAX );
12529     mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM);
12530     sqlite3_mutex_enter(mem.mutex);
12531     for(i=0; i<NSIZE; i++) mem.aiFreelist[i] = -1;
12532     for(i=0; i<=NBLOCK-SZ_MAX; i += SZ_MAX){
12533       mem.aCtrl[i] = (NSIZE-1) | CTRL_FREE;
12534       memsys5Link(i, NSIZE-1);
12535     }
12536   }else{
12537     sqlite3_mutex_enter(mem.mutex);
12538   }
12539 }
12540
12541 /*
12542 ** Return the amount of memory currently checked out.
12543 */
12544 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
12545   return mem.currentOut;
12546 }
12547
12548 /*
12549 ** Return the maximum amount of memory that has ever been
12550 ** checked out since either the beginning of this process
12551 ** or since the most recent reset.
12552 */
12553 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
12554   sqlite3_int64 n;
12555   memsys5Enter();
12556   n = mem.maxOut;
12557   if( resetFlag ){
12558     mem.maxOut = mem.currentOut;
12559   }
12560   sqlite3_mutex_leave(mem.mutex);  
12561   return n;
12562 }
12563
12564
12565 /*
12566 ** Trigger the alarm 
12567 */
12568 static void memsys5Alarm(int nByte){
12569   void (*xCallback)(void*,sqlite3_int64,int);
12570   sqlite3_int64 nowUsed;
12571   void *pArg;
12572   if( mem.alarmCallback==0 || mem.alarmBusy  ) return;
12573   mem.alarmBusy = 1;
12574   xCallback = mem.alarmCallback;
12575   nowUsed = mem.currentOut;
12576   pArg = mem.alarmArg;
12577   sqlite3_mutex_leave(mem.mutex);
12578   xCallback(pArg, nowUsed, nByte);
12579   sqlite3_mutex_enter(mem.mutex);
12580   mem.alarmBusy = 0;
12581 }
12582
12583 /*
12584 ** Change the alarm callback.
12585 **
12586 ** This is a no-op for the static memory allocator.  The purpose
12587 ** of the memory alarm is to support sqlite3_soft_heap_limit().
12588 ** But with this memory allocator, the soft_heap_limit is really
12589 ** a hard limit that is fixed at SQLITE_POW2_MEMORY_SIZE.
12590 */
12591 SQLITE_API int sqlite3_memory_alarm(
12592   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
12593   void *pArg,
12594   sqlite3_int64 iThreshold
12595 ){
12596   memsys5Enter();
12597   mem.alarmCallback = xCallback;
12598   mem.alarmArg = pArg;
12599   mem.alarmThreshold = iThreshold;
12600   sqlite3_mutex_leave(mem.mutex);
12601   return SQLITE_OK;
12602 }
12603
12604 /*
12605 ** Return the size of an outstanding allocation, in bytes.  The
12606 ** size returned omits the 8-byte header overhead.  This only
12607 ** works for chunks that are currently checked out.
12608 */
12609 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
12610   int iSize = 0;
12611   if( p ){
12612     int i = ((Mem5Block*)p) - mem.aPool;
12613     assert( i>=0 && i<NBLOCK );
12614     iSize = 1 << ((mem.aCtrl[i]&CTRL_LOGSIZE) + SQLITE_POW2_LOGMIN);
12615   }
12616   return iSize;
12617 }
12618
12619 /*
12620 ** Find the first entry on the freelist iLogsize.  Unlink that
12621 ** entry and return its index. 
12622 */
12623 static int memsys5UnlinkFirst(int iLogsize){
12624   int i;
12625   int iFirst;
12626
12627   assert( iLogsize>=0 && iLogsize<NSIZE );
12628   i = iFirst = mem.aiFreelist[iLogsize];
12629   assert( iFirst>=0 );
12630   while( i>0 ){
12631     if( i<iFirst ) iFirst = i;
12632     i = mem.aPool[i].u.list.next;
12633   }
12634   memsys5Unlink(iFirst, iLogsize);
12635   return iFirst;
12636 }
12637
12638 /*
12639 ** Return a block of memory of at least nBytes in size.
12640 ** Return NULL if unable.
12641 */
12642 static void *memsys5Malloc(int nByte){
12643   int i;           /* Index of a mem.aPool[] slot */
12644   int iBin;        /* Index into mem.aiFreelist[] */
12645   int iFullSz;     /* Size of allocation rounded up to power of 2 */
12646   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
12647
12648   assert( sqlite3_mutex_held(mem.mutex) );
12649
12650   /* Keep track of the maximum allocation request.  Even unfulfilled
12651   ** requests are counted */
12652   if( nByte>mem.maxRequest ){
12653     mem.maxRequest = nByte;
12654   }
12655
12656   /* Simulate a memory allocation fault */
12657   if( sqlite3FaultStep(SQLITE_FAULTINJECTOR_MALLOC) ) return 0;
12658
12659   /* Round nByte up to the next valid power of two */
12660   if( nByte>POW2_MAX ) return 0;
12661   for(iFullSz=POW2_MIN, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
12662
12663   /* If we will be over the memory alarm threshold after this allocation,
12664   ** then trigger the memory overflow alarm */
12665   if( mem.alarmCallback!=0 && mem.currentOut+iFullSz>=mem.alarmThreshold ){
12666     memsys5Alarm(iFullSz);
12667   }
12668
12669   /* Make sure mem.aiFreelist[iLogsize] contains at least one free
12670   ** block.  If not, then split a block of the next larger power of
12671   ** two in order to create a new free block of size iLogsize.
12672   */
12673   for(iBin=iLogsize; mem.aiFreelist[iBin]<0 && iBin<NSIZE; iBin++){}
12674   if( iBin>=NSIZE ) return 0;
12675   i = memsys5UnlinkFirst(iBin);
12676   while( iBin>iLogsize ){
12677     int newSize;
12678
12679     iBin--;
12680     newSize = 1 << iBin;
12681     mem.aCtrl[i+newSize] = CTRL_FREE | iBin;
12682     memsys5Link(i+newSize, iBin);
12683   }
12684   mem.aCtrl[i] = iLogsize;
12685
12686   /* Update allocator performance statistics. */
12687   mem.nAlloc++;
12688   mem.totalAlloc += iFullSz;
12689   mem.totalExcess += iFullSz - nByte;
12690   mem.currentCount++;
12691   mem.currentOut += iFullSz;
12692   if( mem.maxCount<mem.currentCount ) mem.maxCount = mem.currentCount;
12693   if( mem.maxOut<mem.currentOut ) mem.maxOut = mem.currentOut;
12694
12695   /* Return a pointer to the allocated memory. */
12696   return (void*)&mem.aPool[i];
12697 }
12698
12699 /*
12700 ** Free an outstanding memory allocation.
12701 */
12702 void memsys5Free(void *pOld){
12703   u32 size, iLogsize;
12704   int i;
12705
12706   i = ((Mem5Block*)pOld) - mem.aPool;
12707   assert( sqlite3_mutex_held(mem.mutex) );
12708   assert( i>=0 && i<NBLOCK );
12709   assert( (mem.aCtrl[i] & CTRL_FREE)==0 );
12710   iLogsize = mem.aCtrl[i] & CTRL_LOGSIZE;
12711   size = 1<<iLogsize;
12712   assert( i+size-1<NBLOCK );
12713   mem.aCtrl[i] |= CTRL_FREE;
12714   mem.aCtrl[i+size-1] |= CTRL_FREE;
12715   assert( mem.currentCount>0 );
12716   assert( mem.currentOut>=0 );
12717   mem.currentCount--;
12718   mem.currentOut -= size*POW2_MIN;
12719   assert( mem.currentOut>0 || mem.currentCount==0 );
12720   assert( mem.currentCount>0 || mem.currentOut==0 );
12721
12722   mem.aCtrl[i] = CTRL_FREE | iLogsize;
12723   while( iLogsize<NSIZE-1 ){
12724     int iBuddy;
12725
12726     if( (i>>iLogsize) & 1 ){
12727       iBuddy = i - size;
12728     }else{
12729       iBuddy = i + size;
12730     }
12731     assert( iBuddy>=0 && iBuddy<NBLOCK );
12732     if( mem.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
12733     memsys5Unlink(iBuddy, iLogsize);
12734     iLogsize++;
12735     if( iBuddy<i ){
12736       mem.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
12737       mem.aCtrl[i] = 0;
12738       i = iBuddy;
12739     }else{
12740       mem.aCtrl[i] = CTRL_FREE | iLogsize;
12741       mem.aCtrl[iBuddy] = 0;
12742     }
12743     size *= 2;
12744   }
12745   memsys5Link(i, iLogsize);
12746 }
12747
12748 /*
12749 ** Allocate nBytes of memory
12750 */
12751 SQLITE_API void *sqlite3_malloc(int nBytes){
12752   sqlite3_int64 *p = 0;
12753   if( nBytes>0 ){
12754     memsys5Enter();
12755     p = memsys5Malloc(nBytes);
12756     sqlite3_mutex_leave(mem.mutex);
12757   }
12758   return (void*)p; 
12759 }
12760
12761 /*
12762 ** Free memory.
12763 */
12764 SQLITE_API void sqlite3_free(void *pPrior){
12765   if( pPrior==0 ){
12766     return;
12767   }
12768   assert( mem.mutex!=0 );
12769   sqlite3_mutex_enter(mem.mutex);
12770   memsys5Free(pPrior);
12771   sqlite3_mutex_leave(mem.mutex);  
12772 }
12773
12774 /*
12775 ** Change the size of an existing memory allocation
12776 */
12777 SQLITE_API void *sqlite3_realloc(void *pPrior, int nBytes){
12778   int nOld;
12779   void *p;
12780   if( pPrior==0 ){
12781     return sqlite3_malloc(nBytes);
12782   }
12783   if( nBytes<=0 ){
12784     sqlite3_free(pPrior);
12785     return 0;
12786   }
12787   assert( mem.mutex!=0 );
12788   nOld = sqlite3MallocSize(pPrior);
12789   if( nBytes<=nOld ){
12790     return pPrior;
12791   }
12792   sqlite3_mutex_enter(mem.mutex);
12793   p = memsys5Malloc(nBytes);
12794   if( p ){
12795     memcpy(p, pPrior, nOld);
12796     memsys5Free(pPrior);
12797   }
12798   sqlite3_mutex_leave(mem.mutex);
12799   return p;
12800 }
12801
12802 /*
12803 ** Open the file indicated and write a log of all unfreed memory 
12804 ** allocations into that log.
12805 */
12806 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
12807 #ifdef SQLITE_DEBUG
12808   FILE *out;
12809   int i, j, n;
12810
12811   if( zFilename==0 || zFilename[0]==0 ){
12812     out = stdout;
12813   }else{
12814     out = fopen(zFilename, "w");
12815     if( out==0 ){
12816       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
12817                       zFilename);
12818       return;
12819     }
12820   }
12821   memsys5Enter();
12822   for(i=0; i<NSIZE; i++){
12823     for(n=0, j=mem.aiFreelist[i]; j>=0; j = mem.aPool[j].u.list.next, n++){}
12824     fprintf(out, "freelist items of size %d: %d\n", POW2_MIN << i, n);
12825   }
12826   fprintf(out, "mem.nAlloc       = %llu\n", mem.nAlloc);
12827   fprintf(out, "mem.totalAlloc   = %llu\n", mem.totalAlloc);
12828   fprintf(out, "mem.totalExcess  = %llu\n", mem.totalExcess);
12829   fprintf(out, "mem.currentOut   = %u\n", mem.currentOut);
12830   fprintf(out, "mem.currentCount = %u\n", mem.currentCount);
12831   fprintf(out, "mem.maxOut       = %u\n", mem.maxOut);
12832   fprintf(out, "mem.maxCount     = %u\n", mem.maxCount);
12833   fprintf(out, "mem.maxRequest   = %u\n", mem.maxRequest);
12834   sqlite3_mutex_leave(mem.mutex);
12835   if( out==stdout ){
12836     fflush(stdout);
12837   }else{
12838     fclose(out);
12839   }
12840 #endif
12841 }
12842
12843
12844 #endif /* !SQLITE_POW2_MEMORY_SIZE */
12845
12846 /************** End of mem5.c ************************************************/
12847 /************** Begin file mutex.c *******************************************/
12848 /*
12849 ** 2007 August 14
12850 **
12851 ** The author disclaims copyright to this source code.  In place of
12852 ** a legal notice, here is a blessing:
12853 **
12854 **    May you do good and not evil.
12855 **    May you find forgiveness for yourself and forgive others.
12856 **    May you share freely, never taking more than you give.
12857 **
12858 *************************************************************************
12859 ** This file contains the C functions that implement mutexes.
12860 **
12861 ** The implementation in this file does not provide any mutual
12862 ** exclusion and is thus suitable for use only in applications
12863 ** that use SQLite in a single thread.  But this implementation
12864 ** does do a lot of error checking on mutexes to make sure they
12865 ** are called correctly and at appropriate times.  Hence, this
12866 ** implementation is suitable for testing.
12867 ** debugging purposes
12868 **
12869 ** $Id: mutex.c,v 1.17 2008/03/26 18:34:43 danielk1977 Exp $
12870 */
12871
12872 #ifdef SQLITE_MUTEX_NOOP_DEBUG
12873 /*
12874 ** In this implementation, mutexes do not provide any mutual exclusion.
12875 ** But the error checking is provided.  This implementation is useful
12876 ** for test purposes.
12877 */
12878
12879 /*
12880 ** The mutex object
12881 */
12882 struct sqlite3_mutex {
12883   int id;     /* The mutex type */
12884   int cnt;    /* Number of entries without a matching leave */
12885 };
12886
12887 /*
12888 ** The sqlite3_mutex_alloc() routine allocates a new
12889 ** mutex and returns a pointer to it.  If it returns NULL
12890 ** that means that a mutex could not be allocated. 
12891 */
12892 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
12893   static sqlite3_mutex aStatic[6];
12894   sqlite3_mutex *pNew = 0;
12895   switch( id ){
12896     case SQLITE_MUTEX_FAST:
12897     case SQLITE_MUTEX_RECURSIVE: {
12898       pNew = sqlite3_malloc(sizeof(*pNew));
12899       if( pNew ){
12900         pNew->id = id;
12901         pNew->cnt = 0;
12902       }
12903       break;
12904     }
12905     default: {
12906       assert( id-2 >= 0 );
12907       assert( id-2 < sizeof(aStatic)/sizeof(aStatic[0]) );
12908       pNew = &aStatic[id-2];
12909       pNew->id = id;
12910       break;
12911     }
12912   }
12913   return pNew;
12914 }
12915
12916 /*
12917 ** This routine deallocates a previously allocated mutex.
12918 */
12919 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
12920   assert( p );
12921   assert( p->cnt==0 );
12922   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
12923   sqlite3_free(p);
12924 }
12925
12926 /*
12927 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
12928 ** to enter a mutex.  If another thread is already within the mutex,
12929 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
12930 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
12931 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
12932 ** be entered multiple times by the same thread.  In such cases the,
12933 ** mutex must be exited an equal number of times before another thread
12934 ** can enter.  If the same thread tries to enter any other kind of mutex
12935 ** more than once, the behavior is undefined.
12936 */
12937 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
12938   assert( p );
12939   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
12940   p->cnt++;
12941 }
12942 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
12943   assert( p );
12944   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
12945   p->cnt++;
12946   return SQLITE_OK;
12947 }
12948
12949 /*
12950 ** The sqlite3_mutex_leave() routine exits a mutex that was
12951 ** previously entered by the same thread.  The behavior
12952 ** is undefined if the mutex is not currently entered or
12953 ** is not currently allocated.  SQLite will never do either.
12954 */
12955 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
12956   assert( p );
12957   assert( sqlite3_mutex_held(p) );
12958   p->cnt--;
12959   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
12960 }
12961
12962 /*
12963 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
12964 ** intended for use inside assert() statements.
12965 */
12966 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
12967   return p==0 || p->cnt>0;
12968 }
12969 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
12970   return p==0 || p->cnt==0;
12971 }
12972 #endif /* SQLITE_MUTEX_NOOP_DEBUG */
12973
12974 /************** End of mutex.c ***********************************************/
12975 /************** Begin file mutex_os2.c ***************************************/
12976 /*
12977 ** 2007 August 28
12978 **
12979 ** The author disclaims copyright to this source code.  In place of
12980 ** a legal notice, here is a blessing:
12981 **
12982 **    May you do good and not evil.
12983 **    May you find forgiveness for yourself and forgive others.
12984 **    May you share freely, never taking more than you give.
12985 **
12986 *************************************************************************
12987 ** This file contains the C functions that implement mutexes for OS/2
12988 **
12989 ** $Id: mutex_os2.c,v 1.6 2008/03/26 18:34:43 danielk1977 Exp $
12990 */
12991
12992 /*
12993 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
12994 ** See the mutex.h file for details.
12995 */
12996 #ifdef SQLITE_MUTEX_OS2
12997
12998 /********************** OS/2 Mutex Implementation **********************
12999 **
13000 ** This implementation of mutexes is built using the OS/2 API.
13001 */
13002
13003 /*
13004 ** The mutex object
13005 ** Each recursive mutex is an instance of the following structure.
13006 */
13007 struct sqlite3_mutex {
13008   HMTX mutex;       /* Mutex controlling the lock */
13009   int  id;          /* Mutex type */
13010   int  nRef;        /* Number of references */
13011   TID  owner;       /* Thread holding this mutex */
13012 };
13013
13014 #define OS2_MUTEX_INITIALIZER   0,0,0,0
13015
13016 /*
13017 ** The sqlite3_mutex_alloc() routine allocates a new
13018 ** mutex and returns a pointer to it.  If it returns NULL
13019 ** that means that a mutex could not be allocated. 
13020 ** SQLite will unwind its stack and return an error.  The argument
13021 ** to sqlite3_mutex_alloc() is one of these integer constants:
13022 **
13023 ** <ul>
13024 ** <li>  SQLITE_MUTEX_FAST               0
13025 ** <li>  SQLITE_MUTEX_RECURSIVE          1
13026 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
13027 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
13028 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
13029 ** </ul>
13030 **
13031 ** The first two constants cause sqlite3_mutex_alloc() to create
13032 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
13033 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
13034 ** The mutex implementation does not need to make a distinction
13035 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
13036 ** not want to.  But SQLite will only request a recursive mutex in
13037 ** cases where it really needs one.  If a faster non-recursive mutex
13038 ** implementation is available on the host platform, the mutex subsystem
13039 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
13040 **
13041 ** The other allowed parameters to sqlite3_mutex_alloc() each return
13042 ** a pointer to a static preexisting mutex.  Three static mutexes are
13043 ** used by the current version of SQLite.  Future versions of SQLite
13044 ** may add additional static mutexes.  Static mutexes are for internal
13045 ** use by SQLite only.  Applications that use SQLite mutexes should
13046 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
13047 ** SQLITE_MUTEX_RECURSIVE.
13048 **
13049 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
13050 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
13051 ** returns a different mutex on every call.  But for the static
13052 ** mutex types, the same mutex is returned on every call that has
13053 ** the same type number.
13054 */
13055 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
13056   sqlite3_mutex *p = NULL;
13057   switch( iType ){
13058     case SQLITE_MUTEX_FAST:
13059     case SQLITE_MUTEX_RECURSIVE: {
13060       p = sqlite3MallocZero( sizeof(*p) );
13061       if( p ){
13062         p->id = iType;
13063         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
13064           sqlite3_free( p );
13065           p = NULL;
13066         }
13067       }
13068       break;
13069     }
13070     default: {
13071       static volatile int isInit = 0;
13072       static sqlite3_mutex staticMutexes[] = {
13073         { OS2_MUTEX_INITIALIZER, },
13074         { OS2_MUTEX_INITIALIZER, },
13075         { OS2_MUTEX_INITIALIZER, },
13076         { OS2_MUTEX_INITIALIZER, },
13077         { OS2_MUTEX_INITIALIZER, },
13078         { OS2_MUTEX_INITIALIZER, },
13079       };
13080       if ( !isInit ){
13081         APIRET rc;
13082         PTIB ptib;
13083         PPIB ppib;
13084         HMTX mutex;
13085         char name[32];
13086         DosGetInfoBlocks( &ptib, &ppib );
13087         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
13088                           ppib->pib_ulpid );
13089         while( !isInit ){
13090           mutex = 0;
13091           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
13092           if( rc == NO_ERROR ){
13093             int i;
13094             if( !isInit ){
13095               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
13096                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
13097               }
13098               isInit = 1;
13099             }
13100             DosCloseMutexSem( mutex );
13101           }else if( rc == ERROR_DUPLICATE_NAME ){
13102             DosSleep( 1 );
13103           }else{
13104             return p;
13105           }
13106         }
13107       }
13108       assert( iType-2 >= 0 );
13109       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
13110       p = &staticMutexes[iType-2];
13111       p->id = iType;
13112       break;
13113     }
13114   }
13115   return p;
13116 }
13117
13118
13119 /*
13120 ** This routine deallocates a previously allocated mutex.
13121 ** SQLite is careful to deallocate every mutex that it allocates.
13122 */
13123 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
13124   assert( p );
13125   assert( p->nRef==0 );
13126   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
13127   DosCloseMutexSem( p->mutex );
13128   sqlite3_free( p );
13129 }
13130
13131 /*
13132 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
13133 ** to enter a mutex.  If another thread is already within the mutex,
13134 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
13135 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
13136 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
13137 ** be entered multiple times by the same thread.  In such cases the,
13138 ** mutex must be exited an equal number of times before another thread
13139 ** can enter.  If the same thread tries to enter any other kind of mutex
13140 ** more than once, the behavior is undefined.
13141 */
13142 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
13143   TID tid;
13144   PID holder1;
13145   ULONG holder2;
13146   assert( p );
13147   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13148   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
13149   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
13150   p->owner = tid;
13151   p->nRef++;
13152 }
13153 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
13154   int rc;
13155   TID tid;
13156   PID holder1;
13157   ULONG holder2;
13158   assert( p );
13159   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13160   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
13161     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
13162     p->owner = tid;
13163     p->nRef++;
13164     rc = SQLITE_OK;
13165   } else {
13166     rc = SQLITE_BUSY;
13167   }
13168
13169   return rc;
13170 }
13171
13172 /*
13173 ** The sqlite3_mutex_leave() routine exits a mutex that was
13174 ** previously entered by the same thread.  The behavior
13175 ** is undefined if the mutex is not currently entered or
13176 ** is not currently allocated.  SQLite will never do either.
13177 */
13178 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
13179   TID tid;
13180   PID holder1;
13181   ULONG holder2;
13182   assert( p->nRef>0 );
13183   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
13184   assert( p->owner==tid );
13185   p->nRef--;
13186   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
13187   DosReleaseMutexSem(p->mutex);
13188 }
13189
13190 /*
13191 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
13192 ** intended for use inside assert() statements.
13193 */
13194 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
13195   TID tid;
13196   PID pid;
13197   ULONG ulCount;
13198   PTIB ptib;
13199   if( p!=0 ) {
13200     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
13201   } else {
13202     DosGetInfoBlocks(&ptib, NULL);
13203     tid = ptib->tib_ptib2->tib2_ultid;
13204   }
13205   return p==0 || (p->nRef!=0 && p->owner==tid);
13206 }
13207 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
13208   TID tid;
13209   PID pid;
13210   ULONG ulCount;
13211   PTIB ptib;
13212   if( p!= 0 ) {
13213     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
13214   } else {
13215     DosGetInfoBlocks(&ptib, NULL);
13216     tid = ptib->tib_ptib2->tib2_ultid;
13217   }
13218   return p==0 || p->nRef==0 || p->owner!=tid;
13219 }
13220 #endif /* SQLITE_MUTEX_OS2 */
13221
13222 /************** End of mutex_os2.c *******************************************/
13223 /************** Begin file mutex_unix.c **************************************/
13224 /*
13225 ** 2007 August 28
13226 **
13227 ** The author disclaims copyright to this source code.  In place of
13228 ** a legal notice, here is a blessing:
13229 **
13230 **    May you do good and not evil.
13231 **    May you find forgiveness for yourself and forgive others.
13232 **    May you share freely, never taking more than you give.
13233 **
13234 *************************************************************************
13235 ** This file contains the C functions that implement mutexes for pthreads
13236 **
13237 ** $Id: mutex_unix.c,v 1.7 2008/03/29 12:47:27 rse Exp $
13238 */
13239
13240 /*
13241 ** The code in this file is only used if we are compiling threadsafe
13242 ** under unix with pthreads.
13243 **
13244 ** Note that this implementation requires a version of pthreads that
13245 ** supports recursive mutexes.
13246 */
13247 #ifdef SQLITE_MUTEX_PTHREADS
13248
13249 #include <pthread.h>
13250
13251
13252 /*
13253 ** Each recursive mutex is an instance of the following structure.
13254 */
13255 struct sqlite3_mutex {
13256   pthread_mutex_t mutex;     /* Mutex controlling the lock */
13257   int id;                    /* Mutex type */
13258   int nRef;                  /* Number of entrances */
13259   pthread_t owner;           /* Thread that is within this mutex */
13260 #ifdef SQLITE_DEBUG
13261   int trace;                 /* True to trace changes */
13262 #endif
13263 };
13264 #ifdef SQLITE_DEBUG
13265 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
13266 #else
13267 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
13268 #endif
13269
13270 /*
13271 ** The sqlite3_mutex_alloc() routine allocates a new
13272 ** mutex and returns a pointer to it.  If it returns NULL
13273 ** that means that a mutex could not be allocated.  SQLite
13274 ** will unwind its stack and return an error.  The argument
13275 ** to sqlite3_mutex_alloc() is one of these integer constants:
13276 **
13277 ** <ul>
13278 ** <li>  SQLITE_MUTEX_FAST
13279 ** <li>  SQLITE_MUTEX_RECURSIVE
13280 ** <li>  SQLITE_MUTEX_STATIC_MASTER
13281 ** <li>  SQLITE_MUTEX_STATIC_MEM
13282 ** <li>  SQLITE_MUTEX_STATIC_MEM2
13283 ** <li>  SQLITE_MUTEX_STATIC_PRNG
13284 ** <li>  SQLITE_MUTEX_STATIC_LRU
13285 ** </ul>
13286 **
13287 ** The first two constants cause sqlite3_mutex_alloc() to create
13288 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
13289 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
13290 ** The mutex implementation does not need to make a distinction
13291 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
13292 ** not want to.  But SQLite will only request a recursive mutex in
13293 ** cases where it really needs one.  If a faster non-recursive mutex
13294 ** implementation is available on the host platform, the mutex subsystem
13295 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
13296 **
13297 ** The other allowed parameters to sqlite3_mutex_alloc() each return
13298 ** a pointer to a static preexisting mutex.  Three static mutexes are
13299 ** used by the current version of SQLite.  Future versions of SQLite
13300 ** may add additional static mutexes.  Static mutexes are for internal
13301 ** use by SQLite only.  Applications that use SQLite mutexes should
13302 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
13303 ** SQLITE_MUTEX_RECURSIVE.
13304 **
13305 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
13306 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
13307 ** returns a different mutex on every call.  But for the static 
13308 ** mutex types, the same mutex is returned on every call that has
13309 ** the same type number.
13310 */
13311 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
13312   static sqlite3_mutex staticMutexes[] = {
13313     SQLITE3_MUTEX_INITIALIZER,
13314     SQLITE3_MUTEX_INITIALIZER,
13315     SQLITE3_MUTEX_INITIALIZER,
13316     SQLITE3_MUTEX_INITIALIZER,
13317     SQLITE3_MUTEX_INITIALIZER,
13318     SQLITE3_MUTEX_INITIALIZER
13319   };
13320   sqlite3_mutex *p;
13321   switch( iType ){
13322     case SQLITE_MUTEX_RECURSIVE: {
13323       p = sqlite3MallocZero( sizeof(*p) );
13324       if( p ){
13325 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13326         /* If recursive mutexes are not available, we will have to
13327         ** build our own.  See below. */
13328         pthread_mutex_init(&p->mutex, 0);
13329 #else
13330         /* Use a recursive mutex if it is available */
13331         pthread_mutexattr_t recursiveAttr;
13332         pthread_mutexattr_init(&recursiveAttr);
13333         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
13334         pthread_mutex_init(&p->mutex, &recursiveAttr);
13335         pthread_mutexattr_destroy(&recursiveAttr);
13336 #endif
13337         p->id = iType;
13338       }
13339       break;
13340     }
13341     case SQLITE_MUTEX_FAST: {
13342       p = sqlite3MallocZero( sizeof(*p) );
13343       if( p ){
13344         p->id = iType;
13345         pthread_mutex_init(&p->mutex, 0);
13346       }
13347       break;
13348     }
13349     default: {
13350       assert( iType-2 >= 0 );
13351       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
13352       p = &staticMutexes[iType-2];
13353       p->id = iType;
13354       break;
13355     }
13356   }
13357   return p;
13358 }
13359
13360
13361 /*
13362 ** This routine deallocates a previously
13363 ** allocated mutex.  SQLite is careful to deallocate every
13364 ** mutex that it allocates.
13365 */
13366 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
13367   assert( p );
13368   assert( p->nRef==0 );
13369   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
13370   pthread_mutex_destroy(&p->mutex);
13371   sqlite3_free(p);
13372 }
13373
13374 /*
13375 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
13376 ** to enter a mutex.  If another thread is already within the mutex,
13377 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
13378 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
13379 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
13380 ** be entered multiple times by the same thread.  In such cases the,
13381 ** mutex must be exited an equal number of times before another thread
13382 ** can enter.  If the same thread tries to enter any other kind of mutex
13383 ** more than once, the behavior is undefined.
13384 */
13385 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
13386   assert( p );
13387   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13388
13389 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13390   /* If recursive mutexes are not available, then we have to grow
13391   ** our own.  This implementation assumes that pthread_equal()
13392   ** is atomic - that it cannot be deceived into thinking self
13393   ** and p->owner are equal if p->owner changes between two values
13394   ** that are not equal to self while the comparison is taking place.
13395   ** This implementation also assumes a coherent cache - that 
13396   ** separate processes cannot read different values from the same
13397   ** address at the same time.  If either of these two conditions
13398   ** are not met, then the mutexes will fail and problems will result.
13399   */
13400   {
13401     pthread_t self = pthread_self();
13402     if( p->nRef>0 && pthread_equal(p->owner, self) ){
13403       p->nRef++;
13404     }else{
13405       pthread_mutex_lock(&p->mutex);
13406       assert( p->nRef==0 );
13407       p->owner = self;
13408       p->nRef = 1;
13409     }
13410   }
13411 #else
13412   /* Use the built-in recursive mutexes if they are available.
13413   */
13414   pthread_mutex_lock(&p->mutex);
13415   p->owner = pthread_self();
13416   p->nRef++;
13417 #endif
13418
13419 #ifdef SQLITE_DEBUG
13420   if( p->trace ){
13421     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
13422   }
13423 #endif
13424 }
13425 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
13426   int rc;
13427   assert( p );
13428   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13429
13430 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13431   /* If recursive mutexes are not available, then we have to grow
13432   ** our own.  This implementation assumes that pthread_equal()
13433   ** is atomic - that it cannot be deceived into thinking self
13434   ** and p->owner are equal if p->owner changes between two values
13435   ** that are not equal to self while the comparison is taking place.
13436   ** This implementation also assumes a coherent cache - that 
13437   ** separate processes cannot read different values from the same
13438   ** address at the same time.  If either of these two conditions
13439   ** are not met, then the mutexes will fail and problems will result.
13440   */
13441   {
13442     pthread_t self = pthread_self();
13443     if( p->nRef>0 && pthread_equal(p->owner, self) ){
13444       p->nRef++;
13445       rc = SQLITE_OK;
13446     }else if( pthread_mutex_lock(&p->mutex)==0 ){
13447       assert( p->nRef==0 );
13448       p->owner = self;
13449       p->nRef = 1;
13450       rc = SQLITE_OK;
13451     }else{
13452       rc = SQLITE_BUSY;
13453     }
13454   }
13455 #else
13456   /* Use the built-in recursive mutexes if they are available.
13457   */
13458   if( pthread_mutex_trylock(&p->mutex)==0 ){
13459     p->owner = pthread_self();
13460     p->nRef++;
13461     rc = SQLITE_OK;
13462   }else{
13463     rc = SQLITE_BUSY;
13464   }
13465 #endif
13466
13467 #ifdef SQLITE_DEBUG
13468   if( rc==SQLITE_OK && p->trace ){
13469     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
13470   }
13471 #endif
13472   return rc;
13473 }
13474
13475 /*
13476 ** The sqlite3_mutex_leave() routine exits a mutex that was
13477 ** previously entered by the same thread.  The behavior
13478 ** is undefined if the mutex is not currently entered or
13479 ** is not currently allocated.  SQLite will never do either.
13480 */
13481 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
13482   assert( p );
13483   assert( sqlite3_mutex_held(p) );
13484   p->nRef--;
13485   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
13486
13487 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13488   if( p->nRef==0 ){
13489     pthread_mutex_unlock(&p->mutex);
13490   }
13491 #else
13492   pthread_mutex_unlock(&p->mutex);
13493 #endif
13494
13495 #ifdef SQLITE_DEBUG
13496   if( p->trace ){
13497     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
13498   }
13499 #endif
13500 }
13501
13502 /*
13503 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
13504 ** intended for use only inside assert() statements.  On some platforms,
13505 ** there might be race conditions that can cause these routines to
13506 ** deliver incorrect results.  In particular, if pthread_equal() is
13507 ** not an atomic operation, then these routines might delivery
13508 ** incorrect results.  On most platforms, pthread_equal() is a 
13509 ** comparison of two integers and is therefore atomic.  But we are
13510 ** told that HPUX is not such a platform.  If so, then these routines
13511 ** will not always work correctly on HPUX.
13512 **
13513 ** On those platforms where pthread_equal() is not atomic, SQLite
13514 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
13515 ** make sure no assert() statements are evaluated and hence these
13516 ** routines are never called.
13517 */
13518 #ifndef NDEBUG
13519 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
13520   return p==0 || (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
13521 }
13522 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
13523   return p==0 || p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
13524 }
13525 #endif
13526 #endif /* SQLITE_MUTEX_PTHREAD */
13527
13528 /************** End of mutex_unix.c ******************************************/
13529 /************** Begin file mutex_w32.c ***************************************/
13530 /*
13531 ** 2007 August 14
13532 **
13533 ** The author disclaims copyright to this source code.  In place of
13534 ** a legal notice, here is a blessing:
13535 **
13536 **    May you do good and not evil.
13537 **    May you find forgiveness for yourself and forgive others.
13538 **    May you share freely, never taking more than you give.
13539 **
13540 *************************************************************************
13541 ** This file contains the C functions that implement mutexes for win32
13542 **
13543 ** $Id: mutex_w32.c,v 1.6 2008/03/26 18:34:43 danielk1977 Exp $
13544 */
13545
13546 /*
13547 ** The code in this file is only used if we are compiling multithreaded
13548 ** on a win32 system.
13549 */
13550 #ifdef SQLITE_MUTEX_W32
13551
13552 /*
13553 ** Each recursive mutex is an instance of the following structure.
13554 */
13555 struct sqlite3_mutex {
13556   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
13557   int id;                    /* Mutex type */
13558   int nRef;                  /* Number of enterances */
13559   DWORD owner;               /* Thread holding this mutex */
13560 };
13561
13562 /*
13563 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
13564 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
13565 **
13566 ** Here is an interesting observation:  Win95, Win98, and WinME lack
13567 ** the LockFileEx() API.  But we can still statically link against that
13568 ** API as long as we don't call it win running Win95/98/ME.  A call to
13569 ** this routine is used to determine if the host is Win95/98/ME or
13570 ** WinNT/2K/XP so that we will know whether or not we can safely call
13571 ** the LockFileEx() API.
13572 */
13573 #if OS_WINCE
13574 # define mutexIsNT()  (1)
13575 #else
13576   static int mutexIsNT(void){
13577     static int osType = 0;
13578     if( osType==0 ){
13579       OSVERSIONINFO sInfo;
13580       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
13581       GetVersionEx(&sInfo);
13582       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
13583     }
13584     return osType==2;
13585   }
13586 #endif /* OS_WINCE */
13587
13588
13589 /*
13590 ** The sqlite3_mutex_alloc() routine allocates a new
13591 ** mutex and returns a pointer to it.  If it returns NULL
13592 ** that means that a mutex could not be allocated.  SQLite
13593 ** will unwind its stack and return an error.  The argument
13594 ** to sqlite3_mutex_alloc() is one of these integer constants:
13595 **
13596 ** <ul>
13597 ** <li>  SQLITE_MUTEX_FAST               0
13598 ** <li>  SQLITE_MUTEX_RECURSIVE          1
13599 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
13600 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
13601 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
13602 ** </ul>
13603 **
13604 ** The first two constants cause sqlite3_mutex_alloc() to create
13605 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
13606 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
13607 ** The mutex implementation does not need to make a distinction
13608 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
13609 ** not want to.  But SQLite will only request a recursive mutex in
13610 ** cases where it really needs one.  If a faster non-recursive mutex
13611 ** implementation is available on the host platform, the mutex subsystem
13612 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
13613 **
13614 ** The other allowed parameters to sqlite3_mutex_alloc() each return
13615 ** a pointer to a static preexisting mutex.  Three static mutexes are
13616 ** used by the current version of SQLite.  Future versions of SQLite
13617 ** may add additional static mutexes.  Static mutexes are for internal
13618 ** use by SQLite only.  Applications that use SQLite mutexes should
13619 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
13620 ** SQLITE_MUTEX_RECURSIVE.
13621 **
13622 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
13623 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
13624 ** returns a different mutex on every call.  But for the static 
13625 ** mutex types, the same mutex is returned on every call that has
13626 ** the same type number.
13627 */
13628 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int iType){
13629   sqlite3_mutex *p;
13630
13631   switch( iType ){
13632     case SQLITE_MUTEX_FAST:
13633     case SQLITE_MUTEX_RECURSIVE: {
13634       p = sqlite3MallocZero( sizeof(*p) );
13635       if( p ){
13636         p->id = iType;
13637         InitializeCriticalSection(&p->mutex);
13638       }
13639       break;
13640     }
13641     default: {
13642       static sqlite3_mutex staticMutexes[6];
13643       static int isInit = 0;
13644       while( !isInit ){
13645         static long lock = 0;
13646         if( InterlockedIncrement(&lock)==1 ){
13647           int i;
13648           for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
13649             InitializeCriticalSection(&staticMutexes[i].mutex);
13650           }
13651           isInit = 1;
13652         }else{
13653           Sleep(1);
13654         }
13655       }
13656       assert( iType-2 >= 0 );
13657       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
13658       p = &staticMutexes[iType-2];
13659       p->id = iType;
13660       break;
13661     }
13662   }
13663   return p;
13664 }
13665
13666
13667 /*
13668 ** This routine deallocates a previously
13669 ** allocated mutex.  SQLite is careful to deallocate every
13670 ** mutex that it allocates.
13671 */
13672 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
13673   assert( p );
13674   assert( p->nRef==0 );
13675   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
13676   DeleteCriticalSection(&p->mutex);
13677   sqlite3_free(p);
13678 }
13679
13680 /*
13681 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
13682 ** to enter a mutex.  If another thread is already within the mutex,
13683 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
13684 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
13685 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
13686 ** be entered multiple times by the same thread.  In such cases the,
13687 ** mutex must be exited an equal number of times before another thread
13688 ** can enter.  If the same thread tries to enter any other kind of mutex
13689 ** more than once, the behavior is undefined.
13690 */
13691 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
13692   assert( p );
13693   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13694   EnterCriticalSection(&p->mutex);
13695   p->owner = GetCurrentThreadId(); 
13696   p->nRef++;
13697 }
13698 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
13699   int rc = SQLITE_BUSY;
13700   assert( p );
13701   assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) );
13702   /*
13703   ** The sqlite3_mutex_try() routine is very rarely used, and when it
13704   ** is used it is merely an optimization.  So it is OK for it to always
13705   ** fail.  
13706   **
13707   ** The TryEnterCriticalSection() interface is only available on WinNT.
13708   ** And some windows compilers complain if you try to use it without
13709   ** first doing some #defines that prevent SQLite from building on Win98.
13710   ** For that reason, we will omit this optimization for now.  See
13711   ** ticket #2685.
13712   */
13713 #if 0
13714   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
13715     p->owner = GetCurrentThreadId();
13716     p->nRef++;
13717     rc = SQLITE_OK;
13718   }
13719 #endif
13720   return rc;
13721 }
13722
13723 /*
13724 ** The sqlite3_mutex_leave() routine exits a mutex that was
13725 ** previously entered by the same thread.  The behavior
13726 ** is undefined if the mutex is not currently entered or
13727 ** is not currently allocated.  SQLite will never do either.
13728 */
13729 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
13730   assert( p->nRef>0 );
13731   assert( p->owner==GetCurrentThreadId() );
13732   p->nRef--;
13733   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
13734   LeaveCriticalSection(&p->mutex);
13735 }
13736
13737 /*
13738 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
13739 ** intended for use only inside assert() statements.
13740 */
13741 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
13742   return p==0 || (p->nRef!=0 && p->owner==GetCurrentThreadId());
13743 }
13744 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
13745   return p==0 || p->nRef==0 || p->owner!=GetCurrentThreadId();
13746 }
13747 #endif /* SQLITE_MUTEX_W32 */
13748
13749 /************** End of mutex_w32.c *******************************************/
13750 /************** Begin file malloc.c ******************************************/
13751 /*
13752 ** 2001 September 15
13753 **
13754 ** The author disclaims copyright to this source code.  In place of
13755 ** a legal notice, here is a blessing:
13756 **
13757 **    May you do good and not evil.
13758 **    May you find forgiveness for yourself and forgive others.
13759 **    May you share freely, never taking more than you give.
13760 **
13761 *************************************************************************
13762 ** Memory allocation functions used throughout sqlite.
13763 **
13764 **
13765 ** $Id: malloc.c,v 1.15 2008/03/26 18:34:43 danielk1977 Exp $
13766 */
13767
13768 /*
13769 ** This routine runs when the memory allocator sees that the
13770 ** total memory allocation is about to exceed the soft heap
13771 ** limit.
13772 */
13773 static void softHeapLimitEnforcer(
13774   void *NotUsed, 
13775   sqlite3_int64 inUse,
13776   int allocSize
13777 ){
13778   sqlite3_release_memory(allocSize);
13779 }
13780
13781 /*
13782 ** Set the soft heap-size limit for the current thread. Passing a
13783 ** zero or negative value indicates no limit.
13784 */
13785 SQLITE_API void sqlite3_soft_heap_limit(int n){
13786   sqlite3_uint64 iLimit;
13787   int overage;
13788   if( n<0 ){
13789     iLimit = 0;
13790   }else{
13791     iLimit = n;
13792   }
13793   if( iLimit>0 ){
13794     sqlite3_memory_alarm(softHeapLimitEnforcer, 0, iLimit);
13795   }else{
13796     sqlite3_memory_alarm(0, 0, 0);
13797   }
13798   overage = sqlite3_memory_used() - n;
13799   if( overage>0 ){
13800     sqlite3_release_memory(overage);
13801   }
13802 }
13803
13804 /*
13805 ** Release memory held by SQLite instances created by the current thread.
13806 */
13807 SQLITE_API int sqlite3_release_memory(int n){
13808 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13809   int nRet = sqlite3VdbeReleaseMemory(n);
13810   nRet += sqlite3PagerReleaseMemory(n-nRet);
13811   return nRet;
13812 #else
13813   return SQLITE_OK;
13814 #endif
13815 }
13816
13817
13818 /*
13819 ** Allocate and zero memory.
13820 */ 
13821 SQLITE_PRIVATE void *sqlite3MallocZero(unsigned n){
13822   void *p = sqlite3_malloc(n);
13823   if( p ){
13824     memset(p, 0, n);
13825   }
13826   return p;
13827 }
13828
13829 /*
13830 ** Allocate and zero memory.  If the allocation fails, make
13831 ** the mallocFailed flag in the connection pointer.
13832 */
13833 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, unsigned n){
13834   void *p = sqlite3DbMallocRaw(db, n);
13835   if( p ){
13836     memset(p, 0, n);
13837   }
13838   return p;
13839 }
13840
13841 /*
13842 ** Allocate and zero memory.  If the allocation fails, make
13843 ** the mallocFailed flag in the connection pointer.
13844 */
13845 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, unsigned n){
13846   void *p = 0;
13847   if( !db || db->mallocFailed==0 ){
13848     p = sqlite3_malloc(n);
13849     if( !p && db ){
13850       db->mallocFailed = 1;
13851     }
13852   }
13853   return p;
13854 }
13855
13856 /*
13857 ** Resize the block of memory pointed to by p to n bytes. If the
13858 ** resize fails, set the mallocFailed flag inthe connection object.
13859 */
13860 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
13861   void *pNew = 0;
13862   if( db->mallocFailed==0 ){
13863     pNew = sqlite3_realloc(p, n);
13864     if( !pNew ){
13865       db->mallocFailed = 1;
13866     }
13867   }
13868   return pNew;
13869 }
13870
13871 /*
13872 ** Attempt to reallocate p.  If the reallocation fails, then free p
13873 ** and set the mallocFailed flag in the database connection.
13874 */
13875 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
13876   void *pNew;
13877   pNew = sqlite3DbRealloc(db, p, n);
13878   if( !pNew ){
13879     sqlite3_free(p);
13880   }
13881   return pNew;
13882 }
13883
13884 /*
13885 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
13886 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
13887 ** is because when memory debugging is turned on, these two functions are 
13888 ** called via macros that record the current file and line number in the
13889 ** ThreadData structure.
13890 */
13891 SQLITE_PRIVATE char *sqlite3StrDup(const char *z){
13892   char *zNew;
13893   int n;
13894   if( z==0 ) return 0;
13895   n = strlen(z)+1;
13896   zNew = sqlite3_malloc(n);
13897   if( zNew ) memcpy(zNew, z, n);
13898   return zNew;
13899 }
13900 SQLITE_PRIVATE char *sqlite3StrNDup(const char *z, int n){
13901   char *zNew;
13902   if( z==0 ) return 0;
13903   zNew = sqlite3_malloc(n+1);
13904   if( zNew ){
13905     memcpy(zNew, z, n);
13906     zNew[n] = 0;
13907   }
13908   return zNew;
13909 }
13910
13911 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
13912   char *zNew = sqlite3StrDup(z);
13913   if( z && !zNew ){
13914     db->mallocFailed = 1;
13915   }
13916   return zNew;
13917 }
13918 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
13919   char *zNew = sqlite3StrNDup(z, n);
13920   if( z && !zNew ){
13921     db->mallocFailed = 1;
13922   }
13923   return zNew;
13924 }
13925
13926 /*
13927 ** Create a string from the 2nd and subsequent arguments (up to the
13928 ** first NULL argument), store the string in memory obtained from
13929 ** sqliteMalloc() and make the pointer indicated by the 1st argument
13930 ** point to that string.  The 1st argument must either be NULL or 
13931 ** point to memory obtained from sqliteMalloc().
13932 */
13933 SQLITE_PRIVATE void sqlite3SetString(char **pz, ...){
13934   va_list ap;
13935   int nByte;
13936   const char *z;
13937   char *zResult;
13938
13939   assert( pz!=0 );
13940   nByte = 1;
13941   va_start(ap, pz);
13942   while( (z = va_arg(ap, const char*))!=0 ){
13943     nByte += strlen(z);
13944   }
13945   va_end(ap);
13946   sqlite3_free(*pz);
13947   *pz = zResult = sqlite3_malloc(nByte);
13948   if( zResult==0 ){
13949     return;
13950   }
13951   *zResult = 0;
13952   va_start(ap, pz);
13953   while( (z = va_arg(ap, const char*))!=0 ){
13954     int n = strlen(z);
13955     memcpy(zResult, z, n);
13956     zResult += n;
13957   }
13958   zResult[0] = 0;
13959   va_end(ap);
13960 }
13961
13962
13963 /*
13964 ** This function must be called before exiting any API function (i.e. 
13965 ** returning control to the user) that has called sqlite3_malloc or
13966 ** sqlite3_realloc.
13967 **
13968 ** The returned value is normally a copy of the second argument to this
13969 ** function. However, if a malloc() failure has occured since the previous
13970 ** invocation SQLITE_NOMEM is returned instead. 
13971 **
13972 ** If the first argument, db, is not NULL and a malloc() error has occured,
13973 ** then the connection error-code (the value returned by sqlite3_errcode())
13974 ** is set to SQLITE_NOMEM.
13975 */
13976 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
13977   /* If the db handle is not NULL, then we must hold the connection handle
13978   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
13979   ** is unsafe, as is the call to sqlite3Error().
13980   */
13981   assert( !db || sqlite3_mutex_held(db->mutex) );
13982   if( db && db->mallocFailed ){
13983     sqlite3Error(db, SQLITE_NOMEM, 0);
13984     db->mallocFailed = 0;
13985     rc = SQLITE_NOMEM;
13986   }
13987   return rc & (db ? db->errMask : 0xff);
13988 }
13989
13990 /************** End of malloc.c **********************************************/
13991 /************** Begin file printf.c ******************************************/
13992 /*
13993 ** The "printf" code that follows dates from the 1980's.  It is in
13994 ** the public domain.  The original comments are included here for
13995 ** completeness.  They are very out-of-date but might be useful as
13996 ** an historical reference.  Most of the "enhancements" have been backed
13997 ** out so that the functionality is now the same as standard printf().
13998 **
13999 **************************************************************************
14000 **
14001 ** The following modules is an enhanced replacement for the "printf" subroutines
14002 ** found in the standard C library.  The following enhancements are
14003 ** supported:
14004 **
14005 **      +  Additional functions.  The standard set of "printf" functions
14006 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
14007 **         vsprintf.  This module adds the following:
14008 **
14009 **           *  snprintf -- Works like sprintf, but has an extra argument
14010 **                          which is the size of the buffer written to.
14011 **
14012 **           *  mprintf --  Similar to sprintf.  Writes output to memory
14013 **                          obtained from malloc.
14014 **
14015 **           *  xprintf --  Calls a function to dispose of output.
14016 **
14017 **           *  nprintf --  No output, but returns the number of characters
14018 **                          that would have been output by printf.
14019 **
14020 **           *  A v- version (ex: vsnprintf) of every function is also
14021 **              supplied.
14022 **
14023 **      +  A few extensions to the formatting notation are supported:
14024 **
14025 **           *  The "=" flag (similar to "-") causes the output to be
14026 **              be centered in the appropriately sized field.
14027 **
14028 **           *  The %b field outputs an integer in binary notation.
14029 **
14030 **           *  The %c field now accepts a precision.  The character output
14031 **              is repeated by the number of times the precision specifies.
14032 **
14033 **           *  The %' field works like %c, but takes as its character the
14034 **              next character of the format string, instead of the next
14035 **              argument.  For example,  printf("%.78'-")  prints 78 minus
14036 **              signs, the same as  printf("%.78c",'-').
14037 **
14038 **      +  When compiled using GCC on a SPARC, this version of printf is
14039 **         faster than the library printf for SUN OS 4.1.
14040 **
14041 **      +  All functions are fully reentrant.
14042 **
14043 */
14044
14045 /*
14046 ** Conversion types fall into various categories as defined by the
14047 ** following enumeration.
14048 */
14049 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
14050 #define etFLOAT       2 /* Floating point.  %f */
14051 #define etEXP         3 /* Exponentional notation. %e and %E */
14052 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
14053 #define etSIZE        5 /* Return number of characters processed so far. %n */
14054 #define etSTRING      6 /* Strings. %s */
14055 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
14056 #define etPERCENT     8 /* Percent symbol. %% */
14057 #define etCHARX       9 /* Characters. %c */
14058 /* The rest are extensions, not normally found in printf() */
14059 #define etCHARLIT    10 /* Literal characters.  %' */
14060 #define etSQLESCAPE  11 /* Strings with '\'' doubled.  %q */
14061 #define etSQLESCAPE2 12 /* Strings with '\'' doubled and enclosed in '',
14062                           NULL pointers replaced by SQL NULL.  %Q */
14063 #define etTOKEN      13 /* a pointer to a Token structure */
14064 #define etSRCLIST    14 /* a pointer to a SrcList */
14065 #define etPOINTER    15 /* The %p conversion */
14066 #define etSQLESCAPE3 16 /* %w -> Strings with '\"' doubled */
14067 #define etORDINAL    17 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
14068
14069
14070 /*
14071 ** An "etByte" is an 8-bit unsigned value.
14072 */
14073 typedef unsigned char etByte;
14074
14075 /*
14076 ** Each builtin conversion character (ex: the 'd' in "%d") is described
14077 ** by an instance of the following structure
14078 */
14079 typedef struct et_info {   /* Information about each format field */
14080   char fmttype;            /* The format field code letter */
14081   etByte base;             /* The base for radix conversion */
14082   etByte flags;            /* One or more of FLAG_ constants below */
14083   etByte type;             /* Conversion paradigm */
14084   etByte charset;          /* Offset into aDigits[] of the digits string */
14085   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
14086 } et_info;
14087
14088 /*
14089 ** Allowed values for et_info.flags
14090 */
14091 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
14092 #define FLAG_INTERN  2     /* True if for internal use only */
14093 #define FLAG_STRING  4     /* Allow infinity precision */
14094
14095
14096 /*
14097 ** The following table is searched linearly, so it is good to put the
14098 ** most frequently used conversion types first.
14099 */
14100 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
14101 static const char aPrefix[] = "-x0\000X0";
14102 static const et_info fmtinfo[] = {
14103   {  'd', 10, 1, etRADIX,      0,  0 },
14104   {  's',  0, 4, etSTRING,     0,  0 },
14105   {  'g',  0, 1, etGENERIC,    30, 0 },
14106   {  'z',  0, 4, etDYNSTRING,  0,  0 },
14107   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
14108   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
14109   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
14110   {  'c',  0, 0, etCHARX,      0,  0 },
14111   {  'o',  8, 0, etRADIX,      0,  2 },
14112   {  'u', 10, 0, etRADIX,      0,  0 },
14113   {  'x', 16, 0, etRADIX,      16, 1 },
14114   {  'X', 16, 0, etRADIX,      0,  4 },
14115 #ifndef SQLITE_OMIT_FLOATING_POINT
14116   {  'f',  0, 1, etFLOAT,      0,  0 },
14117   {  'e',  0, 1, etEXP,        30, 0 },
14118   {  'E',  0, 1, etEXP,        14, 0 },
14119   {  'G',  0, 1, etGENERIC,    14, 0 },
14120 #endif
14121   {  'i', 10, 1, etRADIX,      0,  0 },
14122   {  'n',  0, 0, etSIZE,       0,  0 },
14123   {  '%',  0, 0, etPERCENT,    0,  0 },
14124   {  'p', 16, 0, etPOINTER,    0,  1 },
14125   {  'T',  0, 2, etTOKEN,      0,  0 },
14126   {  'S',  0, 2, etSRCLIST,    0,  0 },
14127   {  'r', 10, 3, etORDINAL,    0,  0 },
14128 };
14129 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
14130
14131 /*
14132 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
14133 ** conversions will work.
14134 */
14135 #ifndef SQLITE_OMIT_FLOATING_POINT
14136 /*
14137 ** "*val" is a double such that 0.1 <= *val < 10.0
14138 ** Return the ascii code for the leading digit of *val, then
14139 ** multiply "*val" by 10.0 to renormalize.
14140 **
14141 ** Example:
14142 **     input:     *val = 3.14159
14143 **     output:    *val = 1.4159    function return = '3'
14144 **
14145 ** The counter *cnt is incremented each time.  After counter exceeds
14146 ** 16 (the number of significant digits in a 64-bit float) '0' is
14147 ** always returned.
14148 */
14149 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
14150   int digit;
14151   LONGDOUBLE_TYPE d;
14152   if( (*cnt)++ >= 16 ) return '0';
14153   digit = (int)*val;
14154   d = digit;
14155   digit += '0';
14156   *val = (*val - d)*10.0;
14157   return digit;
14158 }
14159 #endif /* SQLITE_OMIT_FLOATING_POINT */
14160
14161 /*
14162 ** Append N space characters to the given string buffer.
14163 */
14164 static void appendSpace(StrAccum *pAccum, int N){
14165   static const char zSpaces[] = "                             ";
14166   while( N>=sizeof(zSpaces)-1 ){
14167     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
14168     N -= sizeof(zSpaces)-1;
14169   }
14170   if( N>0 ){
14171     sqlite3StrAccumAppend(pAccum, zSpaces, N);
14172   }
14173 }
14174
14175 /*
14176 ** On machines with a small stack size, you can redefine the
14177 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
14178 ** smaller values some %f conversions may go into an infinite loop.
14179 */
14180 #ifndef SQLITE_PRINT_BUF_SIZE
14181 # define SQLITE_PRINT_BUF_SIZE 350
14182 #endif
14183 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
14184
14185 /*
14186 ** The root program.  All variations call this core.
14187 **
14188 ** INPUTS:
14189 **   func   This is a pointer to a function taking three arguments
14190 **            1. A pointer to anything.  Same as the "arg" parameter.
14191 **            2. A pointer to the list of characters to be output
14192 **               (Note, this list is NOT null terminated.)
14193 **            3. An integer number of characters to be output.
14194 **               (Note: This number might be zero.)
14195 **
14196 **   arg    This is the pointer to anything which will be passed as the
14197 **          first argument to "func".  Use it for whatever you like.
14198 **
14199 **   fmt    This is the format string, as in the usual print.
14200 **
14201 **   ap     This is a pointer to a list of arguments.  Same as in
14202 **          vfprint.
14203 **
14204 ** OUTPUTS:
14205 **          The return value is the total number of characters sent to
14206 **          the function "func".  Returns -1 on a error.
14207 **
14208 ** Note that the order in which automatic variables are declared below
14209 ** seems to make a big difference in determining how fast this beast
14210 ** will run.
14211 */
14212 static void vxprintf(
14213   StrAccum *pAccum,                  /* Accumulate results here */
14214   int useExtended,                   /* Allow extended %-conversions */
14215   const char *fmt,                   /* Format string */
14216   va_list ap                         /* arguments */
14217 ){
14218   int c;                     /* Next character in the format string */
14219   char *bufpt;               /* Pointer to the conversion buffer */
14220   int precision;             /* Precision of the current field */
14221   int length;                /* Length of the field */
14222   int idx;                   /* A general purpose loop counter */
14223   int width;                 /* Width of the current field */
14224   etByte flag_leftjustify;   /* True if "-" flag is present */
14225   etByte flag_plussign;      /* True if "+" flag is present */
14226   etByte flag_blanksign;     /* True if " " flag is present */
14227   etByte flag_alternateform; /* True if "#" flag is present */
14228   etByte flag_altform2;      /* True if "!" flag is present */
14229   etByte flag_zeropad;       /* True if field width constant starts with zero */
14230   etByte flag_long;          /* True if "l" flag is present */
14231   etByte flag_longlong;      /* True if the "ll" flag is present */
14232   etByte done;               /* Loop termination flag */
14233   sqlite_uint64 longvalue;   /* Value for integer types */
14234   LONGDOUBLE_TYPE realvalue; /* Value for real types */
14235   const et_info *infop;      /* Pointer to the appropriate info structure */
14236   char buf[etBUFSIZE];       /* Conversion buffer */
14237   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
14238   etByte errorflag = 0;      /* True if an error is encountered */
14239   etByte xtype;              /* Conversion paradigm */
14240   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
14241 #ifndef SQLITE_OMIT_FLOATING_POINT
14242   int  exp, e2;              /* exponent of real numbers */
14243   double rounder;            /* Used for rounding floating point values */
14244   etByte flag_dp;            /* True if decimal point should be shown */
14245   etByte flag_rtz;           /* True if trailing zeros should be removed */
14246   etByte flag_exp;           /* True to force display of the exponent */
14247   int nsd;                   /* Number of significant digits returned */
14248 #endif
14249
14250   length = 0;
14251   bufpt = 0;
14252   for(; (c=(*fmt))!=0; ++fmt){
14253     if( c!='%' ){
14254       int amt;
14255       bufpt = (char *)fmt;
14256       amt = 1;
14257       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
14258       sqlite3StrAccumAppend(pAccum, bufpt, amt);
14259       if( c==0 ) break;
14260     }
14261     if( (c=(*++fmt))==0 ){
14262       errorflag = 1;
14263       sqlite3StrAccumAppend(pAccum, "%", 1);
14264       break;
14265     }
14266     /* Find out what flags are present */
14267     flag_leftjustify = flag_plussign = flag_blanksign = 
14268      flag_alternateform = flag_altform2 = flag_zeropad = 0;
14269     done = 0;
14270     do{
14271       switch( c ){
14272         case '-':   flag_leftjustify = 1;     break;
14273         case '+':   flag_plussign = 1;        break;
14274         case ' ':   flag_blanksign = 1;       break;
14275         case '#':   flag_alternateform = 1;   break;
14276         case '!':   flag_altform2 = 1;        break;
14277         case '0':   flag_zeropad = 1;         break;
14278         default:    done = 1;                 break;
14279       }
14280     }while( !done && (c=(*++fmt))!=0 );
14281     /* Get the field width */
14282     width = 0;
14283     if( c=='*' ){
14284       width = va_arg(ap,int);
14285       if( width<0 ){
14286         flag_leftjustify = 1;
14287         width = -width;
14288       }
14289       c = *++fmt;
14290     }else{
14291       while( c>='0' && c<='9' ){
14292         width = width*10 + c - '0';
14293         c = *++fmt;
14294       }
14295     }
14296     if( width > etBUFSIZE-10 ){
14297       width = etBUFSIZE-10;
14298     }
14299     /* Get the precision */
14300     if( c=='.' ){
14301       precision = 0;
14302       c = *++fmt;
14303       if( c=='*' ){
14304         precision = va_arg(ap,int);
14305         if( precision<0 ) precision = -precision;
14306         c = *++fmt;
14307       }else{
14308         while( c>='0' && c<='9' ){
14309           precision = precision*10 + c - '0';
14310           c = *++fmt;
14311         }
14312       }
14313     }else{
14314       precision = -1;
14315     }
14316     /* Get the conversion type modifier */
14317     if( c=='l' ){
14318       flag_long = 1;
14319       c = *++fmt;
14320       if( c=='l' ){
14321         flag_longlong = 1;
14322         c = *++fmt;
14323       }else{
14324         flag_longlong = 0;
14325       }
14326     }else{
14327       flag_long = flag_longlong = 0;
14328     }
14329     /* Fetch the info entry for the field */
14330     infop = 0;
14331     for(idx=0; idx<etNINFO; idx++){
14332       if( c==fmtinfo[idx].fmttype ){
14333         infop = &fmtinfo[idx];
14334         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
14335           xtype = infop->type;
14336         }else{
14337           return;
14338         }
14339         break;
14340       }
14341     }
14342     zExtra = 0;
14343     if( infop==0 ){
14344       return;
14345     }
14346
14347
14348     /* Limit the precision to prevent overflowing buf[] during conversion */
14349     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
14350       precision = etBUFSIZE-40;
14351     }
14352
14353     /*
14354     ** At this point, variables are initialized as follows:
14355     **
14356     **   flag_alternateform          TRUE if a '#' is present.
14357     **   flag_altform2               TRUE if a '!' is present.
14358     **   flag_plussign               TRUE if a '+' is present.
14359     **   flag_leftjustify            TRUE if a '-' is present or if the
14360     **                               field width was negative.
14361     **   flag_zeropad                TRUE if the width began with 0.
14362     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
14363     **                               the conversion character.
14364     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
14365     **                               the conversion character.
14366     **   flag_blanksign              TRUE if a ' ' is present.
14367     **   width                       The specified field width.  This is
14368     **                               always non-negative.  Zero is the default.
14369     **   precision                   The specified precision.  The default
14370     **                               is -1.
14371     **   xtype                       The class of the conversion.
14372     **   infop                       Pointer to the appropriate info struct.
14373     */
14374     switch( xtype ){
14375       case etPOINTER:
14376         flag_longlong = sizeof(char*)==sizeof(i64);
14377         flag_long = sizeof(char*)==sizeof(long int);
14378         /* Fall through into the next case */
14379       case etORDINAL:
14380       case etRADIX:
14381         if( infop->flags & FLAG_SIGNED ){
14382           i64 v;
14383           if( flag_longlong )   v = va_arg(ap,i64);
14384           else if( flag_long )  v = va_arg(ap,long int);
14385           else                  v = va_arg(ap,int);
14386           if( v<0 ){
14387             longvalue = -v;
14388             prefix = '-';
14389           }else{
14390             longvalue = v;
14391             if( flag_plussign )        prefix = '+';
14392             else if( flag_blanksign )  prefix = ' ';
14393             else                       prefix = 0;
14394           }
14395         }else{
14396           if( flag_longlong )   longvalue = va_arg(ap,u64);
14397           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
14398           else                  longvalue = va_arg(ap,unsigned int);
14399           prefix = 0;
14400         }
14401         if( longvalue==0 ) flag_alternateform = 0;
14402         if( flag_zeropad && precision<width-(prefix!=0) ){
14403           precision = width-(prefix!=0);
14404         }
14405         bufpt = &buf[etBUFSIZE-1];
14406         if( xtype==etORDINAL ){
14407           static const char zOrd[] = "thstndrd";
14408           int x = longvalue % 10;
14409           if( x>=4 || (longvalue/10)%10==1 ){
14410             x = 0;
14411           }
14412           buf[etBUFSIZE-3] = zOrd[x*2];
14413           buf[etBUFSIZE-2] = zOrd[x*2+1];
14414           bufpt -= 2;
14415         }
14416         {
14417           register const char *cset;      /* Use registers for speed */
14418           register int base;
14419           cset = &aDigits[infop->charset];
14420           base = infop->base;
14421           do{                                           /* Convert to ascii */
14422             *(--bufpt) = cset[longvalue%base];
14423             longvalue = longvalue/base;
14424           }while( longvalue>0 );
14425         }
14426         length = &buf[etBUFSIZE-1]-bufpt;
14427         for(idx=precision-length; idx>0; idx--){
14428           *(--bufpt) = '0';                             /* Zero pad */
14429         }
14430         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
14431         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
14432           const char *pre;
14433           char x;
14434           pre = &aPrefix[infop->prefix];
14435           if( *bufpt!=pre[0] ){
14436             for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
14437           }
14438         }
14439         length = &buf[etBUFSIZE-1]-bufpt;
14440         break;
14441       case etFLOAT:
14442       case etEXP:
14443       case etGENERIC:
14444         realvalue = va_arg(ap,double);
14445 #ifndef SQLITE_OMIT_FLOATING_POINT
14446         if( precision<0 ) precision = 6;         /* Set default precision */
14447         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
14448         if( realvalue<0.0 ){
14449           realvalue = -realvalue;
14450           prefix = '-';
14451         }else{
14452           if( flag_plussign )          prefix = '+';
14453           else if( flag_blanksign )    prefix = ' ';
14454           else                         prefix = 0;
14455         }
14456         if( xtype==etGENERIC && precision>0 ) precision--;
14457 #if 0
14458         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
14459         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
14460 #else
14461         /* It makes more sense to use 0.5 */
14462         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
14463 #endif
14464         if( xtype==etFLOAT ) realvalue += rounder;
14465         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
14466         exp = 0;
14467         if( sqlite3IsNaN(realvalue) ){
14468           bufpt = "NaN";
14469           length = 3;
14470           break;
14471         }
14472         if( realvalue>0.0 ){
14473           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
14474           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
14475           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
14476           while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
14477           while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
14478           if( exp>350 || exp<-350 ){
14479             if( prefix=='-' ){
14480               bufpt = "-Inf";
14481             }else if( prefix=='+' ){
14482               bufpt = "+Inf";
14483             }else{
14484               bufpt = "Inf";
14485             }
14486             length = strlen(bufpt);
14487             break;
14488           }
14489         }
14490         bufpt = buf;
14491         /*
14492         ** If the field type is etGENERIC, then convert to either etEXP
14493         ** or etFLOAT, as appropriate.
14494         */
14495         flag_exp = xtype==etEXP;
14496         if( xtype!=etFLOAT ){
14497           realvalue += rounder;
14498           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
14499         }
14500         if( xtype==etGENERIC ){
14501           flag_rtz = !flag_alternateform;
14502           if( exp<-4 || exp>precision ){
14503             xtype = etEXP;
14504           }else{
14505             precision = precision - exp;
14506             xtype = etFLOAT;
14507           }
14508         }else{
14509           flag_rtz = 0;
14510         }
14511         if( xtype==etEXP ){
14512           e2 = 0;
14513         }else{
14514           e2 = exp;
14515         }
14516         nsd = 0;
14517         flag_dp = (precision>0) | flag_alternateform | flag_altform2;
14518         /* The sign in front of the number */
14519         if( prefix ){
14520           *(bufpt++) = prefix;
14521         }
14522         /* Digits prior to the decimal point */
14523         if( e2<0 ){
14524           *(bufpt++) = '0';
14525         }else{
14526           for(; e2>=0; e2--){
14527             *(bufpt++) = et_getdigit(&realvalue,&nsd);
14528           }
14529         }
14530         /* The decimal point */
14531         if( flag_dp ){
14532           *(bufpt++) = '.';
14533         }
14534         /* "0" digits after the decimal point but before the first
14535         ** significant digit of the number */
14536         for(e2++; e2<0 && precision>0; precision--, e2++){
14537           *(bufpt++) = '0';
14538         }
14539         /* Significant digits after the decimal point */
14540         while( (precision--)>0 ){
14541           *(bufpt++) = et_getdigit(&realvalue,&nsd);
14542         }
14543         /* Remove trailing zeros and the "." if no digits follow the "." */
14544         if( flag_rtz && flag_dp ){
14545           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
14546           assert( bufpt>buf );
14547           if( bufpt[-1]=='.' ){
14548             if( flag_altform2 ){
14549               *(bufpt++) = '0';
14550             }else{
14551               *(--bufpt) = 0;
14552             }
14553           }
14554         }
14555         /* Add the "eNNN" suffix */
14556         if( flag_exp || (xtype==etEXP && exp) ){
14557           *(bufpt++) = aDigits[infop->charset];
14558           if( exp<0 ){
14559             *(bufpt++) = '-'; exp = -exp;
14560           }else{
14561             *(bufpt++) = '+';
14562           }
14563           if( exp>=100 ){
14564             *(bufpt++) = (exp/100)+'0';                /* 100's digit */
14565             exp %= 100;
14566           }
14567           *(bufpt++) = exp/10+'0';                     /* 10's digit */
14568           *(bufpt++) = exp%10+'0';                     /* 1's digit */
14569         }
14570         *bufpt = 0;
14571
14572         /* The converted number is in buf[] and zero terminated. Output it.
14573         ** Note that the number is in the usual order, not reversed as with
14574         ** integer conversions. */
14575         length = bufpt-buf;
14576         bufpt = buf;
14577
14578         /* Special case:  Add leading zeros if the flag_zeropad flag is
14579         ** set and we are not left justified */
14580         if( flag_zeropad && !flag_leftjustify && length < width){
14581           int i;
14582           int nPad = width - length;
14583           for(i=width; i>=nPad; i--){
14584             bufpt[i] = bufpt[i-nPad];
14585           }
14586           i = prefix!=0;
14587           while( nPad-- ) bufpt[i++] = '0';
14588           length = width;
14589         }
14590 #endif
14591         break;
14592       case etSIZE:
14593         *(va_arg(ap,int*)) = pAccum->nChar;
14594         length = width = 0;
14595         break;
14596       case etPERCENT:
14597         buf[0] = '%';
14598         bufpt = buf;
14599         length = 1;
14600         break;
14601       case etCHARLIT:
14602       case etCHARX:
14603         c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
14604         if( precision>=0 ){
14605           for(idx=1; idx<precision; idx++) buf[idx] = c;
14606           length = precision;
14607         }else{
14608           length =1;
14609         }
14610         bufpt = buf;
14611         break;
14612       case etSTRING:
14613       case etDYNSTRING:
14614         bufpt = va_arg(ap,char*);
14615         if( bufpt==0 ){
14616           bufpt = "";
14617         }else if( xtype==etDYNSTRING ){
14618           zExtra = bufpt;
14619         }
14620         if( precision>=0 ){
14621           for(length=0; length<precision && bufpt[length]; length++){}
14622         }else{
14623           length = strlen(bufpt);
14624         }
14625         break;
14626       case etSQLESCAPE:
14627       case etSQLESCAPE2:
14628       case etSQLESCAPE3: {
14629         int i, j, n, ch, isnull;
14630         int needQuote;
14631         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
14632         char *escarg = va_arg(ap,char*);
14633         isnull = escarg==0;
14634         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
14635         for(i=n=0; (ch=escarg[i])!=0; i++){
14636           if( ch==q )  n++;
14637         }
14638         needQuote = !isnull && xtype==etSQLESCAPE2;
14639         n += i + 1 + needQuote*2;
14640         if( n>etBUFSIZE ){
14641           bufpt = zExtra = sqlite3_malloc( n );
14642           if( bufpt==0 ) return;
14643         }else{
14644           bufpt = buf;
14645         }
14646         j = 0;
14647         if( needQuote ) bufpt[j++] = q;
14648         for(i=0; (ch=escarg[i])!=0; i++){
14649           bufpt[j++] = ch;
14650           if( ch==q ) bufpt[j++] = ch;
14651         }
14652         if( needQuote ) bufpt[j++] = q;
14653         bufpt[j] = 0;
14654         length = j;
14655         /* The precision is ignored on %q and %Q */
14656         /* if( precision>=0 && precision<length ) length = precision; */
14657         break;
14658       }
14659       case etTOKEN: {
14660         Token *pToken = va_arg(ap, Token*);
14661         if( pToken && pToken->z ){
14662           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
14663         }
14664         length = width = 0;
14665         break;
14666       }
14667       case etSRCLIST: {
14668         SrcList *pSrc = va_arg(ap, SrcList*);
14669         int k = va_arg(ap, int);
14670         struct SrcList_item *pItem = &pSrc->a[k];
14671         assert( k>=0 && k<pSrc->nSrc );
14672         if( pItem->zDatabase && pItem->zDatabase[0] ){
14673           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
14674           sqlite3StrAccumAppend(pAccum, ".", 1);
14675         }
14676         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
14677         length = width = 0;
14678         break;
14679       }
14680     }/* End switch over the format type */
14681     /*
14682     ** The text of the conversion is pointed to by "bufpt" and is
14683     ** "length" characters long.  The field width is "width".  Do
14684     ** the output.
14685     */
14686     if( !flag_leftjustify ){
14687       register int nspace;
14688       nspace = width-length;
14689       if( nspace>0 ){
14690         appendSpace(pAccum, nspace);
14691       }
14692     }
14693     if( length>0 ){
14694       sqlite3StrAccumAppend(pAccum, bufpt, length);
14695     }
14696     if( flag_leftjustify ){
14697       register int nspace;
14698       nspace = width-length;
14699       if( nspace>0 ){
14700         appendSpace(pAccum, nspace);
14701       }
14702     }
14703     if( zExtra ){
14704       sqlite3_free(zExtra);
14705     }
14706   }/* End for loop over the format string */
14707 } /* End of function */
14708
14709 /*
14710 ** Append N bytes of text from z to the StrAccum object.
14711 */
14712 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
14713   if( p->tooBig | p->mallocFailed ){
14714     return;
14715   }
14716   if( N<0 ){
14717     N = strlen(z);
14718   }
14719   if( N==0 ){
14720     return;
14721   }
14722   if( p->nChar+N >= p->nAlloc ){
14723     char *zNew;
14724     if( !p->useMalloc ){
14725       p->tooBig = 1;
14726       N = p->nAlloc - p->nChar - 1;
14727       if( N<=0 ){
14728         return;
14729       }
14730     }else{
14731       i64 szNew = p->nAlloc;
14732       szNew += N + 1;
14733       if( szNew > p->mxAlloc ){
14734         p->nAlloc = p->mxAlloc;
14735         if( ((i64)p->nChar)+((i64)N) >= p->nAlloc ){
14736           sqlite3StrAccumReset(p);
14737           p->tooBig = 1;
14738           return;
14739         }
14740       }else{
14741         p->nAlloc = szNew;
14742       }
14743       zNew = sqlite3_malloc( p->nAlloc );
14744       if( zNew ){
14745         memcpy(zNew, p->zText, p->nChar);
14746         sqlite3StrAccumReset(p);
14747         p->zText = zNew;
14748       }else{
14749         p->mallocFailed = 1;
14750         sqlite3StrAccumReset(p);
14751         return;
14752       }
14753     }
14754   }
14755   memcpy(&p->zText[p->nChar], z, N);
14756   p->nChar += N;
14757 }
14758
14759 /*
14760 ** Finish off a string by making sure it is zero-terminated.
14761 ** Return a pointer to the resulting string.  Return a NULL
14762 ** pointer if any kind of error was encountered.
14763 */
14764 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
14765   if( p->zText ){
14766     p->zText[p->nChar] = 0;
14767     if( p->useMalloc && p->zText==p->zBase ){
14768       p->zText = sqlite3_malloc( p->nChar+1 );
14769       if( p->zText ){
14770         memcpy(p->zText, p->zBase, p->nChar+1);
14771       }else{
14772         p->mallocFailed = 1;
14773       }
14774     }
14775   }
14776   return p->zText;
14777 }
14778
14779 /*
14780 ** Reset an StrAccum string.  Reclaim all malloced memory.
14781 */
14782 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
14783   if( p->zText!=p->zBase ){
14784     sqlite3_free(p->zText);
14785     p->zText = 0;
14786   }
14787 }
14788
14789 /*
14790 ** Initialize a string accumulator
14791 */
14792 static void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
14793   p->zText = p->zBase = zBase;
14794   p->nChar = 0;
14795   p->nAlloc = n;
14796   p->mxAlloc = mx;
14797   p->useMalloc = 1;
14798   p->tooBig = 0;
14799   p->mallocFailed = 0;
14800 }
14801
14802 /*
14803 ** Print into memory obtained from sqliteMalloc().  Use the internal
14804 ** %-conversion extensions.
14805 */
14806 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
14807   char *z;
14808   char zBase[SQLITE_PRINT_BUF_SIZE];
14809   StrAccum acc;
14810   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
14811                       db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
14812   vxprintf(&acc, 1, zFormat, ap);
14813   z = sqlite3StrAccumFinish(&acc);
14814   if( acc.mallocFailed && db ){
14815     db->mallocFailed = 1;
14816   }
14817   return z;
14818 }
14819
14820 /*
14821 ** Print into memory obtained from sqliteMalloc().  Use the internal
14822 ** %-conversion extensions.
14823 */
14824 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
14825   va_list ap;
14826   char *z;
14827   va_start(ap, zFormat);
14828   z = sqlite3VMPrintf(db, zFormat, ap);
14829   va_end(ap);
14830   return z;
14831 }
14832
14833 /*
14834 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
14835 ** %-conversion extensions.
14836 */
14837 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
14838   char *z;
14839   char zBase[SQLITE_PRINT_BUF_SIZE];
14840   StrAccum acc;
14841   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
14842   vxprintf(&acc, 0, zFormat, ap);
14843   z = sqlite3StrAccumFinish(&acc);
14844   return z;
14845 }
14846
14847 /*
14848 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
14849 ** %-conversion extensions.
14850 */
14851 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
14852   va_list ap;
14853   char *z;
14854   va_start(ap, zFormat);
14855   z = sqlite3_vmprintf(zFormat, ap);
14856   va_end(ap);
14857   return z;
14858 }
14859
14860 /*
14861 ** sqlite3_snprintf() works like snprintf() except that it ignores the
14862 ** current locale settings.  This is important for SQLite because we
14863 ** are not able to use a "," as the decimal point in place of "." as
14864 ** specified by some locales.
14865 */
14866 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
14867   char *z;
14868   va_list ap;
14869   StrAccum acc;
14870
14871   if( n<=0 ){
14872     return zBuf;
14873   }
14874   sqlite3StrAccumInit(&acc, zBuf, n, 0);
14875   acc.useMalloc = 0;
14876   va_start(ap,zFormat);
14877   vxprintf(&acc, 0, zFormat, ap);
14878   va_end(ap);
14879   z = sqlite3StrAccumFinish(&acc);
14880   return z;
14881 }
14882
14883 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) || defined(SQLITE_MEMDEBUG)
14884 /*
14885 ** A version of printf() that understands %lld.  Used for debugging.
14886 ** The printf() built into some versions of windows does not understand %lld
14887 ** and segfaults if you give it a long long int.
14888 */
14889 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
14890   va_list ap;
14891   StrAccum acc;
14892   char zBuf[500];
14893   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
14894   acc.useMalloc = 0;
14895   va_start(ap,zFormat);
14896   vxprintf(&acc, 0, zFormat, ap);
14897   va_end(ap);
14898   sqlite3StrAccumFinish(&acc);
14899   fprintf(stdout,"%s", zBuf);
14900   fflush(stdout);
14901 }
14902 #endif
14903
14904 /************** End of printf.c **********************************************/
14905 /************** Begin file random.c ******************************************/
14906 /*
14907 ** 2001 September 15
14908 **
14909 ** The author disclaims copyright to this source code.  In place of
14910 ** a legal notice, here is a blessing:
14911 **
14912 **    May you do good and not evil.
14913 **    May you find forgiveness for yourself and forgive others.
14914 **    May you share freely, never taking more than you give.
14915 **
14916 *************************************************************************
14917 ** This file contains code to implement a pseudo-random number
14918 ** generator (PRNG) for SQLite.
14919 **
14920 ** Random numbers are used by some of the database backends in order
14921 ** to generate random integer keys for tables or random filenames.
14922 **
14923 ** $Id: random.c,v 1.23 2008/03/21 16:45:47 drh Exp $
14924 */
14925
14926
14927 /* All threads share a single random number generator.
14928 ** This structure is the current state of the generator.
14929 */
14930 static struct sqlite3PrngType {
14931   unsigned char isInit;          /* True if initialized */
14932   unsigned char i, j;            /* State variables */
14933   unsigned char s[256];          /* State variables */
14934 } sqlite3Prng;
14935
14936 /*
14937 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
14938 ** must be held while executing this routine.
14939 **
14940 ** Why not just use a library random generator like lrand48() for this?
14941 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
14942 ** good source of random numbers.  The lrand48() library function may
14943 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
14944 ** subtle problems on some systems that could cause problems.  It is hard
14945 ** to know.  To minimize the risk of problems due to bad lrand48()
14946 ** implementations, SQLite uses this random number generator based
14947 ** on RC4, which we know works very well.
14948 **
14949 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
14950 ** randomness any more.  But we will leave this code in all the same.
14951 */
14952 static int randomByte(void){
14953   unsigned char t;
14954
14955
14956   /* Initialize the state of the random number generator once,
14957   ** the first time this routine is called.  The seed value does
14958   ** not need to contain a lot of randomness since we are not
14959   ** trying to do secure encryption or anything like that...
14960   **
14961   ** Nothing in this file or anywhere else in SQLite does any kind of
14962   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
14963   ** number generator) not as an encryption device.
14964   */
14965   if( !sqlite3Prng.isInit ){
14966     int i;
14967     char k[256];
14968     sqlite3Prng.j = 0;
14969     sqlite3Prng.i = 0;
14970     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
14971     for(i=0; i<256; i++){
14972       sqlite3Prng.s[i] = i;
14973     }
14974     for(i=0; i<256; i++){
14975       sqlite3Prng.j += sqlite3Prng.s[i] + k[i];
14976       t = sqlite3Prng.s[sqlite3Prng.j];
14977       sqlite3Prng.s[sqlite3Prng.j] = sqlite3Prng.s[i];
14978       sqlite3Prng.s[i] = t;
14979     }
14980     sqlite3Prng.isInit = 1;
14981   }
14982
14983   /* Generate and return single random byte
14984   */
14985   sqlite3Prng.i++;
14986   t = sqlite3Prng.s[sqlite3Prng.i];
14987   sqlite3Prng.j += t;
14988   sqlite3Prng.s[sqlite3Prng.i] = sqlite3Prng.s[sqlite3Prng.j];
14989   sqlite3Prng.s[sqlite3Prng.j] = t;
14990   t += sqlite3Prng.s[sqlite3Prng.i];
14991   return sqlite3Prng.s[t];
14992 }
14993
14994 /*
14995 ** Return N random bytes.
14996 */
14997 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
14998   unsigned char *zBuf = pBuf;
14999   static sqlite3_mutex *mutex = 0;
15000   if( mutex==0 ){
15001     mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG);
15002   }
15003   sqlite3_mutex_enter(mutex);
15004   while( N-- ){
15005     *(zBuf++) = randomByte();
15006   }
15007   sqlite3_mutex_leave(mutex);
15008 }
15009
15010 #ifndef SQLITE_OMIT_BUILTIN_TEST
15011 /*
15012 ** For testing purposes, we sometimes want to preserve the state of
15013 ** PRNG and restore the PRNG to its saved state at a later time.
15014 ** The sqlite3_test_control() interface calls these routines to
15015 ** control the PRNG.
15016 */
15017 static struct sqlite3PrngType sqlite3SavedPrng;
15018 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
15019   memcpy(&sqlite3SavedPrng, &sqlite3Prng, sizeof(sqlite3Prng));
15020 }
15021 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
15022   memcpy(&sqlite3Prng, &sqlite3SavedPrng, sizeof(sqlite3Prng));
15023 }
15024 SQLITE_PRIVATE void sqlite3PrngResetState(void){
15025   sqlite3Prng.isInit = 0;
15026 }
15027 #endif /* SQLITE_OMIT_BUILTIN_TEST */
15028
15029 /************** End of random.c **********************************************/
15030 /************** Begin file utf.c *********************************************/
15031 /*
15032 ** 2004 April 13
15033 **
15034 ** The author disclaims copyright to this source code.  In place of
15035 ** a legal notice, here is a blessing:
15036 **
15037 **    May you do good and not evil.
15038 **    May you find forgiveness for yourself and forgive others.
15039 **    May you share freely, never taking more than you give.
15040 **
15041 *************************************************************************
15042 ** This file contains routines used to translate between UTF-8, 
15043 ** UTF-16, UTF-16BE, and UTF-16LE.
15044 **
15045 ** $Id: utf.c,v 1.61 2008/03/28 15:44:10 danielk1977 Exp $
15046 **
15047 ** Notes on UTF-8:
15048 **
15049 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
15050 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
15051 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
15052 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
15053 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
15054 **
15055 **
15056 ** Notes on UTF-16:  (with wwww+1==uuuuu)
15057 **
15058 **      Word-0               Word-1          Value
15059 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
15060 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
15061 **
15062 **
15063 ** BOM or Byte Order Mark:
15064 **     0xff 0xfe   little-endian utf-16 follows
15065 **     0xfe 0xff   big-endian utf-16 follows
15066 **
15067 */
15068 /************** Include vdbeInt.h in the middle of utf.c *********************/
15069 /************** Begin file vdbeInt.h *****************************************/
15070 /*
15071 ** 2003 September 6
15072 **
15073 ** The author disclaims copyright to this source code.  In place of
15074 ** a legal notice, here is a blessing:
15075 **
15076 **    May you do good and not evil.
15077 **    May you find forgiveness for yourself and forgive others.
15078 **    May you share freely, never taking more than you give.
15079 **
15080 *************************************************************************
15081 ** This is the header file for information that is private to the
15082 ** VDBE.  This information used to all be at the top of the single
15083 ** source code file "vdbe.c".  When that file became too big (over
15084 ** 6000 lines long) it was split up into several smaller files and
15085 ** this header information was factored out.
15086 */
15087 #ifndef _VDBEINT_H_
15088 #define _VDBEINT_H_
15089
15090 /*
15091 ** intToKey() and keyToInt() used to transform the rowid.  But with
15092 ** the latest versions of the design they are no-ops.
15093 */
15094 #define keyToInt(X)   (X)
15095 #define intToKey(X)   (X)
15096
15097
15098 /*
15099 ** SQL is translated into a sequence of instructions to be
15100 ** executed by a virtual machine.  Each instruction is an instance
15101 ** of the following structure.
15102 */
15103 typedef struct VdbeOp Op;
15104
15105 /*
15106 ** Boolean values
15107 */
15108 typedef unsigned char Bool;
15109
15110 /*
15111 ** A cursor is a pointer into a single BTree within a database file.
15112 ** The cursor can seek to a BTree entry with a particular key, or
15113 ** loop over all entries of the Btree.  You can also insert new BTree
15114 ** entries or retrieve the key or data from the entry that the cursor
15115 ** is currently pointing to.
15116 ** 
15117 ** Every cursor that the virtual machine has open is represented by an
15118 ** instance of the following structure.
15119 **
15120 ** If the Cursor.isTriggerRow flag is set it means that this cursor is
15121 ** really a single row that represents the NEW or OLD pseudo-table of
15122 ** a row trigger.  The data for the row is stored in Cursor.pData and
15123 ** the rowid is in Cursor.iKey.
15124 */
15125 struct Cursor {
15126   BtCursor *pCursor;    /* The cursor structure of the backend */
15127   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
15128   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
15129   i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
15130   Bool zeroed;          /* True if zeroed out and ready for reuse */
15131   Bool rowidIsValid;    /* True if lastRowid is valid */
15132   Bool atFirst;         /* True if pointing to first entry */
15133   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
15134   Bool nullRow;         /* True if pointing to a row with no data */
15135   Bool nextRowidValid;  /* True if the nextRowid field is valid */
15136   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
15137   Bool ephemPseudoTable;
15138   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
15139   Bool isTable;         /* True if a table requiring integer keys */
15140   Bool isIndex;         /* True if an index containing keys only - no data */
15141   u8 bogusIncrKey;      /* Something for pIncrKey to point to if pKeyInfo==0 */
15142   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
15143   Btree *pBt;           /* Separate file holding temporary table */
15144   int nData;            /* Number of bytes in pData */
15145   char *pData;          /* Data for a NEW or OLD pseudo-table */
15146   i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
15147   u8 *pIncrKey;         /* Pointer to pKeyInfo->incrKey */
15148   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
15149   int nField;           /* Number of fields in the header */
15150   i64 seqCount;         /* Sequence counter */
15151   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
15152   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
15153
15154   /* Cached information about the header for the data record that the
15155   ** cursor is currently pointing to.  Only valid if cacheValid is true.
15156   ** aRow might point to (ephemeral) data for the current row, or it might
15157   ** be NULL.
15158   */
15159   int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
15160   int payloadSize;      /* Total number of bytes in the record */
15161   u32 *aType;           /* Type values for all entries in the record */
15162   u32 *aOffset;         /* Cached offsets to the start of each columns data */
15163   u8 *aRow;             /* Data for the current row, if all on one page */
15164 };
15165 typedef struct Cursor Cursor;
15166
15167 /*
15168 ** A value for Cursor.cacheValid that means the cache is always invalid.
15169 */
15170 #define CACHE_STALE 0
15171
15172 /*
15173 ** Internally, the vdbe manipulates nearly all SQL values as Mem
15174 ** structures. Each Mem struct may cache multiple representations (string,
15175 ** integer etc.) of the same value.  A value (and therefore Mem structure)
15176 ** has the following properties:
15177 **
15178 ** Each value has a manifest type. The manifest type of the value stored
15179 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
15180 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
15181 ** SQLITE_BLOB.
15182 */
15183 struct Mem {
15184   union {
15185     i64 i;              /* Integer value. Or FuncDef* when flags==MEM_Agg */
15186     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
15187   } u;
15188   double r;           /* Real value */
15189   sqlite3 *db;        /* The associated database connection */
15190   char *z;            /* String or BLOB value */
15191   int n;              /* Number of characters in string value, excluding '\0' */
15192   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
15193   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
15194   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
15195   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
15196   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
15197 };
15198
15199 /* One or more of the following flags are set to indicate the validOK
15200 ** representations of the value stored in the Mem struct.
15201 **
15202 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
15203 ** No other flags may be set in this case.
15204 **
15205 ** If the MEM_Str flag is set then Mem.z points at a string representation.
15206 ** Usually this is encoded in the same unicode encoding as the main
15207 ** database (see below for exceptions). If the MEM_Term flag is also
15208 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
15209 ** flags may coexist with the MEM_Str flag.
15210 **
15211 ** Multiple of these values can appear in Mem.flags.  But only one
15212 ** at a time can appear in Mem.type.
15213 */
15214 #define MEM_Null      0x0001   /* Value is NULL */
15215 #define MEM_Str       0x0002   /* Value is a string */
15216 #define MEM_Int       0x0004   /* Value is an integer */
15217 #define MEM_Real      0x0008   /* Value is a real number */
15218 #define MEM_Blob      0x0010   /* Value is a BLOB */
15219
15220 #define MemSetTypeFlag(p, f) \
15221   ((p)->flags = ((p)->flags&~(MEM_Int|MEM_Real|MEM_Null|MEM_Blob|MEM_Str))|f)
15222
15223 /* Whenever Mem contains a valid string or blob representation, one of
15224 ** the following flags must be set to determine the memory management
15225 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
15226 ** string is \000 or \u0000 terminated
15227 */
15228 #define MEM_Term      0x0020   /* String rep is nul terminated */
15229 #define MEM_Dyn       0x0040   /* Need to call sqliteFree() on Mem.z */
15230 #define MEM_Static    0x0080   /* Mem.z points to a static string */
15231 #define MEM_Ephem     0x0100   /* Mem.z points to an ephemeral string */
15232 #define MEM_Agg       0x0400   /* Mem.z points to an agg function context */
15233 #define MEM_Zero      0x0800   /* Mem.i contains count of 0s appended to blob */
15234
15235 #ifdef SQLITE_OMIT_INCRBLOB
15236   #undef MEM_Zero
15237   #define MEM_Zero 0x0000
15238 #endif
15239
15240
15241 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
15242 ** additional information about auxiliary information bound to arguments
15243 ** of the function.  This is used to implement the sqlite3_get_auxdata()
15244 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
15245 ** that can be associated with a constant argument to a function.  This
15246 ** allows functions such as "regexp" to compile their constant regular
15247 ** expression argument once and reused the compiled code for multiple
15248 ** invocations.
15249 */
15250 struct VdbeFunc {
15251   FuncDef *pFunc;               /* The definition of the function */
15252   int nAux;                     /* Number of entries allocated for apAux[] */
15253   struct AuxData {
15254     void *pAux;                   /* Aux data for the i-th argument */
15255     void (*xDelete)(void *);      /* Destructor for the aux data */
15256   } apAux[1];                   /* One slot for each function argument */
15257 };
15258
15259 /*
15260 ** The "context" argument for a installable function.  A pointer to an
15261 ** instance of this structure is the first argument to the routines used
15262 ** implement the SQL functions.
15263 **
15264 ** There is a typedef for this structure in sqlite.h.  So all routines,
15265 ** even the public interface to SQLite, can use a pointer to this structure.
15266 ** But this file is the only place where the internal details of this
15267 ** structure are known.
15268 **
15269 ** This structure is defined inside of vdbeInt.h because it uses substructures
15270 ** (Mem) which are only defined there.
15271 */
15272 struct sqlite3_context {
15273   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
15274   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
15275   Mem s;                /* The return value is stored here */
15276   Mem *pMem;            /* Memory cell used to store aggregate context */
15277   int isError;          /* Error code returned by the function. */
15278   CollSeq *pColl;       /* Collating sequence */
15279 };
15280
15281 /*
15282 ** A Set structure is used for quick testing to see if a value
15283 ** is part of a small set.  Sets are used to implement code like
15284 ** this:
15285 **            x.y IN ('hi','hoo','hum')
15286 */
15287 typedef struct Set Set;
15288 struct Set {
15289   Hash hash;             /* A set is just a hash table */
15290   HashElem *prev;        /* Previously accessed hash elemen */
15291 };
15292
15293 /*
15294 ** A FifoPage structure holds a single page of valves.  Pages are arranged
15295 ** in a list.
15296 */
15297 typedef struct FifoPage FifoPage;
15298 struct FifoPage {
15299   int nSlot;         /* Number of entries aSlot[] */
15300   int iWrite;        /* Push the next value into this entry in aSlot[] */
15301   int iRead;         /* Read the next value from this entry in aSlot[] */
15302   FifoPage *pNext;   /* Next page in the fifo */
15303   i64 aSlot[1];      /* One or more slots for rowid values */
15304 };
15305
15306 /*
15307 ** The Fifo structure is typedef-ed in vdbeInt.h.  But the implementation
15308 ** of that structure is private to this file.
15309 **
15310 ** The Fifo structure describes the entire fifo.  
15311 */
15312 typedef struct Fifo Fifo;
15313 struct Fifo {
15314   int nEntry;         /* Total number of entries */
15315   FifoPage *pFirst;   /* First page on the list */
15316   FifoPage *pLast;    /* Last page on the list */
15317 };
15318
15319 /*
15320 ** A Context stores the last insert rowid, the last statement change count,
15321 ** and the current statement change count (i.e. changes since last statement).
15322 ** The current keylist is also stored in the context.
15323 ** Elements of Context structure type make up the ContextStack, which is
15324 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
15325 ** The context is pushed before executing a trigger a popped when the
15326 ** trigger finishes.
15327 */
15328 typedef struct Context Context;
15329 struct Context {
15330   i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
15331   int nChange;      /* Statement changes (Vdbe.nChanges)     */
15332   Fifo sFifo;       /* Records that will participate in a DELETE or UPDATE */
15333 };
15334
15335 /*
15336 ** An instance of the virtual machine.  This structure contains the complete
15337 ** state of the virtual machine.
15338 **
15339 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
15340 ** is really a pointer to an instance of this structure.
15341 **
15342 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
15343 ** any virtual table method invocations made by the vdbe program. It is
15344 ** set to 2 for xDestroy method calls and 1 for all other methods. This
15345 ** variable is used for two purposes: to allow xDestroy methods to execute
15346 ** "DROP TABLE" statements and to prevent some nasty side effects of
15347 ** malloc failure when SQLite is invoked recursively by a virtual table 
15348 ** method function.
15349 */
15350 struct Vdbe {
15351   sqlite3 *db;        /* The whole database */
15352   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
15353   int nOp;            /* Number of instructions in the program */
15354   int nOpAlloc;       /* Number of slots allocated for aOp[] */
15355   Op *aOp;            /* Space to hold the virtual machine's program */
15356   int nLabel;         /* Number of labels used */
15357   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
15358   int *aLabel;        /* Space to hold the labels */
15359   Mem **apArg;        /* Arguments to currently executing user function */
15360   Mem *aColName;      /* Column names to return */
15361   int nCursor;        /* Number of slots in apCsr[] */
15362   Cursor **apCsr;     /* One element of this array for each open cursor */
15363   int nVar;           /* Number of entries in aVar[] */
15364   Mem *aVar;          /* Values for the OP_Variable opcode. */
15365   char **azVar;       /* Name of variables */
15366   int okVar;          /* True if azVar[] has been initialized */
15367   int magic;              /* Magic number for sanity checking */
15368   int nMem;               /* Number of memory locations currently allocated */
15369   Mem *aMem;              /* The memory locations */
15370   int nCallback;          /* Number of callbacks invoked so far */
15371   int cacheCtr;           /* Cursor row cache generation counter */
15372   Fifo sFifo;             /* A list of ROWIDs */
15373   int contextStackTop;    /* Index of top element in the context stack */
15374   int contextStackDepth;  /* The size of the "context" stack */
15375   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
15376   int pc;                 /* The program counter */
15377   int rc;                 /* Value to return */
15378   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
15379   int errorAction;        /* Recovery action to do in case of an error */
15380   int inTempTrans;        /* True if temp database is transactioned */
15381   int returnStack[25];    /* Return address stack for OP_Gosub & OP_Return */
15382   int returnDepth;        /* Next unused element in returnStack[] */
15383   int nResColumn;         /* Number of columns in one row of the result set */
15384   char **azResColumn;     /* Values for one row of result */ 
15385   char *zErrMsg;          /* Error message written here */
15386   Mem *pResultSet;        /* Pointer to an array of results */
15387   u8 explain;             /* True if EXPLAIN present on SQL command */
15388   u8 changeCntOn;         /* True to update the change-counter */
15389   u8 aborted;             /* True if ROLLBACK in another VM causes an abort */
15390   u8 expired;             /* True if the VM needs to be recompiled */
15391   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
15392   u8 inVtabMethod;        /* See comments above */
15393   int nChange;            /* Number of db changes made since last reset */
15394   i64 startTime;          /* Time when query started - used for profiling */
15395   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
15396   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
15397   int nSql;             /* Number of bytes in zSql */
15398   char *zSql;           /* Text of the SQL statement that generated this */
15399 #ifdef SQLITE_DEBUG
15400   FILE *trace;        /* Write an execution trace here, if not NULL */
15401 #endif
15402   int openedStatement;  /* True if this VM has opened a statement journal */
15403 #ifdef SQLITE_SSE
15404   int fetchId;          /* Statement number used by sqlite3_fetch_statement */
15405   int lru;              /* Counter used for LRU cache replacement */
15406 #endif
15407 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15408   Vdbe *pLruPrev;
15409   Vdbe *pLruNext;
15410 #endif
15411 };
15412
15413 /*
15414 ** An instance of the following structure holds information about a
15415 ** single index record that has already been parsed out into individual
15416 ** values.
15417 **
15418 ** A record is an object that contains one or more fields of data.
15419 ** Records are used to store the content of a table row and to store
15420 ** the key of an index.  A blob encoding of a record is created by
15421 ** the OP_MakeRecord opcode of the VDBE and is disassemblied by the
15422 ** OP_Column opcode.
15423 **
15424 ** This structure holds a record that has already been disassembled
15425 ** into its constitutent fields.
15426 */
15427 struct UnpackedRecord {
15428   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
15429   u16 nField;         /* Number of entries in apMem[] */
15430   u8 needFree;        /* True if memory obtained from sqlite3_malloc() */
15431   u8 needDestroy;     /* True if apMem[]s should be destroyed on close */
15432   Mem *aMem;          /* Values */
15433 };
15434
15435 /*
15436 ** The following are allowed values for Vdbe.magic
15437 */
15438 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
15439 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
15440 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
15441 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
15442
15443 /*
15444 ** Function prototypes
15445 */
15446 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
15447 void sqliteVdbePopStack(Vdbe*,int);
15448 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor*);
15449 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
15450 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
15451 #endif
15452 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
15453 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
15454 SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
15455 SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
15456 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
15457
15458 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
15459 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(Cursor*,UnpackedRecord *,int,const unsigned char*,int*);
15460 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
15461 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
15462 SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8*);
15463 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
15464 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
15465 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
15466 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
15467 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
15468 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
15469 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
15470 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
15471 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
15472 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
15473 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
15474 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
15475 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
15476 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
15477 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
15478 SQLITE_PRIVATE int sqlite3VdbeMemDynamicify(Mem*);
15479 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
15480 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
15481 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
15482 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
15483 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
15484 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
15485 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
15486 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
15487 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
15488 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
15489 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
15490 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
15491 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
15492 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
15493 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15494 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
15495 #endif
15496
15497 #ifndef NDEBUG
15498 SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
15499 #endif
15500 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
15501 #ifdef SQLITE_DEBUG
15502 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
15503 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
15504 #endif
15505 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
15506 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo*);
15507 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo*, i64);
15508 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo*, i64*);
15509 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo*);
15510
15511 #ifndef SQLITE_OMIT_INCRBLOB
15512 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
15513 #else
15514   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
15515 #endif
15516
15517 #endif /* !defined(_VDBEINT_H_) */
15518
15519 /************** End of vdbeInt.h *********************************************/
15520 /************** Continuing where we left off in utf.c ************************/
15521
15522 /*
15523 ** The following constant value is used by the SQLITE_BIGENDIAN and
15524 ** SQLITE_LITTLEENDIAN macros.
15525 */
15526 SQLITE_PRIVATE const int sqlite3one = 1;
15527
15528 /*
15529 ** This lookup table is used to help decode the first byte of
15530 ** a multi-byte UTF8 character.
15531 */
15532 static const unsigned char sqlite3UtfTrans1[] = {
15533   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
15534   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
15535   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
15536   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
15537   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
15538   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
15539   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
15540   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
15541 };
15542
15543
15544 #define WRITE_UTF8(zOut, c) {                          \
15545   if( c<0x00080 ){                                     \
15546     *zOut++ = (c&0xFF);                                \
15547   }                                                    \
15548   else if( c<0x00800 ){                                \
15549     *zOut++ = 0xC0 + ((c>>6)&0x1F);                    \
15550     *zOut++ = 0x80 + (c & 0x3F);                       \
15551   }                                                    \
15552   else if( c<0x10000 ){                                \
15553     *zOut++ = 0xE0 + ((c>>12)&0x0F);                   \
15554     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
15555     *zOut++ = 0x80 + (c & 0x3F);                       \
15556   }else{                                               \
15557     *zOut++ = 0xF0 + ((c>>18) & 0x07);                 \
15558     *zOut++ = 0x80 + ((c>>12) & 0x3F);                 \
15559     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
15560     *zOut++ = 0x80 + (c & 0x3F);                       \
15561   }                                                    \
15562 }
15563
15564 #define WRITE_UTF16LE(zOut, c) {                                \
15565   if( c<=0xFFFF ){                                              \
15566     *zOut++ = (c&0x00FF);                                       \
15567     *zOut++ = ((c>>8)&0x00FF);                                  \
15568   }else{                                                        \
15569     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
15570     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
15571     *zOut++ = (c&0x00FF);                                       \
15572     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
15573   }                                                             \
15574 }
15575
15576 #define WRITE_UTF16BE(zOut, c) {                                \
15577   if( c<=0xFFFF ){                                              \
15578     *zOut++ = ((c>>8)&0x00FF);                                  \
15579     *zOut++ = (c&0x00FF);                                       \
15580   }else{                                                        \
15581     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
15582     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
15583     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
15584     *zOut++ = (c&0x00FF);                                       \
15585   }                                                             \
15586 }
15587
15588 #define READ_UTF16LE(zIn, c){                                         \
15589   c = (*zIn++);                                                       \
15590   c += ((*zIn++)<<8);                                                 \
15591   if( c>=0xD800 && c<0xE000 ){                                       \
15592     int c2 = (*zIn++);                                                \
15593     c2 += ((*zIn++)<<8);                                              \
15594     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
15595     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
15596   }                                                                   \
15597 }
15598
15599 #define READ_UTF16BE(zIn, c){                                         \
15600   c = ((*zIn++)<<8);                                                  \
15601   c += (*zIn++);                                                      \
15602   if( c>=0xD800 && c<0xE000 ){                                       \
15603     int c2 = ((*zIn++)<<8);                                           \
15604     c2 += (*zIn++);                                                   \
15605     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
15606     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
15607   }                                                                   \
15608 }
15609
15610 /*
15611 ** Translate a single UTF-8 character.  Return the unicode value.
15612 **
15613 ** During translation, assume that the byte that zTerm points
15614 ** is a 0x00.
15615 **
15616 ** Write a pointer to the next unread byte back into *pzNext.
15617 **
15618 ** Notes On Invalid UTF-8:
15619 **
15620 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
15621 **     be encoded as a multi-byte character.  Any multi-byte character that
15622 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
15623 **
15624 **  *  This routine never allows a UTF16 surrogate value to be encoded.
15625 **     If a multi-byte character attempts to encode a value between
15626 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
15627 **
15628 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
15629 **     byte of a character are interpreted as single-byte characters
15630 **     and rendered as themselves even though they are technically
15631 **     invalid characters.
15632 **
15633 **  *  This routine accepts an infinite number of different UTF8 encodings
15634 **     for unicode values 0x80 and greater.  It do not change over-length
15635 **     encodings to 0xfffd as some systems recommend.
15636 */
15637 SQLITE_PRIVATE int sqlite3Utf8Read(
15638   const unsigned char *z,         /* First byte of UTF-8 character */
15639   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
15640   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
15641 ){
15642   int c = *(z++);
15643   if( c>=0xc0 ){
15644     c = sqlite3UtfTrans1[c-0xc0];
15645     while( z!=zTerm && (*z & 0xc0)==0x80 ){
15646       c = (c<<6) + (0x3f & *(z++));
15647     }
15648     if( c<0x80
15649         || (c&0xFFFFF800)==0xD800
15650         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
15651   }
15652   *pzNext = z;
15653   return c;
15654 }
15655
15656
15657
15658 /*
15659 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
15660 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
15661 */ 
15662 /* #define TRANSLATE_TRACE 1 */
15663
15664 #ifndef SQLITE_OMIT_UTF16
15665 /*
15666 ** This routine transforms the internal text encoding used by pMem to
15667 ** desiredEnc. It is an error if the string is already of the desired
15668 ** encoding, or if *pMem does not contain a string value.
15669 */
15670 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
15671   int len;                    /* Maximum length of output string in bytes */
15672   unsigned char *zOut;                  /* Output buffer */
15673   unsigned char *zIn;                   /* Input iterator */
15674   unsigned char *zTerm;                 /* End of input */
15675   unsigned char *z;                     /* Output iterator */
15676   unsigned int c;
15677
15678   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
15679   assert( pMem->flags&MEM_Str );
15680   assert( pMem->enc!=desiredEnc );
15681   assert( pMem->enc!=0 );
15682   assert( pMem->n>=0 );
15683
15684 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
15685   {
15686     char zBuf[100];
15687     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
15688     fprintf(stderr, "INPUT:  %s\n", zBuf);
15689   }
15690 #endif
15691
15692   /* If the translation is between UTF-16 little and big endian, then 
15693   ** all that is required is to swap the byte order. This case is handled
15694   ** differently from the others.
15695   */
15696   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
15697     u8 temp;
15698     int rc;
15699     rc = sqlite3VdbeMemMakeWriteable(pMem);
15700     if( rc!=SQLITE_OK ){
15701       assert( rc==SQLITE_NOMEM );
15702       return SQLITE_NOMEM;
15703     }
15704     zIn = (u8*)pMem->z;
15705     zTerm = &zIn[pMem->n];
15706     while( zIn<zTerm ){
15707       temp = *zIn;
15708       *zIn = *(zIn+1);
15709       zIn++;
15710       *zIn++ = temp;
15711     }
15712     pMem->enc = desiredEnc;
15713     goto translate_out;
15714   }
15715
15716   /* Set len to the maximum number of bytes required in the output buffer. */
15717   if( desiredEnc==SQLITE_UTF8 ){
15718     /* When converting from UTF-16, the maximum growth results from
15719     ** translating a 2-byte character to a 4-byte UTF-8 character.
15720     ** A single byte is required for the output string
15721     ** nul-terminator.
15722     */
15723     len = pMem->n * 2 + 1;
15724   }else{
15725     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
15726     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
15727     ** character. Two bytes are required in the output buffer for the
15728     ** nul-terminator.
15729     */
15730     len = pMem->n * 2 + 2;
15731   }
15732
15733   /* Set zIn to point at the start of the input buffer and zTerm to point 1
15734   ** byte past the end.
15735   **
15736   ** Variable zOut is set to point at the output buffer, space obtained
15737   ** from sqlite3_malloc().
15738   */
15739   zIn = (u8*)pMem->z;
15740   zTerm = &zIn[pMem->n];
15741   zOut = sqlite3DbMallocRaw(pMem->db, len);
15742   if( !zOut ){
15743     return SQLITE_NOMEM;
15744   }
15745   z = zOut;
15746
15747   if( pMem->enc==SQLITE_UTF8 ){
15748     if( desiredEnc==SQLITE_UTF16LE ){
15749       /* UTF-8 -> UTF-16 Little-endian */
15750       while( zIn<zTerm ){
15751         c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
15752         WRITE_UTF16LE(z, c);
15753       }
15754     }else{
15755       assert( desiredEnc==SQLITE_UTF16BE );
15756       /* UTF-8 -> UTF-16 Big-endian */
15757       while( zIn<zTerm ){
15758         c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
15759         WRITE_UTF16BE(z, c);
15760       }
15761     }
15762     pMem->n = z - zOut;
15763     *z++ = 0;
15764   }else{
15765     assert( desiredEnc==SQLITE_UTF8 );
15766     if( pMem->enc==SQLITE_UTF16LE ){
15767       /* UTF-16 Little-endian -> UTF-8 */
15768       while( zIn<zTerm ){
15769         READ_UTF16LE(zIn, c); 
15770         WRITE_UTF8(z, c);
15771       }
15772     }else{
15773       /* UTF-16 Little-endian -> UTF-8 */
15774       while( zIn<zTerm ){
15775         READ_UTF16BE(zIn, c); 
15776         WRITE_UTF8(z, c);
15777       }
15778     }
15779     pMem->n = z - zOut;
15780   }
15781   *z = 0;
15782   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
15783
15784   sqlite3VdbeMemRelease(pMem);
15785   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
15786   pMem->enc = desiredEnc;
15787   pMem->flags |= (MEM_Term|MEM_Dyn);
15788   pMem->z = (char*)zOut;
15789   pMem->zMalloc = pMem->z;
15790
15791 translate_out:
15792 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
15793   {
15794     char zBuf[100];
15795     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
15796     fprintf(stderr, "OUTPUT: %s\n", zBuf);
15797   }
15798 #endif
15799   return SQLITE_OK;
15800 }
15801
15802 /*
15803 ** This routine checks for a byte-order mark at the beginning of the 
15804 ** UTF-16 string stored in *pMem. If one is present, it is removed and
15805 ** the encoding of the Mem adjusted. This routine does not do any
15806 ** byte-swapping, it just sets Mem.enc appropriately.
15807 **
15808 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
15809 ** changed by this function.
15810 */
15811 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
15812   int rc = SQLITE_OK;
15813   u8 bom = 0;
15814
15815   if( pMem->n<0 || pMem->n>1 ){
15816     u8 b1 = *(u8 *)pMem->z;
15817     u8 b2 = *(((u8 *)pMem->z) + 1);
15818     if( b1==0xFE && b2==0xFF ){
15819       bom = SQLITE_UTF16BE;
15820     }
15821     if( b1==0xFF && b2==0xFE ){
15822       bom = SQLITE_UTF16LE;
15823     }
15824   }
15825   
15826   if( bom ){
15827     rc = sqlite3VdbeMemMakeWriteable(pMem);
15828     if( rc==SQLITE_OK ){
15829       pMem->n -= 2;
15830       memmove(pMem->z, &pMem->z[2], pMem->n);
15831       pMem->z[pMem->n] = '\0';
15832       pMem->z[pMem->n+1] = '\0';
15833       pMem->flags |= MEM_Term;
15834       pMem->enc = bom;
15835     }
15836   }
15837   return rc;
15838 }
15839 #endif /* SQLITE_OMIT_UTF16 */
15840
15841 /*
15842 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
15843 ** return the number of unicode characters in pZ up to (but not including)
15844 ** the first 0x00 byte. If nByte is not less than zero, return the
15845 ** number of unicode characters in the first nByte of pZ (or up to 
15846 ** the first 0x00, whichever comes first).
15847 */
15848 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
15849   int r = 0;
15850   const u8 *z = (const u8*)zIn;
15851   const u8 *zTerm;
15852   if( nByte>=0 ){
15853     zTerm = &z[nByte];
15854   }else{
15855     zTerm = (const u8*)(-1);
15856   }
15857   assert( z<=zTerm );
15858   while( *z!=0 && z<zTerm ){
15859     SQLITE_SKIP_UTF8(z);
15860     r++;
15861   }
15862   return r;
15863 }
15864
15865 /* This test function is not currently used by the automated test-suite. 
15866 ** Hence it is only available in debug builds.
15867 */
15868 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
15869 /*
15870 ** Translate UTF-8 to UTF-8.
15871 **
15872 ** This has the effect of making sure that the string is well-formed
15873 ** UTF-8.  Miscoded characters are removed.
15874 **
15875 ** The translation is done in-place (since it is impossible for the
15876 ** correct UTF-8 encoding to be longer than a malformed encoding).
15877 */
15878 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
15879   unsigned char *zOut = zIn;
15880   unsigned char *zStart = zIn;
15881   unsigned char *zTerm;
15882   u32 c;
15883
15884   while( zIn[0] ){
15885     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
15886     if( c!=0xfffd ){
15887       WRITE_UTF8(zOut, c);
15888     }
15889   }
15890   *zOut = 0;
15891   return zOut - zStart;
15892 }
15893 #endif
15894
15895 #ifndef SQLITE_OMIT_UTF16
15896 /*
15897 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
15898 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
15899 ** be freed by the calling function.
15900 **
15901 ** NULL is returned if there is an allocation error.
15902 */
15903 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
15904   Mem m;
15905   memset(&m, 0, sizeof(m));
15906   m.db = db;
15907   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
15908   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
15909   if( db->mallocFailed ){
15910     sqlite3VdbeMemRelease(&m);
15911     m.z = 0;
15912   }
15913   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
15914   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
15915   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
15916 }
15917
15918 /*
15919 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
15920 ** return the number of bytes up to (but not including), the first pair
15921 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
15922 ** then return the number of bytes in the first nChar unicode characters
15923 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
15924 */
15925 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
15926   unsigned int c = 1;
15927   char const *z = zIn;
15928   int n = 0;
15929   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
15930     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
15931     ** and in other parts of this file means that at one branch will
15932     ** not be covered by coverage testing on any single host. But coverage
15933     ** will be complete if the tests are run on both a little-endian and 
15934     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
15935     ** macros are constant at compile time the compiler can determine
15936     ** which branch will be followed. It is therefore assumed that no runtime
15937     ** penalty is paid for this "if" statement.
15938     */
15939     while( c && ((nChar<0) || n<nChar) ){
15940       READ_UTF16BE(z, c);
15941       n++;
15942     }
15943   }else{
15944     while( c && ((nChar<0) || n<nChar) ){
15945       READ_UTF16LE(z, c);
15946       n++;
15947     }
15948   }
15949   return (z-(char const *)zIn)-((c==0)?2:0);
15950 }
15951
15952 #if defined(SQLITE_TEST)
15953 /*
15954 ** This routine is called from the TCL test function "translate_selftest".
15955 ** It checks that the primitives for serializing and deserializing
15956 ** characters in each encoding are inverses of each other.
15957 */
15958 SQLITE_PRIVATE void sqlite3UtfSelfTest(){
15959   unsigned int i, t;
15960   unsigned char zBuf[20];
15961   unsigned char *z;
15962   unsigned char *zTerm;
15963   int n;
15964   unsigned int c;
15965
15966   for(i=0; i<0x00110000; i++){
15967     z = zBuf;
15968     WRITE_UTF8(z, i);
15969     n = z-zBuf;
15970     z[0] = 0;
15971     zTerm = z;
15972     z = zBuf;
15973     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
15974     t = i;
15975     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
15976     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
15977     assert( c==t );
15978     assert( (z-zBuf)==n );
15979   }
15980   for(i=0; i<0x00110000; i++){
15981     if( i>=0xD800 && i<0xE000 ) continue;
15982     z = zBuf;
15983     WRITE_UTF16LE(z, i);
15984     n = z-zBuf;
15985     z[0] = 0;
15986     z = zBuf;
15987     READ_UTF16LE(z, c);
15988     assert( c==i );
15989     assert( (z-zBuf)==n );
15990   }
15991   for(i=0; i<0x00110000; i++){
15992     if( i>=0xD800 && i<0xE000 ) continue;
15993     z = zBuf;
15994     WRITE_UTF16BE(z, i);
15995     n = z-zBuf;
15996     z[0] = 0;
15997     z = zBuf;
15998     READ_UTF16BE(z, c);
15999     assert( c==i );
16000     assert( (z-zBuf)==n );
16001   }
16002 }
16003 #endif /* SQLITE_TEST */
16004 #endif /* SQLITE_OMIT_UTF16 */
16005
16006 /************** End of utf.c *************************************************/
16007 /************** Begin file util.c ********************************************/
16008 /*
16009 ** 2001 September 15
16010 **
16011 ** The author disclaims copyright to this source code.  In place of
16012 ** a legal notice, here is a blessing:
16013 **
16014 **    May you do good and not evil.
16015 **    May you find forgiveness for yourself and forgive others.
16016 **    May you share freely, never taking more than you give.
16017 **
16018 *************************************************************************
16019 ** Utility functions used throughout sqlite.
16020 **
16021 ** This file contains functions for allocating memory, comparing
16022 ** strings, and stuff like that.
16023 **
16024 ** $Id: util.c,v 1.229 2008/05/13 16:41:50 drh Exp $
16025 */
16026
16027
16028 /*
16029 ** Return true if the floating point value is Not a Number.
16030 */
16031 SQLITE_PRIVATE int sqlite3IsNaN(double x){
16032   /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
16033   ** On the other hand, the use of -ffast-math comes with the following
16034   ** warning:
16035   **
16036   **      This option [-ffast-math] should never be turned on by any
16037   **      -O option since it can result in incorrect output for programs
16038   **      which depend on an exact implementation of IEEE or ISO 
16039   **      rules/specifications for math functions.
16040   */
16041   volatile double y = x;
16042   return x!=y;
16043 }
16044
16045 /*
16046 ** Set the most recent error code and error string for the sqlite
16047 ** handle "db". The error code is set to "err_code".
16048 **
16049 ** If it is not NULL, string zFormat specifies the format of the
16050 ** error string in the style of the printf functions: The following
16051 ** format characters are allowed:
16052 **
16053 **      %s      Insert a string
16054 **      %z      A string that should be freed after use
16055 **      %d      Insert an integer
16056 **      %T      Insert a token
16057 **      %S      Insert the first element of a SrcList
16058 **
16059 ** zFormat and any string tokens that follow it are assumed to be
16060 ** encoded in UTF-8.
16061 **
16062 ** To clear the most recent error for sqlite handle "db", sqlite3Error
16063 ** should be called with err_code set to SQLITE_OK and zFormat set
16064 ** to NULL.
16065 */
16066 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
16067   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
16068     db->errCode = err_code;
16069     if( zFormat ){
16070       char *z;
16071       va_list ap;
16072       va_start(ap, zFormat);
16073       z = sqlite3VMPrintf(db, zFormat, ap);
16074       va_end(ap);
16075       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3_free);
16076     }else{
16077       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
16078     }
16079   }
16080 }
16081
16082 /*
16083 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
16084 ** The following formatting characters are allowed:
16085 **
16086 **      %s      Insert a string
16087 **      %z      A string that should be freed after use
16088 **      %d      Insert an integer
16089 **      %T      Insert a token
16090 **      %S      Insert the first element of a SrcList
16091 **
16092 ** This function should be used to report any error that occurs whilst
16093 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
16094 ** last thing the sqlite3_prepare() function does is copy the error
16095 ** stored by this function into the database handle using sqlite3Error().
16096 ** Function sqlite3Error() should be used during statement execution
16097 ** (sqlite3_step() etc.).
16098 */
16099 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
16100   va_list ap;
16101   pParse->nErr++;
16102   sqlite3_free(pParse->zErrMsg);
16103   va_start(ap, zFormat);
16104   pParse->zErrMsg = sqlite3VMPrintf(pParse->db, zFormat, ap);
16105   va_end(ap);
16106   if( pParse->rc==SQLITE_OK ){
16107     pParse->rc = SQLITE_ERROR;
16108   }
16109 }
16110
16111 /*
16112 ** Clear the error message in pParse, if any
16113 */
16114 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
16115   sqlite3_free(pParse->zErrMsg);
16116   pParse->zErrMsg = 0;
16117   pParse->nErr = 0;
16118 }
16119
16120 /*
16121 ** Convert an SQL-style quoted string into a normal string by removing
16122 ** the quote characters.  The conversion is done in-place.  If the
16123 ** input does not begin with a quote character, then this routine
16124 ** is a no-op.
16125 **
16126 ** 2002-Feb-14: This routine is extended to remove MS-Access style
16127 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
16128 ** "a-b-c".
16129 */
16130 SQLITE_PRIVATE void sqlite3Dequote(char *z){
16131   int quote;
16132   int i, j;
16133   if( z==0 ) return;
16134   quote = z[0];
16135   switch( quote ){
16136     case '\'':  break;
16137     case '"':   break;
16138     case '`':   break;                /* For MySQL compatibility */
16139     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
16140     default:    return;
16141   }
16142   for(i=1, j=0; z[i]; i++){
16143     if( z[i]==quote ){
16144       if( z[i+1]==quote ){
16145         z[j++] = quote;
16146         i++;
16147       }else{
16148         z[j++] = 0;
16149         break;
16150       }
16151     }else{
16152       z[j++] = z[i];
16153     }
16154   }
16155 }
16156
16157 /* An array to map all upper-case characters into their corresponding
16158 ** lower-case character. 
16159 */
16160 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
16161 #ifdef SQLITE_ASCII
16162       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
16163      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
16164      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
16165      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
16166     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
16167     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
16168     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
16169     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
16170     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
16171     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
16172     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
16173     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
16174     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
16175     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
16176     252,253,254,255
16177 #endif
16178 #ifdef SQLITE_EBCDIC
16179       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
16180      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
16181      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
16182      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
16183      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
16184      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
16185      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
16186     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
16187     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
16188     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
16189     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
16190     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
16191     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
16192     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
16193     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
16194     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
16195 #endif
16196 };
16197 #define UpperToLower sqlite3UpperToLower
16198
16199 /*
16200 ** Some systems have stricmp().  Others have strcasecmp().  Because
16201 ** there is no consistency, we will define our own.
16202 */
16203 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
16204   register unsigned char *a, *b;
16205   a = (unsigned char *)zLeft;
16206   b = (unsigned char *)zRight;
16207   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
16208   return UpperToLower[*a] - UpperToLower[*b];
16209 }
16210 SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
16211   register unsigned char *a, *b;
16212   a = (unsigned char *)zLeft;
16213   b = (unsigned char *)zRight;
16214   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
16215   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
16216 }
16217
16218 /*
16219 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
16220 ** string contains any character which is not part of a number. If
16221 ** the string is numeric and contains the '.' character, set *realnum
16222 ** to TRUE (otherwise FALSE).
16223 **
16224 ** An empty string is considered non-numeric.
16225 */
16226 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
16227   int incr = (enc==SQLITE_UTF8?1:2);
16228   if( enc==SQLITE_UTF16BE ) z++;
16229   if( *z=='-' || *z=='+' ) z += incr;
16230   if( !isdigit(*(u8*)z) ){
16231     return 0;
16232   }
16233   z += incr;
16234   if( realnum ) *realnum = 0;
16235   while( isdigit(*(u8*)z) ){ z += incr; }
16236   if( *z=='.' ){
16237     z += incr;
16238     if( !isdigit(*(u8*)z) ) return 0;
16239     while( isdigit(*(u8*)z) ){ z += incr; }
16240     if( realnum ) *realnum = 1;
16241   }
16242   if( *z=='e' || *z=='E' ){
16243     z += incr;
16244     if( *z=='+' || *z=='-' ) z += incr;
16245     if( !isdigit(*(u8*)z) ) return 0;
16246     while( isdigit(*(u8*)z) ){ z += incr; }
16247     if( realnum ) *realnum = 1;
16248   }
16249   return *z==0;
16250 }
16251
16252 /*
16253 ** The string z[] is an ascii representation of a real number.
16254 ** Convert this string to a double.
16255 **
16256 ** This routine assumes that z[] really is a valid number.  If it
16257 ** is not, the result is undefined.
16258 **
16259 ** This routine is used instead of the library atof() function because
16260 ** the library atof() might want to use "," as the decimal point instead
16261 ** of "." depending on how locale is set.  But that would cause problems
16262 ** for SQL.  So this routine always uses "." regardless of locale.
16263 */
16264 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
16265 #ifndef SQLITE_OMIT_FLOATING_POINT
16266   int sign = 1;
16267   const char *zBegin = z;
16268   LONGDOUBLE_TYPE v1 = 0.0;
16269   int nSignificant = 0;
16270   while( isspace(*(u8*)z) ) z++;
16271   if( *z=='-' ){
16272     sign = -1;
16273     z++;
16274   }else if( *z=='+' ){
16275     z++;
16276   }
16277   while( z[0]=='0' ){
16278     z++;
16279   }
16280   while( isdigit(*(u8*)z) ){
16281     v1 = v1*10.0 + (*z - '0');
16282     z++;
16283     nSignificant++;
16284   }
16285   if( *z=='.' ){
16286     LONGDOUBLE_TYPE divisor = 1.0;
16287     z++;
16288     if( nSignificant==0 ){
16289       while( z[0]=='0' ){
16290         divisor *= 10.0;
16291         z++;
16292       }
16293     }
16294     while( isdigit(*(u8*)z) ){
16295       if( nSignificant<18 ){
16296         v1 = v1*10.0 + (*z - '0');
16297         divisor *= 10.0;
16298         nSignificant++;
16299       }
16300       z++;
16301     }
16302     v1 /= divisor;
16303   }
16304   if( *z=='e' || *z=='E' ){
16305     int esign = 1;
16306     int eval = 0;
16307     LONGDOUBLE_TYPE scale = 1.0;
16308     z++;
16309     if( *z=='-' ){
16310       esign = -1;
16311       z++;
16312     }else if( *z=='+' ){
16313       z++;
16314     }
16315     while( isdigit(*(u8*)z) ){
16316       eval = eval*10 + *z - '0';
16317       z++;
16318     }
16319     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
16320     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
16321     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
16322     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
16323     if( esign<0 ){
16324       v1 /= scale;
16325     }else{
16326       v1 *= scale;
16327     }
16328   }
16329   *pResult = sign<0 ? -v1 : v1;
16330   return z - zBegin;
16331 #else
16332   return sqlite3Atoi64(z, pResult);
16333 #endif /* SQLITE_OMIT_FLOATING_POINT */
16334 }
16335
16336 /*
16337 ** Compare the 19-character string zNum against the text representation
16338 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
16339 ** if zNum is less than, equal to, or greater than the string.
16340 **
16341 ** Unlike memcmp() this routine is guaranteed to return the difference
16342 ** in the values of the last digit if the only difference is in the
16343 ** last digit.  So, for example,
16344 **
16345 **      compare2pow63("9223372036854775800")
16346 **
16347 ** will return -8.
16348 */
16349 static int compare2pow63(const char *zNum){
16350   int c;
16351   c = memcmp(zNum,"922337203685477580",18);
16352   if( c==0 ){
16353     c = zNum[18] - '8';
16354   }
16355   return c;
16356 }
16357
16358
16359 /*
16360 ** Return TRUE if zNum is a 64-bit signed integer and write
16361 ** the value of the integer into *pNum.  If zNum is not an integer
16362 ** or is an integer that is too large to be expressed with 64 bits,
16363 ** then return false.
16364 **
16365 ** When this routine was originally written it dealt with only
16366 ** 32-bit numbers.  At that time, it was much faster than the
16367 ** atoi() library routine in RedHat 7.2.
16368 */
16369 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
16370   i64 v = 0;
16371   int neg;
16372   int i, c;
16373   while( isspace(*(u8*)zNum) ) zNum++;
16374   if( *zNum=='-' ){
16375     neg = 1;
16376     zNum++;
16377   }else if( *zNum=='+' ){
16378     neg = 0;
16379     zNum++;
16380   }else{
16381     neg = 0;
16382   }
16383   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
16384   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
16385     v = v*10 + c - '0';
16386   }
16387   *pNum = neg ? -v : v;
16388   if( c!=0 || i==0 || i>19 ){
16389     /* zNum is empty or contains non-numeric text or is longer
16390     ** than 19 digits (thus guaranting that it is too large) */
16391     return 0;
16392   }else if( i<19 ){
16393     /* Less than 19 digits, so we know that it fits in 64 bits */
16394     return 1;
16395   }else{
16396     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
16397     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
16398     ** is 2^63. */
16399     return compare2pow63(zNum)<neg;
16400   }
16401 }
16402
16403 /*
16404 ** The string zNum represents an integer.  There might be some other
16405 ** information following the integer too, but that part is ignored.
16406 ** If the integer that the prefix of zNum represents will fit in a
16407 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
16408 **
16409 ** This routine returns FALSE for the string -9223372036854775808 even that
16410 ** that number will, in theory fit in a 64-bit integer.  Positive
16411 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
16412 ** false.
16413 */
16414 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
16415   int i, c;
16416   int neg = 0;
16417   if( *zNum=='-' ){
16418     neg = 1;
16419     zNum++;
16420   }else if( *zNum=='+' ){
16421     zNum++;
16422   }
16423   if( negFlag ) neg = 1-neg;
16424   while( *zNum=='0' ){
16425     zNum++;   /* Skip leading zeros.  Ticket #2454 */
16426   }
16427   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
16428   if( i<19 ){
16429     /* Guaranteed to fit if less than 19 digits */
16430     return 1;
16431   }else if( i>19 ){
16432     /* Guaranteed to be too big if greater than 19 digits */
16433     return 0;
16434   }else{
16435     /* Compare against 2^63. */
16436     return compare2pow63(zNum)<neg;
16437   }
16438 }
16439
16440 /*
16441 ** If zNum represents an integer that will fit in 32-bits, then set
16442 ** *pValue to that integer and return true.  Otherwise return false.
16443 **
16444 ** Any non-numeric characters that following zNum are ignored.
16445 ** This is different from sqlite3Atoi64() which requires the
16446 ** input number to be zero-terminated.
16447 */
16448 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
16449   sqlite_int64 v = 0;
16450   int i, c;
16451   int neg = 0;
16452   if( zNum[0]=='-' ){
16453     neg = 1;
16454     zNum++;
16455   }else if( zNum[0]=='+' ){
16456     zNum++;
16457   }
16458   while( zNum[0]=='0' ) zNum++;
16459   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
16460     v = v*10 + c;
16461   }
16462
16463   /* The longest decimal representation of a 32 bit integer is 10 digits:
16464   **
16465   **             1234567890
16466   **     2^31 -> 2147483648
16467   */
16468   if( i>10 ){
16469     return 0;
16470   }
16471   if( v-neg>2147483647 ){
16472     return 0;
16473   }
16474   if( neg ){
16475     v = -v;
16476   }
16477   *pValue = (int)v;
16478   return 1;
16479 }
16480
16481 /*
16482 ** The variable-length integer encoding is as follows:
16483 **
16484 ** KEY:
16485 **         A = 0xxxxxxx    7 bits of data and one flag bit
16486 **         B = 1xxxxxxx    7 bits of data and one flag bit
16487 **         C = xxxxxxxx    8 bits of data
16488 **
16489 **  7 bits - A
16490 ** 14 bits - BA
16491 ** 21 bits - BBA
16492 ** 28 bits - BBBA
16493 ** 35 bits - BBBBA
16494 ** 42 bits - BBBBBA
16495 ** 49 bits - BBBBBBA
16496 ** 56 bits - BBBBBBBA
16497 ** 64 bits - BBBBBBBBC
16498 */
16499
16500 /*
16501 ** Write a 64-bit variable-length integer to memory starting at p[0].
16502 ** The length of data write will be between 1 and 9 bytes.  The number
16503 ** of bytes written is returned.
16504 **
16505 ** A variable-length integer consists of the lower 7 bits of each byte
16506 ** for all bytes that have the 8th bit set and one byte with the 8th
16507 ** bit clear.  Except, if we get to the 9th byte, it stores the full
16508 ** 8 bits and is the last byte.
16509 */
16510 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
16511   int i, j, n;
16512   u8 buf[10];
16513   if( v & (((u64)0xff000000)<<32) ){
16514     p[8] = v;
16515     v >>= 8;
16516     for(i=7; i>=0; i--){
16517       p[i] = (v & 0x7f) | 0x80;
16518       v >>= 7;
16519     }
16520     return 9;
16521   }    
16522   n = 0;
16523   do{
16524     buf[n++] = (v & 0x7f) | 0x80;
16525     v >>= 7;
16526   }while( v!=0 );
16527   buf[0] &= 0x7f;
16528   assert( n<=9 );
16529   for(i=0, j=n-1; j>=0; j--, i++){
16530     p[i] = buf[j];
16531   }
16532   return n;
16533 }
16534
16535 /*
16536 ** This routine is a faster version of sqlite3PutVarint() that only
16537 ** works for 32-bit positive integers and which is optimized for
16538 ** the common case of small integers.  A MACRO version, putVarint32,
16539 ** is provided which inlines the single-byte case.  All code should use
16540 ** the MACRO version as this function assumes the single-byte case has
16541 ** already been handled.
16542 */
16543 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
16544 #ifndef putVarint32
16545   if( (v & ~0x7f)==0 ){
16546     p[0] = v;
16547     return 1;
16548   }
16549 #endif
16550   if( (v & ~0x3fff)==0 ){
16551     p[0] = (v>>7) | 0x80;
16552     p[1] = v & 0x7f;
16553     return 2;
16554   }
16555   return sqlite3PutVarint(p, v);
16556 }
16557
16558 /*
16559 ** Read a 64-bit variable-length integer from memory starting at p[0].
16560 ** Return the number of bytes read.  The value is stored in *v.
16561 */
16562 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *p, u64 *v){
16563   u32 a,b,s;
16564
16565   a = *p;
16566   // a: p0 (unmasked)
16567   if (!(a&0x80))
16568   {
16569     *v = a;
16570     return 1;
16571   }
16572
16573   p++;
16574   b = *p;
16575   // b: p1 (unmasked)
16576   if (!(b&0x80))
16577   {
16578     a &= 0x7f;
16579     a = a<<7;
16580     a |= b;
16581     *v = a;
16582     return 2;
16583   }
16584
16585   p++;
16586   a = a<<14;
16587   a |= *p;
16588   // a: p0<<14 | p2 (unmasked)
16589   if (!(a&0x80))
16590   {
16591     a &= (0x7f<<14)|(0x7f);
16592     b &= 0x7f;
16593     b = b<<7;
16594     a |= b;
16595     *v = a;
16596     return 3;
16597   }
16598
16599   // CSE1 from below
16600   a &= (0x7f<<14)|(0x7f);
16601   p++;
16602   b = b<<14;
16603   b |= *p;
16604   // b: p1<<14 | p3 (unmasked)
16605   if (!(b&0x80))
16606   {
16607     b &= (0x7f<<14)|(0x7f);
16608     // moved CSE1 up
16609     // a &= (0x7f<<14)|(0x7f);
16610     a = a<<7;
16611     a |= b;
16612     *v = a;
16613     return 4;
16614   }
16615
16616   // a: p0<<14 | p2 (masked)
16617   // b: p1<<14 | p3 (unmasked)
16618   // 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked)
16619   // moved CSE1 up
16620   // a &= (0x7f<<14)|(0x7f);
16621   b &= (0x7f<<14)|(0x7f);
16622   s = a;
16623   // s: p0<<14 | p2 (masked)
16624
16625   p++;
16626   a = a<<14;
16627   a |= *p;
16628   // a: p0<<28 | p2<<14 | p4 (unmasked)
16629   if (!(a&0x80))
16630   {
16631     // we can skip these cause they were (effectively) done above in calc'ing s
16632     // a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
16633     // b &= (0x7f<<14)|(0x7f);
16634     b = b<<7;
16635     a |= b;
16636     s = s>>18;
16637     *v = ((u64)s)<<32 | a;
16638     return 5;
16639   }
16640
16641   // 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked)
16642   s = s<<7;
16643   s |= b;
16644   // s: p0<<21 | p1<<14 | p2<<7 | p3 (masked)
16645
16646   p++;
16647   b = b<<14;
16648   b |= *p;
16649   // b: p1<<28 | p3<<14 | p5 (unmasked)
16650   if (!(b&0x80))
16651   {
16652     // we can skip this cause it was (effectively) done above in calc'ing s
16653     // b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
16654     a &= (0x7f<<14)|(0x7f);
16655     a = a<<7;
16656     a |= b;
16657     s = s>>18;
16658     *v = ((u64)s)<<32 | a;
16659     return 6;
16660   }
16661
16662   p++;
16663   a = a<<14;
16664   a |= *p;
16665   // a: p2<<28 | p4<<14 | p6 (unmasked)
16666   if (!(a&0x80))
16667   {
16668     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
16669     b &= (0x7f<<14)|(0x7f);
16670     b = b<<7;
16671     a |= b;
16672     s = s>>11;
16673     *v = ((u64)s)<<32 | a;
16674     return 7;
16675   }
16676
16677   // CSE2 from below
16678   a &= (0x7f<<14)|(0x7f);
16679   p++;
16680   b = b<<14;
16681   b |= *p;
16682   // b: p3<<28 | p5<<14 | p7 (unmasked)
16683   if (!(b&0x80))
16684   {
16685     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
16686     // moved CSE2 up
16687     // a &= (0x7f<<14)|(0x7f);
16688     a = a<<7;
16689     a |= b;
16690     s = s>>4;
16691     *v = ((u64)s)<<32 | a;
16692     return 8;
16693   }
16694
16695   p++;
16696   a = a<<15;
16697   a |= *p;
16698   // a: p4<<29 | p6<<15 | p8 (unmasked)
16699
16700   // moved CSE2 up
16701   // a &= (0x7f<<29)|(0x7f<<15)|(0xff);
16702   b &= (0x7f<<14)|(0x7f);
16703   b = b<<8;
16704   a |= b;
16705
16706   s = s<<4;
16707   b = p[-4];
16708   b &= 0x7f;
16709   b = b>>3;
16710   s |= b;
16711
16712   *v = ((u64)s)<<32 | a;
16713
16714   return 9;
16715 }
16716
16717 /*
16718 ** Read a 32-bit variable-length integer from memory starting at p[0].
16719 ** Return the number of bytes read.  The value is stored in *v.
16720 ** A MACRO version, getVarint32, is provided which inlines the 
16721 ** single-byte case.  All code should use the MACRO version as 
16722 ** this function assumes the single-byte case has already been handled.
16723 */
16724 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *p, u32 *v){
16725   u32 a,b;
16726
16727   a = *p;
16728   // a: p0 (unmasked)
16729 #ifndef getVarint32
16730   if (!(a&0x80))
16731   {
16732     *v = a;
16733     return 1;
16734   }
16735 #endif
16736
16737   p++;
16738   b = *p;
16739   // b: p1 (unmasked)
16740   if (!(b&0x80))
16741   {
16742     a &= 0x7f;
16743     a = a<<7;
16744     *v = a | b;
16745     return 2;
16746   }
16747
16748   p++;
16749   a = a<<14;
16750   a |= *p;
16751   // a: p0<<14 | p2 (unmasked)
16752   if (!(a&0x80))
16753   {
16754     a &= (0x7f<<14)|(0x7f);
16755     b &= 0x7f;
16756     b = b<<7;
16757     *v = a | b;
16758     return 3;
16759   }
16760
16761   p++;
16762   b = b<<14;
16763   b |= *p;
16764   // b: p1<<14 | p3 (unmasked)
16765   if (!(b&0x80))
16766   {
16767     b &= (0x7f<<14)|(0x7f);
16768     a &= (0x7f<<14)|(0x7f);
16769     a = a<<7;
16770     *v = a | b;
16771     return 4;
16772   }
16773
16774   p++;
16775   a = a<<14;
16776   a |= *p;
16777   // a: p0<<28 | p2<<14 | p4 (unmasked)
16778   if (!(a&0x80))
16779   {
16780     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
16781     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
16782     b = b<<7;
16783     *v = a | b;
16784     return 5;
16785   }
16786
16787   /* We can only reach this point when reading a corrupt database
16788   ** file.  In that case we are not in any hurry.  Use the (relatively
16789   ** slow) general-purpose sqlite3GetVarint() routine to extract the
16790   ** value. */
16791   {
16792     u64 v64;
16793     int n;
16794
16795     p -= 4;
16796     n = sqlite3GetVarint(p, &v64);
16797     assert( n>5 && n<=9 );
16798     *v = (u32)v64;
16799     return n;
16800   }
16801 }
16802
16803 /*
16804 ** Return the number of bytes that will be needed to store the given
16805 ** 64-bit integer.
16806 */
16807 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
16808   int i = 0;
16809   do{
16810     i++;
16811     v >>= 7;
16812   }while( v!=0 && i<9 );
16813   return i;
16814 }
16815
16816
16817 /*
16818 ** Read or write a four-byte big-endian integer value.
16819 */
16820 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
16821   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
16822 }
16823 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
16824   p[0] = v>>24;
16825   p[1] = v>>16;
16826   p[2] = v>>8;
16827   p[3] = v;
16828 }
16829
16830
16831
16832 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
16833 /*
16834 ** Translate a single byte of Hex into an integer.
16835 ** This routinen only works if h really is a valid hexadecimal
16836 ** character:  0..9a..fA..F
16837 */
16838 static int hexToInt(int h){
16839   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
16840 #ifdef SQLITE_ASCII
16841   h += 9*(1&(h>>6));
16842 #endif
16843 #ifdef SQLITE_EBCDIC
16844   h += 9*(1&~(h>>4));
16845 #endif
16846   return h & 0xf;
16847 }
16848 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
16849
16850 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
16851 /*
16852 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
16853 ** value.  Return a pointer to its binary value.  Space to hold the
16854 ** binary value has been obtained from malloc and must be freed by
16855 ** the calling routine.
16856 */
16857 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
16858   char *zBlob;
16859   int i;
16860
16861   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
16862   n--;
16863   if( zBlob ){
16864     for(i=0; i<n; i+=2){
16865       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
16866     }
16867     zBlob[i/2] = 0;
16868   }
16869   return zBlob;
16870 }
16871 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
16872
16873
16874 /*
16875 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
16876 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
16877 ** when this routine is called.
16878 **
16879 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
16880 ** value indicates that the database connection passed into the API is
16881 ** open and is not being used by another thread.  By changing the value
16882 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
16883 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
16884 ** when the API exits. 
16885 **
16886 ** This routine is a attempt to detect if two threads use the
16887 ** same sqlite* pointer at the same time.  There is a race 
16888 ** condition so it is possible that the error is not detected.
16889 ** But usually the problem will be seen.  The result will be an
16890 ** error which can be used to debug the application that is
16891 ** using SQLite incorrectly.
16892 **
16893 ** Ticket #202:  If db->magic is not a valid open value, take care not
16894 ** to modify the db structure at all.  It could be that db is a stale
16895 ** pointer.  In other words, it could be that there has been a prior
16896 ** call to sqlite3_close(db) and db has been deallocated.  And we do
16897 ** not want to write into deallocated memory.
16898 */
16899 #ifdef SQLITE_DEBUG
16900 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
16901   if( db->magic==SQLITE_MAGIC_OPEN ){
16902     db->magic = SQLITE_MAGIC_BUSY;
16903     assert( sqlite3_mutex_held(db->mutex) );
16904     return 0;
16905   }else if( db->magic==SQLITE_MAGIC_BUSY ){
16906     db->magic = SQLITE_MAGIC_ERROR;
16907     db->u1.isInterrupted = 1;
16908   }
16909   return 1;
16910 }
16911 #endif
16912
16913 /*
16914 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
16915 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
16916 ** when this routine is called.
16917 */
16918 #ifdef SQLITE_DEBUG
16919 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
16920   if( db->magic==SQLITE_MAGIC_BUSY ){
16921     db->magic = SQLITE_MAGIC_OPEN;
16922     assert( sqlite3_mutex_held(db->mutex) );
16923     return 0;
16924   }else{
16925     db->magic = SQLITE_MAGIC_ERROR;
16926     db->u1.isInterrupted = 1;
16927     return 1;
16928   }
16929 }
16930 #endif
16931
16932 /*
16933 ** Check to make sure we have a valid db pointer.  This test is not
16934 ** foolproof but it does provide some measure of protection against
16935 ** misuse of the interface such as passing in db pointers that are
16936 ** NULL or which have been previously closed.  If this routine returns
16937 ** 1 it means that the db pointer is valid and 0 if it should not be
16938 ** dereferenced for any reason.  The calling function should invoke
16939 ** SQLITE_MISUSE immediately.
16940 **
16941 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
16942 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
16943 ** open properly and is not fit for general use but which can be
16944 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
16945 */
16946 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
16947   int magic;
16948   if( db==0 ) return 0;
16949   magic = db->magic;
16950   if( magic!=SQLITE_MAGIC_OPEN &&
16951       magic!=SQLITE_MAGIC_BUSY ) return 0;
16952   return 1;
16953 }
16954 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
16955   int magic;
16956   if( db==0 ) return 0;
16957   magic = db->magic;
16958   if( magic!=SQLITE_MAGIC_SICK &&
16959       magic!=SQLITE_MAGIC_OPEN &&
16960       magic!=SQLITE_MAGIC_BUSY ) return 0;
16961   return 1;
16962 }
16963
16964 /************** End of util.c ************************************************/
16965 /************** Begin file hash.c ********************************************/
16966 /*
16967 ** 2001 September 22
16968 **
16969 ** The author disclaims copyright to this source code.  In place of
16970 ** a legal notice, here is a blessing:
16971 **
16972 **    May you do good and not evil.
16973 **    May you find forgiveness for yourself and forgive others.
16974 **    May you share freely, never taking more than you give.
16975 **
16976 *************************************************************************
16977 ** This is the implementation of generic hash-tables
16978 ** used in SQLite.
16979 **
16980 ** $Id: hash.c,v 1.28 2008/05/13 13:27:34 drh Exp $
16981 */
16982
16983 /* Turn bulk memory into a hash table object by initializing the
16984 ** fields of the Hash structure.
16985 **
16986 ** "pNew" is a pointer to the hash table that is to be initialized.
16987 ** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
16988 ** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING.  The value of keyClass 
16989 ** determines what kind of key the hash table will use.  "copyKey" is
16990 ** true if the hash table should make its own private copy of keys and
16991 ** false if it should just use the supplied pointer.  CopyKey only makes
16992 ** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
16993 ** for other key classes.
16994 */
16995 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
16996   assert( pNew!=0 );
16997   assert( keyClass>=SQLITE_HASH_STRING && keyClass<=SQLITE_HASH_BINARY );
16998   pNew->keyClass = keyClass;
16999 #if 0
17000   if( keyClass==SQLITE_HASH_POINTER || keyClass==SQLITE_HASH_INT ) copyKey = 0;
17001 #endif
17002   pNew->copyKey = copyKey;
17003   pNew->first = 0;
17004   pNew->count = 0;
17005   pNew->htsize = 0;
17006   pNew->ht = 0;
17007 }
17008
17009 /* Remove all entries from a hash table.  Reclaim all memory.
17010 ** Call this routine to delete a hash table or to reset a hash table
17011 ** to the empty state.
17012 */
17013 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
17014   HashElem *elem;         /* For looping over all elements of the table */
17015
17016   assert( pH!=0 );
17017   elem = pH->first;
17018   pH->first = 0;
17019   sqlite3_free(pH->ht);
17020   pH->ht = 0;
17021   pH->htsize = 0;
17022   while( elem ){
17023     HashElem *next_elem = elem->next;
17024     if( pH->copyKey && elem->pKey ){
17025       sqlite3_free(elem->pKey);
17026     }
17027     sqlite3_free(elem);
17028     elem = next_elem;
17029   }
17030   pH->count = 0;
17031 }
17032
17033 #if 0 /* NOT USED */
17034 /*
17035 ** Hash and comparison functions when the mode is SQLITE_HASH_INT
17036 */
17037 static int intHash(const void *pKey, int nKey){
17038   return nKey ^ (nKey<<8) ^ (nKey>>8);
17039 }
17040 static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
17041   return n2 - n1;
17042 }
17043 #endif
17044
17045 #if 0 /* NOT USED */
17046 /*
17047 ** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
17048 */
17049 static int ptrHash(const void *pKey, int nKey){
17050   uptr x = Addr(pKey);
17051   return x ^ (x<<8) ^ (x>>8);
17052 }
17053 static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
17054   if( pKey1==pKey2 ) return 0;
17055   if( pKey1<pKey2 ) return -1;
17056   return 1;
17057 }
17058 #endif
17059
17060 /*
17061 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
17062 */
17063 static int strHash(const void *pKey, int nKey){
17064   const char *z = (const char *)pKey;
17065   int h = 0;
17066   if( nKey<=0 ) nKey = strlen(z);
17067   while( nKey > 0  ){
17068     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
17069     nKey--;
17070   }
17071   return h & 0x7fffffff;
17072 }
17073 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
17074   if( n1!=n2 ) return 1;
17075   return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
17076 }
17077
17078 /*
17079 ** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
17080 */
17081 static int binHash(const void *pKey, int nKey){
17082   int h = 0;
17083   const char *z = (const char *)pKey;
17084   while( nKey-- > 0 ){
17085     h = (h<<3) ^ h ^ *(z++);
17086   }
17087   return h & 0x7fffffff;
17088 }
17089 static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
17090   if( n1!=n2 ) return 1;
17091   return memcmp(pKey1,pKey2,n1);
17092 }
17093
17094 /*
17095 ** Return a pointer to the appropriate hash function given the key class.
17096 **
17097 ** The C syntax in this function definition may be unfamilar to some 
17098 ** programmers, so we provide the following additional explanation:
17099 **
17100 ** The name of the function is "hashFunction".  The function takes a
17101 ** single parameter "keyClass".  The return value of hashFunction()
17102 ** is a pointer to another function.  Specifically, the return value
17103 ** of hashFunction() is a pointer to a function that takes two parameters
17104 ** with types "const void*" and "int" and returns an "int".
17105 */
17106 static int (*hashFunction(int keyClass))(const void*,int){
17107 #if 0  /* HASH_INT and HASH_POINTER are never used */
17108   switch( keyClass ){
17109     case SQLITE_HASH_INT:     return &intHash;
17110     case SQLITE_HASH_POINTER: return &ptrHash;
17111     case SQLITE_HASH_STRING:  return &strHash;
17112     case SQLITE_HASH_BINARY:  return &binHash;;
17113     default: break;
17114   }
17115   return 0;
17116 #else
17117   if( keyClass==SQLITE_HASH_STRING ){
17118     return &strHash;
17119   }else{
17120     assert( keyClass==SQLITE_HASH_BINARY );
17121     return &binHash;
17122   }
17123 #endif
17124 }
17125
17126 /*
17127 ** Return a pointer to the appropriate hash function given the key class.
17128 **
17129 ** For help in interpreted the obscure C code in the function definition,
17130 ** see the header comment on the previous function.
17131 */
17132 static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
17133 #if 0 /* HASH_INT and HASH_POINTER are never used */
17134   switch( keyClass ){
17135     case SQLITE_HASH_INT:     return &intCompare;
17136     case SQLITE_HASH_POINTER: return &ptrCompare;
17137     case SQLITE_HASH_STRING:  return &strCompare;
17138     case SQLITE_HASH_BINARY:  return &binCompare;
17139     default: break;
17140   }
17141   return 0;
17142 #else
17143   if( keyClass==SQLITE_HASH_STRING ){
17144     return &strCompare;
17145   }else{
17146     assert( keyClass==SQLITE_HASH_BINARY );
17147     return &binCompare;
17148   }
17149 #endif
17150 }
17151
17152 /* Link an element into the hash table
17153 */
17154 static void insertElement(
17155   Hash *pH,              /* The complete hash table */
17156   struct _ht *pEntry,    /* The entry into which pNew is inserted */
17157   HashElem *pNew         /* The element to be inserted */
17158 ){
17159   HashElem *pHead;       /* First element already in pEntry */
17160   pHead = pEntry->chain;
17161   if( pHead ){
17162     pNew->next = pHead;
17163     pNew->prev = pHead->prev;
17164     if( pHead->prev ){ pHead->prev->next = pNew; }
17165     else             { pH->first = pNew; }
17166     pHead->prev = pNew;
17167   }else{
17168     pNew->next = pH->first;
17169     if( pH->first ){ pH->first->prev = pNew; }
17170     pNew->prev = 0;
17171     pH->first = pNew;
17172   }
17173   pEntry->count++;
17174   pEntry->chain = pNew;
17175 }
17176
17177
17178 /* Resize the hash table so that it cantains "new_size" buckets.
17179 ** "new_size" must be a power of 2.  The hash table might fail 
17180 ** to resize if sqlite3_malloc() fails.
17181 */
17182 static void rehash(Hash *pH, int new_size){
17183   struct _ht *new_ht;            /* The new hash table */
17184   HashElem *elem, *next_elem;    /* For looping over existing elements */
17185   int (*xHash)(const void*,int); /* The hash function */
17186
17187 #ifdef SQLITE_MALLOC_SOFT_LIMIT
17188   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
17189     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
17190   }
17191   if( new_size==pH->htsize ) return;
17192 #endif
17193
17194   /* There is a call to sqlite3_malloc() inside rehash(). If there is
17195   ** already an allocation at pH->ht, then if this malloc() fails it
17196   ** is benign (since failing to resize a hash table is a performance
17197   ** hit only, not a fatal error).
17198   */
17199   if( pH->htsize>0 ) sqlite3FaultBeginBenign(SQLITE_FAULTINJECTOR_MALLOC);
17200   new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
17201   if( pH->htsize>0 ) sqlite3FaultEndBenign(SQLITE_FAULTINJECTOR_MALLOC);
17202
17203   if( new_ht==0 ) return;
17204   sqlite3_free(pH->ht);
17205   pH->ht = new_ht;
17206   pH->htsize = new_size;
17207   xHash = hashFunction(pH->keyClass);
17208   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
17209     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
17210     next_elem = elem->next;
17211     insertElement(pH, &new_ht[h], elem);
17212   }
17213 }
17214
17215 /* This function (for internal use only) locates an element in an
17216 ** hash table that matches the given key.  The hash for this key has
17217 ** already been computed and is passed as the 4th parameter.
17218 */
17219 static HashElem *findElementGivenHash(
17220   const Hash *pH,     /* The pH to be searched */
17221   const void *pKey,   /* The key we are searching for */
17222   int nKey,
17223   int h               /* The hash for this key. */
17224 ){
17225   HashElem *elem;                /* Used to loop thru the element list */
17226   int count;                     /* Number of elements left to test */
17227   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
17228
17229   if( pH->ht ){
17230     struct _ht *pEntry = &pH->ht[h];
17231     elem = pEntry->chain;
17232     count = pEntry->count;
17233     xCompare = compareFunction(pH->keyClass);
17234     while( count-- && elem ){
17235       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
17236         return elem;
17237       }
17238       elem = elem->next;
17239     }
17240   }
17241   return 0;
17242 }
17243
17244 /* Remove a single entry from the hash table given a pointer to that
17245 ** element and a hash on the element's key.
17246 */
17247 static void removeElementGivenHash(
17248   Hash *pH,         /* The pH containing "elem" */
17249   HashElem* elem,   /* The element to be removed from the pH */
17250   int h             /* Hash value for the element */
17251 ){
17252   struct _ht *pEntry;
17253   if( elem->prev ){
17254     elem->prev->next = elem->next; 
17255   }else{
17256     pH->first = elem->next;
17257   }
17258   if( elem->next ){
17259     elem->next->prev = elem->prev;
17260   }
17261   pEntry = &pH->ht[h];
17262   if( pEntry->chain==elem ){
17263     pEntry->chain = elem->next;
17264   }
17265   pEntry->count--;
17266   if( pEntry->count<=0 ){
17267     pEntry->chain = 0;
17268   }
17269   if( pH->copyKey ){
17270     sqlite3_free(elem->pKey);
17271   }
17272   sqlite3_free( elem );
17273   pH->count--;
17274   if( pH->count<=0 ){
17275     assert( pH->first==0 );
17276     assert( pH->count==0 );
17277     sqlite3HashClear(pH);
17278   }
17279 }
17280
17281 /* Attempt to locate an element of the hash table pH with a key
17282 ** that matches pKey,nKey.  Return a pointer to the corresponding 
17283 ** HashElem structure for this element if it is found, or NULL
17284 ** otherwise.
17285 */
17286 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
17287   int h;             /* A hash on key */
17288   HashElem *elem;    /* The element that matches key */
17289   int (*xHash)(const void*,int);  /* The hash function */
17290
17291   if( pH==0 || pH->ht==0 ) return 0;
17292   xHash = hashFunction(pH->keyClass);
17293   assert( xHash!=0 );
17294   h = (*xHash)(pKey,nKey);
17295   elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
17296   return elem;
17297 }
17298
17299 /* Attempt to locate an element of the hash table pH with a key
17300 ** that matches pKey,nKey.  Return the data for this element if it is
17301 ** found, or NULL if there is no match.
17302 */
17303 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
17304   HashElem *elem;    /* The element that matches key */
17305   elem = sqlite3HashFindElem(pH, pKey, nKey);
17306   return elem ? elem->data : 0;
17307 }
17308
17309 /* Insert an element into the hash table pH.  The key is pKey,nKey
17310 ** and the data is "data".
17311 **
17312 ** If no element exists with a matching key, then a new
17313 ** element is created.  A copy of the key is made if the copyKey
17314 ** flag is set.  NULL is returned.
17315 **
17316 ** If another element already exists with the same key, then the
17317 ** new data replaces the old data and the old data is returned.
17318 ** The key is not copied in this instance.  If a malloc fails, then
17319 ** the new data is returned and the hash table is unchanged.
17320 **
17321 ** If the "data" parameter to this function is NULL, then the
17322 ** element corresponding to "key" is removed from the hash table.
17323 */
17324 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
17325   int hraw;             /* Raw hash value of the key */
17326   int h;                /* the hash of the key modulo hash table size */
17327   HashElem *elem;       /* Used to loop thru the element list */
17328   HashElem *new_elem;   /* New element added to the pH */
17329   int (*xHash)(const void*,int);  /* The hash function */
17330
17331   assert( pH!=0 );
17332   xHash = hashFunction(pH->keyClass);
17333   assert( xHash!=0 );
17334   hraw = (*xHash)(pKey, nKey);
17335   if( pH->htsize ){
17336     h = hraw % pH->htsize;
17337     elem = findElementGivenHash(pH,pKey,nKey,h);
17338     if( elem ){
17339       void *old_data = elem->data;
17340       if( data==0 ){
17341         removeElementGivenHash(pH,elem,h);
17342       }else{
17343         elem->data = data;
17344         if( !pH->copyKey ){
17345           elem->pKey = (void *)pKey;
17346         }
17347         assert(nKey==elem->nKey);
17348       }
17349       return old_data;
17350     }
17351   }
17352   if( data==0 ) return 0;
17353   new_elem = (HashElem*)sqlite3_malloc( sizeof(HashElem) );
17354   if( new_elem==0 ) return data;
17355   if( pH->copyKey && pKey!=0 ){
17356     new_elem->pKey = sqlite3_malloc( nKey );
17357     if( new_elem->pKey==0 ){
17358       sqlite3_free(new_elem);
17359       return data;
17360     }
17361     memcpy((void*)new_elem->pKey, pKey, nKey);
17362   }else{
17363     new_elem->pKey = (void*)pKey;
17364   }
17365   new_elem->nKey = nKey;
17366   pH->count++;
17367   if( pH->htsize==0 ){
17368     rehash(pH, 128/sizeof(pH->ht[0]));
17369     if( pH->htsize==0 ){
17370       pH->count = 0;
17371       if( pH->copyKey ){
17372         sqlite3_free(new_elem->pKey);
17373       }
17374       sqlite3_free(new_elem);
17375       return data;
17376     }
17377   }
17378   if( pH->count > pH->htsize ){
17379     rehash(pH,pH->htsize*2);
17380   }
17381   assert( pH->htsize>0 );
17382   h = hraw % pH->htsize;
17383   insertElement(pH, &pH->ht[h], new_elem);
17384   new_elem->data = data;
17385   return 0;
17386 }
17387
17388 /************** End of hash.c ************************************************/
17389 /************** Begin file opcodes.c *****************************************/
17390 /* Automatically generated.  Do not edit */
17391 /* See the mkopcodec.awk script for details. */
17392 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
17393 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
17394  static const char *const azName[] = { "?",
17395      /*   1 */ "VNext",
17396      /*   2 */ "Affinity",
17397      /*   3 */ "Column",
17398      /*   4 */ "SetCookie",
17399      /*   5 */ "Sequence",
17400      /*   6 */ "MoveGt",
17401      /*   7 */ "RowKey",
17402      /*   8 */ "SCopy",
17403      /*   9 */ "OpenWrite",
17404      /*  10 */ "If",
17405      /*  11 */ "VRowid",
17406      /*  12 */ "CollSeq",
17407      /*  13 */ "OpenRead",
17408      /*  14 */ "Expire",
17409      /*  15 */ "AutoCommit",
17410      /*  16 */ "Not",
17411      /*  17 */ "IntegrityCk",
17412      /*  18 */ "Sort",
17413      /*  19 */ "Copy",
17414      /*  20 */ "Trace",
17415      /*  21 */ "Function",
17416      /*  22 */ "IfNeg",
17417      /*  23 */ "Noop",
17418      /*  24 */ "Return",
17419      /*  25 */ "NewRowid",
17420      /*  26 */ "Variable",
17421      /*  27 */ "String",
17422      /*  28 */ "RealAffinity",
17423      /*  29 */ "VRename",
17424      /*  30 */ "ParseSchema",
17425      /*  31 */ "VOpen",
17426      /*  32 */ "Close",
17427      /*  33 */ "CreateIndex",
17428      /*  34 */ "IsUnique",
17429      /*  35 */ "NotFound",
17430      /*  36 */ "Int64",
17431      /*  37 */ "MustBeInt",
17432      /*  38 */ "Halt",
17433      /*  39 */ "Rowid",
17434      /*  40 */ "IdxLT",
17435      /*  41 */ "AddImm",
17436      /*  42 */ "Statement",
17437      /*  43 */ "RowData",
17438      /*  44 */ "MemMax",
17439      /*  45 */ "NotExists",
17440      /*  46 */ "Gosub",
17441      /*  47 */ "Integer",
17442      /*  48 */ "Prev",
17443      /*  49 */ "VColumn",
17444      /*  50 */ "CreateTable",
17445      /*  51 */ "Last",
17446      /*  52 */ "IncrVacuum",
17447      /*  53 */ "IdxRowid",
17448      /*  54 */ "ResetCount",
17449      /*  55 */ "FifoWrite",
17450      /*  56 */ "ContextPush",
17451      /*  57 */ "DropTrigger",
17452      /*  58 */ "DropIndex",
17453      /*  59 */ "IdxGE",
17454      /*  60 */ "Or",
17455      /*  61 */ "And",
17456      /*  62 */ "IdxDelete",
17457      /*  63 */ "Vacuum",
17458      /*  64 */ "MoveLe",
17459      /*  65 */ "IsNull",
17460      /*  66 */ "NotNull",
17461      /*  67 */ "Ne",
17462      /*  68 */ "Eq",
17463      /*  69 */ "Gt",
17464      /*  70 */ "Le",
17465      /*  71 */ "Lt",
17466      /*  72 */ "Ge",
17467      /*  73 */ "IfNot",
17468      /*  74 */ "BitAnd",
17469      /*  75 */ "BitOr",
17470      /*  76 */ "ShiftLeft",
17471      /*  77 */ "ShiftRight",
17472      /*  78 */ "Add",
17473      /*  79 */ "Subtract",
17474      /*  80 */ "Multiply",
17475      /*  81 */ "Divide",
17476      /*  82 */ "Remainder",
17477      /*  83 */ "Concat",
17478      /*  84 */ "DropTable",
17479      /*  85 */ "MakeRecord",
17480      /*  86 */ "ResultRow",
17481      /*  87 */ "BitNot",
17482      /*  88 */ "String8",
17483      /*  89 */ "Delete",
17484      /*  90 */ "AggFinal",
17485      /*  91 */ "Goto",
17486      /*  92 */ "TableLock",
17487      /*  93 */ "FifoRead",
17488      /*  94 */ "Clear",
17489      /*  95 */ "MoveLt",
17490      /*  96 */ "VerifyCookie",
17491      /*  97 */ "AggStep",
17492      /*  98 */ "SetNumColumns",
17493      /*  99 */ "Transaction",
17494      /* 100 */ "VFilter",
17495      /* 101 */ "VDestroy",
17496      /* 102 */ "ContextPop",
17497      /* 103 */ "Next",
17498      /* 104 */ "IdxInsert",
17499      /* 105 */ "Insert",
17500      /* 106 */ "Destroy",
17501      /* 107 */ "ReadCookie",
17502      /* 108 */ "ForceInt",
17503      /* 109 */ "LoadAnalysis",
17504      /* 110 */ "Explain",
17505      /* 111 */ "OpenPseudo",
17506      /* 112 */ "OpenEphemeral",
17507      /* 113 */ "Null",
17508      /* 114 */ "Move",
17509      /* 115 */ "Blob",
17510      /* 116 */ "Rewind",
17511      /* 117 */ "MoveGe",
17512      /* 118 */ "VBegin",
17513      /* 119 */ "VUpdate",
17514      /* 120 */ "IfZero",
17515      /* 121 */ "VCreate",
17516      /* 122 */ "Found",
17517      /* 123 */ "IfPos",
17518      /* 124 */ "NullRow",
17519      /* 125 */ "Real",
17520      /* 126 */ "NotUsed_126",
17521      /* 127 */ "NotUsed_127",
17522      /* 128 */ "NotUsed_128",
17523      /* 129 */ "NotUsed_129",
17524      /* 130 */ "NotUsed_130",
17525      /* 131 */ "NotUsed_131",
17526      /* 132 */ "NotUsed_132",
17527      /* 133 */ "NotUsed_133",
17528      /* 134 */ "NotUsed_134",
17529      /* 135 */ "NotUsed_135",
17530      /* 136 */ "NotUsed_136",
17531      /* 137 */ "NotUsed_137",
17532      /* 138 */ "ToText",
17533      /* 139 */ "ToBlob",
17534      /* 140 */ "ToNumeric",
17535      /* 141 */ "ToInt",
17536      /* 142 */ "ToReal",
17537   };
17538   return azName[i];
17539 }
17540 #endif
17541
17542 /************** End of opcodes.c *********************************************/
17543 /************** Begin file os_os2.c ******************************************/
17544 /*
17545 ** 2006 Feb 14
17546 **
17547 ** The author disclaims copyright to this source code.  In place of
17548 ** a legal notice, here is a blessing:
17549 **
17550 **    May you do good and not evil.
17551 **    May you find forgiveness for yourself and forgive others.
17552 **    May you share freely, never taking more than you give.
17553 **
17554 ******************************************************************************
17555 **
17556 ** This file contains code that is specific to OS/2.
17557 */
17558
17559
17560 #if OS_OS2
17561
17562 /*
17563 ** A Note About Memory Allocation:
17564 **
17565 ** This driver uses malloc()/free() directly rather than going through
17566 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
17567 ** are designed for use on embedded systems where memory is scarce and
17568 ** malloc failures happen frequently.  OS/2 does not typically run on
17569 ** embedded systems, and when it does the developers normally have bigger
17570 ** problems to worry about than running out of memory.  So there is not
17571 ** a compelling need to use the wrappers.
17572 **
17573 ** But there is a good reason to not use the wrappers.  If we use the
17574 ** wrappers then we will get simulated malloc() failures within this
17575 ** driver.  And that causes all kinds of problems for our tests.  We
17576 ** could enhance SQLite to deal with simulated malloc failures within
17577 ** the OS driver, but the code to deal with those failure would not
17578 ** be exercised on Linux (which does not need to malloc() in the driver)
17579 ** and so we would have difficulty writing coverage tests for that
17580 ** code.  Better to leave the code out, we think.
17581 **
17582 ** The point of this discussion is as follows:  When creating a new
17583 ** OS layer for an embedded system, if you use this file as an example,
17584 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
17585 ** desktops but not so well in embedded systems.
17586 */
17587
17588 /*
17589 ** Macros used to determine whether or not to use threads.
17590 */
17591 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
17592 # define SQLITE_OS2_THREADS 1
17593 #endif
17594
17595 /*
17596 ** Include code that is common to all os_*.c files
17597 */
17598 /************** Include os_common.h in the middle of os_os2.c ****************/
17599 /************** Begin file os_common.h ***************************************/
17600 /*
17601 ** 2004 May 22
17602 **
17603 ** The author disclaims copyright to this source code.  In place of
17604 ** a legal notice, here is a blessing:
17605 **
17606 **    May you do good and not evil.
17607 **    May you find forgiveness for yourself and forgive others.
17608 **    May you share freely, never taking more than you give.
17609 **
17610 ******************************************************************************
17611 **
17612 ** This file contains macros and a little bit of code that is common to
17613 ** all of the platform-specific files (os_*.c) and is #included into those
17614 ** files.
17615 **
17616 ** This file should be #included by the os_*.c files only.  It is not a
17617 ** general purpose header file.
17618 */
17619
17620 /*
17621 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
17622 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
17623 ** switch.  The following code should catch this problem at compile-time.
17624 */
17625 #ifdef MEMORY_DEBUG
17626 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
17627 #endif
17628
17629
17630 /*
17631  * When testing, this global variable stores the location of the
17632  * pending-byte in the database file.
17633  */
17634 #ifdef SQLITE_TEST
17635 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
17636 #endif
17637
17638 #ifdef SQLITE_DEBUG
17639 SQLITE_PRIVATE int sqlite3OSTrace = 0;
17640 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
17641 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
17642 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
17643 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
17644 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
17645 #define OSTRACE6(X,Y,Z,A,B,C) \
17646     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
17647 #define OSTRACE7(X,Y,Z,A,B,C,D) \
17648     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
17649 #else
17650 #define OSTRACE1(X)
17651 #define OSTRACE2(X,Y)
17652 #define OSTRACE3(X,Y,Z)
17653 #define OSTRACE4(X,Y,Z,A)
17654 #define OSTRACE5(X,Y,Z,A,B)
17655 #define OSTRACE6(X,Y,Z,A,B,C)
17656 #define OSTRACE7(X,Y,Z,A,B,C,D)
17657 #endif
17658
17659 /*
17660 ** Macros for performance tracing.  Normally turned off.  Only works
17661 ** on i486 hardware.
17662 */
17663 #ifdef SQLITE_PERFORMANCE_TRACE
17664 __inline__ unsigned long long int hwtime(void){
17665   unsigned long long int x;
17666   __asm__("rdtsc\n\t"
17667           "mov %%edx, %%ecx\n\t"
17668           :"=A" (x));
17669   return x;
17670 }
17671 static unsigned long long int g_start;
17672 static unsigned int elapse;
17673 #define TIMER_START       g_start=hwtime()
17674 #define TIMER_END         elapse=hwtime()-g_start
17675 #define TIMER_ELAPSED     elapse
17676 #else
17677 #define TIMER_START
17678 #define TIMER_END
17679 #define TIMER_ELAPSED     0
17680 #endif
17681
17682 /*
17683 ** If we compile with the SQLITE_TEST macro set, then the following block
17684 ** of code will give us the ability to simulate a disk I/O error.  This
17685 ** is used for testing the I/O recovery logic.
17686 */
17687 #ifdef SQLITE_TEST
17688 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
17689 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
17690 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
17691 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
17692 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
17693 SQLITE_API int sqlite3_diskfull_pending = 0;
17694 SQLITE_API int sqlite3_diskfull = 0;
17695 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
17696 #define SimulateIOError(CODE)  \
17697   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
17698        || sqlite3_io_error_pending-- == 1 )  \
17699               { local_ioerr(); CODE; }
17700 static void local_ioerr(){
17701   IOTRACE(("IOERR\n"));
17702   sqlite3_io_error_hit++;
17703   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
17704 }
17705 #define SimulateDiskfullError(CODE) \
17706    if( sqlite3_diskfull_pending ){ \
17707      if( sqlite3_diskfull_pending == 1 ){ \
17708        local_ioerr(); \
17709        sqlite3_diskfull = 1; \
17710        sqlite3_io_error_hit = 1; \
17711        CODE; \
17712      }else{ \
17713        sqlite3_diskfull_pending--; \
17714      } \
17715    }
17716 #else
17717 #define SimulateIOErrorBenign(X)
17718 #define SimulateIOError(A)
17719 #define SimulateDiskfullError(A)
17720 #endif
17721
17722 /*
17723 ** When testing, keep a count of the number of open files.
17724 */
17725 #ifdef SQLITE_TEST
17726 SQLITE_API int sqlite3_open_file_count = 0;
17727 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
17728 #else
17729 #define OpenCounter(X)
17730 #endif
17731
17732 /************** End of os_common.h *******************************************/
17733 /************** Continuing where we left off in os_os2.c *********************/
17734
17735 /*
17736 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
17737 ** protability layer.
17738 */
17739 typedef struct os2File os2File;
17740 struct os2File {
17741   const sqlite3_io_methods *pMethod;  /* Always the first entry */
17742   HFILE h;                  /* Handle for accessing the file */
17743   char* pathToDel;          /* Name of file to delete on close, NULL if not */
17744   unsigned char locktype;   /* Type of lock currently held on this file */
17745 };
17746
17747 #define LOCK_TIMEOUT 10L /* the default locking timeout */
17748
17749 /*****************************************************************************
17750 ** The next group of routines implement the I/O methods specified
17751 ** by the sqlite3_io_methods object.
17752 ******************************************************************************/
17753
17754 /*
17755 ** Close a file.
17756 */
17757 int os2Close( sqlite3_file *id ){
17758   APIRET rc = NO_ERROR;
17759   os2File *pFile;
17760   if( id && (pFile = (os2File*)id) != 0 ){
17761     OSTRACE2( "CLOSE %d\n", pFile->h );
17762     rc = DosClose( pFile->h );
17763     pFile->locktype = NO_LOCK;
17764     if( pFile->pathToDel != NULL ){
17765       rc = DosForceDelete( (PSZ)pFile->pathToDel );
17766       free( pFile->pathToDel );
17767       pFile->pathToDel = NULL;
17768     }
17769     id = 0;
17770     OpenCounter( -1 );
17771   }
17772
17773   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
17774 }
17775
17776 /*
17777 ** Read data from a file into a buffer.  Return SQLITE_OK if all
17778 ** bytes were read successfully and SQLITE_IOERR if anything goes
17779 ** wrong.
17780 */
17781 int os2Read(
17782   sqlite3_file *id,               /* File to read from */
17783   void *pBuf,                     /* Write content into this buffer */
17784   int amt,                        /* Number of bytes to read */
17785   sqlite3_int64 offset            /* Begin reading at this offset */
17786 ){
17787   ULONG fileLocation = 0L;
17788   ULONG got;
17789   os2File *pFile = (os2File*)id;
17790   assert( id!=0 );
17791   SimulateIOError( return SQLITE_IOERR_READ );
17792   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
17793   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
17794     return SQLITE_IOERR;
17795   }
17796   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
17797     return SQLITE_IOERR_READ;
17798   }
17799   if( got == (ULONG)amt )
17800     return SQLITE_OK;
17801   else {
17802     memset(&((char*)pBuf)[got], 0, amt-got);
17803     return SQLITE_IOERR_SHORT_READ;
17804   }
17805 }
17806
17807 /*
17808 ** Write data from a buffer into a file.  Return SQLITE_OK on success
17809 ** or some other error code on failure.
17810 */
17811 int os2Write(
17812   sqlite3_file *id,               /* File to write into */
17813   const void *pBuf,               /* The bytes to be written */
17814   int amt,                        /* Number of bytes to write */
17815   sqlite3_int64 offset            /* Offset into the file to begin writing at */
17816 ){
17817   ULONG fileLocation = 0L;
17818   APIRET rc = NO_ERROR;
17819   ULONG wrote;
17820   os2File *pFile = (os2File*)id;
17821   assert( id!=0 );
17822   SimulateIOError( return SQLITE_IOERR_WRITE );
17823   SimulateDiskfullError( return SQLITE_FULL );
17824   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
17825   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
17826     return SQLITE_IOERR;
17827   }
17828   assert( amt>0 );
17829   while( amt > 0 &&
17830          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
17831          wrote > 0
17832   ){
17833     amt -= wrote;
17834     pBuf = &((char*)pBuf)[wrote];
17835   }
17836
17837   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
17838 }
17839
17840 /*
17841 ** Truncate an open file to a specified size
17842 */
17843 int os2Truncate( sqlite3_file *id, i64 nByte ){
17844   APIRET rc = NO_ERROR;
17845   os2File *pFile = (os2File*)id;
17846   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
17847   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
17848   rc = DosSetFileSize( pFile->h, nByte );
17849   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
17850 }
17851
17852 #ifdef SQLITE_TEST
17853 /*
17854 ** Count the number of fullsyncs and normal syncs.  This is used to test
17855 ** that syncs and fullsyncs are occuring at the right times.
17856 */
17857 SQLITE_API int sqlite3_sync_count = 0;
17858 SQLITE_API int sqlite3_fullsync_count = 0;
17859 #endif
17860
17861 /*
17862 ** Make sure all writes to a particular file are committed to disk.
17863 */
17864 int os2Sync( sqlite3_file *id, int flags ){
17865   os2File *pFile = (os2File*)id;
17866   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
17867 #ifdef SQLITE_TEST
17868   if( flags & SQLITE_SYNC_FULL){
17869     sqlite3_fullsync_count++;
17870   }
17871   sqlite3_sync_count++;
17872 #endif
17873   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
17874 }
17875
17876 /*
17877 ** Determine the current size of a file in bytes
17878 */
17879 int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
17880   APIRET rc = NO_ERROR;
17881   FILESTATUS3 fsts3FileInfo;
17882   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
17883   assert( id!=0 );
17884   SimulateIOError( return SQLITE_IOERR );
17885   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
17886   if( rc == NO_ERROR ){
17887     *pSize = fsts3FileInfo.cbFile;
17888     return SQLITE_OK;
17889   }else{
17890     return SQLITE_IOERR;
17891   }
17892 }
17893
17894 /*
17895 ** Acquire a reader lock.
17896 */
17897 static int getReadLock( os2File *pFile ){
17898   FILELOCK  LockArea,
17899             UnlockArea;
17900   APIRET res;
17901   memset(&LockArea, 0, sizeof(LockArea));
17902   memset(&UnlockArea, 0, sizeof(UnlockArea));
17903   LockArea.lOffset = SHARED_FIRST;
17904   LockArea.lRange = SHARED_SIZE;
17905   UnlockArea.lOffset = 0L;
17906   UnlockArea.lRange = 0L;
17907   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
17908   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
17909   return res;
17910 }
17911
17912 /*
17913 ** Undo a readlock
17914 */
17915 static int unlockReadLock( os2File *id ){
17916   FILELOCK  LockArea,
17917             UnlockArea;
17918   APIRET res;
17919   memset(&LockArea, 0, sizeof(LockArea));
17920   memset(&UnlockArea, 0, sizeof(UnlockArea));
17921   LockArea.lOffset = 0L;
17922   LockArea.lRange = 0L;
17923   UnlockArea.lOffset = SHARED_FIRST;
17924   UnlockArea.lRange = SHARED_SIZE;
17925   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
17926   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
17927   return res;
17928 }
17929
17930 /*
17931 ** Lock the file with the lock specified by parameter locktype - one
17932 ** of the following:
17933 **
17934 **     (1) SHARED_LOCK
17935 **     (2) RESERVED_LOCK
17936 **     (3) PENDING_LOCK
17937 **     (4) EXCLUSIVE_LOCK
17938 **
17939 ** Sometimes when requesting one lock state, additional lock states
17940 ** are inserted in between.  The locking might fail on one of the later
17941 ** transitions leaving the lock state different from what it started but
17942 ** still short of its goal.  The following chart shows the allowed
17943 ** transitions and the inserted intermediate states:
17944 **
17945 **    UNLOCKED -> SHARED
17946 **    SHARED -> RESERVED
17947 **    SHARED -> (PENDING) -> EXCLUSIVE
17948 **    RESERVED -> (PENDING) -> EXCLUSIVE
17949 **    PENDING -> EXCLUSIVE
17950 **
17951 ** This routine will only increase a lock.  The os2Unlock() routine
17952 ** erases all locks at once and returns us immediately to locking level 0.
17953 ** It is not possible to lower the locking level one step at a time.  You
17954 ** must go straight to locking level 0.
17955 */
17956 int os2Lock( sqlite3_file *id, int locktype ){
17957   int rc = SQLITE_OK;       /* Return code from subroutines */
17958   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
17959   int newLocktype;       /* Set pFile->locktype to this value before exiting */
17960   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
17961   FILELOCK  LockArea,
17962             UnlockArea;
17963   os2File *pFile = (os2File*)id;
17964   memset(&LockArea, 0, sizeof(LockArea));
17965   memset(&UnlockArea, 0, sizeof(UnlockArea));
17966   assert( pFile!=0 );
17967   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
17968
17969   /* If there is already a lock of this type or more restrictive on the
17970   ** os2File, do nothing. Don't use the end_lock: exit path, as
17971   ** sqlite3_mutex_enter() hasn't been called yet.
17972   */
17973   if( pFile->locktype>=locktype ){
17974     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
17975     return SQLITE_OK;
17976   }
17977
17978   /* Make sure the locking sequence is correct
17979   */
17980   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
17981   assert( locktype!=PENDING_LOCK );
17982   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
17983
17984   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
17985   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
17986   ** the PENDING_LOCK byte is temporary.
17987   */
17988   newLocktype = pFile->locktype;
17989   if( pFile->locktype==NO_LOCK
17990       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
17991   ){
17992     LockArea.lOffset = PENDING_BYTE;
17993     LockArea.lRange = 1L;
17994     UnlockArea.lOffset = 0L;
17995     UnlockArea.lRange = 0L;
17996
17997     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
17998     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
17999     if( res == NO_ERROR ){
18000       gotPendingLock = 1;
18001       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
18002     }
18003   }
18004
18005   /* Acquire a shared lock
18006   */
18007   if( locktype==SHARED_LOCK && res == NO_ERROR ){
18008     assert( pFile->locktype==NO_LOCK );
18009     res = getReadLock(pFile);
18010     if( res == NO_ERROR ){
18011       newLocktype = SHARED_LOCK;
18012     }
18013     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
18014   }
18015
18016   /* Acquire a RESERVED lock
18017   */
18018   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
18019     assert( pFile->locktype==SHARED_LOCK );
18020     LockArea.lOffset = RESERVED_BYTE;
18021     LockArea.lRange = 1L;
18022     UnlockArea.lOffset = 0L;
18023     UnlockArea.lRange = 0L;
18024     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
18025     if( res == NO_ERROR ){
18026       newLocktype = RESERVED_LOCK;
18027     }
18028     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
18029   }
18030
18031   /* Acquire a PENDING lock
18032   */
18033   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
18034     newLocktype = PENDING_LOCK;
18035     gotPendingLock = 0;
18036     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
18037   }
18038
18039   /* Acquire an EXCLUSIVE lock
18040   */
18041   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
18042     assert( pFile->locktype>=SHARED_LOCK );
18043     res = unlockReadLock(pFile);
18044     OSTRACE2( "unreadlock = %d\n", res );
18045     LockArea.lOffset = SHARED_FIRST;
18046     LockArea.lRange = SHARED_SIZE;
18047     UnlockArea.lOffset = 0L;
18048     UnlockArea.lRange = 0L;
18049     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
18050     if( res == NO_ERROR ){
18051       newLocktype = EXCLUSIVE_LOCK;
18052     }else{
18053       OSTRACE2( "OS/2 error-code = %d\n", res );
18054       getReadLock(pFile);
18055     }
18056     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
18057   }
18058
18059   /* If we are holding a PENDING lock that ought to be released, then
18060   ** release it now.
18061   */
18062   if( gotPendingLock && locktype==SHARED_LOCK ){
18063     int r;
18064     LockArea.lOffset = 0L;
18065     LockArea.lRange = 0L;
18066     UnlockArea.lOffset = PENDING_BYTE;
18067     UnlockArea.lRange = 1L;
18068     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
18069     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
18070   }
18071
18072   /* Update the state of the lock has held in the file descriptor then
18073   ** return the appropriate result code.
18074   */
18075   if( res == NO_ERROR ){
18076     rc = SQLITE_OK;
18077   }else{
18078     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
18079               locktype, newLocktype );
18080     rc = SQLITE_BUSY;
18081   }
18082   pFile->locktype = newLocktype;
18083   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
18084   return rc;
18085 }
18086
18087 /*
18088 ** This routine checks if there is a RESERVED lock held on the specified
18089 ** file by this or any other process. If such a lock is held, return
18090 ** non-zero, otherwise zero.
18091 */
18092 int os2CheckReservedLock( sqlite3_file *id ){
18093   int r = 0;
18094   os2File *pFile = (os2File*)id;
18095   assert( pFile!=0 );
18096   if( pFile->locktype>=RESERVED_LOCK ){
18097     r = 1;
18098     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
18099   }else{
18100     FILELOCK  LockArea,
18101               UnlockArea;
18102     APIRET rc = NO_ERROR;
18103     memset(&LockArea, 0, sizeof(LockArea));
18104     memset(&UnlockArea, 0, sizeof(UnlockArea));
18105     LockArea.lOffset = RESERVED_BYTE;
18106     LockArea.lRange = 1L;
18107     UnlockArea.lOffset = 0L;
18108     UnlockArea.lRange = 0L;
18109     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
18110     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
18111     if( rc == NO_ERROR ){
18112       APIRET rcu = NO_ERROR; /* return code for unlocking */
18113       LockArea.lOffset = 0L;
18114       LockArea.lRange = 0L;
18115       UnlockArea.lOffset = RESERVED_BYTE;
18116       UnlockArea.lRange = 1L;
18117       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
18118       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
18119     }
18120     r = !(rc == NO_ERROR);
18121     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
18122   }
18123   return r;
18124 }
18125
18126 /*
18127 ** Lower the locking level on file descriptor id to locktype.  locktype
18128 ** must be either NO_LOCK or SHARED_LOCK.
18129 **
18130 ** If the locking level of the file descriptor is already at or below
18131 ** the requested locking level, this routine is a no-op.
18132 **
18133 ** It is not possible for this routine to fail if the second argument
18134 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
18135 ** might return SQLITE_IOERR;
18136 */
18137 int os2Unlock( sqlite3_file *id, int locktype ){
18138   int type;
18139   os2File *pFile = (os2File*)id;
18140   APIRET rc = SQLITE_OK;
18141   APIRET res = NO_ERROR;
18142   FILELOCK  LockArea,
18143             UnlockArea;
18144   memset(&LockArea, 0, sizeof(LockArea));
18145   memset(&UnlockArea, 0, sizeof(UnlockArea));
18146   assert( pFile!=0 );
18147   assert( locktype<=SHARED_LOCK );
18148   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
18149   type = pFile->locktype;
18150   if( type>=EXCLUSIVE_LOCK ){
18151     LockArea.lOffset = 0L;
18152     LockArea.lRange = 0L;
18153     UnlockArea.lOffset = SHARED_FIRST;
18154     UnlockArea.lRange = SHARED_SIZE;
18155     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
18156     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
18157     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
18158       /* This should never happen.  We should always be able to
18159       ** reacquire the read lock */
18160       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
18161       rc = SQLITE_IOERR_UNLOCK;
18162     }
18163   }
18164   if( type>=RESERVED_LOCK ){
18165     LockArea.lOffset = 0L;
18166     LockArea.lRange = 0L;
18167     UnlockArea.lOffset = RESERVED_BYTE;
18168     UnlockArea.lRange = 1L;
18169     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
18170     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
18171   }
18172   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
18173     res = unlockReadLock(pFile);
18174     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
18175   }
18176   if( type>=PENDING_LOCK ){
18177     LockArea.lOffset = 0L;
18178     LockArea.lRange = 0L;
18179     UnlockArea.lOffset = PENDING_BYTE;
18180     UnlockArea.lRange = 1L;
18181     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
18182     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
18183   }
18184   pFile->locktype = locktype;
18185   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
18186   return rc;
18187 }
18188
18189 /*
18190 ** Control and query of the open file handle.
18191 */
18192 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
18193   switch( op ){
18194     case SQLITE_FCNTL_LOCKSTATE: {
18195       *(int*)pArg = ((os2File*)id)->locktype;
18196       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
18197       return SQLITE_OK;
18198     }
18199   }
18200   return SQLITE_ERROR;
18201 }
18202
18203 /*
18204 ** Return the sector size in bytes of the underlying block device for
18205 ** the specified file. This is almost always 512 bytes, but may be
18206 ** larger for some devices.
18207 **
18208 ** SQLite code assumes this function cannot fail. It also assumes that
18209 ** if two files are created in the same file-system directory (i.e.
18210 ** a database and its journal file) that the sector size will be the
18211 ** same for both.
18212 */
18213 static int os2SectorSize(sqlite3_file *id){
18214   return SQLITE_DEFAULT_SECTOR_SIZE;
18215 }
18216
18217 /*
18218 ** Return a vector of device characteristics.
18219 */
18220 static int os2DeviceCharacteristics(sqlite3_file *id){
18221   return 0;
18222 }
18223
18224 /*
18225 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
18226 ** The two-step process: first convert the incoming UTF-8 string
18227 ** into UCS-2 and then from UCS-2 to the current codepage.
18228 ** The returned char pointer has to be freed.
18229 */
18230 char *convertUtf8PathToCp(const char *in)
18231 {
18232   UconvObject uconv;
18233   UniChar ucsUtf8Cp[12],
18234           tempPath[CCHMAXPATH];
18235   char *out;
18236   int rc = 0;
18237
18238   out = (char *)calloc(CCHMAXPATH, 1);
18239
18240   /* determine string for the conversion of UTF-8 which is CP1208 */
18241   rc = UniMapCpToUcsCp(1208, ucsUtf8Cp, 12);
18242   rc = UniCreateUconvObject(ucsUtf8Cp, &uconv);
18243   rc = UniStrToUcs(uconv, tempPath, (char *)in, CCHMAXPATH);
18244   rc = UniFreeUconvObject(uconv);
18245
18246   /* conversion for current codepage which can be used for paths */
18247   rc = UniCreateUconvObject((UniChar *)L"@path=yes", &uconv);
18248   rc = UniStrFromUcs(uconv, out, tempPath, CCHMAXPATH);
18249   rc = UniFreeUconvObject(uconv);
18250
18251   return out;
18252 }
18253
18254 /*
18255 ** Helper function to convert filenames from local codepage to UTF-8.
18256 ** The two-step process: first convert the incoming codepage-specific
18257 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
18258 ** The returned char pointer has to be freed.
18259 */
18260 char *convertCpPathToUtf8(const char *in)
18261 {
18262   UconvObject uconv;
18263   UniChar ucsUtf8Cp[12],
18264           tempPath[CCHMAXPATH];
18265   char *out;
18266   int rc = 0;
18267
18268   out = (char *)calloc(CCHMAXPATH, 1);
18269
18270   /* conversion for current codepage which can be used for paths */
18271   rc = UniCreateUconvObject((UniChar *)L"@path=yes", &uconv);
18272   rc = UniStrToUcs(uconv, tempPath, (char *)in, CCHMAXPATH);
18273   rc = UniFreeUconvObject(uconv);
18274
18275   /* determine string for the conversion of UTF-8 which is CP1208 */
18276   rc = UniMapCpToUcsCp(1208, ucsUtf8Cp, 12);
18277   rc = UniCreateUconvObject(ucsUtf8Cp, &uconv);
18278   rc = UniStrFromUcs(uconv, out, tempPath, CCHMAXPATH);
18279   rc = UniFreeUconvObject(uconv);
18280
18281   return out;
18282 }
18283
18284 /*
18285 ** This vector defines all the methods that can operate on an
18286 ** sqlite3_file for os2.
18287 */
18288 static const sqlite3_io_methods os2IoMethod = {
18289   1,                        /* iVersion */
18290   os2Close,
18291   os2Read,
18292   os2Write,
18293   os2Truncate,
18294   os2Sync,
18295   os2FileSize,
18296   os2Lock,
18297   os2Unlock,
18298   os2CheckReservedLock,
18299   os2FileControl,
18300   os2SectorSize,
18301   os2DeviceCharacteristics
18302 };
18303
18304 /***************************************************************************
18305 ** Here ends the I/O methods that form the sqlite3_io_methods object.
18306 **
18307 ** The next block of code implements the VFS methods.
18308 ****************************************************************************/
18309
18310 /*
18311 ** Open a file.
18312 */
18313 static int os2Open(
18314   sqlite3_vfs *pVfs,            /* Not used */
18315   const char *zName,            /* Name of the file */
18316   sqlite3_file *id,             /* Write the SQLite file handle here */
18317   int flags,                    /* Open mode flags */
18318   int *pOutFlags                /* Status return flags */
18319 ){
18320   HFILE h;
18321   ULONG ulFileAttribute = 0;
18322   ULONG ulOpenFlags = 0;
18323   ULONG ulOpenMode = 0;
18324   os2File *pFile = (os2File*)id;
18325   APIRET rc = NO_ERROR;
18326   ULONG ulAction;
18327
18328   memset( pFile, 0, sizeof(*pFile) );
18329
18330   OSTRACE2( "OPEN want %d\n", flags );
18331
18332   //ulOpenMode = flags & SQLITE_OPEN_READWRITE ? OPEN_ACCESS_READWRITE : OPEN_ACCESS_READONLY;
18333   if( flags & SQLITE_OPEN_READWRITE ){
18334     ulOpenMode |= OPEN_ACCESS_READWRITE;
18335     OSTRACE1( "OPEN read/write\n" );
18336   }else{
18337     ulOpenMode |= OPEN_ACCESS_READONLY;
18338     OSTRACE1( "OPEN read only\n" );
18339   }
18340
18341   //ulOpenFlags = flags & SQLITE_OPEN_CREATE ? OPEN_ACTION_CREATE_IF_NEW : OPEN_ACTION_FAIL_IF_NEW;
18342   if( flags & SQLITE_OPEN_CREATE ){
18343     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
18344     OSTRACE1( "OPEN open new/create\n" );
18345   }else{
18346     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
18347     OSTRACE1( "OPEN open existing\n" );
18348   }
18349
18350   //ulOpenMode |= flags & SQLITE_OPEN_MAIN_DB ? OPEN_SHARE_DENYNONE : OPEN_SHARE_DENYWRITE;
18351   if( flags & SQLITE_OPEN_MAIN_DB ){
18352     ulOpenMode |= OPEN_SHARE_DENYNONE;
18353     OSTRACE1( "OPEN share read/write\n" );
18354   }else{
18355     ulOpenMode |= OPEN_SHARE_DENYWRITE;
18356     OSTRACE1( "OPEN share read only\n" );
18357   }
18358
18359   if( flags & (SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_TEMP_JOURNAL
18360                | SQLITE_OPEN_SUBJOURNAL) ){
18361     char pathUtf8[CCHMAXPATH];
18362     //ulFileAttribute = FILE_HIDDEN;  //for debugging, we want to make sure it is deleted
18363     ulFileAttribute = FILE_NORMAL;
18364     sqlite3OsFullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
18365     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
18366     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
18367   }else{
18368     ulFileAttribute = FILE_ARCHIVED | FILE_NORMAL;
18369     pFile->pathToDel = NULL;
18370     OSTRACE1( "OPEN normal file attribute\n" );
18371   }
18372
18373   /* always open in random access mode for possibly better speed */
18374   ulOpenMode |= OPEN_FLAGS_RANDOM;
18375   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
18376   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
18377
18378   char *zNameCp = convertUtf8PathToCp( zName );
18379   rc = DosOpen( (PSZ)zNameCp,
18380                 &h,
18381                 &ulAction,
18382                 0L,
18383                 ulFileAttribute,
18384                 ulOpenFlags,
18385                 ulOpenMode,
18386                 (PEAOP2)NULL );
18387   free( zNameCp );
18388   if( rc != NO_ERROR ){
18389     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
18390               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
18391     free( pFile->pathToDel );
18392     pFile->pathToDel = NULL;
18393     if( flags & SQLITE_OPEN_READWRITE ){
18394       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
18395       return os2Open( 0, zName, id,
18396                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
18397                       pOutFlags );
18398     }else{
18399       return SQLITE_CANTOPEN;
18400     }
18401   }
18402
18403   if( pOutFlags ){
18404     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
18405   }
18406
18407   pFile->pMethod = &os2IoMethod;
18408   pFile->h = h;
18409   OpenCounter(+1);
18410   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
18411   return SQLITE_OK;
18412 }
18413
18414 /*
18415 ** Delete the named file.
18416 */
18417 int os2Delete(
18418   sqlite3_vfs *pVfs,                     /* Not used on os2 */
18419   const char *zFilename,                 /* Name of file to delete */
18420   int syncDir                            /* Not used on os2 */
18421 ){
18422   APIRET rc = NO_ERROR;
18423   SimulateIOError(return SQLITE_IOERR_DELETE);
18424   char *zFilenameCp = convertUtf8PathToCp( zFilename );
18425   rc = DosDelete( (PSZ)zFilenameCp );
18426   free( zFilenameCp );
18427   OSTRACE2( "DELETE \"%s\"\n", zFilename );
18428   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
18429 }
18430
18431 /*
18432 ** Check the existance and status of a file.
18433 */
18434 static int os2Access(
18435   sqlite3_vfs *pVfs,        /* Not used on os2 */
18436   const char *zFilename,    /* Name of file to check */
18437   int flags                 /* Type of test to make on this file */
18438 ){
18439   FILESTATUS3 fsts3ConfigInfo;
18440   APIRET rc = NO_ERROR;
18441
18442   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
18443   char *zFilenameCp = convertUtf8PathToCp( zFilename );
18444   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
18445                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
18446   free( zFilenameCp );
18447   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
18448             fsts3ConfigInfo.attrFile, flags, rc );
18449   switch( flags ){
18450     case SQLITE_ACCESS_READ:
18451     case SQLITE_ACCESS_EXISTS:
18452       rc = (rc == NO_ERROR);
18453       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
18454       break;
18455     case SQLITE_ACCESS_READWRITE:
18456       rc = (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0;
18457       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
18458       break;
18459     default:
18460       assert( !"Invalid flags argument" );
18461   }
18462   return rc;
18463 }
18464
18465
18466 /*
18467 ** Create a temporary file name in zBuf.  zBuf must be big enough to
18468 ** hold at pVfs->mxPathname characters.
18469 */
18470 static int os2GetTempname( sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
18471   static const unsigned char zChars[] =
18472     "abcdefghijklmnopqrstuvwxyz"
18473     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
18474     "0123456789";
18475   int i, j;
18476   char zTempPathBuf[3];
18477   PSZ zTempPath = (PSZ)&zTempPathBuf;
18478   char *zTempPathUTF;
18479   if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
18480     if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
18481       if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
18482            ULONG ulDriveNum = 0, ulDriveMap = 0;
18483            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
18484            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
18485       }
18486     }
18487   }
18488   /* strip off a trailing slashes or backslashes, otherwise we would get *
18489    * multiple (back)slashes which causes DosOpen() to fail               */
18490   j = strlen(zTempPath);
18491   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ) ){
18492     j--;
18493   }
18494   zTempPath[j] = '\0';
18495   zTempPathUTF = convertCpPathToUtf8( zTempPath );
18496   sqlite3_snprintf( nBuf-30, zBuf,
18497                     "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
18498   free( zTempPathUTF );
18499   j = strlen( zBuf );
18500   sqlite3_randomness( 20, &zBuf[j] );
18501   for( i = 0; i < 20; i++, j++ ){
18502     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
18503   }
18504   zBuf[j] = 0;
18505   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
18506   return SQLITE_OK;
18507 }
18508
18509
18510 /*
18511 ** Turn a relative pathname into a full pathname.  Write the full
18512 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
18513 ** bytes in size.
18514 */
18515 static int os2FullPathname(
18516   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
18517   const char *zRelative,      /* Possibly relative input path */
18518   int nFull,                  /* Size of output buffer in bytes */
18519   char *zFull                 /* Output buffer */
18520 ){
18521   char *zRelativeCp = convertUtf8PathToCp( zRelative );
18522   char zFullCp[CCHMAXPATH];
18523   char *zFullUTF;
18524   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
18525                                 CCHMAXPATH );
18526   free( zRelativeCp );
18527   zFullUTF = convertCpPathToUtf8( zFullCp );
18528   sqlite3_snprintf( nFull, zFull, zFullUTF );
18529   free( zFullUTF );
18530   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
18531 }
18532
18533 #ifndef SQLITE_OMIT_LOAD_EXTENSION
18534 /*
18535 ** Interfaces for opening a shared library, finding entry points
18536 ** within the shared library, and closing the shared library.
18537 */
18538 /*
18539 ** Interfaces for opening a shared library, finding entry points
18540 ** within the shared library, and closing the shared library.
18541 */
18542 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
18543   UCHAR loadErr[256];
18544   HMODULE hmod;
18545   APIRET rc;
18546   char *zFilenameCp = convertUtf8PathToCp(zFilename);
18547   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
18548   free(zFilenameCp);
18549   return rc != NO_ERROR ? 0 : (void*)hmod;
18550 }
18551 /*
18552 ** A no-op since the error code is returned on the DosLoadModule call.
18553 ** os2Dlopen returns zero if DosLoadModule is not successful.
18554 */
18555 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
18556 /* no-op */
18557 }
18558 void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
18559   PFN pfn;
18560   APIRET rc;
18561   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
18562   if( rc != NO_ERROR ){
18563     /* if the symbol itself was not found, search again for the same
18564      * symbol with an extra underscore, that might be needed depending
18565      * on the calling convention */
18566     char _zSymbol[256] = "_";
18567     strncat(_zSymbol, zSymbol, 255);
18568     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
18569   }
18570   return rc != NO_ERROR ? 0 : (void*)pfn;
18571 }
18572 void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
18573   DosFreeModule((HMODULE)pHandle);
18574 }
18575 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
18576   #define os2DlOpen 0
18577   #define os2DlError 0
18578   #define os2DlSym 0
18579   #define os2DlClose 0
18580 #endif
18581
18582
18583 /*
18584 ** Write up to nBuf bytes of randomness into zBuf.
18585 */
18586 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
18587   ULONG sizeofULong = sizeof(ULONG);
18588   int n = 0;
18589   if( sizeof(DATETIME) <= nBuf - n ){
18590     DATETIME x;
18591     DosGetDateTime(&x);
18592     memcpy(&zBuf[n], &x, sizeof(x));
18593     n += sizeof(x);
18594   }
18595
18596   if( sizeofULong <= nBuf - n ){
18597     PPIB ppib;
18598     DosGetInfoBlocks(NULL, &ppib);
18599     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
18600     n += sizeofULong;
18601   }
18602
18603   if( sizeofULong <= nBuf - n ){
18604     PTIB ptib;
18605     DosGetInfoBlocks(&ptib, NULL);
18606     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
18607     n += sizeofULong;
18608   }
18609
18610   /* if we still haven't filled the buffer yet the following will */
18611   /* grab everything once instead of making several calls for a single item */
18612   if( sizeofULong <= nBuf - n ){
18613     ULONG ulSysInfo[QSV_MAX];
18614     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
18615
18616     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
18617     n += sizeofULong;
18618
18619     if( sizeofULong <= nBuf - n ){
18620       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
18621       n += sizeofULong;
18622     }
18623     if( sizeofULong <= nBuf - n ){
18624       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
18625       n += sizeofULong;
18626     }
18627     if( sizeofULong <= nBuf - n ){
18628       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
18629       n += sizeofULong;
18630     }
18631     if( sizeofULong <= nBuf - n ){
18632       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
18633       n += sizeofULong;
18634     }
18635   }
18636
18637   return n;
18638 }
18639
18640 /*
18641 ** Sleep for a little while.  Return the amount of time slept.
18642 ** The argument is the number of microseconds we want to sleep.
18643 ** The return value is the number of microseconds of sleep actually
18644 ** requested from the underlying operating system, a number which
18645 ** might be greater than or equal to the argument, but not less
18646 ** than the argument.
18647 */
18648 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
18649   DosSleep( (microsec/1000) );
18650   return microsec;
18651 }
18652
18653 /*
18654 ** The following variable, if set to a non-zero value, becomes the result
18655 ** returned from sqlite3OsCurrentTime().  This is used for testing.
18656 */
18657 #ifdef SQLITE_TEST
18658 SQLITE_API int sqlite3_current_time = 0;
18659 #endif
18660
18661 /*
18662 ** Find the current time (in Universal Coordinated Time).  Write the
18663 ** current time and date as a Julian Day number into *prNow and
18664 ** return 0.  Return 1 if the time and date cannot be found.
18665 */
18666 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
18667   double now;
18668   SHORT minute; /* needs to be able to cope with negative timezone offset */
18669   USHORT second, hour,
18670          day, month, year;
18671   DATETIME dt;
18672   DosGetDateTime( &dt );
18673   second = (USHORT)dt.seconds;
18674   minute = (SHORT)dt.minutes + dt.timezone;
18675   hour = (USHORT)dt.hours;
18676   day = (USHORT)dt.day;
18677   month = (USHORT)dt.month;
18678   year = (USHORT)dt.year;
18679
18680   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
18681      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
18682   /* Calculate the Julian days */
18683   now = day - 32076 +
18684     1461*(year + 4800 + (month - 14)/12)/4 +
18685     367*(month - 2 - (month - 14)/12*12)/12 -
18686     3*((year + 4900 + (month - 14)/12)/100)/4;
18687
18688   /* Add the fractional hours, mins and seconds */
18689   now += (hour + 12.0)/24.0;
18690   now += minute/1440.0;
18691   now += second/86400.0;
18692   *prNow = now;
18693 #ifdef SQLITE_TEST
18694   if( sqlite3_current_time ){
18695     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
18696   }
18697 #endif
18698   return 0;
18699 }
18700
18701 /*
18702 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
18703 ** a function rather than give the structure global scope because
18704 ** some compilers (MSVC) do not allow forward declarations of
18705 ** initialized structures.
18706 */
18707 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
18708   static sqlite3_vfs os2Vfs = {
18709     1,                 /* iVersion */
18710     sizeof(os2File),   /* szOsFile */
18711     CCHMAXPATH,        /* mxPathname */
18712     0,                 /* pNext */
18713     "os2",             /* zName */
18714     0,                 /* pAppData */
18715
18716     os2Open,           /* xOpen */
18717     os2Delete,         /* xDelete */
18718     os2Access,         /* xAccess */
18719     os2GetTempname,    /* xGetTempname */
18720     os2FullPathname,   /* xFullPathname */
18721     os2DlOpen,         /* xDlOpen */
18722     os2DlError,        /* xDlError */
18723     os2DlSym,          /* xDlSym */
18724     os2DlClose,        /* xDlClose */
18725     os2Randomness,     /* xRandomness */
18726     os2Sleep,          /* xSleep */
18727     os2CurrentTime     /* xCurrentTime */
18728   };
18729
18730   return &os2Vfs;
18731 }
18732
18733 #endif /* OS_OS2 */
18734
18735 /************** End of os_os2.c **********************************************/
18736 /************** Begin file os_unix.c *****************************************/
18737 /*
18738 ** 2004 May 22
18739 **
18740 ** The author disclaims copyright to this source code.  In place of
18741 ** a legal notice, here is a blessing:
18742 **
18743 **    May you do good and not evil.
18744 **    May you find forgiveness for yourself and forgive others.
18745 **    May you share freely, never taking more than you give.
18746 **
18747 ******************************************************************************
18748 **
18749 ** This file contains code that is specific to Unix systems.
18750 */
18751 #if OS_UNIX              /* This file is used on unix only */
18752
18753 /* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
18754
18755 /*
18756 ** These #defines should enable >2GB file support on Posix if the
18757 ** underlying operating system supports it.  If the OS lacks
18758 ** large file support, these should be no-ops.
18759 **
18760 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
18761 ** on the compiler command line.  This is necessary if you are compiling
18762 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
18763 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
18764 ** without this option, LFS is enable.  But LFS does not exist in the kernel
18765 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
18766 ** portability you should omit LFS.
18767 */
18768 #ifndef SQLITE_DISABLE_LFS
18769 # define _LARGE_FILE       1
18770 # ifndef _FILE_OFFSET_BITS
18771 #   define _FILE_OFFSET_BITS 64
18772 # endif
18773 # define _LARGEFILE_SOURCE 1
18774 #endif
18775
18776 /*
18777 ** standard include files.
18778 */
18779 #include <sys/types.h>
18780 #include <sys/stat.h>
18781 #include <fcntl.h>
18782 #include <unistd.h>
18783 #include <sys/time.h>
18784 #include <errno.h>
18785 #ifdef SQLITE_ENABLE_LOCKING_STYLE
18786 #include <sys/ioctl.h>
18787 #include <sys/param.h>
18788 #include <sys/mount.h>
18789 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
18790
18791 /*
18792 ** If we are to be thread-safe, include the pthreads header and define
18793 ** the SQLITE_UNIX_THREADS macro.
18794 */
18795 #if SQLITE_THREADSAFE
18796 # define SQLITE_UNIX_THREADS 1
18797 #endif
18798
18799 /*
18800 ** Default permissions when creating a new file
18801 */
18802 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
18803 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
18804 #endif
18805
18806 /*
18807 ** Maximum supported path-length.
18808 */
18809 #define MAX_PATHNAME 512
18810
18811
18812 /*
18813 ** The unixFile structure is subclass of sqlite3_file specific for the unix
18814 ** protability layer.
18815 */
18816 typedef struct unixFile unixFile;
18817 struct unixFile {
18818   sqlite3_io_methods const *pMethod;  /* Always the first entry */
18819 #ifdef SQLITE_TEST
18820   /* In test mode, increase the size of this structure a bit so that 
18821   ** it is larger than the struct CrashFile defined in test6.c.
18822   */
18823   char aPadding[32];
18824 #endif
18825   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
18826   struct lockInfo *pLock;   /* Info about locks on this inode */
18827 #ifdef SQLITE_ENABLE_LOCKING_STYLE
18828   void *lockingContext;     /* Locking style specific state */
18829 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
18830   int h;                    /* The file descriptor */
18831   unsigned char locktype;   /* The type of lock held on this fd */
18832   int dirfd;                /* File descriptor for the directory */
18833 #if SQLITE_THREADSAFE
18834   pthread_t tid;            /* The thread that "owns" this unixFile */
18835 #endif
18836 };
18837
18838 /*
18839 ** Include code that is common to all os_*.c files
18840 */
18841 /************** Include os_common.h in the middle of os_unix.c ***************/
18842 /************** Begin file os_common.h ***************************************/
18843 /*
18844 ** 2004 May 22
18845 **
18846 ** The author disclaims copyright to this source code.  In place of
18847 ** a legal notice, here is a blessing:
18848 **
18849 **    May you do good and not evil.
18850 **    May you find forgiveness for yourself and forgive others.
18851 **    May you share freely, never taking more than you give.
18852 **
18853 ******************************************************************************
18854 **
18855 ** This file contains macros and a little bit of code that is common to
18856 ** all of the platform-specific files (os_*.c) and is #included into those
18857 ** files.
18858 **
18859 ** This file should be #included by the os_*.c files only.  It is not a
18860 ** general purpose header file.
18861 */
18862
18863 /*
18864 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
18865 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
18866 ** switch.  The following code should catch this problem at compile-time.
18867 */
18868 #ifdef MEMORY_DEBUG
18869 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
18870 #endif
18871
18872
18873 /*
18874  * When testing, this global variable stores the location of the
18875  * pending-byte in the database file.
18876  */
18877 #ifdef SQLITE_TEST
18878 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
18879 #endif
18880
18881 #ifdef SQLITE_DEBUG
18882 SQLITE_PRIVATE int sqlite3OSTrace = 0;
18883 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
18884 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
18885 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
18886 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
18887 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
18888 #define OSTRACE6(X,Y,Z,A,B,C) \
18889     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
18890 #define OSTRACE7(X,Y,Z,A,B,C,D) \
18891     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
18892 #else
18893 #define OSTRACE1(X)
18894 #define OSTRACE2(X,Y)
18895 #define OSTRACE3(X,Y,Z)
18896 #define OSTRACE4(X,Y,Z,A)
18897 #define OSTRACE5(X,Y,Z,A,B)
18898 #define OSTRACE6(X,Y,Z,A,B,C)
18899 #define OSTRACE7(X,Y,Z,A,B,C,D)
18900 #endif
18901
18902 /*
18903 ** Macros for performance tracing.  Normally turned off.  Only works
18904 ** on i486 hardware.
18905 */
18906 #ifdef SQLITE_PERFORMANCE_TRACE
18907 __inline__ unsigned long long int hwtime(void){
18908   unsigned long long int x;
18909   __asm__("rdtsc\n\t"
18910           "mov %%edx, %%ecx\n\t"
18911           :"=A" (x));
18912   return x;
18913 }
18914 static unsigned long long int g_start;
18915 static unsigned int elapse;
18916 #define TIMER_START       g_start=hwtime()
18917 #define TIMER_END         elapse=hwtime()-g_start
18918 #define TIMER_ELAPSED     elapse
18919 #else
18920 #define TIMER_START
18921 #define TIMER_END
18922 #define TIMER_ELAPSED     0
18923 #endif
18924
18925 /*
18926 ** If we compile with the SQLITE_TEST macro set, then the following block
18927 ** of code will give us the ability to simulate a disk I/O error.  This
18928 ** is used for testing the I/O recovery logic.
18929 */
18930 #ifdef SQLITE_TEST
18931 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
18932 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
18933 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
18934 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
18935 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
18936 SQLITE_API int sqlite3_diskfull_pending = 0;
18937 SQLITE_API int sqlite3_diskfull = 0;
18938 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
18939 #define SimulateIOError(CODE)  \
18940   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
18941        || sqlite3_io_error_pending-- == 1 )  \
18942               { local_ioerr(); CODE; }
18943 static void local_ioerr(){
18944   IOTRACE(("IOERR\n"));
18945   sqlite3_io_error_hit++;
18946   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
18947 }
18948 #define SimulateDiskfullError(CODE) \
18949    if( sqlite3_diskfull_pending ){ \
18950      if( sqlite3_diskfull_pending == 1 ){ \
18951        local_ioerr(); \
18952        sqlite3_diskfull = 1; \
18953        sqlite3_io_error_hit = 1; \
18954        CODE; \
18955      }else{ \
18956        sqlite3_diskfull_pending--; \
18957      } \
18958    }
18959 #else
18960 #define SimulateIOErrorBenign(X)
18961 #define SimulateIOError(A)
18962 #define SimulateDiskfullError(A)
18963 #endif
18964
18965 /*
18966 ** When testing, keep a count of the number of open files.
18967 */
18968 #ifdef SQLITE_TEST
18969 SQLITE_API int sqlite3_open_file_count = 0;
18970 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
18971 #else
18972 #define OpenCounter(X)
18973 #endif
18974
18975 /************** End of os_common.h *******************************************/
18976 /************** Continuing where we left off in os_unix.c ********************/
18977
18978 /*
18979 ** Define various macros that are missing from some systems.
18980 */
18981 #ifndef O_LARGEFILE
18982 # define O_LARGEFILE 0
18983 #endif
18984 #ifdef SQLITE_DISABLE_LFS
18985 # undef O_LARGEFILE
18986 # define O_LARGEFILE 0
18987 #endif
18988 #ifndef O_NOFOLLOW
18989 # define O_NOFOLLOW 0
18990 #endif
18991 #ifndef O_BINARY
18992 # define O_BINARY 0
18993 #endif
18994
18995 /*
18996 ** The DJGPP compiler environment looks mostly like Unix, but it
18997 ** lacks the fcntl() system call.  So redefine fcntl() to be something
18998 ** that always succeeds.  This means that locking does not occur under
18999 ** DJGPP.  But it is DOS - what did you expect?
19000 */
19001 #ifdef __DJGPP__
19002 # define fcntl(A,B,C) 0
19003 #endif
19004
19005 /*
19006 ** The threadid macro resolves to the thread-id or to 0.  Used for
19007 ** testing and debugging only.
19008 */
19009 #if SQLITE_THREADSAFE
19010 #define threadid pthread_self()
19011 #else
19012 #define threadid 0
19013 #endif
19014
19015 /*
19016 ** Set or check the unixFile.tid field.  This field is set when an unixFile
19017 ** is first opened.  All subsequent uses of the unixFile verify that the
19018 ** same thread is operating on the unixFile.  Some operating systems do
19019 ** not allow locks to be overridden by other threads and that restriction
19020 ** means that sqlite3* database handles cannot be moved from one thread
19021 ** to another.  This logic makes sure a user does not try to do that
19022 ** by mistake.
19023 **
19024 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
19025 ** another as long as we are running on a system that supports threads
19026 ** overriding each others locks (which now the most common behavior)
19027 ** or if no locks are held.  But the unixFile.pLock field needs to be
19028 ** recomputed because its key includes the thread-id.  See the 
19029 ** transferOwnership() function below for additional information
19030 */
19031 #if SQLITE_THREADSAFE
19032 # define SET_THREADID(X)   (X)->tid = pthread_self()
19033 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
19034                             !pthread_equal((X)->tid, pthread_self()))
19035 #else
19036 # define SET_THREADID(X)
19037 # define CHECK_THREADID(X) 0
19038 #endif
19039
19040 /*
19041 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
19042 ** section 6.5.2.2 lines 483 through 490 specify that when a process
19043 ** sets or clears a lock, that operation overrides any prior locks set
19044 ** by the same process.  It does not explicitly say so, but this implies
19045 ** that it overrides locks set by the same process using a different
19046 ** file descriptor.  Consider this test case:
19047 **
19048 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
19049 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
19050 **
19051 ** Suppose ./file1 and ./file2 are really the same file (because
19052 ** one is a hard or symbolic link to the other) then if you set
19053 ** an exclusive lock on fd1, then try to get an exclusive lock
19054 ** on fd2, it works.  I would have expected the second lock to
19055 ** fail since there was already a lock on the file due to fd1.
19056 ** But not so.  Since both locks came from the same process, the
19057 ** second overrides the first, even though they were on different
19058 ** file descriptors opened on different file names.
19059 **
19060 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
19061 ** that we cannot use POSIX locks to synchronize file access among
19062 ** competing threads of the same process.  POSIX locks will work fine
19063 ** to synchronize access for threads in separate processes, but not
19064 ** threads within the same process.
19065 **
19066 ** To work around the problem, SQLite has to manage file locks internally
19067 ** on its own.  Whenever a new database is opened, we have to find the
19068 ** specific inode of the database file (the inode is determined by the
19069 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
19070 ** and check for locks already existing on that inode.  When locks are
19071 ** created or removed, we have to look at our own internal record of the
19072 ** locks to see if another thread has previously set a lock on that same
19073 ** inode.
19074 **
19075 ** The sqlite3_file structure for POSIX is no longer just an integer file
19076 ** descriptor.  It is now a structure that holds the integer file
19077 ** descriptor and a pointer to a structure that describes the internal
19078 ** locks on the corresponding inode.  There is one locking structure
19079 ** per inode, so if the same inode is opened twice, both unixFile structures
19080 ** point to the same locking structure.  The locking structure keeps
19081 ** a reference count (so we will know when to delete it) and a "cnt"
19082 ** field that tells us its internal lock status.  cnt==0 means the
19083 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
19084 ** cnt>0 means there are cnt shared locks on the file.
19085 **
19086 ** Any attempt to lock or unlock a file first checks the locking
19087 ** structure.  The fcntl() system call is only invoked to set a 
19088 ** POSIX lock if the internal lock structure transitions between
19089 ** a locked and an unlocked state.
19090 **
19091 ** 2004-Jan-11:
19092 ** More recent discoveries about POSIX advisory locks.  (The more
19093 ** I discover, the more I realize the a POSIX advisory locks are
19094 ** an abomination.)
19095 **
19096 ** If you close a file descriptor that points to a file that has locks,
19097 ** all locks on that file that are owned by the current process are
19098 ** released.  To work around this problem, each unixFile structure contains
19099 ** a pointer to an openCnt structure.  There is one openCnt structure
19100 ** per open inode, which means that multiple unixFile can point to a single
19101 ** openCnt.  When an attempt is made to close an unixFile, if there are
19102 ** other unixFile open on the same inode that are holding locks, the call
19103 ** to close() the file descriptor is deferred until all of the locks clear.
19104 ** The openCnt structure keeps a list of file descriptors that need to
19105 ** be closed and that list is walked (and cleared) when the last lock
19106 ** clears.
19107 **
19108 ** First, under Linux threads, because each thread has a separate
19109 ** process ID, lock operations in one thread do not override locks
19110 ** to the same file in other threads.  Linux threads behave like
19111 ** separate processes in this respect.  But, if you close a file
19112 ** descriptor in linux threads, all locks are cleared, even locks
19113 ** on other threads and even though the other threads have different
19114 ** process IDs.  Linux threads is inconsistent in this respect.
19115 ** (I'm beginning to think that linux threads is an abomination too.)
19116 ** The consequence of this all is that the hash table for the lockInfo
19117 ** structure has to include the process id as part of its key because
19118 ** locks in different threads are treated as distinct.  But the 
19119 ** openCnt structure should not include the process id in its
19120 ** key because close() clears lock on all threads, not just the current
19121 ** thread.  Were it not for this goofiness in linux threads, we could
19122 ** combine the lockInfo and openCnt structures into a single structure.
19123 **
19124 ** 2004-Jun-28:
19125 ** On some versions of linux, threads can override each others locks.
19126 ** On others not.  Sometimes you can change the behavior on the same
19127 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
19128 ** POSIX standard is silent as to which behavior is correct, as far
19129 ** as I can tell, so other versions of unix might show the same
19130 ** inconsistency.  There is no little doubt in my mind that posix
19131 ** advisory locks and linux threads are profoundly broken.
19132 **
19133 ** To work around the inconsistencies, we have to test at runtime 
19134 ** whether or not threads can override each others locks.  This test
19135 ** is run once, the first time any lock is attempted.  A static 
19136 ** variable is set to record the results of this test for future
19137 ** use.
19138 */
19139
19140 /*
19141 ** An instance of the following structure serves as the key used
19142 ** to locate a particular lockInfo structure given its inode.
19143 **
19144 ** If threads cannot override each others locks, then we set the
19145 ** lockKey.tid field to the thread ID.  If threads can override
19146 ** each others locks then tid is always set to zero.  tid is omitted
19147 ** if we compile without threading support.
19148 */
19149 struct lockKey {
19150   dev_t dev;       /* Device number */
19151   ino_t ino;       /* Inode number */
19152 #if SQLITE_THREADSAFE
19153   pthread_t tid;   /* Thread ID or zero if threads can override each other */
19154 #endif
19155 };
19156
19157 /*
19158 ** An instance of the following structure is allocated for each open
19159 ** inode on each thread with a different process ID.  (Threads have
19160 ** different process IDs on linux, but not on most other unixes.)
19161 **
19162 ** A single inode can have multiple file descriptors, so each unixFile
19163 ** structure contains a pointer to an instance of this object and this
19164 ** object keeps a count of the number of unixFile pointing to it.
19165 */
19166 struct lockInfo {
19167   struct lockKey key;  /* The lookup key */
19168   int cnt;             /* Number of SHARED locks held */
19169   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
19170   int nRef;            /* Number of pointers to this structure */
19171 };
19172
19173 /*
19174 ** An instance of the following structure serves as the key used
19175 ** to locate a particular openCnt structure given its inode.  This
19176 ** is the same as the lockKey except that the thread ID is omitted.
19177 */
19178 struct openKey {
19179   dev_t dev;   /* Device number */
19180   ino_t ino;   /* Inode number */
19181 };
19182
19183 /*
19184 ** An instance of the following structure is allocated for each open
19185 ** inode.  This structure keeps track of the number of locks on that
19186 ** inode.  If a close is attempted against an inode that is holding
19187 ** locks, the close is deferred until all locks clear by adding the
19188 ** file descriptor to be closed to the pending list.
19189 */
19190 struct openCnt {
19191   struct openKey key;   /* The lookup key */
19192   int nRef;             /* Number of pointers to this structure */
19193   int nLock;            /* Number of outstanding locks */
19194   int nPending;         /* Number of pending close() operations */
19195   int *aPending;        /* Malloced space holding fd's awaiting a close() */
19196 };
19197
19198 /* 
19199 ** These hash tables map inodes and file descriptors (really, lockKey and
19200 ** openKey structures) into lockInfo and openCnt structures.  Access to 
19201 ** these hash tables must be protected by a mutex.
19202 */
19203 static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
19204 static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
19205
19206 #ifdef SQLITE_ENABLE_LOCKING_STYLE
19207 /*
19208 ** The locking styles are associated with the different file locking
19209 ** capabilities supported by different file systems.  
19210 **
19211 ** POSIX locking style fully supports shared and exclusive byte-range locks 
19212 ** ADP locking only supports exclusive byte-range locks
19213 ** FLOCK only supports a single file-global exclusive lock
19214 ** DOTLOCK isn't a true locking style, it refers to the use of a special
19215 **   file named the same as the database file with a '.lock' extension, this
19216 **   can be used on file systems that do not offer any reliable file locking
19217 ** NO locking means that no locking will be attempted, this is only used for
19218 **   read-only file systems currently
19219 ** UNSUPPORTED means that no locking will be attempted, this is only used for
19220 **   file systems that are known to be unsupported
19221 */
19222 typedef enum {
19223   posixLockingStyle = 0,       /* standard posix-advisory locks */
19224   afpLockingStyle,             /* use afp locks */
19225   flockLockingStyle,           /* use flock() */
19226   dotlockLockingStyle,         /* use <file>.lock files */
19227   noLockingStyle,              /* useful for read-only file system */
19228   unsupportedLockingStyle      /* indicates unsupported file system */
19229 } sqlite3LockingStyle;
19230 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
19231
19232 /*
19233 ** Helper functions to obtain and relinquish the global mutex.
19234 */
19235 static void enterMutex(){
19236   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
19237 }
19238 static void leaveMutex(){
19239   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
19240 }
19241
19242 #if SQLITE_THREADSAFE
19243 /*
19244 ** This variable records whether or not threads can override each others
19245 ** locks.
19246 **
19247 **    0:  No.  Threads cannot override each others locks.
19248 **    1:  Yes.  Threads can override each others locks.
19249 **   -1:  We don't know yet.
19250 **
19251 ** On some systems, we know at compile-time if threads can override each
19252 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
19253 ** will be set appropriately.  On other systems, we have to check at
19254 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
19255 ** undefined.
19256 **
19257 ** This variable normally has file scope only.  But during testing, we make
19258 ** it a global so that the test code can change its value in order to verify
19259 ** that the right stuff happens in either case.
19260 */
19261 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
19262 # define SQLITE_THREAD_OVERRIDE_LOCK -1
19263 #endif
19264 #ifdef SQLITE_TEST
19265 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
19266 #else
19267 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
19268 #endif
19269
19270 /*
19271 ** This structure holds information passed into individual test
19272 ** threads by the testThreadLockingBehavior() routine.
19273 */
19274 struct threadTestData {
19275   int fd;                /* File to be locked */
19276   struct flock lock;     /* The locking operation */
19277   int result;            /* Result of the locking operation */
19278 };
19279
19280 #ifdef SQLITE_LOCK_TRACE
19281 /*
19282 ** Print out information about all locking operations.
19283 **
19284 ** This routine is used for troubleshooting locks on multithreaded
19285 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
19286 ** command-line option on the compiler.  This code is normally
19287 ** turned off.
19288 */
19289 static int lockTrace(int fd, int op, struct flock *p){
19290   char *zOpName, *zType;
19291   int s;
19292   int savedErrno;
19293   if( op==F_GETLK ){
19294     zOpName = "GETLK";
19295   }else if( op==F_SETLK ){
19296     zOpName = "SETLK";
19297   }else{
19298     s = fcntl(fd, op, p);
19299     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
19300     return s;
19301   }
19302   if( p->l_type==F_RDLCK ){
19303     zType = "RDLCK";
19304   }else if( p->l_type==F_WRLCK ){
19305     zType = "WRLCK";
19306   }else if( p->l_type==F_UNLCK ){
19307     zType = "UNLCK";
19308   }else{
19309     assert( 0 );
19310   }
19311   assert( p->l_whence==SEEK_SET );
19312   s = fcntl(fd, op, p);
19313   savedErrno = errno;
19314   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
19315      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
19316      (int)p->l_pid, s);
19317   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
19318     struct flock l2;
19319     l2 = *p;
19320     fcntl(fd, F_GETLK, &l2);
19321     if( l2.l_type==F_RDLCK ){
19322       zType = "RDLCK";
19323     }else if( l2.l_type==F_WRLCK ){
19324       zType = "WRLCK";
19325     }else if( l2.l_type==F_UNLCK ){
19326       zType = "UNLCK";
19327     }else{
19328       assert( 0 );
19329     }
19330     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
19331        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
19332   }
19333   errno = savedErrno;
19334   return s;
19335 }
19336 #define fcntl lockTrace
19337 #endif /* SQLITE_LOCK_TRACE */
19338
19339 /*
19340 ** The testThreadLockingBehavior() routine launches two separate
19341 ** threads on this routine.  This routine attempts to lock a file
19342 ** descriptor then returns.  The success or failure of that attempt
19343 ** allows the testThreadLockingBehavior() procedure to determine
19344 ** whether or not threads can override each others locks.
19345 */
19346 static void *threadLockingTest(void *pArg){
19347   struct threadTestData *pData = (struct threadTestData*)pArg;
19348   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
19349   return pArg;
19350 }
19351
19352 /*
19353 ** This procedure attempts to determine whether or not threads
19354 ** can override each others locks then sets the 
19355 ** threadsOverrideEachOthersLocks variable appropriately.
19356 */
19357 static void testThreadLockingBehavior(int fd_orig){
19358   int fd;
19359   struct threadTestData d[2];
19360   pthread_t t[2];
19361
19362   fd = dup(fd_orig);
19363   if( fd<0 ) return;
19364   memset(d, 0, sizeof(d));
19365   d[0].fd = fd;
19366   d[0].lock.l_type = F_RDLCK;
19367   d[0].lock.l_len = 1;
19368   d[0].lock.l_start = 0;
19369   d[0].lock.l_whence = SEEK_SET;
19370   d[1] = d[0];
19371   d[1].lock.l_type = F_WRLCK;
19372   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
19373   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
19374   pthread_join(t[0], 0);
19375   pthread_join(t[1], 0);
19376   close(fd);
19377   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
19378 }
19379 #endif /* SQLITE_THREADSAFE */
19380
19381 /*
19382 ** Release a lockInfo structure previously allocated by findLockInfo().
19383 */
19384 static void releaseLockInfo(struct lockInfo *pLock){
19385   if (pLock == NULL)
19386     return;
19387   pLock->nRef--;
19388   if( pLock->nRef==0 ){
19389     sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
19390     sqlite3_free(pLock);
19391   }
19392 }
19393
19394 /*
19395 ** Release a openCnt structure previously allocated by findLockInfo().
19396 */
19397 static void releaseOpenCnt(struct openCnt *pOpen){
19398   if (pOpen == NULL)
19399     return;
19400   pOpen->nRef--;
19401   if( pOpen->nRef==0 ){
19402     sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
19403     free(pOpen->aPending);
19404     sqlite3_free(pOpen);
19405   }
19406 }
19407
19408 #ifdef SQLITE_ENABLE_LOCKING_STYLE
19409 /*
19410 ** Tests a byte-range locking query to see if byte range locks are 
19411 ** supported, if not we fall back to dotlockLockingStyle.
19412 */
19413 static sqlite3LockingStyle sqlite3TestLockingStyle(
19414   const char *filePath, 
19415   int fd
19416 ){
19417   /* test byte-range lock using fcntl */
19418   struct flock lockInfo;
19419   
19420   lockInfo.l_len = 1;
19421   lockInfo.l_start = 0;
19422   lockInfo.l_whence = SEEK_SET;
19423   lockInfo.l_type = F_RDLCK;
19424   
19425   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
19426     return posixLockingStyle;
19427   } 
19428   
19429   /* testing for flock can give false positives.  So if if the above test
19430   ** fails, then we fall back to using dot-lock style locking.
19431   */  
19432   return dotlockLockingStyle;
19433 }
19434
19435 /* 
19436 ** Examines the f_fstypename entry in the statfs structure as returned by 
19437 ** stat() for the file system hosting the database file, assigns the 
19438 ** appropriate locking style based on its value.  These values and 
19439 ** assignments are based on Darwin/OSX behavior and have not been tested on 
19440 ** other systems.
19441 */
19442 static sqlite3LockingStyle sqlite3DetectLockingStyle(
19443   const char *filePath, 
19444   int fd
19445 ){
19446
19447 #ifdef SQLITE_FIXED_LOCKING_STYLE
19448   return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
19449 #else
19450   struct statfs fsInfo;
19451
19452   if( statfs(filePath, &fsInfo) == -1 ){
19453     return sqlite3TestLockingStyle(filePath, fd);
19454   }
19455   if( fsInfo.f_flags & MNT_RDONLY ){
19456     return noLockingStyle;
19457   }
19458   if( strcmp(fsInfo.f_fstypename, "hfs")==0 ||
19459       strcmp(fsInfo.f_fstypename, "ufs")==0 ){
19460     return posixLockingStyle;
19461   }
19462   if( strcmp(fsInfo.f_fstypename, "afpfs")==0 ){
19463     return afpLockingStyle;
19464   }
19465   if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
19466     return sqlite3TestLockingStyle(filePath, fd);
19467   }
19468   if( strcmp(fsInfo.f_fstypename, "smbfs")==0 ){
19469     return flockLockingStyle;
19470   }
19471   if( strcmp(fsInfo.f_fstypename, "msdos")==0 ){
19472     return dotlockLockingStyle;
19473   }
19474   if( strcmp(fsInfo.f_fstypename, "webdav")==0 ){
19475     return unsupportedLockingStyle;
19476   }
19477   return sqlite3TestLockingStyle(filePath, fd);  
19478 #endif /* SQLITE_FIXED_LOCKING_STYLE */
19479 }
19480
19481 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
19482
19483 /*
19484 ** Given a file descriptor, locate lockInfo and openCnt structures that
19485 ** describes that file descriptor.  Create new ones if necessary.  The
19486 ** return values might be uninitialized if an error occurs.
19487 **
19488 ** Return an appropriate error code.
19489 */
19490 static int findLockInfo(
19491   int fd,                      /* The file descriptor used in the key */
19492   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
19493   struct openCnt **ppOpen      /* Return the openCnt structure here */
19494 ){
19495   int rc;
19496   struct lockKey key1;
19497   struct openKey key2;
19498   struct stat statbuf;
19499   struct lockInfo *pLock;
19500   struct openCnt *pOpen;
19501   rc = fstat(fd, &statbuf);
19502   if( rc!=0 ){
19503 #ifdef EOVERFLOW
19504     if( errno==EOVERFLOW ) return SQLITE_NOLFS;
19505 #endif
19506     return SQLITE_IOERR;
19507   }
19508
19509   memset(&key1, 0, sizeof(key1));
19510   key1.dev = statbuf.st_dev;
19511   key1.ino = statbuf.st_ino;
19512 #if SQLITE_THREADSAFE
19513   if( threadsOverrideEachOthersLocks<0 ){
19514     testThreadLockingBehavior(fd);
19515   }
19516   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
19517 #endif
19518   memset(&key2, 0, sizeof(key2));
19519   key2.dev = statbuf.st_dev;
19520   key2.ino = statbuf.st_ino;
19521   pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
19522   if( pLock==0 ){
19523     struct lockInfo *pOld;
19524     pLock = sqlite3_malloc( sizeof(*pLock) );
19525     if( pLock==0 ){
19526       rc = SQLITE_NOMEM;
19527       goto exit_findlockinfo;
19528     }
19529     pLock->key = key1;
19530     pLock->nRef = 1;
19531     pLock->cnt = 0;
19532     pLock->locktype = 0;
19533     pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
19534     if( pOld!=0 ){
19535       assert( pOld==pLock );
19536       sqlite3_free(pLock);
19537       rc = SQLITE_NOMEM;
19538       goto exit_findlockinfo;
19539     }
19540   }else{
19541     pLock->nRef++;
19542   }
19543   *ppLock = pLock;
19544   if( ppOpen!=0 ){
19545     pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
19546     if( pOpen==0 ){
19547       struct openCnt *pOld;
19548       pOpen = sqlite3_malloc( sizeof(*pOpen) );
19549       if( pOpen==0 ){
19550         releaseLockInfo(pLock);
19551         rc = SQLITE_NOMEM;
19552         goto exit_findlockinfo;
19553       }
19554       pOpen->key = key2;
19555       pOpen->nRef = 1;
19556       pOpen->nLock = 0;
19557       pOpen->nPending = 0;
19558       pOpen->aPending = 0;
19559       pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
19560       if( pOld!=0 ){
19561         assert( pOld==pOpen );
19562         sqlite3_free(pOpen);
19563         releaseLockInfo(pLock);
19564         rc = SQLITE_NOMEM;
19565         goto exit_findlockinfo;
19566       }
19567     }else{
19568       pOpen->nRef++;
19569     }
19570     *ppOpen = pOpen;
19571   }
19572
19573 exit_findlockinfo:
19574   return rc;
19575 }
19576
19577 #ifdef SQLITE_DEBUG
19578 /*
19579 ** Helper function for printing out trace information from debugging
19580 ** binaries. This returns the string represetation of the supplied
19581 ** integer lock-type.
19582 */
19583 static const char *locktypeName(int locktype){
19584   switch( locktype ){
19585   case NO_LOCK: return "NONE";
19586   case SHARED_LOCK: return "SHARED";
19587   case RESERVED_LOCK: return "RESERVED";
19588   case PENDING_LOCK: return "PENDING";
19589   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
19590   }
19591   return "ERROR";
19592 }
19593 #endif
19594
19595 /*
19596 ** If we are currently in a different thread than the thread that the
19597 ** unixFile argument belongs to, then transfer ownership of the unixFile
19598 ** over to the current thread.
19599 **
19600 ** A unixFile is only owned by a thread on systems where one thread is
19601 ** unable to override locks created by a different thread.  RedHat9 is
19602 ** an example of such a system.
19603 **
19604 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
19605 ** If the unixFile is locked and an ownership is wrong, then return
19606 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
19607 */
19608 #if SQLITE_THREADSAFE
19609 static int transferOwnership(unixFile *pFile){
19610   int rc;
19611   pthread_t hSelf;
19612   if( threadsOverrideEachOthersLocks ){
19613     /* Ownership transfers not needed on this system */
19614     return SQLITE_OK;
19615   }
19616   hSelf = pthread_self();
19617   if( pthread_equal(pFile->tid, hSelf) ){
19618     /* We are still in the same thread */
19619     OSTRACE1("No-transfer, same thread\n");
19620     return SQLITE_OK;
19621   }
19622   if( pFile->locktype!=NO_LOCK ){
19623     /* We cannot change ownership while we are holding a lock! */
19624     return SQLITE_MISUSE;
19625   }
19626   OSTRACE4("Transfer ownership of %d from %d to %d\n",
19627             pFile->h, pFile->tid, hSelf);
19628   pFile->tid = hSelf;
19629   if (pFile->pLock != NULL) {
19630     releaseLockInfo(pFile->pLock);
19631     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
19632     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
19633            locktypeName(pFile->locktype),
19634            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
19635     return rc;
19636   } else {
19637     return SQLITE_OK;
19638   }
19639 }
19640 #else
19641   /* On single-threaded builds, ownership transfer is a no-op */
19642 # define transferOwnership(X) SQLITE_OK
19643 #endif
19644
19645 /*
19646 ** Seek to the offset passed as the second argument, then read cnt 
19647 ** bytes into pBuf. Return the number of bytes actually read.
19648 **
19649 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
19650 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
19651 ** one system to another.  Since SQLite does not define USE_PREAD
19652 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
19653 ** See tickets #2741 and #2681.
19654 */
19655 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
19656   int got;
19657   i64 newOffset;
19658   TIMER_START;
19659 #if defined(USE_PREAD)
19660   got = pread(id->h, pBuf, cnt, offset);
19661   SimulateIOError( got = -1 );
19662 #elif defined(USE_PREAD64)
19663   got = pread64(id->h, pBuf, cnt, offset);
19664   SimulateIOError( got = -1 );
19665 #else
19666   newOffset = lseek(id->h, offset, SEEK_SET);
19667   SimulateIOError( newOffset-- );
19668   if( newOffset!=offset ){
19669     return -1;
19670   }
19671   got = read(id->h, pBuf, cnt);
19672 #endif
19673   TIMER_END;
19674   OSTRACE5("READ    %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
19675   return got;
19676 }
19677
19678 /*
19679 ** Read data from a file into a buffer.  Return SQLITE_OK if all
19680 ** bytes were read successfully and SQLITE_IOERR if anything goes
19681 ** wrong.
19682 */
19683 static int unixRead(
19684   sqlite3_file *id, 
19685   void *pBuf, 
19686   int amt,
19687   sqlite3_int64 offset
19688 ){
19689   int got;
19690   assert( id );
19691   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
19692   if( got==amt ){
19693     return SQLITE_OK;
19694   }else if( got<0 ){
19695     return SQLITE_IOERR_READ;
19696   }else{
19697     memset(&((char*)pBuf)[got], 0, amt-got);
19698     return SQLITE_IOERR_SHORT_READ;
19699   }
19700 }
19701
19702 /*
19703 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
19704 ** Return the number of bytes actually read.  Update the offset.
19705 */
19706 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
19707   int got;
19708   i64 newOffset;
19709   TIMER_START;
19710 #if defined(USE_PREAD)
19711   got = pwrite(id->h, pBuf, cnt, offset);
19712 #elif defined(USE_PREAD64)
19713   got = pwrite64(id->h, pBuf, cnt, offset);
19714 #else
19715   newOffset = lseek(id->h, offset, SEEK_SET);
19716   if( newOffset!=offset ){
19717     return -1;
19718   }
19719   got = write(id->h, pBuf, cnt);
19720 #endif
19721   TIMER_END;
19722   OSTRACE5("WRITE   %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
19723   return got;
19724 }
19725
19726
19727 /*
19728 ** Write data from a buffer into a file.  Return SQLITE_OK on success
19729 ** or some other error code on failure.
19730 */
19731 static int unixWrite(
19732   sqlite3_file *id, 
19733   const void *pBuf, 
19734   int amt,
19735   sqlite3_int64 offset 
19736 ){
19737   int wrote = 0;
19738   assert( id );
19739   assert( amt>0 );
19740   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
19741     amt -= wrote;
19742     offset += wrote;
19743     pBuf = &((char*)pBuf)[wrote];
19744   }
19745   SimulateIOError(( wrote=(-1), amt=1 ));
19746   SimulateDiskfullError(( wrote=0, amt=1 ));
19747   if( amt>0 ){
19748     if( wrote<0 ){
19749       return SQLITE_IOERR_WRITE;
19750     }else{
19751       return SQLITE_FULL;
19752     }
19753   }
19754   return SQLITE_OK;
19755 }
19756
19757 #ifdef SQLITE_TEST
19758 /*
19759 ** Count the number of fullsyncs and normal syncs.  This is used to test
19760 ** that syncs and fullsyncs are occuring at the right times.
19761 */
19762 SQLITE_API int sqlite3_sync_count = 0;
19763 SQLITE_API int sqlite3_fullsync_count = 0;
19764 #endif
19765
19766 /*
19767 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
19768 ** Otherwise use fsync() in its place.
19769 */
19770 #ifndef HAVE_FDATASYNC
19771 # define fdatasync fsync
19772 #endif
19773
19774 /*
19775 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
19776 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
19777 ** only available on Mac OS X.  But that could change.
19778 */
19779 #ifdef F_FULLFSYNC
19780 # define HAVE_FULLFSYNC 1
19781 #else
19782 # define HAVE_FULLFSYNC 0
19783 #endif
19784
19785
19786 /*
19787 ** The fsync() system call does not work as advertised on many
19788 ** unix systems.  The following procedure is an attempt to make
19789 ** it work better.
19790 **
19791 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
19792 ** for testing when we want to run through the test suite quickly.
19793 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
19794 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
19795 ** or power failure will likely corrupt the database file.
19796 */
19797 static int full_fsync(int fd, int fullSync, int dataOnly){
19798   int rc;
19799
19800   /* Record the number of times that we do a normal fsync() and 
19801   ** FULLSYNC.  This is used during testing to verify that this procedure
19802   ** gets called with the correct arguments.
19803   */
19804 #ifdef SQLITE_TEST
19805   if( fullSync ) sqlite3_fullsync_count++;
19806   sqlite3_sync_count++;
19807 #endif
19808
19809   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
19810   ** no-op
19811   */
19812 #ifdef SQLITE_NO_SYNC
19813   rc = SQLITE_OK;
19814 #else
19815
19816 #if HAVE_FULLFSYNC
19817   if( fullSync ){
19818     rc = fcntl(fd, F_FULLFSYNC, 0);
19819   }else{
19820     rc = 1;
19821   }
19822   /* If the FULLFSYNC failed, fall back to attempting an fsync().
19823    * It shouldn't be possible for fullfsync to fail on the local 
19824    * file system (on OSX), so failure indicates that FULLFSYNC
19825    * isn't supported for this file system. So, attempt an fsync 
19826    * and (for now) ignore the overhead of a superfluous fcntl call.  
19827    * It'd be better to detect fullfsync support once and avoid 
19828    * the fcntl call every time sync is called.
19829    */
19830   if( rc ) rc = fsync(fd);
19831
19832 #else 
19833   if( dataOnly ){
19834     rc = fdatasync(fd);
19835   }else{
19836     rc = fsync(fd);
19837   }
19838 #endif /* HAVE_FULLFSYNC */
19839 #endif /* defined(SQLITE_NO_SYNC) */
19840
19841   return rc;
19842 }
19843
19844 /*
19845 ** Make sure all writes to a particular file are committed to disk.
19846 **
19847 ** If dataOnly==0 then both the file itself and its metadata (file
19848 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
19849 ** file data is synced.
19850 **
19851 ** Under Unix, also make sure that the directory entry for the file
19852 ** has been created by fsync-ing the directory that contains the file.
19853 ** If we do not do this and we encounter a power failure, the directory
19854 ** entry for the journal might not exist after we reboot.  The next
19855 ** SQLite to access the file will not know that the journal exists (because
19856 ** the directory entry for the journal was never created) and the transaction
19857 ** will not roll back - possibly leading to database corruption.
19858 */
19859 static int unixSync(sqlite3_file *id, int flags){
19860   int rc;
19861   unixFile *pFile = (unixFile*)id;
19862
19863   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
19864   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
19865
19866   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
19867   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
19868       || (flags&0x0F)==SQLITE_SYNC_FULL
19869   );
19870
19871   assert( pFile );
19872   OSTRACE2("SYNC    %-3d\n", pFile->h);
19873   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
19874   SimulateIOError( rc=1 );
19875   if( rc ){
19876     return SQLITE_IOERR_FSYNC;
19877   }
19878   if( pFile->dirfd>=0 ){
19879     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
19880             HAVE_FULLFSYNC, isFullsync);
19881 #ifndef SQLITE_DISABLE_DIRSYNC
19882     /* The directory sync is only attempted if full_fsync is
19883     ** turned off or unavailable.  If a full_fsync occurred above,
19884     ** then the directory sync is superfluous.
19885     */
19886     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
19887        /*
19888        ** We have received multiple reports of fsync() returning
19889        ** errors when applied to directories on certain file systems.
19890        ** A failed directory sync is not a big deal.  So it seems
19891        ** better to ignore the error.  Ticket #1657
19892        */
19893        /* return SQLITE_IOERR; */
19894     }
19895 #endif
19896     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
19897     pFile->dirfd = -1;    /* when we are done. */
19898   }
19899   return SQLITE_OK;
19900 }
19901
19902 /*
19903 ** Truncate an open file to a specified size
19904 */
19905 static int unixTruncate(sqlite3_file *id, i64 nByte){
19906   int rc;
19907   assert( id );
19908   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
19909   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
19910   if( rc ){
19911     return SQLITE_IOERR_TRUNCATE;
19912   }else{
19913     return SQLITE_OK;
19914   }
19915 }
19916
19917 /*
19918 ** Determine the current size of a file in bytes
19919 */
19920 static int unixFileSize(sqlite3_file *id, i64 *pSize){
19921   int rc;
19922   struct stat buf;
19923   assert( id );
19924   rc = fstat(((unixFile*)id)->h, &buf);
19925   SimulateIOError( rc=1 );
19926   if( rc!=0 ){
19927     return SQLITE_IOERR_FSTAT;
19928   }
19929   *pSize = buf.st_size;
19930   return SQLITE_OK;
19931 }
19932
19933 /*
19934 ** This routine checks if there is a RESERVED lock held on the specified
19935 ** file by this or any other process. If such a lock is held, return
19936 ** non-zero.  If the file is unlocked or holds only SHARED locks, then
19937 ** return zero.
19938 */
19939 static int unixCheckReservedLock(sqlite3_file *id){
19940   int r = 0;
19941   unixFile *pFile = (unixFile*)id;
19942
19943   assert( pFile );
19944   enterMutex(); /* Because pFile->pLock is shared across threads */
19945
19946   /* Check if a thread in this process holds such a lock */
19947   if( pFile->pLock->locktype>SHARED_LOCK ){
19948     r = 1;
19949   }
19950
19951   /* Otherwise see if some other process holds it.
19952   */
19953   if( !r ){
19954     struct flock lock;
19955     lock.l_whence = SEEK_SET;
19956     lock.l_start = RESERVED_BYTE;
19957     lock.l_len = 1;
19958     lock.l_type = F_WRLCK;
19959     fcntl(pFile->h, F_GETLK, &lock);
19960     if( lock.l_type!=F_UNLCK ){
19961       r = 1;
19962     }
19963   }
19964   
19965   leaveMutex();
19966   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
19967
19968   return r;
19969 }
19970
19971 /*
19972 ** Lock the file with the lock specified by parameter locktype - one
19973 ** of the following:
19974 **
19975 **     (1) SHARED_LOCK
19976 **     (2) RESERVED_LOCK
19977 **     (3) PENDING_LOCK
19978 **     (4) EXCLUSIVE_LOCK
19979 **
19980 ** Sometimes when requesting one lock state, additional lock states
19981 ** are inserted in between.  The locking might fail on one of the later
19982 ** transitions leaving the lock state different from what it started but
19983 ** still short of its goal.  The following chart shows the allowed
19984 ** transitions and the inserted intermediate states:
19985 **
19986 **    UNLOCKED -> SHARED
19987 **    SHARED -> RESERVED
19988 **    SHARED -> (PENDING) -> EXCLUSIVE
19989 **    RESERVED -> (PENDING) -> EXCLUSIVE
19990 **    PENDING -> EXCLUSIVE
19991 **
19992 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
19993 ** routine to lower a locking level.
19994 */
19995 static int unixLock(sqlite3_file *id, int locktype){
19996   /* The following describes the implementation of the various locks and
19997   ** lock transitions in terms of the POSIX advisory shared and exclusive
19998   ** lock primitives (called read-locks and write-locks below, to avoid
19999   ** confusion with SQLite lock names). The algorithms are complicated
20000   ** slightly in order to be compatible with windows systems simultaneously
20001   ** accessing the same database file, in case that is ever required.
20002   **
20003   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
20004   ** byte', each single bytes at well known offsets, and the 'shared byte
20005   ** range', a range of 510 bytes at a well known offset.
20006   **
20007   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
20008   ** byte'.  If this is successful, a random byte from the 'shared byte
20009   ** range' is read-locked and the lock on the 'pending byte' released.
20010   **
20011   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
20012   ** A RESERVED lock is implemented by grabbing a write-lock on the
20013   ** 'reserved byte'. 
20014   **
20015   ** A process may only obtain a PENDING lock after it has obtained a
20016   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
20017   ** on the 'pending byte'. This ensures that no new SHARED locks can be
20018   ** obtained, but existing SHARED locks are allowed to persist. A process
20019   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
20020   ** This property is used by the algorithm for rolling back a journal file
20021   ** after a crash.
20022   **
20023   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
20024   ** implemented by obtaining a write-lock on the entire 'shared byte
20025   ** range'. Since all other locks require a read-lock on one of the bytes
20026   ** within this range, this ensures that no other locks are held on the
20027   ** database. 
20028   **
20029   ** The reason a single byte cannot be used instead of the 'shared byte
20030   ** range' is that some versions of windows do not support read-locks. By
20031   ** locking a random byte from a range, concurrent SHARED locks may exist
20032   ** even if the locking primitive used is always a write-lock.
20033   */
20034   int rc = SQLITE_OK;
20035   unixFile *pFile = (unixFile*)id;
20036   struct lockInfo *pLock = pFile->pLock;
20037   struct flock lock;
20038   int s;
20039
20040   assert( pFile );
20041   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
20042       locktypeName(locktype), locktypeName(pFile->locktype),
20043       locktypeName(pLock->locktype), pLock->cnt , getpid());
20044
20045   /* If there is already a lock of this type or more restrictive on the
20046   ** unixFile, do nothing. Don't use the end_lock: exit path, as
20047   ** enterMutex() hasn't been called yet.
20048   */
20049   if( pFile->locktype>=locktype ){
20050     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
20051             locktypeName(locktype));
20052     return SQLITE_OK;
20053   }
20054
20055   /* Make sure the locking sequence is correct
20056   */
20057   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20058   assert( locktype!=PENDING_LOCK );
20059   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20060
20061   /* This mutex is needed because pFile->pLock is shared across threads
20062   */
20063   enterMutex();
20064
20065   /* Make sure the current thread owns the pFile.
20066   */
20067   rc = transferOwnership(pFile);
20068   if( rc!=SQLITE_OK ){
20069     leaveMutex();
20070     return rc;
20071   }
20072   pLock = pFile->pLock;
20073
20074   /* If some thread using this PID has a lock via a different unixFile*
20075   ** handle that precludes the requested lock, return BUSY.
20076   */
20077   if( (pFile->locktype!=pLock->locktype && 
20078           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
20079   ){
20080     rc = SQLITE_BUSY;
20081     goto end_lock;
20082   }
20083
20084   /* If a SHARED lock is requested, and some thread using this PID already
20085   ** has a SHARED or RESERVED lock, then increment reference counts and
20086   ** return SQLITE_OK.
20087   */
20088   if( locktype==SHARED_LOCK && 
20089       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
20090     assert( locktype==SHARED_LOCK );
20091     assert( pFile->locktype==0 );
20092     assert( pLock->cnt>0 );
20093     pFile->locktype = SHARED_LOCK;
20094     pLock->cnt++;
20095     pFile->pOpen->nLock++;
20096     goto end_lock;
20097   }
20098
20099   lock.l_len = 1L;
20100
20101   lock.l_whence = SEEK_SET;
20102
20103   /* A PENDING lock is needed before acquiring a SHARED lock and before
20104   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
20105   ** be released.
20106   */
20107   if( locktype==SHARED_LOCK 
20108       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
20109   ){
20110     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
20111     lock.l_start = PENDING_BYTE;
20112     s = fcntl(pFile->h, F_SETLK, &lock);
20113     if( s==(-1) ){
20114       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
20115       goto end_lock;
20116     }
20117   }
20118
20119
20120   /* If control gets to this point, then actually go ahead and make
20121   ** operating system calls for the specified lock.
20122   */
20123   if( locktype==SHARED_LOCK ){
20124     assert( pLock->cnt==0 );
20125     assert( pLock->locktype==0 );
20126
20127     /* Now get the read-lock */
20128     lock.l_start = SHARED_FIRST;
20129     lock.l_len = SHARED_SIZE;
20130     s = fcntl(pFile->h, F_SETLK, &lock);
20131
20132     /* Drop the temporary PENDING lock */
20133     lock.l_start = PENDING_BYTE;
20134     lock.l_len = 1L;
20135     lock.l_type = F_UNLCK;
20136     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
20137       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
20138       goto end_lock;
20139     }
20140     if( s==(-1) ){
20141       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
20142     }else{
20143       pFile->locktype = SHARED_LOCK;
20144       pFile->pOpen->nLock++;
20145       pLock->cnt = 1;
20146     }
20147   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
20148     /* We are trying for an exclusive lock but another thread in this
20149     ** same process is still holding a shared lock. */
20150     rc = SQLITE_BUSY;
20151   }else{
20152     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
20153     ** assumed that there is a SHARED or greater lock on the file
20154     ** already.
20155     */
20156     assert( 0!=pFile->locktype );
20157     lock.l_type = F_WRLCK;
20158     switch( locktype ){
20159       case RESERVED_LOCK:
20160         lock.l_start = RESERVED_BYTE;
20161         break;
20162       case EXCLUSIVE_LOCK:
20163         lock.l_start = SHARED_FIRST;
20164         lock.l_len = SHARED_SIZE;
20165         break;
20166       default:
20167         assert(0);
20168     }
20169     s = fcntl(pFile->h, F_SETLK, &lock);
20170     if( s==(-1) ){
20171       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
20172     }
20173   }
20174   
20175   if( rc==SQLITE_OK ){
20176     pFile->locktype = locktype;
20177     pLock->locktype = locktype;
20178   }else if( locktype==EXCLUSIVE_LOCK ){
20179     pFile->locktype = PENDING_LOCK;
20180     pLock->locktype = PENDING_LOCK;
20181   }
20182
20183 end_lock:
20184   leaveMutex();
20185   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
20186       rc==SQLITE_OK ? "ok" : "failed");
20187   return rc;
20188 }
20189
20190 /*
20191 ** Lower the locking level on file descriptor pFile to locktype.  locktype
20192 ** must be either NO_LOCK or SHARED_LOCK.
20193 **
20194 ** If the locking level of the file descriptor is already at or below
20195 ** the requested locking level, this routine is a no-op.
20196 */
20197 static int unixUnlock(sqlite3_file *id, int locktype){
20198   struct lockInfo *pLock;
20199   struct flock lock;
20200   int rc = SQLITE_OK;
20201   unixFile *pFile = (unixFile*)id;
20202   int h;
20203
20204   assert( pFile );
20205   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
20206       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
20207
20208   assert( locktype<=SHARED_LOCK );
20209   if( pFile->locktype<=locktype ){
20210     return SQLITE_OK;
20211   }
20212   if( CHECK_THREADID(pFile) ){
20213     return SQLITE_MISUSE;
20214   }
20215   enterMutex();
20216   h = pFile->h;
20217   pLock = pFile->pLock;
20218   assert( pLock->cnt!=0 );
20219   if( pFile->locktype>SHARED_LOCK ){
20220     assert( pLock->locktype==pFile->locktype );
20221     SimulateIOErrorBenign(1);
20222     SimulateIOError( h=(-1) )
20223     SimulateIOErrorBenign(0);
20224     if( locktype==SHARED_LOCK ){
20225       lock.l_type = F_RDLCK;
20226       lock.l_whence = SEEK_SET;
20227       lock.l_start = SHARED_FIRST;
20228       lock.l_len = SHARED_SIZE;
20229       if( fcntl(h, F_SETLK, &lock)==(-1) ){
20230         rc = SQLITE_IOERR_RDLOCK;
20231       }
20232     }
20233     lock.l_type = F_UNLCK;
20234     lock.l_whence = SEEK_SET;
20235     lock.l_start = PENDING_BYTE;
20236     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
20237     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
20238       pLock->locktype = SHARED_LOCK;
20239     }else{
20240       rc = SQLITE_IOERR_UNLOCK;
20241     }
20242   }
20243   if( locktype==NO_LOCK ){
20244     struct openCnt *pOpen;
20245
20246     /* Decrement the shared lock counter.  Release the lock using an
20247     ** OS call only when all threads in this same process have released
20248     ** the lock.
20249     */
20250     pLock->cnt--;
20251     if( pLock->cnt==0 ){
20252       lock.l_type = F_UNLCK;
20253       lock.l_whence = SEEK_SET;
20254       lock.l_start = lock.l_len = 0L;
20255       SimulateIOErrorBenign(1);
20256       SimulateIOError( h=(-1) )
20257       SimulateIOErrorBenign(0);
20258       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
20259         pLock->locktype = NO_LOCK;
20260       }else{
20261         rc = SQLITE_IOERR_UNLOCK;
20262         pLock->cnt = 1;
20263       }
20264     }
20265
20266     /* Decrement the count of locks against this same file.  When the
20267     ** count reaches zero, close any other file descriptors whose close
20268     ** was deferred because of outstanding locks.
20269     */
20270     if( rc==SQLITE_OK ){
20271       pOpen = pFile->pOpen;
20272       pOpen->nLock--;
20273       assert( pOpen->nLock>=0 );
20274       if( pOpen->nLock==0 && pOpen->nPending>0 ){
20275         int i;
20276         for(i=0; i<pOpen->nPending; i++){
20277           close(pOpen->aPending[i]);
20278         }
20279         free(pOpen->aPending);
20280         pOpen->nPending = 0;
20281         pOpen->aPending = 0;
20282       }
20283     }
20284   }
20285   leaveMutex();
20286   if( rc==SQLITE_OK ) pFile->locktype = locktype;
20287   return rc;
20288 }
20289
20290 /*
20291 ** Close a file.
20292 */
20293 static int unixClose(sqlite3_file *id){
20294   unixFile *pFile = (unixFile *)id;
20295   if( !pFile ) return SQLITE_OK;
20296   unixUnlock(id, NO_LOCK);
20297   if( pFile->dirfd>=0 ) close(pFile->dirfd);
20298   pFile->dirfd = -1;
20299   enterMutex();
20300
20301   if( pFile->pOpen->nLock ){
20302     /* If there are outstanding locks, do not actually close the file just
20303     ** yet because that would clear those locks.  Instead, add the file
20304     ** descriptor to pOpen->aPending.  It will be automatically closed when
20305     ** the last lock is cleared.
20306     */
20307     int *aNew;
20308     struct openCnt *pOpen = pFile->pOpen;
20309     aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
20310     if( aNew==0 ){
20311       /* If a malloc fails, just leak the file descriptor */
20312     }else{
20313       pOpen->aPending = aNew;
20314       pOpen->aPending[pOpen->nPending] = pFile->h;
20315       pOpen->nPending++;
20316     }
20317   }else{
20318     /* There are no outstanding locks so we can close the file immediately */
20319     close(pFile->h);
20320   }
20321   releaseLockInfo(pFile->pLock);
20322   releaseOpenCnt(pFile->pOpen);
20323
20324   leaveMutex();
20325   OSTRACE2("CLOSE   %-3d\n", pFile->h);
20326   OpenCounter(-1);
20327   memset(pFile, 0, sizeof(unixFile));
20328   return SQLITE_OK;
20329 }
20330
20331
20332 #ifdef SQLITE_ENABLE_LOCKING_STYLE
20333 #pragma mark AFP Support
20334
20335 /*
20336  ** The afpLockingContext structure contains all afp lock specific state
20337  */
20338 typedef struct afpLockingContext afpLockingContext;
20339 struct afpLockingContext {
20340   unsigned long long sharedLockByte;
20341   const char *filePath;
20342 };
20343
20344 struct ByteRangeLockPB2
20345 {
20346   unsigned long long offset;        /* offset to first byte to lock */
20347   unsigned long long length;        /* nbr of bytes to lock */
20348   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
20349   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
20350   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
20351   int fd;                           /* file desc to assoc this lock with */
20352 };
20353
20354 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
20355
20356 /* 
20357 ** Return 0 on success, 1 on failure.  To match the behavior of the 
20358 ** normal posix file locking (used in unixLock for example), we should 
20359 ** provide 'richer' return codes - specifically to differentiate between
20360 ** 'file busy' and 'file system error' results.
20361 */
20362 static int _AFPFSSetLock(
20363   const char *path, 
20364   int fd, 
20365   unsigned long long offset, 
20366   unsigned long long length, 
20367   int setLockFlag
20368 ){
20369   struct ByteRangeLockPB2       pb;
20370   int                     err;
20371   
20372   pb.unLockFlag = setLockFlag ? 0 : 1;
20373   pb.startEndFlag = 0;
20374   pb.offset = offset;
20375   pb.length = length; 
20376   pb.fd = fd;
20377   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
20378     (setLockFlag?"ON":"OFF"), fd, offset, length);
20379   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
20380   if ( err==-1 ) {
20381     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
20382       strerror(errno));
20383     return 1; /* error */
20384   } else {
20385     return 0;
20386   }
20387 }
20388
20389 /*
20390  ** This routine checks if there is a RESERVED lock held on the specified
20391  ** file by this or any other process. If such a lock is held, return
20392  ** non-zero.  If the file is unlocked or holds only SHARED locks, then
20393  ** return zero.
20394  */
20395 static int afpUnixCheckReservedLock(sqlite3_file *id){
20396   int r = 0;
20397   unixFile *pFile = (unixFile*)id;
20398   
20399   assert( pFile ); 
20400   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
20401   
20402   /* Check if a thread in this process holds such a lock */
20403   if( pFile->locktype>SHARED_LOCK ){
20404     r = 1;
20405   }
20406   
20407   /* Otherwise see if some other process holds it.
20408    */
20409   if ( !r ) {
20410     /* lock the byte */
20411     int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
20412     if (failed) {
20413       /* if we failed to get the lock then someone else must have it */
20414       r = 1;
20415     } else {
20416       /* if we succeeded in taking the reserved lock, unlock it to restore
20417       ** the original state */
20418       _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
20419     }
20420   }
20421   OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
20422   
20423   return r;
20424 }
20425
20426 /* AFP-style locking following the behavior of unixLock, see the unixLock 
20427 ** function comments for details of lock management. */
20428 static int afpUnixLock(sqlite3_file *id, int locktype){
20429   int rc = SQLITE_OK;
20430   unixFile *pFile = (unixFile*)id;
20431   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
20432   int gotPendingLock = 0;
20433   
20434   assert( pFile );
20435   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
20436          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
20437
20438   /* If there is already a lock of this type or more restrictive on the
20439   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
20440   ** enterMutex() hasn't been called yet.
20441   */
20442   if( pFile->locktype>=locktype ){
20443     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
20444            locktypeName(locktype));
20445     return SQLITE_OK;
20446   }
20447
20448   /* Make sure the locking sequence is correct
20449   */
20450   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20451   assert( locktype!=PENDING_LOCK );
20452   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20453   
20454   /* This mutex is needed because pFile->pLock is shared across threads
20455   */
20456   enterMutex();
20457
20458   /* Make sure the current thread owns the pFile.
20459   */
20460   rc = transferOwnership(pFile);
20461   if( rc!=SQLITE_OK ){
20462     leaveMutex();
20463     return rc;
20464   }
20465     
20466   /* A PENDING lock is needed before acquiring a SHARED lock and before
20467   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
20468   ** be released.
20469   */
20470   if( locktype==SHARED_LOCK 
20471       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
20472   ){
20473     int failed;
20474     failed = _AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 1);
20475     if (failed) {
20476       rc = SQLITE_BUSY;
20477       goto afp_end_lock;
20478     }
20479   }
20480   
20481   /* If control gets to this point, then actually go ahead and make
20482   ** operating system calls for the specified lock.
20483   */
20484   if( locktype==SHARED_LOCK ){
20485     int lk, failed;
20486     int tries = 0;
20487     
20488     /* Now get the read-lock */
20489     /* note that the quality of the randomness doesn't matter that much */
20490     lk = random(); 
20491     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
20492     failed = _AFPFSSetLock(context->filePath, pFile->h, 
20493       SHARED_FIRST+context->sharedLockByte, 1, 1);
20494     
20495     /* Drop the temporary PENDING lock */
20496     if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
20497       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
20498       goto afp_end_lock;
20499     }
20500     
20501     if( failed ){
20502       rc = SQLITE_BUSY;
20503     } else {
20504       pFile->locktype = SHARED_LOCK;
20505     }
20506   }else{
20507     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
20508     ** assumed that there is a SHARED or greater lock on the file
20509     ** already.
20510     */
20511     int failed = 0;
20512     assert( 0!=pFile->locktype );
20513     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
20514         /* Acquire a RESERVED lock */
20515         failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
20516     }
20517     if (!failed && locktype == EXCLUSIVE_LOCK) {
20518       /* Acquire an EXCLUSIVE lock */
20519         
20520       /* Remove the shared lock before trying the range.  we'll need to 
20521       ** reestablish the shared lock if we can't get the  afpUnixUnlock
20522       */
20523       if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
20524                          context->sharedLockByte, 1, 0)) {
20525         /* now attemmpt to get the exclusive lock range */
20526         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
20527                                SHARED_SIZE, 1);
20528         if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
20529                                     context->sharedLockByte, 1, 1)) {
20530           rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
20531         }
20532       } else {
20533         /* */
20534         rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
20535       }
20536     }
20537     if( failed && rc == SQLITE_OK){
20538       rc = SQLITE_BUSY;
20539     }
20540   }
20541   
20542   if( rc==SQLITE_OK ){
20543     pFile->locktype = locktype;
20544   }else if( locktype==EXCLUSIVE_LOCK ){
20545     pFile->locktype = PENDING_LOCK;
20546   }
20547   
20548 afp_end_lock:
20549   leaveMutex();
20550   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
20551          rc==SQLITE_OK ? "ok" : "failed");
20552   return rc;
20553 }
20554
20555 /*
20556 ** Lower the locking level on file descriptor pFile to locktype.  locktype
20557 ** must be either NO_LOCK or SHARED_LOCK.
20558 **
20559 ** If the locking level of the file descriptor is already at or below
20560 ** the requested locking level, this routine is a no-op.
20561 */
20562 static int afpUnixUnlock(sqlite3_file *id, int locktype) {
20563   struct flock lock;
20564   int rc = SQLITE_OK;
20565   unixFile *pFile = (unixFile*)id;
20566   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
20567
20568   assert( pFile );
20569   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
20570          pFile->locktype, getpid());
20571   
20572   assert( locktype<=SHARED_LOCK );
20573   if( pFile->locktype<=locktype ){
20574     return SQLITE_OK;
20575   }
20576   if( CHECK_THREADID(pFile) ){
20577     return SQLITE_MISUSE;
20578   }
20579   enterMutex();
20580   if( pFile->locktype>SHARED_LOCK ){
20581     if( locktype==SHARED_LOCK ){
20582       int failed = 0;
20583
20584       /* unlock the exclusive range - then re-establish the shared lock */
20585       if (pFile->locktype==EXCLUSIVE_LOCK) {
20586         failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
20587                                  SHARED_SIZE, 0);
20588         if (!failed) {
20589           /* successfully removed the exclusive lock */
20590           if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
20591                             context->sharedLockByte, 1, 1)) {
20592             /* failed to re-establish our shared lock */
20593             rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
20594           }
20595         } else {
20596           /* This should never happen - failed to unlock the exclusive range */
20597           rc = SQLITE_IOERR_UNLOCK;
20598         } 
20599       }
20600     }
20601     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
20602       if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
20603         /* failed to release the pending lock */
20604         rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
20605       }
20606     } 
20607     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
20608       if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
20609         /* failed to release the reserved lock */
20610         rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
20611       }
20612     } 
20613   }
20614   if( locktype==NO_LOCK ){
20615     int failed = _AFPFSSetLock(context->filePath, pFile->h, 
20616                                SHARED_FIRST + context->sharedLockByte, 1, 0);
20617     if (failed) {
20618       rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
20619     }
20620   }
20621   if (rc == SQLITE_OK)
20622     pFile->locktype = locktype;
20623   leaveMutex();
20624   return rc;
20625 }
20626
20627 /*
20628 ** Close a file & cleanup AFP specific locking context 
20629 */
20630 static int afpUnixClose(sqlite3_file *id) {
20631   unixFile *pFile = (unixFile*)id;
20632
20633   if( !pFile ) return SQLITE_OK;
20634   afpUnixUnlock(id, NO_LOCK);
20635   sqlite3_free(pFile->lockingContext);
20636   if( pFile->dirfd>=0 ) close(pFile->dirfd);
20637   pFile->dirfd = -1;
20638   enterMutex();
20639   close(pFile->h);
20640   leaveMutex();
20641   OSTRACE2("CLOSE   %-3d\n", pFile->h);
20642   OpenCounter(-1);
20643   memset(pFile, 0, sizeof(unixFile));
20644   return SQLITE_OK;
20645 }
20646
20647
20648 #pragma mark flock() style locking
20649
20650 /*
20651 ** The flockLockingContext is not used
20652 */
20653 typedef void flockLockingContext;
20654
20655 static int flockUnixCheckReservedLock(sqlite3_file *id){
20656   unixFile *pFile = (unixFile*)id;
20657   
20658   if (pFile->locktype == RESERVED_LOCK) {
20659     return 1; /* already have a reserved lock */
20660   } else {
20661     /* attempt to get the lock */
20662     int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
20663     if (!rc) {
20664       /* got the lock, unlock it */
20665       flock(pFile->h, LOCK_UN);
20666       return 0;  /* no one has it reserved */
20667     }
20668     return 1; /* someone else might have it reserved */
20669   }
20670 }
20671
20672 static int flockUnixLock(sqlite3_file *id, int locktype) {
20673   unixFile *pFile = (unixFile*)id;
20674   
20675   /* if we already have a lock, it is exclusive.  
20676   ** Just adjust level and punt on outta here. */
20677   if (pFile->locktype > NO_LOCK) {
20678     pFile->locktype = locktype;
20679     return SQLITE_OK;
20680   }
20681   
20682   /* grab an exclusive lock */
20683   int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
20684   if (rc) {
20685     /* didn't get, must be busy */
20686     return SQLITE_BUSY;
20687   } else {
20688     /* got it, set the type and return ok */
20689     pFile->locktype = locktype;
20690     return SQLITE_OK;
20691   }
20692 }
20693
20694 static int flockUnixUnlock(sqlite3_file *id, int locktype) {
20695   unixFile *pFile = (unixFile*)id;
20696   
20697   assert( locktype<=SHARED_LOCK );
20698   
20699   /* no-op if possible */
20700   if( pFile->locktype==locktype ){
20701     return SQLITE_OK;
20702   }
20703   
20704   /* shared can just be set because we always have an exclusive */
20705   if (locktype==SHARED_LOCK) {
20706     pFile->locktype = locktype;
20707     return SQLITE_OK;
20708   }
20709   
20710   /* no, really, unlock. */
20711   int rc = flock(pFile->h, LOCK_UN);
20712   if (rc)
20713     return SQLITE_IOERR_UNLOCK;
20714   else {
20715     pFile->locktype = NO_LOCK;
20716     return SQLITE_OK;
20717   }
20718 }
20719
20720 /*
20721 ** Close a file.
20722 */
20723 static int flockUnixClose(sqlite3_file *id) {
20724   unixFile *pFile = (unixFile*)id;
20725   
20726   if( !pFile ) return SQLITE_OK;
20727   flockUnixUnlock(id, NO_LOCK);
20728   
20729   if( pFile->dirfd>=0 ) close(pFile->dirfd);
20730   pFile->dirfd = -1;
20731
20732   enterMutex();
20733   close(pFile->h);  
20734   leaveMutex();
20735   OSTRACE2("CLOSE   %-3d\n", pFile->h);
20736   OpenCounter(-1);
20737   memset(pFile, 0, sizeof(unixFile));
20738   return SQLITE_OK;
20739 }
20740
20741 #pragma mark Old-School .lock file based locking
20742
20743 /*
20744 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
20745 ** specific state
20746 */
20747 typedef struct dotlockLockingContext dotlockLockingContext;
20748 struct dotlockLockingContext {
20749   char *lockPath;
20750 };
20751
20752
20753 static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
20754   unixFile *pFile = (unixFile*)id;
20755   dotlockLockingContext *context;
20756
20757   context = (dotlockLockingContext*)pFile->lockingContext;
20758   if (pFile->locktype == RESERVED_LOCK) {
20759     return 1; /* already have a reserved lock */
20760   } else {
20761     struct stat statBuf;
20762     if (lstat(context->lockPath,&statBuf) == 0){
20763       /* file exists, someone else has the lock */
20764       return 1;
20765     }else{
20766       /* file does not exist, we could have it if we want it */
20767       return 0;
20768     }
20769   }
20770 }
20771
20772 static int dotlockUnixLock(sqlite3_file *id, int locktype) {
20773   unixFile *pFile = (unixFile*)id;
20774   dotlockLockingContext *context;
20775   int fd;
20776
20777   context = (dotlockLockingContext*)pFile->lockingContext;
20778   
20779   /* if we already have a lock, it is exclusive.  
20780   ** Just adjust level and punt on outta here. */
20781   if (pFile->locktype > NO_LOCK) {
20782     pFile->locktype = locktype;
20783     
20784     /* Always update the timestamp on the old file */
20785     utimes(context->lockPath,NULL);
20786     return SQLITE_OK;
20787   }
20788   
20789   /* check to see if lock file already exists */
20790   struct stat statBuf;
20791   if (lstat(context->lockPath,&statBuf) == 0){
20792     return SQLITE_BUSY; /* it does, busy */
20793   }
20794   
20795   /* grab an exclusive lock */
20796   fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
20797   if( fd<0 ){
20798     /* failed to open/create the file, someone else may have stolen the lock */
20799     return SQLITE_BUSY; 
20800   }
20801   close(fd);
20802   
20803   /* got it, set the type and return ok */
20804   pFile->locktype = locktype;
20805   return SQLITE_OK;
20806 }
20807
20808 static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
20809   unixFile *pFile = (unixFile*)id;
20810   dotlockLockingContext *context;
20811
20812   context = (dotlockLockingContext*)pFile->lockingContext;
20813   
20814   assert( locktype<=SHARED_LOCK );
20815   
20816   /* no-op if possible */
20817   if( pFile->locktype==locktype ){
20818     return SQLITE_OK;
20819   }
20820   
20821   /* shared can just be set because we always have an exclusive */
20822   if (locktype==SHARED_LOCK) {
20823     pFile->locktype = locktype;
20824     return SQLITE_OK;
20825   }
20826   
20827   /* no, really, unlock. */
20828   unlink(context->lockPath);
20829   pFile->locktype = NO_LOCK;
20830   return SQLITE_OK;
20831 }
20832
20833 /*
20834  ** Close a file.
20835  */
20836 static int dotlockUnixClose(sqlite3_file *id) {
20837   unixFile *pFile = (unixFile*)id;
20838   
20839   if( !pFile ) return SQLITE_OK;
20840   dotlockUnixUnlock(id, NO_LOCK);
20841   sqlite3_free(pFile->lockingContext);
20842   if( pFile->dirfd>=0 ) close(pFile->dirfd);
20843   pFile->dirfd = -1;
20844   enterMutex();  
20845   close(pFile->h);
20846   leaveMutex();
20847   OSTRACE2("CLOSE   %-3d\n", pFile->h);
20848   OpenCounter(-1);
20849   memset(pFile, 0, sizeof(unixFile));
20850   return SQLITE_OK;
20851 }
20852
20853
20854 #pragma mark No locking
20855
20856 /*
20857 ** The nolockLockingContext is void
20858 */
20859 typedef void nolockLockingContext;
20860
20861 static int nolockUnixCheckReservedLock(sqlite3_file *id) {
20862   return 0;
20863 }
20864
20865 static int nolockUnixLock(sqlite3_file *id, int locktype) {
20866   return SQLITE_OK;
20867 }
20868
20869 static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
20870   return SQLITE_OK;
20871 }
20872
20873 /*
20874 ** Close a file.
20875 */
20876 static int nolockUnixClose(sqlite3_file *id) {
20877   unixFile *pFile = (unixFile*)id;
20878   
20879   if( !pFile ) return SQLITE_OK;
20880   if( pFile->dirfd>=0 ) close(pFile->dirfd);
20881   pFile->dirfd = -1;
20882   enterMutex();
20883   close(pFile->h);
20884   leaveMutex();
20885   OSTRACE2("CLOSE   %-3d\n", pFile->h);
20886   OpenCounter(-1);
20887   memset(pFile, 0, sizeof(unixFile));
20888   return SQLITE_OK;
20889 }
20890
20891 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
20892
20893
20894 /*
20895 ** Information and control of an open file handle.
20896 */
20897 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
20898   switch( op ){
20899     case SQLITE_FCNTL_LOCKSTATE: {
20900       *(int*)pArg = ((unixFile*)id)->locktype;
20901       return SQLITE_OK;
20902     }
20903   }
20904   return SQLITE_ERROR;
20905 }
20906
20907 /*
20908 ** Return the sector size in bytes of the underlying block device for
20909 ** the specified file. This is almost always 512 bytes, but may be
20910 ** larger for some devices.
20911 **
20912 ** SQLite code assumes this function cannot fail. It also assumes that
20913 ** if two files are created in the same file-system directory (i.e.
20914 ** a database and its journal file) that the sector size will be the
20915 ** same for both.
20916 */
20917 static int unixSectorSize(sqlite3_file *id){
20918   return SQLITE_DEFAULT_SECTOR_SIZE;
20919 }
20920
20921 /*
20922 ** Return the device characteristics for the file. This is always 0.
20923 */
20924 static int unixDeviceCharacteristics(sqlite3_file *id){
20925   return 0;
20926 }
20927
20928 /*
20929 ** This vector defines all the methods that can operate on an sqlite3_file
20930 ** for unix.
20931 */
20932 static const sqlite3_io_methods sqlite3UnixIoMethod = {
20933   1,                        /* iVersion */
20934   unixClose,
20935   unixRead,
20936   unixWrite,
20937   unixTruncate,
20938   unixSync,
20939   unixFileSize,
20940   unixLock,
20941   unixUnlock,
20942   unixCheckReservedLock,
20943   unixFileControl,
20944   unixSectorSize,
20945   unixDeviceCharacteristics
20946 };
20947
20948 #ifdef SQLITE_ENABLE_LOCKING_STYLE
20949 /*
20950 ** This vector defines all the methods that can operate on an sqlite3_file
20951 ** for unix with AFP style file locking.
20952 */
20953 static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
20954   1,                        /* iVersion */
20955   afpUnixClose,
20956   unixRead,
20957   unixWrite,
20958   unixTruncate,
20959   unixSync,
20960   unixFileSize,
20961   afpUnixLock,
20962   afpUnixUnlock,
20963   afpUnixCheckReservedLock,
20964   unixFileControl,
20965   unixSectorSize,
20966   unixDeviceCharacteristics
20967 };
20968
20969 /*
20970 ** This vector defines all the methods that can operate on an sqlite3_file
20971 ** for unix with flock() style file locking.
20972 */
20973 static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
20974   1,                        /* iVersion */
20975   flockUnixClose,
20976   unixRead,
20977   unixWrite,
20978   unixTruncate,
20979   unixSync,
20980   unixFileSize,
20981   flockUnixLock,
20982   flockUnixUnlock,
20983   flockUnixCheckReservedLock,
20984   unixFileControl,
20985   unixSectorSize,
20986   unixDeviceCharacteristics
20987 };
20988
20989 /*
20990 ** This vector defines all the methods that can operate on an sqlite3_file
20991 ** for unix with dotlock style file locking.
20992 */
20993 static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
20994   1,                        /* iVersion */
20995   dotlockUnixClose,
20996   unixRead,
20997   unixWrite,
20998   unixTruncate,
20999   unixSync,
21000   unixFileSize,
21001   dotlockUnixLock,
21002   dotlockUnixUnlock,
21003   dotlockUnixCheckReservedLock,
21004   unixFileControl,
21005   unixSectorSize,
21006   unixDeviceCharacteristics
21007 };
21008
21009 /*
21010 ** This vector defines all the methods that can operate on an sqlite3_file
21011 ** for unix with nolock style file locking.
21012 */
21013 static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
21014   1,                        /* iVersion */
21015   nolockUnixClose,
21016   unixRead,
21017   unixWrite,
21018   unixTruncate,
21019   unixSync,
21020   unixFileSize,
21021   nolockUnixLock,
21022   nolockUnixUnlock,
21023   nolockUnixCheckReservedLock,
21024   unixFileControl,
21025   unixSectorSize,
21026   unixDeviceCharacteristics
21027 };
21028
21029 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
21030
21031 /*
21032 ** Allocate memory for a new unixFile and initialize that unixFile.
21033 ** Write a pointer to the new unixFile into *pId.
21034 ** If we run out of memory, close the file and return an error.
21035 */
21036 #ifdef SQLITE_ENABLE_LOCKING_STYLE
21037 /* 
21038 ** When locking extensions are enabled, the filepath and locking style 
21039 ** are needed to determine the unixFile pMethod to use for locking operations.
21040 ** The locking-style specific lockingContext data structure is created 
21041 ** and assigned here also.
21042 */
21043 static int fillInUnixFile(
21044   int h,                  /* Open file descriptor of file being opened */
21045   int dirfd,              /* Directory file descriptor */
21046   sqlite3_file *pId,      /* Write to the unixFile structure here */
21047   const char *zFilename   /* Name of the file being opened */
21048 ){
21049   sqlite3LockingStyle lockingStyle;
21050   unixFile *pNew = (unixFile *)pId;
21051   int rc;
21052
21053 #ifdef FD_CLOEXEC
21054   fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
21055 #endif
21056
21057   lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
21058   if ( lockingStyle==posixLockingStyle ){
21059     enterMutex();
21060     rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
21061     leaveMutex();
21062     if( rc ){
21063       if( dirfd>=0 ) close(dirfd);
21064       close(h);
21065       return rc;
21066     }
21067   } else {
21068     /*  pLock and pOpen are only used for posix advisory locking */
21069     pNew->pLock = NULL;
21070     pNew->pOpen = NULL;
21071   }
21072
21073   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
21074   pNew->dirfd = -1;
21075   pNew->h = h;
21076   pNew->dirfd = dirfd;
21077   SET_THREADID(pNew);
21078     
21079   switch(lockingStyle) {
21080     case afpLockingStyle: {
21081       /* afp locking uses the file path so it needs to be included in
21082       ** the afpLockingContext */
21083       afpLockingContext *context;
21084       pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
21085       pNew->lockingContext = context = sqlite3_malloc( sizeof(*context) );
21086       if( context==0 ){
21087         close(h);
21088         if( dirfd>=0 ) close(dirfd);
21089         return SQLITE_NOMEM;
21090       }
21091
21092       /* NB: zFilename exists and remains valid until the file is closed
21093       ** according to requirement F11141.  So we do not need to make a
21094       ** copy of the filename. */
21095       context->filePath = zFilename;
21096       srandomdev();
21097       break;
21098     }
21099     case flockLockingStyle:
21100       /* flock locking doesn't need additional lockingContext information */
21101       pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
21102       break;
21103     case dotlockLockingStyle: {
21104       /* dotlock locking uses the file path so it needs to be included in
21105       ** the dotlockLockingContext */
21106       dotlockLockingContext *context;
21107       int nFilename;
21108       nFilename = strlen(zFilename);
21109       pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
21110       pNew->lockingContext = context = 
21111          sqlite3_malloc( sizeof(*context) + nFilename + 6 );
21112       if( context==0 ){
21113         close(h);
21114         if( dirfd>=0 ) close(dirfd);
21115         return SQLITE_NOMEM;
21116       }
21117       context->lockPath = (char*)&context[1];
21118       sqlite3_snprintf(nFilename, context->lockPath,
21119                        "%s.lock", zFilename);
21120       break;
21121     }
21122     case posixLockingStyle:
21123       /* posix locking doesn't need additional lockingContext information */
21124       pNew->pMethod = &sqlite3UnixIoMethod;
21125       break;
21126     case noLockingStyle:
21127     case unsupportedLockingStyle:
21128     default: 
21129       pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
21130   }
21131   OpenCounter(+1);
21132   return SQLITE_OK;
21133 }
21134 #else /* SQLITE_ENABLE_LOCKING_STYLE */
21135 static int fillInUnixFile(
21136   int h,                 /* Open file descriptor on file being opened */
21137   int dirfd,
21138   sqlite3_file *pId,     /* Write to the unixFile structure here */
21139   const char *zFilename  /* Name of the file being opened */
21140 ){
21141   unixFile *pNew = (unixFile *)pId;
21142   int rc;
21143
21144 #ifdef FD_CLOEXEC
21145   fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
21146 #endif
21147
21148   enterMutex();
21149   rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
21150   leaveMutex();
21151   if( rc ){
21152     if( dirfd>=0 ) close(dirfd);
21153     close(h);
21154     return rc;
21155   }
21156
21157   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
21158   pNew->dirfd = -1;
21159   pNew->h = h;
21160   pNew->dirfd = dirfd;
21161   SET_THREADID(pNew);
21162
21163   pNew->pMethod = &sqlite3UnixIoMethod;
21164   OpenCounter(+1);
21165   return SQLITE_OK;
21166 }
21167 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
21168
21169 /*
21170 ** Open a file descriptor to the directory containing file zFilename.
21171 ** If successful, *pFd is set to the opened file descriptor and
21172 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
21173 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
21174 ** value.
21175 **
21176 ** If SQLITE_OK is returned, the caller is responsible for closing
21177 ** the file descriptor *pFd using close().
21178 */
21179 static int openDirectory(const char *zFilename, int *pFd){
21180   int ii;
21181   int fd = -1;
21182   char zDirname[MAX_PATHNAME+1];
21183
21184   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
21185   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
21186   if( ii>0 ){
21187     zDirname[ii] = '\0';
21188     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
21189     if( fd>=0 ){
21190 #ifdef FD_CLOEXEC
21191       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
21192 #endif
21193       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
21194     }
21195   }
21196   *pFd = fd;
21197   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
21198 }
21199
21200 /*
21201 ** Open the file zPath.
21202 ** 
21203 ** Previously, the SQLite OS layer used three functions in place of this
21204 ** one:
21205 **
21206 **     sqlite3OsOpenReadWrite();
21207 **     sqlite3OsOpenReadOnly();
21208 **     sqlite3OsOpenExclusive();
21209 **
21210 ** These calls correspond to the following combinations of flags:
21211 **
21212 **     ReadWrite() ->     (READWRITE | CREATE)
21213 **     ReadOnly()  ->     (READONLY) 
21214 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
21215 **
21216 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
21217 ** true, the file was configured to be automatically deleted when the
21218 ** file handle closed. To achieve the same effect using this new 
21219 ** interface, add the DELETEONCLOSE flag to those specified above for 
21220 ** OpenExclusive().
21221 */
21222 static int unixOpen(
21223   sqlite3_vfs *pVfs, 
21224   const char *zPath, 
21225   sqlite3_file *pFile,
21226   int flags,
21227   int *pOutFlags
21228 ){
21229   int fd = 0;                    /* File descriptor returned by open() */
21230   int dirfd = -1;                /* Directory file descriptor */
21231   int oflags = 0;                /* Flags to pass to open() */
21232   int eType = flags&0xFFFFFF00;  /* Type of file to open */
21233
21234   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
21235   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
21236   int isCreate     = (flags & SQLITE_OPEN_CREATE);
21237   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
21238   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
21239
21240   /* If creating a master or main-file journal, this function will open
21241   ** a file-descriptor on the directory too. The first time unixSync()
21242   ** is called the directory file descriptor will be fsync()ed and close()d.
21243   */
21244   int isOpenDirectory = (isCreate && 
21245       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
21246   );
21247
21248   /* Check the following statements are true: 
21249   **
21250   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
21251   **   (b) if CREATE is set, then READWRITE must also be set, and
21252   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
21253   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
21254   */
21255   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
21256   assert(isCreate==0 || isReadWrite);
21257   assert(isExclusive==0 || isCreate);
21258   assert(isDelete==0 || isCreate);
21259
21260
21261   /* The main DB, main journal, and master journal are never automatically
21262   ** deleted
21263   */
21264   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
21265   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
21266   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
21267
21268   /* Assert that the upper layer has set one of the "file-type" flags. */
21269   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
21270        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
21271        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
21272        || eType==SQLITE_OPEN_TRANSIENT_DB
21273   );
21274
21275   if( isReadonly )  oflags |= O_RDONLY;
21276   if( isReadWrite ) oflags |= O_RDWR;
21277   if( isCreate )    oflags |= O_CREAT;
21278   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
21279   oflags |= (O_LARGEFILE|O_BINARY);
21280
21281   memset(pFile, 0, sizeof(unixFile));
21282   fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
21283   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
21284     /* Failed to open the file for read/write access. Try read-only. */
21285     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
21286     flags |= SQLITE_OPEN_READONLY;
21287     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
21288   }
21289   if( fd<0 ){
21290     return SQLITE_CANTOPEN;
21291   }
21292   if( isDelete ){
21293     unlink(zPath);
21294   }
21295   if( pOutFlags ){
21296     *pOutFlags = flags;
21297   }
21298
21299   assert(fd!=0);
21300   if( isOpenDirectory ){
21301     int rc = openDirectory(zPath, &dirfd);
21302     if( rc!=SQLITE_OK ){
21303       close(fd);
21304       return rc;
21305     }
21306   }
21307   return fillInUnixFile(fd, dirfd, pFile, zPath);
21308 }
21309
21310 /*
21311 ** Delete the file at zPath. If the dirSync argument is true, fsync()
21312 ** the directory after deleting the file.
21313 */
21314 static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
21315   int rc = SQLITE_OK;
21316   SimulateIOError(return SQLITE_IOERR_DELETE);
21317   unlink(zPath);
21318   if( dirSync ){
21319     int fd;
21320     rc = openDirectory(zPath, &fd);
21321     if( rc==SQLITE_OK ){
21322       if( fsync(fd) ){
21323         rc = SQLITE_IOERR_DIR_FSYNC;
21324       }
21325       close(fd);
21326     }
21327   }
21328   return rc;
21329 }
21330
21331 /*
21332 ** Test the existance of or access permissions of file zPath. The
21333 ** test performed depends on the value of flags:
21334 **
21335 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
21336 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
21337 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
21338 **
21339 ** Otherwise return 0.
21340 */
21341 static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
21342   int amode = 0;
21343   switch( flags ){
21344     case SQLITE_ACCESS_EXISTS:
21345       amode = F_OK;
21346       break;
21347     case SQLITE_ACCESS_READWRITE:
21348       amode = W_OK|R_OK;
21349       break;
21350     case SQLITE_ACCESS_READ:
21351       amode = R_OK;
21352       break;
21353
21354     default:
21355       assert(!"Invalid flags argument");
21356   }
21357   return (access(zPath, amode)==0);
21358 }
21359
21360 /*
21361 ** Create a temporary file name in zBuf.  zBuf must be allocated
21362 ** by the calling process and must be big enough to hold at least
21363 ** pVfs->mxPathname bytes.
21364 */
21365 static int unixGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21366   static const char *azDirs[] = {
21367      0,
21368      "/var/tmp",
21369      "/usr/tmp",
21370      "/tmp",
21371      ".",
21372   };
21373   static const unsigned char zChars[] =
21374     "abcdefghijklmnopqrstuvwxyz"
21375     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
21376     "0123456789";
21377   int i, j;
21378   struct stat buf;
21379   const char *zDir = ".";
21380
21381   /* It's odd to simulate an io-error here, but really this is just
21382   ** using the io-error infrastructure to test that SQLite handles this
21383   ** function failing. 
21384   */
21385   SimulateIOError( return SQLITE_ERROR );
21386
21387   azDirs[0] = sqlite3_temp_directory;
21388   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
21389     if( azDirs[i]==0 ) continue;
21390     if( stat(azDirs[i], &buf) ) continue;
21391     if( !S_ISDIR(buf.st_mode) ) continue;
21392     if( access(azDirs[i], 07) ) continue;
21393     zDir = azDirs[i];
21394     break;
21395   }
21396
21397   /* Check that the output buffer is large enough for the temporary file 
21398   ** name. If it is not, return SQLITE_ERROR.
21399   */
21400   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
21401     return SQLITE_ERROR;
21402   }
21403
21404   do{
21405     assert( pVfs->mxPathname==MAX_PATHNAME );
21406     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
21407     j = strlen(zBuf);
21408     sqlite3_randomness(15, &zBuf[j]);
21409     for(i=0; i<15; i++, j++){
21410       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21411     }
21412     zBuf[j] = 0;
21413   }while( access(zBuf,0)==0 );
21414   return SQLITE_OK;
21415 }
21416
21417
21418 /*
21419 ** Turn a relative pathname into a full pathname. The relative path
21420 ** is stored as a nul-terminated string in the buffer pointed to by
21421 ** zPath. 
21422 **
21423 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
21424 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
21425 ** this buffer before returning.
21426 */
21427 static int unixFullPathname(
21428   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
21429   const char *zPath,            /* Possibly relative input path */
21430   int nOut,                     /* Size of output buffer in bytes */
21431   char *zOut                    /* Output buffer */
21432 ){
21433
21434   /* It's odd to simulate an io-error here, but really this is just
21435   ** using the io-error infrastructure to test that SQLite handles this
21436   ** function failing. This function could fail if, for example, the
21437   ** current working directly has been unlinked.
21438   */
21439   SimulateIOError( return SQLITE_ERROR );
21440
21441   assert( pVfs->mxPathname==MAX_PATHNAME );
21442   zOut[nOut-1] = '\0';
21443   if( zPath[0]=='/' ){
21444     sqlite3_snprintf(nOut, zOut, "%s", zPath);
21445   }else{
21446     int nCwd;
21447     if( getcwd(zOut, nOut-1)==0 ){
21448       return SQLITE_CANTOPEN;
21449     }
21450     nCwd = strlen(zOut);
21451     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
21452   }
21453   return SQLITE_OK;
21454
21455 #if 0
21456   /*
21457   ** Remove "/./" path elements and convert "/A/./" path elements
21458   ** to just "/".
21459   */
21460   if( zFull ){
21461     int i, j;
21462     for(i=j=0; zFull[i]; i++){
21463       if( zFull[i]=='/' ){
21464         if( zFull[i+1]=='/' ) continue;
21465         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
21466           i += 1;
21467           continue;
21468         }
21469         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
21470           while( j>0 && zFull[j-1]!='/' ){ j--; }
21471           i += 3;
21472           continue;
21473         }
21474       }
21475       zFull[j++] = zFull[i];
21476     }
21477     zFull[j] = 0;
21478   }
21479 #endif
21480 }
21481
21482
21483 #ifndef SQLITE_OMIT_LOAD_EXTENSION
21484 /*
21485 ** Interfaces for opening a shared library, finding entry points
21486 ** within the shared library, and closing the shared library.
21487 */
21488 #include <dlfcn.h>
21489 static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21490   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
21491 }
21492
21493 /*
21494 ** SQLite calls this function immediately after a call to unixDlSym() or
21495 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
21496 ** message is available, it is written to zBufOut. If no error message
21497 ** is available, zBufOut is left unmodified and SQLite uses a default
21498 ** error message.
21499 */
21500 static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21501   char *zErr;
21502   enterMutex();
21503   zErr = dlerror();
21504   if( zErr ){
21505     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
21506   }
21507   leaveMutex();
21508 }
21509 static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21510   return dlsym(pHandle, zSymbol);
21511 }
21512 static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
21513   dlclose(pHandle);
21514 }
21515 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21516   #define unixDlOpen  0
21517   #define unixDlError 0
21518   #define unixDlSym   0
21519   #define unixDlClose 0
21520 #endif
21521
21522 /*
21523 ** Write nBuf bytes of random data to the supplied buffer zBuf.
21524 */
21525 static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21526
21527   assert(nBuf>=(sizeof(time_t)+sizeof(int)));
21528
21529   /* We have to initialize zBuf to prevent valgrind from reporting
21530   ** errors.  The reports issued by valgrind are incorrect - we would
21531   ** prefer that the randomness be increased by making use of the
21532   ** uninitialized space in zBuf - but valgrind errors tend to worry
21533   ** some users.  Rather than argue, it seems easier just to initialize
21534   ** the whole array and silence valgrind, even if that means less randomness
21535   ** in the random seed.
21536   **
21537   ** When testing, initializing zBuf[] to zero is all we do.  That means
21538   ** that we always use the same random number sequence.  This makes the
21539   ** tests repeatable.
21540   */
21541   memset(zBuf, 0, nBuf);
21542 #if !defined(SQLITE_TEST)
21543   {
21544     int pid, fd;
21545     fd = open("/dev/urandom", O_RDONLY);
21546     if( fd<0 ){
21547       time_t t;
21548       time(&t);
21549       memcpy(zBuf, &t, sizeof(t));
21550       pid = getpid();
21551       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
21552     }else{
21553       read(fd, zBuf, nBuf);
21554       close(fd);
21555     }
21556   }
21557 #endif
21558   return SQLITE_OK;
21559 }
21560
21561
21562 /*
21563 ** Sleep for a little while.  Return the amount of time slept.
21564 ** The argument is the number of microseconds we want to sleep.
21565 ** The return value is the number of microseconds of sleep actually
21566 ** requested from the underlying operating system, a number which
21567 ** might be greater than or equal to the argument, but not less
21568 ** than the argument.
21569 */
21570 static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
21571 #if defined(HAVE_USLEEP) && HAVE_USLEEP
21572   usleep(microseconds);
21573   return microseconds;
21574 #else
21575   int seconds = (microseconds+999999)/1000000;
21576   sleep(seconds);
21577   return seconds*1000000;
21578 #endif
21579 }
21580
21581 /*
21582 ** The following variable, if set to a non-zero value, becomes the result
21583 ** returned from sqlite3OsCurrentTime().  This is used for testing.
21584 */
21585 #ifdef SQLITE_TEST
21586 SQLITE_API int sqlite3_current_time = 0;
21587 #endif
21588
21589 /*
21590 ** Find the current time (in Universal Coordinated Time).  Write the
21591 ** current time and date as a Julian Day number into *prNow and
21592 ** return 0.  Return 1 if the time and date cannot be found.
21593 */
21594 static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
21595 #ifdef NO_GETTOD
21596   time_t t;
21597   time(&t);
21598   *prNow = t/86400.0 + 2440587.5;
21599 #else
21600   struct timeval sNow;
21601   gettimeofday(&sNow, 0);
21602   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
21603 #endif
21604 #ifdef SQLITE_TEST
21605   if( sqlite3_current_time ){
21606     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21607   }
21608 #endif
21609   return 0;
21610 }
21611
21612 /*
21613 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
21614 ** a function rather than give the structure global scope because
21615 ** some compilers (MSVC) do not allow forward declarations of
21616 ** initialized structures.
21617 */
21618 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
21619   static sqlite3_vfs unixVfs = {
21620     1,                  /* iVersion */
21621     sizeof(unixFile),   /* szOsFile */
21622     MAX_PATHNAME,       /* mxPathname */
21623     0,                  /* pNext */
21624     "unix",             /* zName */
21625     0,                  /* pAppData */
21626   
21627     unixOpen,           /* xOpen */
21628     unixDelete,         /* xDelete */
21629     unixAccess,         /* xAccess */
21630     unixGetTempname,    /* xGetTempName */
21631     unixFullPathname,   /* xFullPathname */
21632     unixDlOpen,         /* xDlOpen */
21633     unixDlError,        /* xDlError */
21634     unixDlSym,          /* xDlSym */
21635     unixDlClose,        /* xDlClose */
21636     unixRandomness,     /* xRandomness */
21637     unixSleep,          /* xSleep */
21638     unixCurrentTime     /* xCurrentTime */
21639   };
21640   
21641   return &unixVfs;
21642 }
21643  
21644 #endif /* OS_UNIX */
21645
21646 /************** End of os_unix.c *********************************************/
21647 /************** Begin file os_win.c ******************************************/
21648 /*
21649 ** 2004 May 22
21650 **
21651 ** The author disclaims copyright to this source code.  In place of
21652 ** a legal notice, here is a blessing:
21653 **
21654 **    May you do good and not evil.
21655 **    May you find forgiveness for yourself and forgive others.
21656 **    May you share freely, never taking more than you give.
21657 **
21658 ******************************************************************************
21659 **
21660 ** This file contains code that is specific to windows.
21661 */
21662 #if OS_WIN               /* This file is used for windows only */
21663
21664
21665 /*
21666 ** A Note About Memory Allocation:
21667 **
21668 ** This driver uses malloc()/free() directly rather than going through
21669 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
21670 ** are designed for use on embedded systems where memory is scarce and
21671 ** malloc failures happen frequently.  Win32 does not typically run on
21672 ** embedded systems, and when it does the developers normally have bigger
21673 ** problems to worry about than running out of memory.  So there is not
21674 ** a compelling need to use the wrappers.
21675 **
21676 ** But there is a good reason to not use the wrappers.  If we use the
21677 ** wrappers then we will get simulated malloc() failures within this
21678 ** driver.  And that causes all kinds of problems for our tests.  We
21679 ** could enhance SQLite to deal with simulated malloc failures within
21680 ** the OS driver, but the code to deal with those failure would not
21681 ** be exercised on Linux (which does not need to malloc() in the driver)
21682 ** and so we would have difficulty writing coverage tests for that
21683 ** code.  Better to leave the code out, we think.
21684 **
21685 ** The point of this discussion is as follows:  When creating a new
21686 ** OS layer for an embedded system, if you use this file as an example,
21687 ** avoid the use of malloc()/free().  Those routines work ok on windows
21688 ** desktops but not so well in embedded systems.
21689 */
21690
21691 #include <winbase.h>
21692
21693 #ifdef __CYGWIN__
21694 # include <sys/cygwin.h>
21695 #endif
21696
21697 /*
21698 ** Macros used to determine whether or not to use threads.
21699 */
21700 #if defined(THREADSAFE) && THREADSAFE
21701 # define SQLITE_W32_THREADS 1
21702 #endif
21703
21704 /*
21705 ** Include code that is common to all os_*.c files
21706 */
21707 /************** Include os_common.h in the middle of os_win.c ****************/
21708 /************** Begin file os_common.h ***************************************/
21709 /*
21710 ** 2004 May 22
21711 **
21712 ** The author disclaims copyright to this source code.  In place of
21713 ** a legal notice, here is a blessing:
21714 **
21715 **    May you do good and not evil.
21716 **    May you find forgiveness for yourself and forgive others.
21717 **    May you share freely, never taking more than you give.
21718 **
21719 ******************************************************************************
21720 **
21721 ** This file contains macros and a little bit of code that is common to
21722 ** all of the platform-specific files (os_*.c) and is #included into those
21723 ** files.
21724 **
21725 ** This file should be #included by the os_*.c files only.  It is not a
21726 ** general purpose header file.
21727 */
21728
21729 /*
21730 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21731 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21732 ** switch.  The following code should catch this problem at compile-time.
21733 */
21734 #ifdef MEMORY_DEBUG
21735 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21736 #endif
21737
21738
21739 /*
21740  * When testing, this global variable stores the location of the
21741  * pending-byte in the database file.
21742  */
21743 #ifdef SQLITE_TEST
21744 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
21745 #endif
21746
21747 #ifdef SQLITE_DEBUG
21748 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21749 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21750 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21751 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21752 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21753 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21754 #define OSTRACE6(X,Y,Z,A,B,C) \
21755     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21756 #define OSTRACE7(X,Y,Z,A,B,C,D) \
21757     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21758 #else
21759 #define OSTRACE1(X)
21760 #define OSTRACE2(X,Y)
21761 #define OSTRACE3(X,Y,Z)
21762 #define OSTRACE4(X,Y,Z,A)
21763 #define OSTRACE5(X,Y,Z,A,B)
21764 #define OSTRACE6(X,Y,Z,A,B,C)
21765 #define OSTRACE7(X,Y,Z,A,B,C,D)
21766 #endif
21767
21768 /*
21769 ** Macros for performance tracing.  Normally turned off.  Only works
21770 ** on i486 hardware.
21771 */
21772 #ifdef SQLITE_PERFORMANCE_TRACE
21773 __inline__ unsigned long long int hwtime(void){
21774   unsigned long long int x;
21775   __asm__("rdtsc\n\t"
21776           "mov %%edx, %%ecx\n\t"
21777           :"=A" (x));
21778   return x;
21779 }
21780 static unsigned long long int g_start;
21781 static unsigned int elapse;
21782 #define TIMER_START       g_start=hwtime()
21783 #define TIMER_END         elapse=hwtime()-g_start
21784 #define TIMER_ELAPSED     elapse
21785 #else
21786 #define TIMER_START
21787 #define TIMER_END
21788 #define TIMER_ELAPSED     0
21789 #endif
21790
21791 /*
21792 ** If we compile with the SQLITE_TEST macro set, then the following block
21793 ** of code will give us the ability to simulate a disk I/O error.  This
21794 ** is used for testing the I/O recovery logic.
21795 */
21796 #ifdef SQLITE_TEST
21797 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21798 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21799 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21800 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21801 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21802 SQLITE_API int sqlite3_diskfull_pending = 0;
21803 SQLITE_API int sqlite3_diskfull = 0;
21804 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21805 #define SimulateIOError(CODE)  \
21806   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21807        || sqlite3_io_error_pending-- == 1 )  \
21808               { local_ioerr(); CODE; }
21809 static void local_ioerr(){
21810   IOTRACE(("IOERR\n"));
21811   sqlite3_io_error_hit++;
21812   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21813 }
21814 #define SimulateDiskfullError(CODE) \
21815    if( sqlite3_diskfull_pending ){ \
21816      if( sqlite3_diskfull_pending == 1 ){ \
21817        local_ioerr(); \
21818        sqlite3_diskfull = 1; \
21819        sqlite3_io_error_hit = 1; \
21820        CODE; \
21821      }else{ \
21822        sqlite3_diskfull_pending--; \
21823      } \
21824    }
21825 #else
21826 #define SimulateIOErrorBenign(X)
21827 #define SimulateIOError(A)
21828 #define SimulateDiskfullError(A)
21829 #endif
21830
21831 /*
21832 ** When testing, keep a count of the number of open files.
21833 */
21834 #ifdef SQLITE_TEST
21835 SQLITE_API int sqlite3_open_file_count = 0;
21836 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21837 #else
21838 #define OpenCounter(X)
21839 #endif
21840
21841 /************** End of os_common.h *******************************************/
21842 /************** Continuing where we left off in os_win.c *********************/
21843
21844 /*
21845 ** Determine if we are dealing with WindowsCE - which has a much
21846 ** reduced API.
21847 */
21848 #if defined(_WIN32_WCE)
21849 # define OS_WINCE 1
21850 # define AreFileApisANSI() 1
21851 #else
21852 # define OS_WINCE 0
21853 #endif
21854
21855 /*
21856 ** WinCE lacks native support for file locking so we have to fake it
21857 ** with some code of our own.
21858 */
21859 #if OS_WINCE
21860 typedef struct winceLock {
21861   int nReaders;       /* Number of reader locks obtained */
21862   BOOL bPending;      /* Indicates a pending lock has been obtained */
21863   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
21864   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
21865 } winceLock;
21866 #endif
21867
21868 /*
21869 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
21870 ** portability layer.
21871 */
21872 typedef struct winFile winFile;
21873 struct winFile {
21874   const sqlite3_io_methods *pMethod;/* Must be first */
21875   HANDLE h;               /* Handle for accessing the file */
21876   unsigned char locktype; /* Type of lock currently held on this file */
21877   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
21878 #if OS_WINCE
21879   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
21880   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
21881   HANDLE hShared;         /* Shared memory segment used for locking */
21882   winceLock local;        /* Locks obtained by this instance of winFile */
21883   winceLock *shared;      /* Global shared lock memory for the file  */
21884 #endif
21885 };
21886
21887
21888 /*
21889 ** The following variable is (normally) set once and never changes
21890 ** thereafter.  It records whether the operating system is Win95
21891 ** or WinNT.
21892 **
21893 ** 0:   Operating system unknown.
21894 ** 1:   Operating system is Win95.
21895 ** 2:   Operating system is WinNT.
21896 **
21897 ** In order to facilitate testing on a WinNT system, the test fixture
21898 ** can manually set this value to 1 to emulate Win98 behavior.
21899 */
21900 #ifdef SQLITE_TEST
21901 SQLITE_API int sqlite3_os_type = 0;
21902 #else
21903 static int sqlite3_os_type = 0;
21904 #endif
21905
21906 /*
21907 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
21908 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
21909 **
21910 ** Here is an interesting observation:  Win95, Win98, and WinME lack
21911 ** the LockFileEx() API.  But we can still statically link against that
21912 ** API as long as we don't call it win running Win95/98/ME.  A call to
21913 ** this routine is used to determine if the host is Win95/98/ME or
21914 ** WinNT/2K/XP so that we will know whether or not we can safely call
21915 ** the LockFileEx() API.
21916 */
21917 #if OS_WINCE
21918 # define isNT()  (1)
21919 #else
21920   static int isNT(void){
21921     if( sqlite3_os_type==0 ){
21922       OSVERSIONINFO sInfo;
21923       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
21924       GetVersionEx(&sInfo);
21925       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
21926     }
21927     return sqlite3_os_type==2;
21928   }
21929 #endif /* OS_WINCE */
21930
21931 /*
21932 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
21933 **
21934 ** Space to hold the returned string is obtained from malloc.
21935 */
21936 static WCHAR *utf8ToUnicode(const char *zFilename){
21937   int nChar;
21938   WCHAR *zWideFilename;
21939
21940   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
21941   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
21942   if( zWideFilename==0 ){
21943     return 0;
21944   }
21945   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
21946   if( nChar==0 ){
21947     free(zWideFilename);
21948     zWideFilename = 0;
21949   }
21950   return zWideFilename;
21951 }
21952
21953 /*
21954 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
21955 ** obtained from malloc().
21956 */
21957 static char *unicodeToUtf8(const WCHAR *zWideFilename){
21958   int nByte;
21959   char *zFilename;
21960
21961   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
21962   zFilename = malloc( nByte );
21963   if( zFilename==0 ){
21964     return 0;
21965   }
21966   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
21967                               0, 0);
21968   if( nByte == 0 ){
21969     free(zFilename);
21970     zFilename = 0;
21971   }
21972   return zFilename;
21973 }
21974
21975 /*
21976 ** Convert an ansi string to microsoft unicode, based on the
21977 ** current codepage settings for file apis.
21978 ** 
21979 ** Space to hold the returned string is obtained
21980 ** from malloc.
21981 */
21982 static WCHAR *mbcsToUnicode(const char *zFilename){
21983   int nByte;
21984   WCHAR *zMbcsFilename;
21985   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
21986
21987   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
21988   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
21989   if( zMbcsFilename==0 ){
21990     return 0;
21991   }
21992   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
21993   if( nByte==0 ){
21994     free(zMbcsFilename);
21995     zMbcsFilename = 0;
21996   }
21997   return zMbcsFilename;
21998 }
21999
22000 /*
22001 ** Convert microsoft unicode to multibyte character string, based on the
22002 ** user's Ansi codepage.
22003 **
22004 ** Space to hold the returned string is obtained from
22005 ** malloc().
22006 */
22007 static char *unicodeToMbcs(const WCHAR *zWideFilename){
22008   int nByte;
22009   char *zFilename;
22010   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
22011
22012   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
22013   zFilename = malloc( nByte );
22014   if( zFilename==0 ){
22015     return 0;
22016   }
22017   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
22018                               0, 0);
22019   if( nByte == 0 ){
22020     free(zFilename);
22021     zFilename = 0;
22022   }
22023   return zFilename;
22024 }
22025
22026 /*
22027 ** Convert multibyte character string to UTF-8.  Space to hold the
22028 ** returned string is obtained from malloc().
22029 */
22030 static char *mbcsToUtf8(const char *zFilename){
22031   char *zFilenameUtf8;
22032   WCHAR *zTmpWide;
22033
22034   zTmpWide = mbcsToUnicode(zFilename);
22035   if( zTmpWide==0 ){
22036     return 0;
22037   }
22038   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
22039   free(zTmpWide);
22040   return zFilenameUtf8;
22041 }
22042
22043 /*
22044 ** Convert UTF-8 to multibyte character string.  Space to hold the 
22045 ** returned string is obtained from malloc().
22046 */
22047 static char *utf8ToMbcs(const char *zFilename){
22048   char *zFilenameMbcs;
22049   WCHAR *zTmpWide;
22050
22051   zTmpWide = utf8ToUnicode(zFilename);
22052   if( zTmpWide==0 ){
22053     return 0;
22054   }
22055   zFilenameMbcs = unicodeToMbcs(zTmpWide);
22056   free(zTmpWide);
22057   return zFilenameMbcs;
22058 }
22059
22060 #if OS_WINCE
22061 /*************************************************************************
22062 ** This section contains code for WinCE only.
22063 */
22064 /*
22065 ** WindowsCE does not have a localtime() function.  So create a
22066 ** substitute.
22067 */
22068 struct tm *__cdecl localtime(const time_t *t)
22069 {
22070   static struct tm y;
22071   FILETIME uTm, lTm;
22072   SYSTEMTIME pTm;
22073   sqlite3_int64 t64;
22074   t64 = *t;
22075   t64 = (t64 + 11644473600)*10000000;
22076   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
22077   uTm.dwHighDateTime= t64 >> 32;
22078   FileTimeToLocalFileTime(&uTm,&lTm);
22079   FileTimeToSystemTime(&lTm,&pTm);
22080   y.tm_year = pTm.wYear - 1900;
22081   y.tm_mon = pTm.wMonth - 1;
22082   y.tm_wday = pTm.wDayOfWeek;
22083   y.tm_mday = pTm.wDay;
22084   y.tm_hour = pTm.wHour;
22085   y.tm_min = pTm.wMinute;
22086   y.tm_sec = pTm.wSecond;
22087   return &y;
22088 }
22089
22090 /* This will never be called, but defined to make the code compile */
22091 #define GetTempPathA(a,b)
22092
22093 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
22094 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
22095 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
22096
22097 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
22098
22099 /*
22100 ** Acquire a lock on the handle h
22101 */
22102 static void winceMutexAcquire(HANDLE h){
22103    DWORD dwErr;
22104    do {
22105      dwErr = WaitForSingleObject(h, INFINITE);
22106    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
22107 }
22108 /*
22109 ** Release a lock acquired by winceMutexAcquire()
22110 */
22111 #define winceMutexRelease(h) ReleaseMutex(h)
22112
22113 /*
22114 ** Create the mutex and shared memory used for locking in the file
22115 ** descriptor pFile
22116 */
22117 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
22118   WCHAR *zTok;
22119   WCHAR *zName = utf8ToUnicode(zFilename);
22120   BOOL bInit = TRUE;
22121
22122   /* Initialize the local lockdata */
22123   ZeroMemory(&pFile->local, sizeof(pFile->local));
22124
22125   /* Replace the backslashes from the filename and lowercase it
22126   ** to derive a mutex name. */
22127   zTok = CharLowerW(zName);
22128   for (;*zTok;zTok++){
22129     if (*zTok == '\\') *zTok = '_';
22130   }
22131
22132   /* Create/open the named mutex */
22133   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
22134   if (!pFile->hMutex){
22135     free(zName);
22136     return FALSE;
22137   }
22138
22139   /* Acquire the mutex before continuing */
22140   winceMutexAcquire(pFile->hMutex);
22141   
22142   /* Since the names of named mutexes, semaphores, file mappings etc are 
22143   ** case-sensitive, take advantage of that by uppercasing the mutex name
22144   ** and using that as the shared filemapping name.
22145   */
22146   CharUpperW(zName);
22147   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
22148                                        PAGE_READWRITE, 0, sizeof(winceLock),
22149                                        zName);  
22150
22151   /* Set a flag that indicates we're the first to create the memory so it 
22152   ** must be zero-initialized */
22153   if (GetLastError() == ERROR_ALREADY_EXISTS){
22154     bInit = FALSE;
22155   }
22156
22157   free(zName);
22158
22159   /* If we succeeded in making the shared memory handle, map it. */
22160   if (pFile->hShared){
22161     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
22162              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
22163     /* If mapping failed, close the shared memory handle and erase it */
22164     if (!pFile->shared){
22165       CloseHandle(pFile->hShared);
22166       pFile->hShared = NULL;
22167     }
22168   }
22169
22170   /* If shared memory could not be created, then close the mutex and fail */
22171   if (pFile->hShared == NULL){
22172     winceMutexRelease(pFile->hMutex);
22173     CloseHandle(pFile->hMutex);
22174     pFile->hMutex = NULL;
22175     return FALSE;
22176   }
22177   
22178   /* Initialize the shared memory if we're supposed to */
22179   if (bInit) {
22180     ZeroMemory(pFile->shared, sizeof(winceLock));
22181   }
22182
22183   winceMutexRelease(pFile->hMutex);
22184   return TRUE;
22185 }
22186
22187 /*
22188 ** Destroy the part of winFile that deals with wince locks
22189 */
22190 static void winceDestroyLock(winFile *pFile){
22191   if (pFile->hMutex){
22192     /* Acquire the mutex */
22193     winceMutexAcquire(pFile->hMutex);
22194
22195     /* The following blocks should probably assert in debug mode, but they
22196        are to cleanup in case any locks remained open */
22197     if (pFile->local.nReaders){
22198       pFile->shared->nReaders --;
22199     }
22200     if (pFile->local.bReserved){
22201       pFile->shared->bReserved = FALSE;
22202     }
22203     if (pFile->local.bPending){
22204       pFile->shared->bPending = FALSE;
22205     }
22206     if (pFile->local.bExclusive){
22207       pFile->shared->bExclusive = FALSE;
22208     }
22209
22210     /* De-reference and close our copy of the shared memory handle */
22211     UnmapViewOfFile(pFile->shared);
22212     CloseHandle(pFile->hShared);
22213
22214     /* Done with the mutex */
22215     winceMutexRelease(pFile->hMutex);    
22216     CloseHandle(pFile->hMutex);
22217     pFile->hMutex = NULL;
22218   }
22219 }
22220
22221 /* 
22222 ** An implementation of the LockFile() API of windows for wince
22223 */
22224 static BOOL winceLockFile(
22225   HANDLE *phFile,
22226   DWORD dwFileOffsetLow,
22227   DWORD dwFileOffsetHigh,
22228   DWORD nNumberOfBytesToLockLow,
22229   DWORD nNumberOfBytesToLockHigh
22230 ){
22231   winFile *pFile = HANDLE_TO_WINFILE(phFile);
22232   BOOL bReturn = FALSE;
22233
22234   if (!pFile->hMutex) return TRUE;
22235   winceMutexAcquire(pFile->hMutex);
22236
22237   /* Wanting an exclusive lock? */
22238   if (dwFileOffsetLow == SHARED_FIRST
22239        && nNumberOfBytesToLockLow == SHARED_SIZE){
22240     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
22241        pFile->shared->bExclusive = TRUE;
22242        pFile->local.bExclusive = TRUE;
22243        bReturn = TRUE;
22244     }
22245   }
22246
22247   /* Want a read-only lock? */
22248   else if ((dwFileOffsetLow >= SHARED_FIRST &&
22249             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
22250             nNumberOfBytesToLockLow == 1){
22251     if (pFile->shared->bExclusive == 0){
22252       pFile->local.nReaders ++;
22253       if (pFile->local.nReaders == 1){
22254         pFile->shared->nReaders ++;
22255       }
22256       bReturn = TRUE;
22257     }
22258   }
22259
22260   /* Want a pending lock? */
22261   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
22262     /* If no pending lock has been acquired, then acquire it */
22263     if (pFile->shared->bPending == 0) {
22264       pFile->shared->bPending = TRUE;
22265       pFile->local.bPending = TRUE;
22266       bReturn = TRUE;
22267     }
22268   }
22269   /* Want a reserved lock? */
22270   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
22271     if (pFile->shared->bReserved == 0) {
22272       pFile->shared->bReserved = TRUE;
22273       pFile->local.bReserved = TRUE;
22274       bReturn = TRUE;
22275     }
22276   }
22277
22278   winceMutexRelease(pFile->hMutex);
22279   return bReturn;
22280 }
22281
22282 /*
22283 ** An implementation of the UnlockFile API of windows for wince
22284 */
22285 static BOOL winceUnlockFile(
22286   HANDLE *phFile,
22287   DWORD dwFileOffsetLow,
22288   DWORD dwFileOffsetHigh,
22289   DWORD nNumberOfBytesToUnlockLow,
22290   DWORD nNumberOfBytesToUnlockHigh
22291 ){
22292   winFile *pFile = HANDLE_TO_WINFILE(phFile);
22293   BOOL bReturn = FALSE;
22294
22295   if (!pFile->hMutex) return TRUE;
22296   winceMutexAcquire(pFile->hMutex);
22297
22298   /* Releasing a reader lock or an exclusive lock */
22299   if (dwFileOffsetLow >= SHARED_FIRST &&
22300        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
22301     /* Did we have an exclusive lock? */
22302     if (pFile->local.bExclusive){
22303       pFile->local.bExclusive = FALSE;
22304       pFile->shared->bExclusive = FALSE;
22305       bReturn = TRUE;
22306     }
22307
22308     /* Did we just have a reader lock? */
22309     else if (pFile->local.nReaders){
22310       pFile->local.nReaders --;
22311       if (pFile->local.nReaders == 0)
22312       {
22313         pFile->shared->nReaders --;
22314       }
22315       bReturn = TRUE;
22316     }
22317   }
22318
22319   /* Releasing a pending lock */
22320   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
22321     if (pFile->local.bPending){
22322       pFile->local.bPending = FALSE;
22323       pFile->shared->bPending = FALSE;
22324       bReturn = TRUE;
22325     }
22326   }
22327   /* Releasing a reserved lock */
22328   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
22329     if (pFile->local.bReserved) {
22330       pFile->local.bReserved = FALSE;
22331       pFile->shared->bReserved = FALSE;
22332       bReturn = TRUE;
22333     }
22334   }
22335
22336   winceMutexRelease(pFile->hMutex);
22337   return bReturn;
22338 }
22339
22340 /*
22341 ** An implementation of the LockFileEx() API of windows for wince
22342 */
22343 static BOOL winceLockFileEx(
22344   HANDLE *phFile,
22345   DWORD dwFlags,
22346   DWORD dwReserved,
22347   DWORD nNumberOfBytesToLockLow,
22348   DWORD nNumberOfBytesToLockHigh,
22349   LPOVERLAPPED lpOverlapped
22350 ){
22351   /* If the caller wants a shared read lock, forward this call
22352   ** to winceLockFile */
22353   if (lpOverlapped->Offset == SHARED_FIRST &&
22354       dwFlags == 1 &&
22355       nNumberOfBytesToLockLow == SHARED_SIZE){
22356     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
22357   }
22358   return FALSE;
22359 }
22360 /*
22361 ** End of the special code for wince
22362 *****************************************************************************/
22363 #endif /* OS_WINCE */
22364
22365 /*****************************************************************************
22366 ** The next group of routines implement the I/O methods specified
22367 ** by the sqlite3_io_methods object.
22368 ******************************************************************************/
22369
22370 /*
22371 ** Close a file.
22372 **
22373 ** It is reported that an attempt to close a handle might sometimes
22374 ** fail.  This is a very unreasonable result, but windows is notorious
22375 ** for being unreasonable so I do not doubt that it might happen.  If
22376 ** the close fails, we pause for 100 milliseconds and try again.  As
22377 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
22378 ** giving up and returning an error.
22379 */
22380 #define MX_CLOSE_ATTEMPT 3
22381 static int winClose(sqlite3_file *id){
22382   int rc, cnt = 0;
22383   winFile *pFile = (winFile*)id;
22384   OSTRACE2("CLOSE %d\n", pFile->h);
22385   do{
22386     rc = CloseHandle(pFile->h);
22387   }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
22388 #if OS_WINCE
22389 #define WINCE_DELETION_ATTEMPTS 3
22390   winceDestroyLock(pFile);
22391   if( pFile->zDeleteOnClose ){
22392     int cnt = 0;
22393     while(
22394            DeleteFileW(pFile->zDeleteOnClose)==0
22395         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
22396         && cnt++ < WINCE_DELETION_ATTEMPTS
22397     ){
22398        Sleep(100);  /* Wait a little before trying again */
22399     }
22400     free(pFile->zDeleteOnClose);
22401   }
22402 #endif
22403   OpenCounter(-1);
22404   return rc ? SQLITE_OK : SQLITE_IOERR;
22405 }
22406
22407 /*
22408 ** Some microsoft compilers lack this definition.
22409 */
22410 #ifndef INVALID_SET_FILE_POINTER
22411 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
22412 #endif
22413
22414 /*
22415 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22416 ** bytes were read successfully and SQLITE_IOERR if anything goes
22417 ** wrong.
22418 */
22419 static int winRead(
22420   sqlite3_file *id,          /* File to read from */
22421   void *pBuf,                /* Write content into this buffer */
22422   int amt,                   /* Number of bytes to read */
22423   sqlite3_int64 offset       /* Begin reading at this offset */
22424 ){
22425   LONG upperBits = (offset>>32) & 0x7fffffff;
22426   LONG lowerBits = offset & 0xffffffff;
22427   DWORD rc;
22428   DWORD got;
22429   winFile *pFile = (winFile*)id;
22430   assert( id!=0 );
22431   SimulateIOError(return SQLITE_IOERR_READ);
22432   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
22433   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
22434   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
22435     return SQLITE_FULL;
22436   }
22437   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
22438     return SQLITE_IOERR_READ;
22439   }
22440   if( got==(DWORD)amt ){
22441     return SQLITE_OK;
22442   }else{
22443     memset(&((char*)pBuf)[got], 0, amt-got);
22444     return SQLITE_IOERR_SHORT_READ;
22445   }
22446 }
22447
22448 /*
22449 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22450 ** or some other error code on failure.
22451 */
22452 static int winWrite(
22453   sqlite3_file *id,         /* File to write into */
22454   const void *pBuf,         /* The bytes to be written */
22455   int amt,                  /* Number of bytes to write */
22456   sqlite3_int64 offset      /* Offset into the file to begin writing at */
22457 ){
22458   LONG upperBits = (offset>>32) & 0x7fffffff;
22459   LONG lowerBits = offset & 0xffffffff;
22460   DWORD rc;
22461   DWORD wrote;
22462   winFile *pFile = (winFile*)id;
22463   assert( id!=0 );
22464   SimulateIOError(return SQLITE_IOERR_WRITE);
22465   SimulateDiskfullError(return SQLITE_FULL);
22466   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
22467   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
22468   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
22469     return SQLITE_FULL;
22470   }
22471   assert( amt>0 );
22472   while(
22473      amt>0
22474      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
22475      && wrote>0
22476   ){
22477     amt -= wrote;
22478     pBuf = &((char*)pBuf)[wrote];
22479   }
22480   if( !rc || amt>(int)wrote ){
22481     return SQLITE_FULL;
22482   }
22483   return SQLITE_OK;
22484 }
22485
22486 /*
22487 ** Truncate an open file to a specified size
22488 */
22489 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
22490   LONG upperBits = (nByte>>32) & 0x7fffffff;
22491   LONG lowerBits = nByte & 0xffffffff;
22492   winFile *pFile = (winFile*)id;
22493   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
22494   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
22495   SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
22496   SetEndOfFile(pFile->h);
22497   return SQLITE_OK;
22498 }
22499
22500 #ifdef SQLITE_TEST
22501 /*
22502 ** Count the number of fullsyncs and normal syncs.  This is used to test
22503 ** that syncs and fullsyncs are occuring at the right times.
22504 */
22505 SQLITE_API int sqlite3_sync_count = 0;
22506 SQLITE_API int sqlite3_fullsync_count = 0;
22507 #endif
22508
22509 /*
22510 ** Make sure all writes to a particular file are committed to disk.
22511 */
22512 static int winSync(sqlite3_file *id, int flags){
22513   winFile *pFile = (winFile*)id;
22514   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
22515 #ifdef SQLITE_TEST
22516   if( flags & SQLITE_SYNC_FULL ){
22517     sqlite3_fullsync_count++;
22518   }
22519   sqlite3_sync_count++;
22520 #endif
22521   if( FlushFileBuffers(pFile->h) ){
22522     return SQLITE_OK;
22523   }else{
22524     return SQLITE_IOERR;
22525   }
22526 }
22527
22528 /*
22529 ** Determine the current size of a file in bytes
22530 */
22531 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
22532   winFile *pFile = (winFile*)id;
22533   DWORD upperBits, lowerBits;
22534   SimulateIOError(return SQLITE_IOERR_FSTAT);
22535   lowerBits = GetFileSize(pFile->h, &upperBits);
22536   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
22537   return SQLITE_OK;
22538 }
22539
22540 /*
22541 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
22542 */
22543 #ifndef LOCKFILE_FAIL_IMMEDIATELY
22544 # define LOCKFILE_FAIL_IMMEDIATELY 1
22545 #endif
22546
22547 /*
22548 ** Acquire a reader lock.
22549 ** Different API routines are called depending on whether or not this
22550 ** is Win95 or WinNT.
22551 */
22552 static int getReadLock(winFile *pFile){
22553   int res;
22554   if( isNT() ){
22555     OVERLAPPED ovlp;
22556     ovlp.Offset = SHARED_FIRST;
22557     ovlp.OffsetHigh = 0;
22558     ovlp.hEvent = 0;
22559     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
22560                      0, SHARED_SIZE, 0, &ovlp);
22561   }else{
22562     int lk;
22563     sqlite3_randomness(sizeof(lk), &lk);
22564     pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
22565     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
22566   }
22567   return res;
22568 }
22569
22570 /*
22571 ** Undo a readlock
22572 */
22573 static int unlockReadLock(winFile *pFile){
22574   int res;
22575   if( isNT() ){
22576     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
22577   }else{
22578     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
22579   }
22580   return res;
22581 }
22582
22583 /*
22584 ** Lock the file with the lock specified by parameter locktype - one
22585 ** of the following:
22586 **
22587 **     (1) SHARED_LOCK
22588 **     (2) RESERVED_LOCK
22589 **     (3) PENDING_LOCK
22590 **     (4) EXCLUSIVE_LOCK
22591 **
22592 ** Sometimes when requesting one lock state, additional lock states
22593 ** are inserted in between.  The locking might fail on one of the later
22594 ** transitions leaving the lock state different from what it started but
22595 ** still short of its goal.  The following chart shows the allowed
22596 ** transitions and the inserted intermediate states:
22597 **
22598 **    UNLOCKED -> SHARED
22599 **    SHARED -> RESERVED
22600 **    SHARED -> (PENDING) -> EXCLUSIVE
22601 **    RESERVED -> (PENDING) -> EXCLUSIVE
22602 **    PENDING -> EXCLUSIVE
22603 **
22604 ** This routine will only increase a lock.  The winUnlock() routine
22605 ** erases all locks at once and returns us immediately to locking level 0.
22606 ** It is not possible to lower the locking level one step at a time.  You
22607 ** must go straight to locking level 0.
22608 */
22609 static int winLock(sqlite3_file *id, int locktype){
22610   int rc = SQLITE_OK;    /* Return code from subroutines */
22611   int res = 1;           /* Result of a windows lock call */
22612   int newLocktype;       /* Set pFile->locktype to this value before exiting */
22613   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22614   winFile *pFile = (winFile*)id;
22615
22616   assert( pFile!=0 );
22617   OSTRACE5("LOCK %d %d was %d(%d)\n",
22618           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
22619
22620   /* If there is already a lock of this type or more restrictive on the
22621   ** OsFile, do nothing. Don't use the end_lock: exit path, as
22622   ** sqlite3OsEnterMutex() hasn't been called yet.
22623   */
22624   if( pFile->locktype>=locktype ){
22625     return SQLITE_OK;
22626   }
22627
22628   /* Make sure the locking sequence is correct
22629   */
22630   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22631   assert( locktype!=PENDING_LOCK );
22632   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22633
22634   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22635   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
22636   ** the PENDING_LOCK byte is temporary.
22637   */
22638   newLocktype = pFile->locktype;
22639   if( pFile->locktype==NO_LOCK
22640    || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22641   ){
22642     int cnt = 3;
22643     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
22644       /* Try 3 times to get the pending lock.  The pending lock might be
22645       ** held by another reader process who will release it momentarily.
22646       */
22647       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
22648       Sleep(1);
22649     }
22650     gotPendingLock = res;
22651   }
22652
22653   /* Acquire a shared lock
22654   */
22655   if( locktype==SHARED_LOCK && res ){
22656     assert( pFile->locktype==NO_LOCK );
22657     res = getReadLock(pFile);
22658     if( res ){
22659       newLocktype = SHARED_LOCK;
22660     }
22661   }
22662
22663   /* Acquire a RESERVED lock
22664   */
22665   if( locktype==RESERVED_LOCK && res ){
22666     assert( pFile->locktype==SHARED_LOCK );
22667     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
22668     if( res ){
22669       newLocktype = RESERVED_LOCK;
22670     }
22671   }
22672
22673   /* Acquire a PENDING lock
22674   */
22675   if( locktype==EXCLUSIVE_LOCK && res ){
22676     newLocktype = PENDING_LOCK;
22677     gotPendingLock = 0;
22678   }
22679
22680   /* Acquire an EXCLUSIVE lock
22681   */
22682   if( locktype==EXCLUSIVE_LOCK && res ){
22683     assert( pFile->locktype>=SHARED_LOCK );
22684     res = unlockReadLock(pFile);
22685     OSTRACE2("unreadlock = %d\n", res);
22686     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
22687     if( res ){
22688       newLocktype = EXCLUSIVE_LOCK;
22689     }else{
22690       OSTRACE2("error-code = %d\n", GetLastError());
22691       getReadLock(pFile);
22692     }
22693   }
22694
22695   /* If we are holding a PENDING lock that ought to be released, then
22696   ** release it now.
22697   */
22698   if( gotPendingLock && locktype==SHARED_LOCK ){
22699     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
22700   }
22701
22702   /* Update the state of the lock has held in the file descriptor then
22703   ** return the appropriate result code.
22704   */
22705   if( res ){
22706     rc = SQLITE_OK;
22707   }else{
22708     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22709            locktype, newLocktype);
22710     rc = SQLITE_BUSY;
22711   }
22712   pFile->locktype = newLocktype;
22713   return rc;
22714 }
22715
22716 /*
22717 ** This routine checks if there is a RESERVED lock held on the specified
22718 ** file by this or any other process. If such a lock is held, return
22719 ** non-zero, otherwise zero.
22720 */
22721 static int winCheckReservedLock(sqlite3_file *id){
22722   int rc;
22723   winFile *pFile = (winFile*)id;
22724   assert( pFile!=0 );
22725   if( pFile->locktype>=RESERVED_LOCK ){
22726     rc = 1;
22727     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
22728   }else{
22729     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
22730     if( rc ){
22731       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
22732     }
22733     rc = !rc;
22734     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
22735   }
22736   return rc;
22737 }
22738
22739 /*
22740 ** Lower the locking level on file descriptor id to locktype.  locktype
22741 ** must be either NO_LOCK or SHARED_LOCK.
22742 **
22743 ** If the locking level of the file descriptor is already at or below
22744 ** the requested locking level, this routine is a no-op.
22745 **
22746 ** It is not possible for this routine to fail if the second argument
22747 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22748 ** might return SQLITE_IOERR;
22749 */
22750 static int winUnlock(sqlite3_file *id, int locktype){
22751   int type;
22752   winFile *pFile = (winFile*)id;
22753   int rc = SQLITE_OK;
22754   assert( pFile!=0 );
22755   assert( locktype<=SHARED_LOCK );
22756   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
22757           pFile->locktype, pFile->sharedLockByte);
22758   type = pFile->locktype;
22759   if( type>=EXCLUSIVE_LOCK ){
22760     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
22761     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
22762       /* This should never happen.  We should always be able to
22763       ** reacquire the read lock */
22764       rc = SQLITE_IOERR_UNLOCK;
22765     }
22766   }
22767   if( type>=RESERVED_LOCK ){
22768     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
22769   }
22770   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22771     unlockReadLock(pFile);
22772   }
22773   if( type>=PENDING_LOCK ){
22774     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
22775   }
22776   pFile->locktype = locktype;
22777   return rc;
22778 }
22779
22780 /*
22781 ** Control and query of the open file handle.
22782 */
22783 static int winFileControl(sqlite3_file *id, int op, void *pArg){
22784   switch( op ){
22785     case SQLITE_FCNTL_LOCKSTATE: {
22786       *(int*)pArg = ((winFile*)id)->locktype;
22787       return SQLITE_OK;
22788     }
22789   }
22790   return SQLITE_ERROR;
22791 }
22792
22793 /*
22794 ** Return the sector size in bytes of the underlying block device for
22795 ** the specified file. This is almost always 512 bytes, but may be
22796 ** larger for some devices.
22797 **
22798 ** SQLite code assumes this function cannot fail. It also assumes that
22799 ** if two files are created in the same file-system directory (i.e.
22800 ** a database and its journal file) that the sector size will be the
22801 ** same for both.
22802 */
22803 static int winSectorSize(sqlite3_file *id){
22804   return SQLITE_DEFAULT_SECTOR_SIZE;
22805 }
22806
22807 /*
22808 ** Return a vector of device characteristics.
22809 */
22810 static int winDeviceCharacteristics(sqlite3_file *id){
22811   return 0;
22812 }
22813
22814 /*
22815 ** This vector defines all the methods that can operate on an
22816 ** sqlite3_file for win32.
22817 */
22818 static const sqlite3_io_methods winIoMethod = {
22819   1,                        /* iVersion */
22820   winClose,
22821   winRead,
22822   winWrite,
22823   winTruncate,
22824   winSync,
22825   winFileSize,
22826   winLock,
22827   winUnlock,
22828   winCheckReservedLock,
22829   winFileControl,
22830   winSectorSize,
22831   winDeviceCharacteristics
22832 };
22833
22834 /***************************************************************************
22835 ** Here ends the I/O methods that form the sqlite3_io_methods object.
22836 **
22837 ** The next block of code implements the VFS methods.
22838 ****************************************************************************/
22839
22840 /*
22841 ** Convert a UTF-8 filename into whatever form the underlying
22842 ** operating system wants filenames in.  Space to hold the result
22843 ** is obtained from malloc and must be freed by the calling
22844 ** function.
22845 */
22846 static void *convertUtf8Filename(const char *zFilename){
22847   void *zConverted = 0;
22848   if( isNT() ){
22849     zConverted = utf8ToUnicode(zFilename);
22850   }else{
22851     zConverted = utf8ToMbcs(zFilename);
22852   }
22853   /* caller will handle out of memory */
22854   return zConverted;
22855 }
22856
22857 /*
22858 ** Open a file.
22859 */
22860 static int winOpen(
22861   sqlite3_vfs *pVfs,        /* Not used */
22862   const char *zName,        /* Name of the file (UTF-8) */
22863   sqlite3_file *id,         /* Write the SQLite file handle here */
22864   int flags,                /* Open mode flags */
22865   int *pOutFlags            /* Status return flags */
22866 ){
22867   HANDLE h;
22868   DWORD dwDesiredAccess;
22869   DWORD dwShareMode;
22870   DWORD dwCreationDisposition;
22871   DWORD dwFlagsAndAttributes = 0;
22872   int isTemp;
22873   winFile *pFile = (winFile*)id;
22874   void *zConverted = convertUtf8Filename(zName);
22875   if( zConverted==0 ){
22876     return SQLITE_NOMEM;
22877   }
22878
22879   if( flags & SQLITE_OPEN_READWRITE ){
22880     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
22881   }else{
22882     dwDesiredAccess = GENERIC_READ;
22883   }
22884   if( flags & SQLITE_OPEN_CREATE ){
22885     dwCreationDisposition = OPEN_ALWAYS;
22886   }else{
22887     dwCreationDisposition = OPEN_EXISTING;
22888   }
22889   if( flags & SQLITE_OPEN_MAIN_DB ){
22890     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
22891   }else{
22892     dwShareMode = 0;
22893   }
22894   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
22895 #if OS_WINCE
22896     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
22897 #else
22898     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
22899                                | FILE_ATTRIBUTE_HIDDEN
22900                                | FILE_FLAG_DELETE_ON_CLOSE;
22901 #endif
22902     isTemp = 1;
22903   }else{
22904     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
22905     isTemp = 0;
22906   }
22907   /* Reports from the internet are that performance is always
22908   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
22909   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
22910   if( isNT() ){
22911     h = CreateFileW((WCHAR*)zConverted,
22912        dwDesiredAccess,
22913        dwShareMode,
22914        NULL,
22915        dwCreationDisposition,
22916        dwFlagsAndAttributes,
22917        NULL
22918     );
22919   }else{
22920 #if OS_WINCE
22921     return SQLITE_NOMEM;
22922 #else
22923     h = CreateFileA((char*)zConverted,
22924        dwDesiredAccess,
22925        dwShareMode,
22926        NULL,
22927        dwCreationDisposition,
22928        dwFlagsAndAttributes,
22929        NULL
22930     );
22931 #endif
22932   }
22933   if( h==INVALID_HANDLE_VALUE ){
22934     free(zConverted);
22935     if( flags & SQLITE_OPEN_READWRITE ){
22936       return winOpen(0, zName, id, 
22937              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
22938     }else{
22939       return SQLITE_CANTOPEN;
22940     }
22941   }
22942   if( pOutFlags ){
22943     if( flags & SQLITE_OPEN_READWRITE ){
22944       *pOutFlags = SQLITE_OPEN_READWRITE;
22945     }else{
22946       *pOutFlags = SQLITE_OPEN_READONLY;
22947     }
22948   }
22949   memset(pFile, 0, sizeof(*pFile));
22950   pFile->pMethod = &winIoMethod;
22951   pFile->h = h;
22952 #if OS_WINCE
22953   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
22954                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
22955        && !winceCreateLock(zName, pFile)
22956   ){
22957     CloseHandle(h);
22958     free(zConverted);
22959     return SQLITE_CANTOPEN;
22960   }
22961   if( isTemp ){
22962     pFile->zDeleteOnClose = zConverted;
22963   }else
22964 #endif
22965   {
22966     free(zConverted);
22967   }
22968   OpenCounter(+1);
22969   return SQLITE_OK;
22970 }
22971
22972 /*
22973 ** Delete the named file.
22974 **
22975 ** Note that windows does not allow a file to be deleted if some other
22976 ** process has it open.  Sometimes a virus scanner or indexing program
22977 ** will open a journal file shortly after it is created in order to do
22978 ** whatever does.  While this other process is holding the
22979 ** file open, we will be unable to delete it.  To work around this
22980 ** problem, we delay 100 milliseconds and try to delete again.  Up
22981 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
22982 ** up and returning an error.
22983 */
22984 #define MX_DELETION_ATTEMPTS 5
22985 static int winDelete(
22986   sqlite3_vfs *pVfs,          /* Not used on win32 */
22987   const char *zFilename,      /* Name of file to delete */
22988   int syncDir                 /* Not used on win32 */
22989 ){
22990   int cnt = 0;
22991   int rc;
22992   void *zConverted = convertUtf8Filename(zFilename);
22993   if( zConverted==0 ){
22994     return SQLITE_NOMEM;
22995   }
22996   SimulateIOError(return SQLITE_IOERR_DELETE);
22997   if( isNT() ){
22998     do{
22999       DeleteFileW(zConverted);
23000     }while( (rc = GetFileAttributesW(zConverted))!=0xffffffff 
23001             && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
23002   }else{
23003 #if OS_WINCE
23004     return SQLITE_NOMEM;
23005 #else
23006     do{
23007       DeleteFileA(zConverted);
23008     }while( (rc = GetFileAttributesA(zConverted))!=0xffffffff
23009             && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
23010 #endif
23011   }
23012   free(zConverted);
23013   OSTRACE2("DELETE \"%s\"\n", zFilename);
23014   return rc==0xffffffff ? SQLITE_OK : SQLITE_IOERR_DELETE;
23015 }
23016
23017 /*
23018 ** Check the existance and status of a file.
23019 */
23020 static int winAccess(
23021   sqlite3_vfs *pVfs,         /* Not used on win32 */
23022   const char *zFilename,     /* Name of file to check */
23023   int flags                  /* Type of test to make on this file */
23024 ){
23025   DWORD attr;
23026   int rc;
23027   void *zConverted = convertUtf8Filename(zFilename);
23028   if( zConverted==0 ){
23029     return SQLITE_NOMEM;
23030   }
23031   if( isNT() ){
23032     attr = GetFileAttributesW((WCHAR*)zConverted);
23033   }else{
23034 #if OS_WINCE
23035     return SQLITE_NOMEM;
23036 #else
23037     attr = GetFileAttributesA((char*)zConverted);
23038 #endif
23039   }
23040   free(zConverted);
23041   switch( flags ){
23042     case SQLITE_ACCESS_READ:
23043     case SQLITE_ACCESS_EXISTS:
23044       rc = attr!=0xffffffff;
23045       break;
23046     case SQLITE_ACCESS_READWRITE:
23047       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
23048       break;
23049     default:
23050       assert(!"Invalid flags argument");
23051   }
23052   return rc;
23053 }
23054
23055
23056 /*
23057 ** Create a temporary file name in zBuf.  zBuf must be big enough to
23058 ** hold at pVfs->mxPathname characters.
23059 */
23060 static int winGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23061   static char zChars[] =
23062     "abcdefghijklmnopqrstuvwxyz"
23063     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23064     "0123456789";
23065   int i, j;
23066   char zTempPath[MAX_PATH+1];
23067   if( sqlite3_temp_directory ){
23068     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
23069   }else if( isNT() ){
23070     char *zMulti;
23071     WCHAR zWidePath[MAX_PATH];
23072     GetTempPathW(MAX_PATH-30, zWidePath);
23073     zMulti = unicodeToUtf8(zWidePath);
23074     if( zMulti ){
23075       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
23076       free(zMulti);
23077     }else{
23078       return SQLITE_NOMEM;
23079     }
23080   }else{
23081     char *zUtf8;
23082     char zMbcsPath[MAX_PATH];
23083     GetTempPathA(MAX_PATH-30, zMbcsPath);
23084     zUtf8 = mbcsToUtf8(zMbcsPath);
23085     if( zUtf8 ){
23086       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
23087       free(zUtf8);
23088     }else{
23089       return SQLITE_NOMEM;
23090     }
23091   }
23092   for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
23093   zTempPath[i] = 0;
23094   sqlite3_snprintf(nBuf-30, zBuf,
23095                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23096   j = strlen(zBuf);
23097   sqlite3_randomness(20, &zBuf[j]);
23098   for(i=0; i<20; i++, j++){
23099     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23100   }
23101   zBuf[j] = 0;
23102   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
23103   return SQLITE_OK; 
23104 }
23105
23106 /*
23107 ** Turn a relative pathname into a full pathname.  Write the full
23108 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
23109 ** bytes in size.
23110 */
23111 static int winFullPathname(
23112   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
23113   const char *zRelative,        /* Possibly relative input path */
23114   int nFull,                    /* Size of output buffer in bytes */
23115   char *zFull                   /* Output buffer */
23116 ){
23117
23118 #if defined(__CYGWIN__)
23119   cygwin_conv_to_full_win32_path(zRelative, zFull);
23120   return SQLITE_OK;
23121 #endif
23122
23123 #if OS_WINCE
23124   /* WinCE has no concept of a relative pathname, or so I am told. */
23125   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
23126   return SQLITE_OK;
23127 #endif
23128
23129 #if !OS_WINCE && !defined(__CYGWIN__)
23130   int nByte;
23131   void *zConverted;
23132   char *zOut;
23133   zConverted = convertUtf8Filename(zRelative);
23134   if( isNT() ){
23135     WCHAR *zTemp;
23136     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
23137     zTemp = malloc( nByte*sizeof(zTemp[0]) );
23138     if( zTemp==0 ){
23139       free(zConverted);
23140       return SQLITE_NOMEM;
23141     }
23142     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
23143     free(zConverted);
23144     zOut = unicodeToUtf8(zTemp);
23145     free(zTemp);
23146   }else{
23147     char *zTemp;
23148     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
23149     zTemp = malloc( nByte*sizeof(zTemp[0]) );
23150     if( zTemp==0 ){
23151       free(zConverted);
23152       return SQLITE_NOMEM;
23153     }
23154     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
23155     free(zConverted);
23156     zOut = mbcsToUtf8(zTemp);
23157     free(zTemp);
23158   }
23159   if( zOut ){
23160     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
23161     free(zOut);
23162     return SQLITE_OK;
23163   }else{
23164     return SQLITE_NOMEM;
23165   }
23166 #endif
23167 }
23168
23169 #ifndef SQLITE_OMIT_LOAD_EXTENSION
23170 /*
23171 ** Interfaces for opening a shared library, finding entry points
23172 ** within the shared library, and closing the shared library.
23173 */
23174 /*
23175 ** Interfaces for opening a shared library, finding entry points
23176 ** within the shared library, and closing the shared library.
23177 */
23178 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
23179   HANDLE h;
23180   void *zConverted = convertUtf8Filename(zFilename);
23181   if( zConverted==0 ){
23182     return 0;
23183   }
23184   if( isNT() ){
23185     h = LoadLibraryW((WCHAR*)zConverted);
23186   }else{
23187 #if OS_WINCE
23188     return 0;
23189 #else
23190     h = LoadLibraryA((char*)zConverted);
23191 #endif
23192   }
23193   free(zConverted);
23194   return (void*)h;
23195 }
23196 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
23197 #if OS_WINCE
23198   int error = GetLastError();
23199   if( error>0x7FFFFFF ){
23200     sqlite3_snprintf(nBuf, zBufOut, "OsError 0x%x", error);
23201   }else{
23202     sqlite3_snprintf(nBuf, zBufOut, "OsError %d", error);
23203   }
23204 #else
23205   FormatMessageA(
23206     FORMAT_MESSAGE_FROM_SYSTEM,
23207     NULL,
23208     GetLastError(),
23209     0,
23210     zBufOut,
23211     nBuf-1,
23212     0
23213   );
23214 #endif
23215 }
23216 void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
23217 #if OS_WINCE
23218   /* The GetProcAddressA() routine is only available on wince. */
23219   return GetProcAddressA((HANDLE)pHandle, zSymbol);
23220 #else
23221   /* All other windows platforms expect GetProcAddress() to take
23222   ** an Ansi string regardless of the _UNICODE setting */
23223   return GetProcAddress((HANDLE)pHandle, zSymbol);
23224 #endif
23225 }
23226 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
23227   FreeLibrary((HANDLE)pHandle);
23228 }
23229 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
23230   #define winDlOpen  0
23231   #define winDlError 0
23232   #define winDlSym   0
23233   #define winDlClose 0
23234 #endif
23235
23236
23237 /*
23238 ** Write up to nBuf bytes of randomness into zBuf.
23239 */
23240 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
23241   int n = 0;
23242   if( sizeof(SYSTEMTIME)<=nBuf-n ){
23243     SYSTEMTIME x;
23244     GetSystemTime(&x);
23245     memcpy(&zBuf[n], &x, sizeof(x));
23246     n += sizeof(x);
23247   }
23248   if( sizeof(DWORD)<=nBuf-n ){
23249     DWORD pid = GetCurrentProcessId();
23250     memcpy(&zBuf[n], &pid, sizeof(pid));
23251     n += sizeof(pid);
23252   }
23253   if( sizeof(DWORD)<=nBuf-n ){
23254     DWORD cnt = GetTickCount();
23255     memcpy(&zBuf[n], &cnt, sizeof(cnt));
23256     n += sizeof(cnt);
23257   }
23258   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
23259     LARGE_INTEGER i;
23260     QueryPerformanceCounter(&i);
23261     memcpy(&zBuf[n], &i, sizeof(i));
23262     n += sizeof(i);
23263   }
23264   return n;
23265 }
23266
23267
23268 /*
23269 ** Sleep for a little while.  Return the amount of time slept.
23270 */
23271 static int winSleep(sqlite3_vfs *pVfs, int microsec){
23272   Sleep((microsec+999)/1000);
23273   return ((microsec+999)/1000)*1000;
23274 }
23275
23276 /*
23277 ** The following variable, if set to a non-zero value, becomes the result
23278 ** returned from sqlite3OsCurrentTime().  This is used for testing.
23279 */
23280 #ifdef SQLITE_TEST
23281 SQLITE_API int sqlite3_current_time = 0;
23282 #endif
23283
23284 /*
23285 ** Find the current time (in Universal Coordinated Time).  Write the
23286 ** current time and date as a Julian Day number into *prNow and
23287 ** return 0.  Return 1 if the time and date cannot be found.
23288 */
23289 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
23290   FILETIME ft;
23291   /* FILETIME structure is a 64-bit value representing the number of 
23292      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
23293   */
23294   double now;
23295 #if OS_WINCE
23296   SYSTEMTIME time;
23297   GetSystemTime(&time);
23298   SystemTimeToFileTime(&time,&ft);
23299 #else
23300   GetSystemTimeAsFileTime( &ft );
23301 #endif
23302   now = ((double)ft.dwHighDateTime) * 4294967296.0; 
23303   *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
23304 #ifdef SQLITE_TEST
23305   if( sqlite3_current_time ){
23306     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
23307   }
23308 #endif
23309   return 0;
23310 }
23311
23312
23313 /*
23314 ** Return a pointer to the sqlite3DefaultVfs structure.   We use
23315 ** a function rather than give the structure global scope because
23316 ** some compilers (MSVC) do not allow forward declarations of
23317 ** initialized structures.
23318 */
23319 SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void){
23320   static sqlite3_vfs winVfs = {
23321     1,                 /* iVersion */
23322     sizeof(winFile),   /* szOsFile */
23323     MAX_PATH,          /* mxPathname */
23324     0,                 /* pNext */
23325     "win32",           /* zName */
23326     0,                 /* pAppData */
23327   
23328     winOpen,           /* xOpen */
23329     winDelete,         /* xDelete */
23330     winAccess,         /* xAccess */
23331     winGetTempname,    /* xGetTempName */
23332     winFullPathname,   /* xFullPathname */
23333     winDlOpen,         /* xDlOpen */
23334     winDlError,        /* xDlError */
23335     winDlSym,          /* xDlSym */
23336     winDlClose,        /* xDlClose */
23337     winRandomness,     /* xRandomness */
23338     winSleep,          /* xSleep */
23339     winCurrentTime     /* xCurrentTime */
23340   };
23341   
23342   return &winVfs;
23343 }
23344
23345 #endif /* OS_WIN */
23346
23347 /************** End of os_win.c **********************************************/
23348 /************** Begin file bitvec.c ******************************************/
23349 /*
23350 ** 2008 February 16
23351 **
23352 ** The author disclaims copyright to this source code.  In place of
23353 ** a legal notice, here is a blessing:
23354 **
23355 **    May you do good and not evil.
23356 **    May you find forgiveness for yourself and forgive others.
23357 **    May you share freely, never taking more than you give.
23358 **
23359 *************************************************************************
23360 ** This file implements an object that represents a fixed-length
23361 ** bitmap.  Bits are numbered starting with 1.
23362 **
23363 ** A bitmap is used to record what pages a database file have been
23364 ** journalled during a transaction.  Usually only a few pages are
23365 ** journalled.  So the bitmap is usually sparse and has low cardinality.
23366 ** But sometimes (for example when during a DROP of a large table) most
23367 ** or all of the pages get journalled.  In those cases, the bitmap becomes
23368 ** dense.  The algorithm needs to handle both cases well.
23369 **
23370 ** The size of the bitmap is fixed when the object is created.
23371 **
23372 ** All bits are clear when the bitmap is created.  Individual bits
23373 ** may be set or cleared one at a time.
23374 **
23375 ** Test operations are about 100 times more common that set operations.
23376 ** Clear operations are exceedingly rare.  There are usually between
23377 ** 5 and 500 set operations per Bitvec object, though the number of sets can
23378 ** sometimes grow into tens of thousands or larger.  The size of the
23379 ** Bitvec object is the number of pages in the database file at the
23380 ** start of a transaction, and is thus usually less than a few thousand,
23381 ** but can be as large as 2 billion for a really big database.
23382 **
23383 ** @(#) $Id: bitvec.c,v 1.5 2008/05/13 13:27:34 drh Exp $
23384 */
23385
23386 #define BITVEC_SZ        512
23387 /* Round the union size down to the nearest pointer boundary, since that's how 
23388 ** it will be aligned within the Bitvec struct. */
23389 #define BITVEC_USIZE     (((BITVEC_SZ-12)/sizeof(Bitvec*))*sizeof(Bitvec*))
23390 #define BITVEC_NCHAR     BITVEC_USIZE
23391 #define BITVEC_NBIT      (BITVEC_NCHAR*8)
23392 #define BITVEC_NINT      (BITVEC_USIZE/4)
23393 #define BITVEC_MXHASH    (BITVEC_NINT/2)
23394 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
23395
23396 #define BITVEC_HASH(X)   (((X)*37)%BITVEC_NINT)
23397
23398 /*
23399 ** A bitmap is an instance of the following structure.
23400 **
23401 ** This bitmap records the existance of zero or more bits
23402 ** with values between 1 and iSize, inclusive.
23403 **
23404 ** There are three possible representations of the bitmap.
23405 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
23406 ** bitmap.  The least significant bit is bit 1.
23407 **
23408 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
23409 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
23410 **
23411 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
23412 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
23413 ** handles up to iDivisor separate values of i.  apSub[0] holds
23414 ** values between 1 and iDivisor.  apSub[1] holds values between
23415 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
23416 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
23417 ** to hold deal with values between 1 and iDivisor.
23418 */
23419 struct Bitvec {
23420   u32 iSize;      /* Maximum bit index */
23421   u32 nSet;       /* Number of bits that are set */
23422   u32 iDivisor;   /* Number of bits handled by each apSub[] entry */
23423   union {
23424     u8 aBitmap[BITVEC_NCHAR];    /* Bitmap representation */
23425     u32 aHash[BITVEC_NINT];      /* Hash table representation */
23426     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
23427   } u;
23428 };
23429
23430 /*
23431 ** Create a new bitmap object able to handle bits between 0 and iSize,
23432 ** inclusive.  Return a pointer to the new object.  Return NULL if 
23433 ** malloc fails.
23434 */
23435 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
23436   Bitvec *p;
23437   assert( sizeof(*p)==BITVEC_SZ );
23438   p = sqlite3MallocZero( sizeof(*p) );
23439   if( p ){
23440     p->iSize = iSize;
23441   }
23442   return p;
23443 }
23444
23445 /*
23446 ** Check to see if the i-th bit is set.  Return true or false.
23447 ** If p is NULL (if the bitmap has not been created) or if
23448 ** i is out of range, then return false.
23449 */
23450 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
23451   if( p==0 ) return 0;
23452   if( i>p->iSize || i==0 ) return 0;
23453   if( p->iSize<=BITVEC_NBIT ){
23454     i--;
23455     return (p->u.aBitmap[i/8] & (1<<(i&7)))!=0;
23456   }
23457   if( p->iDivisor>0 ){
23458     u32 bin = (i-1)/p->iDivisor;
23459     i = (i-1)%p->iDivisor + 1;
23460     return sqlite3BitvecTest(p->u.apSub[bin], i);
23461   }else{
23462     u32 h = BITVEC_HASH(i);
23463     while( p->u.aHash[h] ){
23464       if( p->u.aHash[h]==i ) return 1;
23465       h++;
23466       if( h>=BITVEC_NINT ) h = 0;
23467     }
23468     return 0;
23469   }
23470 }
23471
23472 /*
23473 ** Set the i-th bit.  Return 0 on success and an error code if
23474 ** anything goes wrong.
23475 */
23476 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
23477   u32 h;
23478   assert( p!=0 );
23479   assert( i>0 );
23480   assert( i<=p->iSize );
23481   if( p->iSize<=BITVEC_NBIT ){
23482     i--;
23483     p->u.aBitmap[i/8] |= 1 << (i&7);
23484     return SQLITE_OK;
23485   }
23486   if( p->iDivisor ){
23487     u32 bin = (i-1)/p->iDivisor;
23488     i = (i-1)%p->iDivisor + 1;
23489     if( p->u.apSub[bin]==0 ){
23490       sqlite3FaultBeginBenign(SQLITE_FAULTINJECTOR_MALLOC);
23491       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
23492       sqlite3FaultEndBenign(SQLITE_FAULTINJECTOR_MALLOC);
23493       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
23494     }
23495     return sqlite3BitvecSet(p->u.apSub[bin], i);
23496   }
23497   h = BITVEC_HASH(i);
23498   while( p->u.aHash[h] ){
23499     if( p->u.aHash[h]==i ) return SQLITE_OK;
23500     h++;
23501     if( h==BITVEC_NINT ) h = 0;
23502   }
23503   p->nSet++;
23504   if( p->nSet>=BITVEC_MXHASH ){
23505     int j, rc;
23506     u32 aiValues[BITVEC_NINT];
23507     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
23508     memset(p->u.apSub, 0, sizeof(p->u.apSub[0])*BITVEC_NPTR);
23509     p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
23510     rc = sqlite3BitvecSet(p, i);
23511     for(j=0; j<BITVEC_NINT; j++){
23512       if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
23513     }
23514     return rc;
23515   }
23516   p->u.aHash[h] = i;
23517   return SQLITE_OK;
23518 }
23519
23520 /*
23521 ** Clear the i-th bit.  Return 0 on success and an error code if
23522 ** anything goes wrong.
23523 */
23524 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
23525   assert( p!=0 );
23526   assert( i>0 );
23527   if( p->iSize<=BITVEC_NBIT ){
23528     i--;
23529     p->u.aBitmap[i/8] &= ~(1 << (i&7));
23530   }else if( p->iDivisor ){
23531     u32 bin = (i-1)/p->iDivisor;
23532     i = (i-1)%p->iDivisor + 1;
23533     if( p->u.apSub[bin] ){
23534       sqlite3BitvecClear(p->u.apSub[bin], i);
23535     }
23536   }else{
23537     int j;
23538     u32 aiValues[BITVEC_NINT];
23539     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
23540     memset(p->u.aHash, 0, sizeof(p->u.aHash[0])*BITVEC_NINT);
23541     p->nSet = 0;
23542     for(j=0; j<BITVEC_NINT; j++){
23543       if( aiValues[j] && aiValues[j]!=i ){
23544         sqlite3BitvecSet(p, aiValues[j]);
23545       }
23546     }
23547   }
23548 }
23549
23550 /*
23551 ** Destroy a bitmap object.  Reclaim all memory used.
23552 */
23553 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
23554   if( p==0 ) return;
23555   if( p->iDivisor ){
23556     int i;
23557     for(i=0; i<BITVEC_NPTR; i++){
23558       sqlite3BitvecDestroy(p->u.apSub[i]);
23559     }
23560   }
23561   sqlite3_free(p);
23562 }
23563
23564 #ifndef SQLITE_OMIT_BUILTIN_TEST
23565 /*
23566 ** Let V[] be an array of unsigned characters sufficient to hold
23567 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
23568 ** Then the following macros can be used to set, clear, or test
23569 ** individual bits within V.
23570 */
23571 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
23572 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
23573 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
23574
23575 /*
23576 ** This routine runs an extensive test of the Bitvec code.
23577 **
23578 ** The input is an array of integers that acts as a program
23579 ** to test the Bitvec.  The integers are opcodes followed
23580 ** by 0, 1, or 3 operands, depending on the opcode.  Another
23581 ** opcode follows immediately after the last operand.
23582 **
23583 ** There are 6 opcodes numbered from 0 through 5.  0 is the
23584 ** "halt" opcode and causes the test to end.
23585 **
23586 **    0          Halt and return the number of errors
23587 **    1 N S X    Set N bits beginning with S and incrementing by X
23588 **    2 N S X    Clear N bits beginning with S and incrementing by X
23589 **    3 N        Set N randomly chosen bits
23590 **    4 N        Clear N randomly chosen bits
23591 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
23592 **
23593 ** The opcodes 1 through 4 perform set and clear operations are performed
23594 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
23595 ** Opcode 5 works on the linear array only, not on the Bitvec.
23596 ** Opcode 5 is used to deliberately induce a fault in order to
23597 ** confirm that error detection works.
23598 **
23599 ** At the conclusion of the test the linear array is compared
23600 ** against the Bitvec object.  If there are any differences,
23601 ** an error is returned.  If they are the same, zero is returned.
23602 **
23603 ** If a memory allocation error occurs, return -1.
23604 */
23605 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
23606   Bitvec *pBitvec = 0;
23607   unsigned char *pV = 0;
23608   int rc = -1;
23609   int i, nx, pc, op;
23610
23611   /* Allocate the Bitvec to be tested and a linear array of
23612   ** bits to act as the reference */
23613   pBitvec = sqlite3BitvecCreate( sz );
23614   pV = sqlite3_malloc( (sz+7)/8 + 1 );
23615   if( pBitvec==0 || pV==0 ) goto bitvec_end;
23616   memset(pV, 0, (sz+7)/8 + 1);
23617
23618   /* Run the program */
23619   pc = 0;
23620   while( (op = aOp[pc])!=0 ){
23621     switch( op ){
23622       case 1:
23623       case 2:
23624       case 5: {
23625         nx = 4;
23626         i = aOp[pc+2] - 1;
23627         aOp[pc+2] += aOp[pc+3];
23628         break;
23629       }
23630       case 3:
23631       case 4: 
23632       default: {
23633         nx = 2;
23634         sqlite3_randomness(sizeof(i), &i);
23635         break;
23636       }
23637     }
23638     if( (--aOp[pc+1]) > 0 ) nx = 0;
23639     pc += nx;
23640     i = (i & 0x7fffffff)%sz;
23641     if( (op & 1)!=0 ){
23642       SETBIT(pV, (i+1));
23643       if( op!=5 ){
23644         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
23645       }
23646     }else{
23647       CLEARBIT(pV, (i+1));
23648       sqlite3BitvecClear(pBitvec, i+1);
23649     }
23650   }
23651
23652   /* Test to make sure the linear array exactly matches the
23653   ** Bitvec object.  Start with the assumption that they do
23654   ** match (rc==0).  Change rc to non-zero if a discrepancy
23655   ** is found.
23656   */
23657   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
23658           + sqlite3BitvecTest(pBitvec, 0);
23659   for(i=1; i<=sz; i++){
23660     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
23661       rc = i;
23662       break;
23663     }
23664   }
23665
23666   /* Free allocated structure */
23667 bitvec_end:
23668   sqlite3_free(pV);
23669   sqlite3BitvecDestroy(pBitvec);
23670   return rc;
23671 }
23672 #endif /* SQLITE_OMIT_BUILTIN_TEST */
23673
23674 /************** End of bitvec.c **********************************************/
23675 /************** Begin file pager.c *******************************************/
23676 /*
23677 ** 2001 September 15
23678 **
23679 ** The author disclaims copyright to this source code.  In place of
23680 ** a legal notice, here is a blessing:
23681 **
23682 **    May you do good and not evil.
23683 **    May you find forgiveness for yourself and forgive others.
23684 **    May you share freely, never taking more than you give.
23685 **
23686 *************************************************************************
23687 ** This is the implementation of the page cache subsystem or "pager".
23688 ** 
23689 ** The pager is used to access a database disk file.  It implements
23690 ** atomic commit and rollback through the use of a journal file that
23691 ** is separate from the database file.  The pager also implements file
23692 ** locking to prevent two processes from writing the same database
23693 ** file simultaneously, or one process from reading the database while
23694 ** another is writing.
23695 **
23696 ** @(#) $Id: pager.c,v 1.446 2008/05/13 13:27:34 drh Exp $
23697 */
23698 #ifndef SQLITE_OMIT_DISKIO
23699
23700 /*
23701 ** Macros for troubleshooting.  Normally turned off
23702 */
23703 #if 0
23704 #define sqlite3DebugPrintf printf
23705 #define PAGERTRACE1(X)       sqlite3DebugPrintf(X)
23706 #define PAGERTRACE2(X,Y)     sqlite3DebugPrintf(X,Y)
23707 #define PAGERTRACE3(X,Y,Z)   sqlite3DebugPrintf(X,Y,Z)
23708 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
23709 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
23710 #else
23711 #define PAGERTRACE1(X)
23712 #define PAGERTRACE2(X,Y)
23713 #define PAGERTRACE3(X,Y,Z)
23714 #define PAGERTRACE4(X,Y,Z,W)
23715 #define PAGERTRACE5(X,Y,Z,W,V)
23716 #endif
23717
23718 /*
23719 ** The following two macros are used within the PAGERTRACEX() macros above
23720 ** to print out file-descriptors. 
23721 **
23722 ** PAGERID() takes a pointer to a Pager struct as its argument. The
23723 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
23724 ** struct as its argument.
23725 */
23726 #define PAGERID(p) ((int)(p->fd))
23727 #define FILEHANDLEID(fd) ((int)fd)
23728
23729 /*
23730 ** The page cache as a whole is always in one of the following
23731 ** states:
23732 **
23733 **   PAGER_UNLOCK        The page cache is not currently reading or 
23734 **                       writing the database file.  There is no
23735 **                       data held in memory.  This is the initial
23736 **                       state.
23737 **
23738 **   PAGER_SHARED        The page cache is reading the database.
23739 **                       Writing is not permitted.  There can be
23740 **                       multiple readers accessing the same database
23741 **                       file at the same time.
23742 **
23743 **   PAGER_RESERVED      This process has reserved the database for writing
23744 **                       but has not yet made any changes.  Only one process
23745 **                       at a time can reserve the database.  The original
23746 **                       database file has not been modified so other
23747 **                       processes may still be reading the on-disk
23748 **                       database file.
23749 **
23750 **   PAGER_EXCLUSIVE     The page cache is writing the database.
23751 **                       Access is exclusive.  No other processes or
23752 **                       threads can be reading or writing while one
23753 **                       process is writing.
23754 **
23755 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
23756 **                       after all dirty pages have been written to the
23757 **                       database file and the file has been synced to
23758 **                       disk. All that remains to do is to remove or
23759 **                       truncate the journal file and the transaction 
23760 **                       will be committed.
23761 **
23762 ** The page cache comes up in PAGER_UNLOCK.  The first time a
23763 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
23764 ** After all pages have been released using sqlite_page_unref(),
23765 ** the state transitions back to PAGER_UNLOCK.  The first time
23766 ** that sqlite3PagerWrite() is called, the state transitions to
23767 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
23768 ** called on an outstanding page which means that the pager must
23769 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
23770 ** PAGER_RESERVED means that there is an open rollback journal.
23771 ** The transition to PAGER_EXCLUSIVE occurs before any changes
23772 ** are made to the database file, though writes to the rollback
23773 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
23774 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
23775 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
23776 */
23777 #define PAGER_UNLOCK      0
23778 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
23779 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
23780 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
23781 #define PAGER_SYNCED      5
23782
23783 /*
23784 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
23785 ** then failed attempts to get a reserved lock will invoke the busy callback.
23786 ** This is off by default.  To see why, consider the following scenario:
23787 ** 
23788 ** Suppose thread A already has a shared lock and wants a reserved lock.
23789 ** Thread B already has a reserved lock and wants an exclusive lock.  If
23790 ** both threads are using their busy callbacks, it might be a long time
23791 ** be for one of the threads give up and allows the other to proceed.
23792 ** But if the thread trying to get the reserved lock gives up quickly
23793 ** (if it never invokes its busy callback) then the contention will be
23794 ** resolved quickly.
23795 */
23796 #ifndef SQLITE_BUSY_RESERVED_LOCK
23797 # define SQLITE_BUSY_RESERVED_LOCK 0
23798 #endif
23799
23800 /*
23801 ** This macro rounds values up so that if the value is an address it
23802 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
23803 */
23804 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
23805
23806 typedef struct PgHdr PgHdr;
23807
23808 /*
23809 ** Each pager stores all currently unreferenced pages in a list sorted
23810 ** in least-recently-used (LRU) order (i.e. the first item on the list has 
23811 ** not been referenced in a long time, the last item has been recently
23812 ** used). An instance of this structure is included as part of each
23813 ** pager structure for this purpose (variable Pager.lru).
23814 **
23815 ** Additionally, if memory-management is enabled, all unreferenced pages 
23816 ** are stored in a global LRU list (global variable sqlite3LruPageList).
23817 **
23818 ** In both cases, the PagerLruList.pFirstSynced variable points to
23819 ** the first page in the corresponding list that does not require an
23820 ** fsync() operation before its memory can be reclaimed. If no such
23821 ** page exists, PagerLruList.pFirstSynced is set to NULL.
23822 */
23823 typedef struct PagerLruList PagerLruList;
23824 struct PagerLruList {
23825   PgHdr *pFirst;         /* First page in LRU list */
23826   PgHdr *pLast;          /* Last page in LRU list (the most recently used) */
23827   PgHdr *pFirstSynced;   /* First page in list with PgHdr.needSync==0 */
23828 };
23829
23830 /*
23831 ** The following structure contains the next and previous pointers used
23832 ** to link a PgHdr structure into a PagerLruList linked list. 
23833 */
23834 typedef struct PagerLruLink PagerLruLink;
23835 struct PagerLruLink {
23836   PgHdr *pNext;
23837   PgHdr *pPrev;
23838 };
23839
23840 /*
23841 ** Each in-memory image of a page begins with the following header.
23842 ** This header is only visible to this pager module.  The client
23843 ** code that calls pager sees only the data that follows the header.
23844 **
23845 ** Client code should call sqlite3PagerWrite() on a page prior to making
23846 ** any modifications to that page.  The first time sqlite3PagerWrite()
23847 ** is called, the original page contents are written into the rollback
23848 ** journal and PgHdr.inJournal and PgHdr.needSync are set.  Later, once
23849 ** the journal page has made it onto the disk surface, PgHdr.needSync
23850 ** is cleared.  The modified page cannot be written back into the original
23851 ** database file until the journal pages has been synced to disk and the
23852 ** PgHdr.needSync has been cleared.
23853 **
23854 ** The PgHdr.dirty flag is set when sqlite3PagerWrite() is called and
23855 ** is cleared again when the page content is written back to the original
23856 ** database file.
23857 **
23858 ** Details of important structure elements:
23859 **
23860 ** needSync
23861 **
23862 **     If this is true, this means that it is not safe to write the page
23863 **     content to the database because the original content needed
23864 **     for rollback has not by synced to the main rollback journal.
23865 **     The original content may have been written to the rollback journal
23866 **     but it has not yet been synced.  So we cannot write to the database
23867 **     file because power failure might cause the page in the journal file
23868 **     to never reach the disk.  It is as if the write to the journal file
23869 **     does not occur until the journal file is synced.
23870 **     
23871 **     This flag is false if the page content exactly matches what
23872 **     currently exists in the database file.  The needSync flag is also
23873 **     false if the original content has been written to the main rollback
23874 **     journal and synced.  If the page represents a new page that has
23875 **     been added onto the end of the database during the current
23876 **     transaction, the needSync flag is true until the original database
23877 **     size in the journal header has been synced to disk.
23878 **
23879 ** inJournal
23880 **
23881 **     This is true if the original page has been written into the main
23882 **     rollback journal.  This is always false for new pages added to
23883 **     the end of the database file during the current transaction.
23884 **     And this flag says nothing about whether or not the journal
23885 **     has been synced to disk.  For pages that are in the original
23886 **     database file, the following expression should always be true:
23887 **
23888 **       inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno)
23889 **
23890 **     The pPager->pInJournal object is only valid for the original
23891 **     pages of the database, not new pages that are added to the end
23892 **     of the database, so obviously the above expression cannot be
23893 **     valid for new pages.  For new pages inJournal is always 0.
23894 **
23895 ** dirty
23896 **
23897 **     When true, this means that the content of the page has been
23898 **     modified and needs to be written back to the database file.
23899 **     If false, it means that either the content of the page is
23900 **     unchanged or else the content is unimportant and we do not
23901 **     care whether or not it is preserved.
23902 **
23903 ** alwaysRollback
23904 **
23905 **     This means that the sqlite3PagerDontRollback() API should be
23906 **     ignored for this page.  The DontRollback() API attempts to say
23907 **     that the content of the page on disk is unimportant (it is an
23908 **     unused page on the freelist) so that it is unnecessary to 
23909 **     rollback changes to this page because the content of the page
23910 **     can change without changing the meaning of the database.  This
23911 **     flag overrides any DontRollback() attempt.  This flag is set
23912 **     when a page that originally contained valid data is added to
23913 **     the freelist.  Later in the same transaction, this page might
23914 **     be pulled from the freelist and reused for something different
23915 **     and at that point the DontRollback() API will be called because
23916 **     pages taken from the freelist do not need to be protected by
23917 **     the rollback journal.  But this flag says that the page was
23918 **     not originally part of the freelist so that it still needs to
23919 **     be rolled back in spite of any subsequent DontRollback() calls.
23920 **
23921 ** needRead 
23922 **
23923 **     This flag means (when true) that the content of the page has
23924 **     not yet been loaded from disk.  The in-memory content is just
23925 **     garbage.  (Actually, we zero the content, but you should not
23926 **     make any assumptions about the content nevertheless.)  If the
23927 **     content is needed in the future, it should be read from the
23928 **     original database file.
23929 */
23930 struct PgHdr {
23931   Pager *pPager;                 /* The pager to which this page belongs */
23932   Pgno pgno;                     /* The page number for this page */
23933   PgHdr *pNextHash, *pPrevHash;  /* Hash collision chain for PgHdr.pgno */
23934   PagerLruLink free;             /* Next and previous free pages */
23935   PgHdr *pNextAll;               /* A list of all pages */
23936   u8 inJournal;                  /* TRUE if has been written to journal */
23937   u8 dirty;                      /* TRUE if we need to write back changes */
23938   u8 needSync;                   /* Sync journal before writing this page */
23939   u8 alwaysRollback;             /* Disable DontRollback() for this page */
23940   u8 needRead;                   /* Read content if PagerWrite() is called */
23941   short int nRef;                /* Number of users of this page */
23942   PgHdr *pDirty, *pPrevDirty;    /* Dirty pages */
23943 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23944   PagerLruLink gfree;            /* Global list of nRef==0 pages */
23945 #endif
23946 #ifdef SQLITE_CHECK_PAGES
23947   u32 pageHash;
23948 #endif
23949   void *pData;                   /* Page data */
23950   /* Pager.nExtra bytes of local data appended to this header */
23951 };
23952
23953 /*
23954 ** For an in-memory only database, some extra information is recorded about
23955 ** each page so that changes can be rolled back.  (Journal files are not
23956 ** used for in-memory databases.)  The following information is added to
23957 ** the end of every EXTRA block for in-memory databases.
23958 **
23959 ** This information could have been added directly to the PgHdr structure.
23960 ** But then it would take up an extra 8 bytes of storage on every PgHdr
23961 ** even for disk-based databases.  Splitting it out saves 8 bytes.  This
23962 ** is only a savings of 0.8% but those percentages add up.
23963 */
23964 typedef struct PgHistory PgHistory;
23965 struct PgHistory {
23966   u8 *pOrig;     /* Original page text.  Restore to this on a full rollback */
23967   u8 *pStmt;     /* Text as it was at the beginning of the current statement */
23968   PgHdr *pNextStmt, *pPrevStmt;  /* List of pages in the statement journal */
23969   u8 inStmt;                     /* TRUE if in the statement subjournal */
23970 };
23971
23972 /*
23973 ** A macro used for invoking the codec if there is one
23974 */
23975 #ifdef SQLITE_HAS_CODEC
23976 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
23977 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
23978 #else
23979 # define CODEC1(P,D,N,X) /* NO-OP */
23980 # define CODEC2(P,D,N,X) ((char*)D)
23981 #endif
23982
23983 /*
23984 ** Convert a pointer to a PgHdr into a pointer to its data
23985 ** and back again.
23986 */
23987 #define PGHDR_TO_DATA(P)    ((P)->pData)
23988 #define PGHDR_TO_EXTRA(G,P) ((void*)&((G)[1]))
23989 #define PGHDR_TO_HIST(P,PGR)  \
23990             ((PgHistory*)&((char*)(&(P)[1]))[(PGR)->nExtra])
23991
23992 /*
23993 ** A open page cache is an instance of the following structure.
23994 **
23995 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
23996 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
23997 ** and is returned as the result of every major pager API call.  The
23998 ** SQLITE_FULL return code is slightly different. It persists only until the
23999 ** next successful rollback is performed on the pager cache. Also,
24000 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
24001 ** APIs, they may still be used successfully.
24002 */
24003 struct Pager {
24004   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
24005   u8 journalOpen;             /* True if journal file descriptors is valid */
24006   u8 journalStarted;          /* True if header of journal is synced */
24007   u8 useJournal;              /* Use a rollback journal on this file */
24008   u8 noReadlock;              /* Do not bother to obtain readlocks */
24009   u8 stmtOpen;                /* True if the statement subjournal is open */
24010   u8 stmtInUse;               /* True we are in a statement subtransaction */
24011   u8 stmtAutoopen;            /* Open stmt journal when main journal is opened*/
24012   u8 noSync;                  /* Do not sync the journal if true */
24013   u8 fullSync;                /* Do extra syncs of the journal for robustness */
24014   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
24015   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
24016   u8 tempFile;                /* zFilename is a temporary file */
24017   u8 readOnly;                /* True for a read-only database */
24018   u8 needSync;                /* True if an fsync() is needed on the journal */
24019   u8 dirtyCache;              /* True if cached pages have changed */
24020   u8 alwaysRollback;          /* Disable DontRollback() for all pages */
24021   u8 memDb;                   /* True to inhibit all file I/O */
24022   u8 setMaster;               /* True if a m-j name has been written to jrnl */
24023   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
24024   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
24025   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
24026   u8 dbModified;              /* True if there are any changes to the Db */
24027   u8 changeCountDone;         /* Set after incrementing the change-counter */
24028   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
24029   int errCode;                /* One of several kinds of errors */
24030   int dbSize;                 /* Number of pages in the file */
24031   int origDbSize;             /* dbSize before the current change */
24032   int stmtSize;               /* Size of database (in pages) at stmt_begin() */
24033   int nRec;                   /* Number of pages written to the journal */
24034   u32 cksumInit;              /* Quasi-random value added to every checksum */
24035   int stmtNRec;               /* Number of records in stmt subjournal */
24036   int nExtra;                 /* Add this many bytes to each in-memory page */
24037   int pageSize;               /* Number of bytes in a page */
24038   int nPage;                  /* Total number of in-memory pages */
24039   int nRef;                   /* Number of in-memory pages with PgHdr.nRef>0 */
24040   int mxPage;                 /* Maximum number of pages to hold in cache */
24041   Pgno mxPgno;                /* Maximum allowed size of the database */
24042   Bitvec *pInJournal;         /* One bit for each page in the database file */
24043   Bitvec *pInStmt;            /* One bit for each page in the database */
24044   char *zFilename;            /* Name of the database file */
24045   char *zJournal;             /* Name of the journal file */
24046   char *zDirectory;           /* Directory hold database and journal files */
24047   char *zStmtJrnl;            /* Name of the statement journal file */
24048   sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
24049   sqlite3_file *stfd;         /* File descriptor for the statement subjournal*/
24050   BusyHandler *pBusyHandler;  /* Pointer to sqlite.busyHandler */
24051   PagerLruList lru;           /* LRU list of free pages */
24052   PgHdr *pAll;                /* List of all pages */
24053   PgHdr *pStmt;               /* List of pages in the statement subjournal */
24054   PgHdr *pDirty;              /* List of all dirty pages */
24055   i64 journalOff;             /* Current byte offset in the journal file */
24056   i64 journalHdr;             /* Byte offset to previous journal header */
24057   i64 stmtHdrOff;             /* First journal header written this statement */
24058   i64 stmtCksum;              /* cksumInit when statement was started */
24059   i64 stmtJSize;              /* Size of journal at stmt_begin() */
24060   int sectorSize;             /* Assumed sector size during rollback */
24061 #ifdef SQLITE_TEST
24062   int nHit, nMiss;            /* Cache hits and missing */
24063   int nRead, nWrite;          /* Database pages read/written */
24064 #endif
24065   void (*xDestructor)(DbPage*,int); /* Call this routine when freeing pages */
24066   void (*xReiniter)(DbPage*,int);   /* Call this routine when reloading pages */
24067 #ifdef SQLITE_HAS_CODEC
24068   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
24069   void *pCodecArg;            /* First argument to xCodec() */
24070 #endif
24071   int nHash;                  /* Size of the pager hash table */
24072   PgHdr **aHash;              /* Hash table to map page number to PgHdr */
24073 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24074   Pager *pNext;               /* Doubly linked list of pagers on which */
24075   Pager *pPrev;               /* sqlite3_release_memory() will work */
24076   int iInUseMM;               /* Non-zero if unavailable to MM */
24077   int iInUseDB;               /* Non-zero if in sqlite3_release_memory() */
24078 #endif
24079   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
24080   char dbFileVers[16];        /* Changes whenever database file changes */
24081 };
24082
24083 /*
24084 ** The following global variables hold counters used for
24085 ** testing purposes only.  These variables do not exist in
24086 ** a non-testing build.  These variables are not thread-safe.
24087 */
24088 #ifdef SQLITE_TEST
24089 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
24090 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
24091 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
24092 SQLITE_API int sqlite3_pager_pgfree_count = 0;    /* Number of cache pages freed */
24093 # define PAGER_INCR(v)  v++
24094 #else
24095 # define PAGER_INCR(v)
24096 #endif
24097
24098 /*
24099 ** The following variable points to the head of a double-linked list
24100 ** of all pagers that are eligible for page stealing by the
24101 ** sqlite3_release_memory() interface.  Access to this list is
24102 ** protected by the SQLITE_MUTEX_STATIC_MEM2 mutex.
24103 */
24104 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24105 static Pager *sqlite3PagerList = 0;
24106 static PagerLruList sqlite3LruPageList = {0, 0, 0};
24107 #endif
24108
24109
24110 /*
24111 ** Journal files begin with the following magic string.  The data
24112 ** was obtained from /dev/random.  It is used only as a sanity check.
24113 **
24114 ** Since version 2.8.0, the journal format contains additional sanity
24115 ** checking information.  If the power fails while the journal is begin
24116 ** written, semi-random garbage data might appear in the journal
24117 ** file after power is restored.  If an attempt is then made
24118 ** to roll the journal back, the database could be corrupted.  The additional
24119 ** sanity checking data is an attempt to discover the garbage in the
24120 ** journal and ignore it.
24121 **
24122 ** The sanity checking information for the new journal format consists
24123 ** of a 32-bit checksum on each page of data.  The checksum covers both
24124 ** the page number and the pPager->pageSize bytes of data for the page.
24125 ** This cksum is initialized to a 32-bit random value that appears in the
24126 ** journal file right after the header.  The random initializer is important,
24127 ** because garbage data that appears at the end of a journal is likely
24128 ** data that was once in other files that have now been deleted.  If the
24129 ** garbage data came from an obsolete journal file, the checksums might
24130 ** be correct.  But by initializing the checksum to random value which
24131 ** is different for every journal, we minimize that risk.
24132 */
24133 static const unsigned char aJournalMagic[] = {
24134   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
24135 };
24136
24137 /*
24138 ** The size of the header and of each page in the journal is determined
24139 ** by the following macros.
24140 */
24141 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
24142
24143 /*
24144 ** The journal header size for this pager. In the future, this could be
24145 ** set to some value read from the disk controller. The important
24146 ** characteristic is that it is the same size as a disk sector.
24147 */
24148 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
24149
24150 /*
24151 ** The macro MEMDB is true if we are dealing with an in-memory database.
24152 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
24153 ** the value of MEMDB will be a constant and the compiler will optimize
24154 ** out code that would never execute.
24155 */
24156 #ifdef SQLITE_OMIT_MEMORYDB
24157 # define MEMDB 0
24158 #else
24159 # define MEMDB pPager->memDb
24160 #endif
24161
24162 /*
24163 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
24164 ** reserved for working around a windows/posix incompatibility). It is
24165 ** used in the journal to signify that the remainder of the journal file 
24166 ** is devoted to storing a master journal name - there are no more pages to
24167 ** roll back. See comments for function writeMasterJournal() for details.
24168 */
24169 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
24170 #define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
24171
24172 /*
24173 ** The maximum legal page number is (2^31 - 1).
24174 */
24175 #define PAGER_MAX_PGNO 2147483647
24176
24177 /*
24178 ** The pagerEnter() and pagerLeave() routines acquire and release
24179 ** a mutex on each pager.  The mutex is recursive.
24180 **
24181 ** This is a special-purpose mutex.  It only provides mutual exclusion
24182 ** between the Btree and the Memory Management sqlite3_release_memory()
24183 ** function.  It does not prevent, for example, two Btrees from accessing
24184 ** the same pager at the same time.  Other general-purpose mutexes in
24185 ** the btree layer handle that chore.
24186 */
24187 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24188   static void pagerEnter(Pager *p){
24189     p->iInUseDB++;
24190     if( p->iInUseMM && p->iInUseDB==1 ){
24191 #ifndef SQLITE_MUTEX_NOOP
24192       sqlite3_mutex *mutex;
24193       mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
24194 #endif
24195       p->iInUseDB = 0;
24196       sqlite3_mutex_enter(mutex);
24197       p->iInUseDB = 1;
24198       sqlite3_mutex_leave(mutex);
24199     }
24200     assert( p->iInUseMM==0 );
24201   }
24202   static void pagerLeave(Pager *p){
24203     p->iInUseDB--;
24204     assert( p->iInUseDB>=0 );
24205   }
24206 #else
24207 # define pagerEnter(X)
24208 # define pagerLeave(X)
24209 #endif
24210
24211 /*
24212 ** Add page pPg to the end of the linked list managed by structure
24213 ** pList (pPg becomes the last entry in the list - the most recently 
24214 ** used). Argument pLink should point to either pPg->free or pPg->gfree,
24215 ** depending on whether pPg is being added to the pager-specific or
24216 ** global LRU list.
24217 */
24218 static void listAdd(PagerLruList *pList, PagerLruLink *pLink, PgHdr *pPg){
24219   pLink->pNext = 0;
24220   pLink->pPrev = pList->pLast;
24221
24222 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24223   assert(pLink==&pPg->free || pLink==&pPg->gfree);
24224   assert(pLink==&pPg->gfree || pList!=&sqlite3LruPageList);
24225 #endif
24226
24227   if( pList->pLast ){
24228     int iOff = (char *)pLink - (char *)pPg;
24229     PagerLruLink *pLastLink = (PagerLruLink *)(&((u8 *)pList->pLast)[iOff]);
24230     pLastLink->pNext = pPg;
24231   }else{
24232     assert(!pList->pFirst);
24233     pList->pFirst = pPg;
24234   }
24235
24236   pList->pLast = pPg;
24237   if( !pList->pFirstSynced && pPg->needSync==0 ){
24238     pList->pFirstSynced = pPg;
24239   }
24240 }
24241
24242 /*
24243 ** Remove pPg from the list managed by the structure pointed to by pList.
24244 **
24245 ** Argument pLink should point to either pPg->free or pPg->gfree, depending 
24246 ** on whether pPg is being added to the pager-specific or global LRU list.
24247 */
24248 static void listRemove(PagerLruList *pList, PagerLruLink *pLink, PgHdr *pPg){
24249   int iOff = (char *)pLink - (char *)pPg;
24250
24251 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24252   assert(pLink==&pPg->free || pLink==&pPg->gfree);
24253   assert(pLink==&pPg->gfree || pList!=&sqlite3LruPageList);
24254 #endif
24255
24256   if( pPg==pList->pFirst ){
24257     pList->pFirst = pLink->pNext;
24258   }
24259   if( pPg==pList->pLast ){
24260     pList->pLast = pLink->pPrev;
24261   }
24262   if( pLink->pPrev ){
24263     PagerLruLink *pPrevLink = (PagerLruLink *)(&((u8 *)pLink->pPrev)[iOff]);
24264     pPrevLink->pNext = pLink->pNext;
24265   }
24266   if( pLink->pNext ){
24267     PagerLruLink *pNextLink = (PagerLruLink *)(&((u8 *)pLink->pNext)[iOff]);
24268     pNextLink->pPrev = pLink->pPrev;
24269   }
24270   if( pPg==pList->pFirstSynced ){
24271     PgHdr *p = pLink->pNext;
24272     while( p && p->needSync ){
24273       PagerLruLink *pL = (PagerLruLink *)(&((u8 *)p)[iOff]);
24274       p = pL->pNext;
24275     }
24276     pList->pFirstSynced = p;
24277   }
24278
24279   pLink->pNext = pLink->pPrev = 0;
24280 }
24281
24282 /* 
24283 ** Add page pPg to the list of free pages for the pager. If 
24284 ** memory-management is enabled, also add the page to the global 
24285 ** list of free pages.
24286 */
24287 static void lruListAdd(PgHdr *pPg){
24288   listAdd(&pPg->pPager->lru, &pPg->free, pPg);
24289 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24290   if( !pPg->pPager->memDb ){
24291     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
24292     listAdd(&sqlite3LruPageList, &pPg->gfree, pPg);
24293     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
24294   }
24295 #endif
24296 }
24297
24298 /* 
24299 ** Remove page pPg from the list of free pages for the associated pager.
24300 ** If memory-management is enabled, also remove pPg from the global list
24301 ** of free pages.
24302 */
24303 static void lruListRemove(PgHdr *pPg){
24304   listRemove(&pPg->pPager->lru, &pPg->free, pPg);
24305 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24306   if( !pPg->pPager->memDb ){
24307     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
24308     listRemove(&sqlite3LruPageList, &pPg->gfree, pPg);
24309     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
24310   }
24311 #endif
24312 }
24313
24314 /* 
24315 ** This function is called just after the needSync flag has been cleared
24316 ** from all pages managed by pPager (usually because the journal file
24317 ** has just been synced). It updates the pPager->lru.pFirstSynced variable
24318 ** and, if memory-management is enabled, the sqlite3LruPageList.pFirstSynced
24319 ** variable also.
24320 */
24321 static void lruListSetFirstSynced(Pager *pPager){
24322   pPager->lru.pFirstSynced = pPager->lru.pFirst;
24323 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24324   if( !pPager->memDb ){
24325     PgHdr *p;
24326     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
24327     for(p=sqlite3LruPageList.pFirst; p && p->needSync; p=p->gfree.pNext);
24328     assert(p==pPager->lru.pFirstSynced || p==sqlite3LruPageList.pFirstSynced);
24329     sqlite3LruPageList.pFirstSynced = p;
24330     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
24331   }
24332 #endif
24333 }
24334
24335 /*
24336 ** Return true if page *pPg has already been written to the statement
24337 ** journal (or statement snapshot has been created, if *pPg is part
24338 ** of an in-memory database).
24339 */
24340 static int pageInStatement(PgHdr *pPg){
24341   Pager *pPager = pPg->pPager;
24342   if( MEMDB ){
24343     return PGHDR_TO_HIST(pPg, pPager)->inStmt;
24344   }else{
24345     return sqlite3BitvecTest(pPager->pInStmt, pPg->pgno);
24346   }
24347 }
24348
24349 /*
24350 ** Change the size of the pager hash table to N.  N must be a power
24351 ** of two.
24352 */
24353 static void pager_resize_hash_table(Pager *pPager, int N){
24354   PgHdr **aHash, *pPg;
24355   assert( N>0 && (N&(N-1))==0 );
24356 #ifdef SQLITE_MALLOC_SOFT_LIMIT
24357   if( N*sizeof(aHash[0])>SQLITE_MALLOC_SOFT_LIMIT ){
24358     N = SQLITE_MALLOC_SOFT_LIMIT/sizeof(aHash[0]);
24359   }
24360   if( N==pPager->nHash ) return;
24361 #endif
24362   pagerLeave(pPager);
24363   if( pPager->aHash!=0 ) sqlite3FaultBeginBenign(SQLITE_FAULTINJECTOR_MALLOC);
24364   aHash = sqlite3MallocZero( sizeof(aHash[0])*N );
24365   if( pPager->aHash!=0 ) sqlite3FaultEndBenign(SQLITE_FAULTINJECTOR_MALLOC);
24366   pagerEnter(pPager);
24367   if( aHash==0 ){
24368     /* Failure to rehash is not an error.  It is only a performance hit. */
24369     return;
24370   }
24371   sqlite3_free(pPager->aHash);
24372   pPager->nHash = N;
24373   pPager->aHash = aHash;
24374   for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
24375     int h;
24376     if( pPg->pgno==0 ){
24377       assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
24378       continue;
24379     }
24380     h = pPg->pgno & (N-1);
24381     pPg->pNextHash = aHash[h];
24382     if( aHash[h] ){
24383       aHash[h]->pPrevHash = pPg;
24384     }
24385     aHash[h] = pPg;
24386     pPg->pPrevHash = 0;
24387   }
24388 }
24389
24390 /*
24391 ** Read a 32-bit integer from the given file descriptor.  Store the integer
24392 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
24393 ** error code is something goes wrong.
24394 **
24395 ** All values are stored on disk as big-endian.
24396 */
24397 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
24398   unsigned char ac[4];
24399   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
24400   if( rc==SQLITE_OK ){
24401     *pRes = sqlite3Get4byte(ac);
24402   }
24403   return rc;
24404 }
24405
24406 /*
24407 ** Write a 32-bit integer into a string buffer in big-endian byte order.
24408 */
24409 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
24410
24411 /*
24412 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
24413 ** on success or an error code is something goes wrong.
24414 */
24415 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
24416   char ac[4];
24417   put32bits(ac, val);
24418   return sqlite3OsWrite(fd, ac, 4, offset);
24419 }
24420
24421 /*
24422 ** If file pFd is open, call sqlite3OsUnlock() on it.
24423 */
24424 static int osUnlock(sqlite3_file *pFd, int eLock){
24425   if( !pFd->pMethods ){
24426     return SQLITE_OK;
24427   }
24428   return sqlite3OsUnlock(pFd, eLock);
24429 }
24430
24431 /*
24432 ** This function determines whether or not the atomic-write optimization
24433 ** can be used with this pager. The optimization can be used if:
24434 **
24435 **  (a) the value returned by OsDeviceCharacteristics() indicates that
24436 **      a database page may be written atomically, and
24437 **  (b) the value returned by OsSectorSize() is less than or equal
24438 **      to the page size.
24439 **
24440 ** If the optimization cannot be used, 0 is returned. If it can be used,
24441 ** then the value returned is the size of the journal file when it
24442 ** contains rollback data for exactly one page.
24443 */
24444 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
24445 static int jrnlBufferSize(Pager *pPager){
24446   int dc;           /* Device characteristics */
24447   int nSector;      /* Sector size */
24448   int nPage;        /* Page size */
24449   sqlite3_file *fd = pPager->fd;
24450
24451   if( fd->pMethods ){
24452     dc = sqlite3OsDeviceCharacteristics(fd);
24453     nSector = sqlite3OsSectorSize(fd);
24454     nPage = pPager->pageSize;
24455   }
24456
24457   assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
24458   assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
24459
24460   if( !fd->pMethods || (dc&(SQLITE_IOCAP_ATOMIC|(nPage>>8))&&nSector<=nPage) ){
24461     return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
24462   }
24463   return 0;
24464 }
24465 #endif
24466
24467 /*
24468 ** This function should be called when an error occurs within the pager
24469 ** code. The first argument is a pointer to the pager structure, the
24470 ** second the error-code about to be returned by a pager API function. 
24471 ** The value returned is a copy of the second argument to this function. 
24472 **
24473 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
24474 ** the error becomes persistent. Until the persisten error is cleared,
24475 ** subsequent API calls on this Pager will immediately return the same 
24476 ** error code.
24477 **
24478 ** A persistent error indicates that the contents of the pager-cache 
24479 ** cannot be trusted. This state can be cleared by completely discarding 
24480 ** the contents of the pager-cache. If a transaction was active when
24481 ** the persistent error occured, then the rollback journal may need
24482 ** to be replayed.
24483 */
24484 static void pager_unlock(Pager *pPager);
24485 static int pager_error(Pager *pPager, int rc){
24486   int rc2 = rc & 0xff;
24487   assert(
24488        pPager->errCode==SQLITE_FULL ||
24489        pPager->errCode==SQLITE_OK ||
24490        (pPager->errCode & 0xff)==SQLITE_IOERR
24491   );
24492   if(
24493     rc2==SQLITE_FULL ||
24494     rc2==SQLITE_IOERR ||
24495     rc2==SQLITE_CORRUPT
24496   ){
24497     pPager->errCode = rc;
24498     if( pPager->state==PAGER_UNLOCK && pPager->nRef==0 ){
24499       /* If the pager is already unlocked, call pager_unlock() now to
24500       ** clear the error state and ensure that the pager-cache is 
24501       ** completely empty.
24502       */
24503       pager_unlock(pPager);
24504     }
24505   }
24506   return rc;
24507 }
24508
24509 /*
24510 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
24511 ** on the cache using a hash function.  This is used for testing
24512 ** and debugging only.
24513 */
24514 #ifdef SQLITE_CHECK_PAGES
24515 /*
24516 ** Return a 32-bit hash of the page data for pPage.
24517 */
24518 static u32 pager_datahash(int nByte, unsigned char *pData){
24519   u32 hash = 0;
24520   int i;
24521   for(i=0; i<nByte; i++){
24522     hash = (hash*1039) + pData[i];
24523   }
24524   return hash;
24525 }
24526 static u32 pager_pagehash(PgHdr *pPage){
24527   return pager_datahash(pPage->pPager->pageSize, 
24528                         (unsigned char *)PGHDR_TO_DATA(pPage));
24529 }
24530
24531 /*
24532 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
24533 ** is defined, and NDEBUG is not defined, an assert() statement checks
24534 ** that the page is either dirty or still matches the calculated page-hash.
24535 */
24536 #define CHECK_PAGE(x) checkPage(x)
24537 static void checkPage(PgHdr *pPg){
24538   Pager *pPager = pPg->pPager;
24539   assert( !pPg->pageHash || pPager->errCode || MEMDB || pPg->dirty || 
24540       pPg->pageHash==pager_pagehash(pPg) );
24541 }
24542
24543 #else
24544 #define pager_datahash(X,Y)  0
24545 #define pager_pagehash(X)  0
24546 #define CHECK_PAGE(x)
24547 #endif
24548
24549 /*
24550 ** When this is called the journal file for pager pPager must be open.
24551 ** The master journal file name is read from the end of the file and 
24552 ** written into memory supplied by the caller. 
24553 **
24554 ** zMaster must point to a buffer of at least nMaster bytes allocated by
24555 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
24556 ** enough space to write the master journal name). If the master journal
24557 ** name in the journal is longer than nMaster bytes (including a
24558 ** nul-terminator), then this is handled as if no master journal name
24559 ** were present in the journal.
24560 **
24561 ** If no master journal file name is present zMaster[0] is set to 0 and
24562 ** SQLITE_OK returned.
24563 */
24564 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, int nMaster){
24565   int rc;
24566   u32 len;
24567   i64 szJ;
24568   u32 cksum;
24569   int i;
24570   unsigned char aMagic[8]; /* A buffer to hold the magic header */
24571
24572   zMaster[0] = '\0';
24573
24574   rc = sqlite3OsFileSize(pJrnl, &szJ);
24575   if( rc!=SQLITE_OK || szJ<16 ) return rc;
24576
24577   rc = read32bits(pJrnl, szJ-16, &len);
24578   if( rc!=SQLITE_OK ) return rc;
24579
24580   if( len>=nMaster ){
24581     return SQLITE_OK;
24582   }
24583
24584   rc = read32bits(pJrnl, szJ-12, &cksum);
24585   if( rc!=SQLITE_OK ) return rc;
24586
24587   rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
24588   if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
24589
24590   rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
24591   if( rc!=SQLITE_OK ){
24592     return rc;
24593   }
24594   zMaster[len] = '\0';
24595
24596   /* See if the checksum matches the master journal name */
24597   for(i=0; i<len; i++){
24598     cksum -= zMaster[i];
24599    }
24600   if( cksum ){
24601     /* If the checksum doesn't add up, then one or more of the disk sectors
24602     ** containing the master journal filename is corrupted. This means
24603     ** definitely roll back, so just return SQLITE_OK and report a (nul)
24604     ** master-journal filename.
24605     */
24606     zMaster[0] = '\0';
24607   }
24608    
24609   return SQLITE_OK;
24610 }
24611
24612 /*
24613 ** Seek the journal file descriptor to the next sector boundary where a
24614 ** journal header may be read or written. Pager.journalOff is updated with
24615 ** the new seek offset.
24616 **
24617 ** i.e for a sector size of 512:
24618 **
24619 ** Input Offset              Output Offset
24620 ** ---------------------------------------
24621 ** 0                         0
24622 ** 512                       512
24623 ** 100                       512
24624 ** 2000                      2048
24625 ** 
24626 */
24627 static void seekJournalHdr(Pager *pPager){
24628   i64 offset = 0;
24629   i64 c = pPager->journalOff;
24630   if( c ){
24631     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
24632   }
24633   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
24634   assert( offset>=c );
24635   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
24636   pPager->journalOff = offset;
24637 }
24638
24639 /*
24640 ** Write zeros over the header of the journal file.  This has the
24641 ** effect of invalidating the journal file and committing the
24642 ** transaction.
24643 */
24644 static int zeroJournalHdr(Pager *pPager, int doTruncate){
24645   int rc = SQLITE_OK;
24646   static const char zeroHdr[28];
24647
24648   if( pPager->journalOff ){
24649     IOTRACE(("JZEROHDR %p\n", pPager))
24650     if( doTruncate ){
24651       rc = sqlite3OsTruncate(pPager->jfd, 0);
24652     }else{
24653       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
24654     }
24655     if( rc==SQLITE_OK ){
24656       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
24657     }
24658   }
24659   return rc;
24660 }
24661
24662 /*
24663 ** The journal file must be open when this routine is called. A journal
24664 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
24665 ** current location.
24666 **
24667 ** The format for the journal header is as follows:
24668 ** - 8 bytes: Magic identifying journal format.
24669 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
24670 ** - 4 bytes: Random number used for page hash.
24671 ** - 4 bytes: Initial database page count.
24672 ** - 4 bytes: Sector size used by the process that wrote this journal.
24673 ** - 4 bytes: Database page size.
24674 ** 
24675 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
24676 */
24677 static int writeJournalHdr(Pager *pPager){
24678   int rc = SQLITE_OK;
24679   char *zHeader = pPager->pTmpSpace;
24680   int nHeader = pPager->pageSize;
24681   int nWrite;
24682
24683   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
24684     nHeader = JOURNAL_HDR_SZ(pPager);
24685   }
24686
24687   if( pPager->stmtHdrOff==0 ){
24688     pPager->stmtHdrOff = pPager->journalOff;
24689   }
24690
24691   seekJournalHdr(pPager);
24692   pPager->journalHdr = pPager->journalOff;
24693
24694   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
24695
24696   /* 
24697   ** Write the nRec Field - the number of page records that follow this
24698   ** journal header. Normally, zero is written to this value at this time.
24699   ** After the records are added to the journal (and the journal synced, 
24700   ** if in full-sync mode), the zero is overwritten with the true number
24701   ** of records (see syncJournal()).
24702   **
24703   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
24704   ** reading the journal this value tells SQLite to assume that the
24705   ** rest of the journal file contains valid page records. This assumption
24706   ** is dangerous, as if a failure occured whilst writing to the journal
24707   ** file it may contain some garbage data. There are two scenarios
24708   ** where this risk can be ignored:
24709   **
24710   **   * When the pager is in no-sync mode. Corruption can follow a
24711   **     power failure in this case anyway.
24712   **
24713   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
24714   **     that garbage data is never appended to the journal file.
24715   */
24716   assert(pPager->fd->pMethods||pPager->noSync);
24717   if( (pPager->noSync) 
24718    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
24719   ){
24720     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
24721   }else{
24722     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
24723   }
24724
24725   /* The random check-hash initialiser */ 
24726   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
24727   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
24728   /* The initial database size */
24729   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
24730   /* The assumed sector size for this process */
24731   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
24732   if( pPager->journalHdr==0 ){
24733     /* The page size */
24734     put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
24735   }
24736
24737   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
24738     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
24739     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
24740     pPager->journalOff += nHeader;
24741   }
24742
24743   return rc;
24744 }
24745
24746 /*
24747 ** The journal file must be open when this is called. A journal header file
24748 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
24749 ** file. See comments above function writeJournalHdr() for a description of
24750 ** the journal header format.
24751 **
24752 ** If the header is read successfully, *nRec is set to the number of
24753 ** page records following this header and *dbSize is set to the size of the
24754 ** database before the transaction began, in pages. Also, pPager->cksumInit
24755 ** is set to the value read from the journal header. SQLITE_OK is returned
24756 ** in this case.
24757 **
24758 ** If the journal header file appears to be corrupted, SQLITE_DONE is
24759 ** returned and *nRec and *dbSize are not set.  If JOURNAL_HDR_SZ bytes
24760 ** cannot be read from the journal file an error code is returned.
24761 */
24762 static int readJournalHdr(
24763   Pager *pPager, 
24764   i64 journalSize,
24765   u32 *pNRec, 
24766   u32 *pDbSize
24767 ){
24768   int rc;
24769   unsigned char aMagic[8]; /* A buffer to hold the magic header */
24770   i64 jrnlOff;
24771   int iPageSize;
24772
24773   seekJournalHdr(pPager);
24774   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
24775     return SQLITE_DONE;
24776   }
24777   jrnlOff = pPager->journalOff;
24778
24779   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
24780   if( rc ) return rc;
24781   jrnlOff += sizeof(aMagic);
24782
24783   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
24784     return SQLITE_DONE;
24785   }
24786
24787   rc = read32bits(pPager->jfd, jrnlOff, pNRec);
24788   if( rc ) return rc;
24789
24790   rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
24791   if( rc ) return rc;
24792
24793   rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
24794   if( rc ) return rc;
24795
24796   rc = read32bits(pPager->jfd, jrnlOff+16, (u32 *)&iPageSize);
24797   if( rc==SQLITE_OK 
24798    && iPageSize>=512 
24799    && iPageSize<=SQLITE_MAX_PAGE_SIZE 
24800    && ((iPageSize-1)&iPageSize)==0 
24801   ){
24802     u16 pagesize = iPageSize;
24803     rc = sqlite3PagerSetPagesize(pPager, &pagesize);
24804   }
24805   if( rc ) return rc;
24806
24807   /* Update the assumed sector-size to match the value used by 
24808   ** the process that created this journal. If this journal was
24809   ** created by a process other than this one, then this routine
24810   ** is being called from within pager_playback(). The local value
24811   ** of Pager.sectorSize is restored at the end of that routine.
24812   */
24813   rc = read32bits(pPager->jfd, jrnlOff+12, (u32 *)&pPager->sectorSize);
24814   if( rc ) return rc;
24815
24816   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
24817   return SQLITE_OK;
24818 }
24819
24820
24821 /*
24822 ** Write the supplied master journal name into the journal file for pager
24823 ** pPager at the current location. The master journal name must be the last
24824 ** thing written to a journal file. If the pager is in full-sync mode, the
24825 ** journal file descriptor is advanced to the next sector boundary before
24826 ** anything is written. The format is:
24827 **
24828 ** + 4 bytes: PAGER_MJ_PGNO.
24829 ** + N bytes: length of master journal name.
24830 ** + 4 bytes: N
24831 ** + 4 bytes: Master journal name checksum.
24832 ** + 8 bytes: aJournalMagic[].
24833 **
24834 ** The master journal page checksum is the sum of the bytes in the master
24835 ** journal name.
24836 **
24837 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
24838 ** this call is a no-op.
24839 */
24840 static int writeMasterJournal(Pager *pPager, const char *zMaster){
24841   int rc;
24842   int len; 
24843   int i; 
24844   i64 jrnlOff;
24845   i64 jrnlSize;
24846   u32 cksum = 0;
24847   char zBuf[sizeof(aJournalMagic)+2*4];
24848
24849   if( !zMaster || pPager->setMaster) return SQLITE_OK;
24850   pPager->setMaster = 1;
24851
24852   len = strlen(zMaster);
24853   for(i=0; i<len; i++){
24854     cksum += zMaster[i];
24855   }
24856
24857   /* If in full-sync mode, advance to the next disk sector before writing
24858   ** the master journal name. This is in case the previous page written to
24859   ** the journal has already been synced.
24860   */
24861   if( pPager->fullSync ){
24862     seekJournalHdr(pPager);
24863   }
24864   jrnlOff = pPager->journalOff;
24865   pPager->journalOff += (len+20);
24866
24867   rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
24868   if( rc!=SQLITE_OK ) return rc;
24869   jrnlOff += 4;
24870
24871   rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
24872   if( rc!=SQLITE_OK ) return rc;
24873   jrnlOff += len;
24874
24875   put32bits(zBuf, len);
24876   put32bits(&zBuf[4], cksum);
24877   memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
24878   rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
24879   jrnlOff += 8+sizeof(aJournalMagic);
24880   pPager->needSync = !pPager->noSync;
24881
24882   /* If the pager is in peristent-journal mode, then the physical 
24883   ** journal-file may extend past the end of the master-journal name
24884   ** and 8 bytes of magic data just written to the file. This is 
24885   ** dangerous because the code to rollback a hot-journal file
24886   ** will not be able to find the master-journal name to determine 
24887   ** whether or not the journal is hot. 
24888   **
24889   ** Easiest thing to do in this scenario is to truncate the journal 
24890   ** file to the required size.
24891   */ 
24892   if( (rc==SQLITE_OK)
24893    && (rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))==SQLITE_OK
24894    && jrnlSize>jrnlOff
24895   ){
24896     rc = sqlite3OsTruncate(pPager->jfd, jrnlOff);
24897   }
24898   return rc;
24899 }
24900
24901 /*
24902 ** Add or remove a page from the list of all pages that are in the
24903 ** statement journal.
24904 **
24905 ** The Pager keeps a separate list of pages that are currently in
24906 ** the statement journal.  This helps the sqlite3PagerStmtCommit()
24907 ** routine run MUCH faster for the common case where there are many
24908 ** pages in memory but only a few are in the statement journal.
24909 */
24910 static void page_add_to_stmt_list(PgHdr *pPg){
24911   Pager *pPager = pPg->pPager;
24912   PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
24913   assert( MEMDB );
24914   if( !pHist->inStmt ){
24915     assert( pHist->pPrevStmt==0 && pHist->pNextStmt==0 );
24916     if( pPager->pStmt ){
24917       PGHDR_TO_HIST(pPager->pStmt, pPager)->pPrevStmt = pPg;
24918     }
24919     pHist->pNextStmt = pPager->pStmt;
24920     pPager->pStmt = pPg;
24921     pHist->inStmt = 1;
24922   }
24923 }
24924
24925 /*
24926 ** Find a page in the hash table given its page number.  Return
24927 ** a pointer to the page or NULL if not found.
24928 */
24929 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
24930   PgHdr *p;
24931   if( pPager->aHash==0 ) return 0;
24932   p = pPager->aHash[pgno & (pPager->nHash-1)];
24933   while( p && p->pgno!=pgno ){
24934     p = p->pNextHash;
24935   }
24936   return p;
24937 }
24938
24939 /*
24940 ** Clear the in-memory cache.  This routine
24941 ** sets the state of the pager back to what it was when it was first
24942 ** opened.  Any outstanding pages are invalidated and subsequent attempts
24943 ** to access those pages will likely result in a coredump.
24944 */
24945 static void pager_reset(Pager *pPager){
24946   PgHdr *pPg, *pNext;
24947   if( pPager->errCode ) return;
24948   for(pPg=pPager->pAll; pPg; pPg=pNext){
24949     IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
24950     PAGER_INCR(sqlite3_pager_pgfree_count);
24951     pNext = pPg->pNextAll;
24952     lruListRemove(pPg);
24953     sqlite3_free(pPg->pData);
24954     sqlite3_free(pPg);
24955   }
24956   assert(pPager->lru.pFirst==0);
24957   assert(pPager->lru.pFirstSynced==0);
24958   assert(pPager->lru.pLast==0);
24959   pPager->pStmt = 0;
24960   pPager->pAll = 0;
24961   pPager->pDirty = 0;
24962   pPager->nHash = 0;
24963   sqlite3_free(pPager->aHash);
24964   pPager->nPage = 0;
24965   pPager->aHash = 0;
24966   pPager->nRef = 0;
24967 }
24968
24969 /*
24970 ** Unlock the database file. 
24971 **
24972 ** If the pager is currently in error state, discard the contents of 
24973 ** the cache and reset the Pager structure internal state. If there is
24974 ** an open journal-file, then the next time a shared-lock is obtained
24975 ** on the pager file (by this or any other process), it will be
24976 ** treated as a hot-journal and rolled back.
24977 */
24978 static void pager_unlock(Pager *pPager){
24979   if( !pPager->exclusiveMode ){
24980     if( !MEMDB ){
24981       int rc = osUnlock(pPager->fd, NO_LOCK);
24982       if( rc ) pPager->errCode = rc;
24983       pPager->dbSize = -1;
24984       IOTRACE(("UNLOCK %p\n", pPager))
24985
24986       /* Always close the journal file when dropping the database lock.
24987       ** Otherwise, another connection with journal_mode=delete might
24988       ** delete the file out from under us.
24989       */
24990       if( pPager->journalOpen ){
24991         sqlite3OsClose(pPager->jfd);
24992         pPager->journalOpen = 0;
24993         sqlite3BitvecDestroy(pPager->pInJournal);
24994         pPager->pInJournal = 0;
24995       }
24996
24997       /* If Pager.errCode is set, the contents of the pager cache cannot be
24998       ** trusted. Now that the pager file is unlocked, the contents of the
24999       ** cache can be discarded and the error code safely cleared.
25000       */
25001       if( pPager->errCode ){
25002         if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;
25003         pager_reset(pPager);
25004         if( pPager->stmtOpen ){
25005           sqlite3OsClose(pPager->stfd);
25006           sqlite3BitvecDestroy(pPager->pInStmt);
25007           pPager->pInStmt = 0;
25008         }
25009         pPager->stmtOpen = 0;
25010         pPager->stmtInUse = 0;
25011         pPager->journalOff = 0;
25012         pPager->journalStarted = 0;
25013         pPager->stmtAutoopen = 0;
25014         pPager->origDbSize = 0;
25015       }
25016     }
25017
25018     if( !MEMDB || pPager->errCode==SQLITE_OK ){
25019       pPager->state = PAGER_UNLOCK;
25020       pPager->changeCountDone = 0;
25021     }
25022   }
25023 }
25024
25025 /*
25026 ** Execute a rollback if a transaction is active and unlock the 
25027 ** database file. If the pager has already entered the error state, 
25028 ** do not attempt the rollback.
25029 */
25030 static void pagerUnlockAndRollback(Pager *p){
25031   /* assert( p->state>=PAGER_RESERVED || p->journalOpen==0 ); */
25032   if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
25033     sqlite3FaultBeginBenign(-1);
25034     sqlite3PagerRollback(p);
25035     sqlite3FaultEndBenign(-1);
25036   }
25037   pager_unlock(p);
25038 #if 0
25039   assert( p->errCode || !p->journalOpen || (p->exclusiveMode&&!p->journalOff) );
25040   assert( p->errCode || !p->stmtOpen || p->exclusiveMode );
25041 #endif
25042 }
25043
25044 /*
25045 ** This routine ends a transaction.  A transaction is ended by either
25046 ** a COMMIT or a ROLLBACK.
25047 **
25048 ** When this routine is called, the pager has the journal file open and
25049 ** a RESERVED or EXCLUSIVE lock on the database.  This routine will release
25050 ** the database lock and acquires a SHARED lock in its place if that is
25051 ** the appropriate thing to do.  Release locks usually is appropriate,
25052 ** unless we are in exclusive access mode or unless this is a 
25053 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
25054 **
25055 ** The journal file is either deleted or truncated.
25056 **
25057 ** TODO: Consider keeping the journal file open for temporary databases.
25058 ** This might give a performance improvement on windows where opening
25059 ** a file is an expensive operation.
25060 */
25061 static int pager_end_transaction(Pager *pPager, int hasMaster){
25062   PgHdr *pPg;
25063   int rc = SQLITE_OK;
25064   int rc2 = SQLITE_OK;
25065   assert( !MEMDB );
25066   if( pPager->state<PAGER_RESERVED ){
25067     return SQLITE_OK;
25068   }
25069   sqlite3PagerStmtCommit(pPager);
25070   if( pPager->stmtOpen && !pPager->exclusiveMode ){
25071     sqlite3OsClose(pPager->stfd);
25072     pPager->stmtOpen = 0;
25073   }
25074   if( pPager->journalOpen ){
25075     if( pPager->exclusiveMode 
25076      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
25077     ){
25078       rc = zeroJournalHdr(pPager, hasMaster);
25079       pager_error(pPager, rc);
25080       pPager->journalOff = 0;
25081       pPager->journalStarted = 0;
25082     }else{
25083       sqlite3OsClose(pPager->jfd);
25084       pPager->journalOpen = 0;
25085       if( rc==SQLITE_OK ){
25086         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
25087       }
25088     }
25089     sqlite3BitvecDestroy(pPager->pInJournal);
25090     pPager->pInJournal = 0;
25091     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
25092       pPg->inJournal = 0;
25093       pPg->dirty = 0;
25094       pPg->needSync = 0;
25095       pPg->alwaysRollback = 0;
25096 #ifdef SQLITE_CHECK_PAGES
25097       pPg->pageHash = pager_pagehash(pPg);
25098 #endif
25099     }
25100     pPager->pDirty = 0;
25101     pPager->dirtyCache = 0;
25102     pPager->nRec = 0;
25103   }else{
25104     assert( pPager->pInJournal==0 );
25105   }
25106
25107   if( !pPager->exclusiveMode ){
25108     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
25109     pPager->state = PAGER_SHARED;
25110   }else if( pPager->state==PAGER_SYNCED ){
25111     pPager->state = PAGER_EXCLUSIVE;
25112   }
25113   pPager->origDbSize = 0;
25114   pPager->setMaster = 0;
25115   pPager->needSync = 0;
25116   lruListSetFirstSynced(pPager);
25117   pPager->dbSize = -1;
25118   pPager->dbModified = 0;
25119
25120   return (rc==SQLITE_OK?rc2:rc);
25121 }
25122
25123 /*
25124 ** Compute and return a checksum for the page of data.
25125 **
25126 ** This is not a real checksum.  It is really just the sum of the 
25127 ** random initial value and the page number.  We experimented with
25128 ** a checksum of the entire data, but that was found to be too slow.
25129 **
25130 ** Note that the page number is stored at the beginning of data and
25131 ** the checksum is stored at the end.  This is important.  If journal
25132 ** corruption occurs due to a power failure, the most likely scenario
25133 ** is that one end or the other of the record will be changed.  It is
25134 ** much less likely that the two ends of the journal record will be
25135 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
25136 ** though fast and simple, catches the mostly likely kind of corruption.
25137 **
25138 ** FIX ME:  Consider adding every 200th (or so) byte of the data to the
25139 ** checksum.  That way if a single page spans 3 or more disk sectors and
25140 ** only the middle sector is corrupt, we will still have a reasonable
25141 ** chance of failing the checksum and thus detecting the problem.
25142 */
25143 static u32 pager_cksum(Pager *pPager, const u8 *aData){
25144   u32 cksum = pPager->cksumInit;
25145   int i = pPager->pageSize-200;
25146   while( i>0 ){
25147     cksum += aData[i];
25148     i -= 200;
25149   }
25150   return cksum;
25151 }
25152
25153 /* Forward declaration */
25154 static void makeClean(PgHdr*);
25155
25156 /*
25157 ** Read a single page from the journal file opened on file descriptor
25158 ** jfd.  Playback this one page.
25159 **
25160 ** If useCksum==0 it means this journal does not use checksums.  Checksums
25161 ** are not used in statement journals because statement journals do not
25162 ** need to survive power failures.
25163 */
25164 static int pager_playback_one_page(
25165   Pager *pPager, 
25166   sqlite3_file *jfd,
25167   i64 offset,
25168   int useCksum
25169 ){
25170   int rc;
25171   PgHdr *pPg;                   /* An existing page in the cache */
25172   Pgno pgno;                    /* The page number of a page in journal */
25173   u32 cksum;                    /* Checksum used for sanity checking */
25174   u8 *aData = (u8 *)pPager->pTmpSpace;   /* Temp storage for a page */
25175
25176   /* useCksum should be true for the main journal and false for
25177   ** statement journals.  Verify that this is always the case
25178   */
25179   assert( jfd == (useCksum ? pPager->jfd : pPager->stfd) );
25180   assert( aData );
25181
25182   rc = read32bits(jfd, offset, &pgno);
25183   if( rc!=SQLITE_OK ) return rc;
25184   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, offset+4);
25185   if( rc!=SQLITE_OK ) return rc;
25186   pPager->journalOff += pPager->pageSize + 4;
25187
25188   /* Sanity checking on the page.  This is more important that I originally
25189   ** thought.  If a power failure occurs while the journal is being written,
25190   ** it could cause invalid data to be written into the journal.  We need to
25191   ** detect this invalid data (with high probability) and ignore it.
25192   */
25193   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
25194     return SQLITE_DONE;
25195   }
25196   if( pgno>(unsigned)pPager->dbSize ){
25197     return SQLITE_OK;
25198   }
25199   if( useCksum ){
25200     rc = read32bits(jfd, offset+pPager->pageSize+4, &cksum);
25201     if( rc ) return rc;
25202     pPager->journalOff += 4;
25203     if( pager_cksum(pPager, aData)!=cksum ){
25204       return SQLITE_DONE;
25205     }
25206   }
25207
25208   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
25209
25210   /* If the pager is in RESERVED state, then there must be a copy of this
25211   ** page in the pager cache. In this case just update the pager cache,
25212   ** not the database file. The page is left marked dirty in this case.
25213   **
25214   ** An exception to the above rule: If the database is in no-sync mode
25215   ** and a page is moved during an incremental vacuum then the page may
25216   ** not be in the pager cache. Later: if a malloc() or IO error occurs
25217   ** during a Movepage() call, then the page may not be in the cache
25218   ** either. So the condition described in the above paragraph is not
25219   ** assert()able.
25220   **
25221   ** If in EXCLUSIVE state, then we update the pager cache if it exists
25222   ** and the main file. The page is then marked not dirty.
25223   **
25224   ** Ticket #1171:  The statement journal might contain page content that is
25225   ** different from the page content at the start of the transaction.
25226   ** This occurs when a page is changed prior to the start of a statement
25227   ** then changed again within the statement.  When rolling back such a
25228   ** statement we must not write to the original database unless we know
25229   ** for certain that original page contents are synced into the main rollback
25230   ** journal.  Otherwise, a power loss might leave modified data in the
25231   ** database file without an entry in the rollback journal that can
25232   ** restore the database to its original form.  Two conditions must be
25233   ** met before writing to the database files. (1) the database must be
25234   ** locked.  (2) we know that the original page content is fully synced
25235   ** in the main journal either because the page is not in cache or else
25236   ** the page is marked as needSync==0.
25237   **
25238   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
25239   ** is possible to fail a statement on a database that does not yet exist.
25240   ** Do not attempt to write if database file has never been opened.
25241   */
25242   pPg = pager_lookup(pPager, pgno);
25243   PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
25244                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
25245   if( pPager->state>=PAGER_EXCLUSIVE && (pPg==0 || pPg->needSync==0)
25246         && pPager->fd->pMethods ){
25247     i64 offset = (pgno-1)*(i64)pPager->pageSize;
25248     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, offset);
25249     if( pPg ){
25250       makeClean(pPg);
25251     }
25252   }
25253   if( pPg ){
25254     /* No page should ever be explicitly rolled back that is in use, except
25255     ** for page 1 which is held in use in order to keep the lock on the
25256     ** database active. However such a page may be rolled back as a result
25257     ** of an internal error resulting in an automatic call to
25258     ** sqlite3PagerRollback().
25259     */
25260     void *pData;
25261     /* assert( pPg->nRef==0 || pPg->pgno==1 ); */
25262     pData = PGHDR_TO_DATA(pPg);
25263     memcpy(pData, aData, pPager->pageSize);
25264     if( pPager->xReiniter ){
25265       pPager->xReiniter(pPg, pPager->pageSize);
25266     }
25267 #ifdef SQLITE_CHECK_PAGES
25268     pPg->pageHash = pager_pagehash(pPg);
25269 #endif
25270     /* If this was page 1, then restore the value of Pager.dbFileVers.
25271     ** Do this before any decoding. */
25272     if( pgno==1 ){
25273       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
25274     }
25275
25276     /* Decode the page just read from disk */
25277     CODEC1(pPager, pData, pPg->pgno, 3);
25278   }
25279   return rc;
25280 }
25281
25282 /*
25283 ** Parameter zMaster is the name of a master journal file. A single journal
25284 ** file that referred to the master journal file has just been rolled back.
25285 ** This routine checks if it is possible to delete the master journal file,
25286 ** and does so if it is.
25287 **
25288 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
25289 ** available for use within this function.
25290 **
25291 **
25292 ** The master journal file contains the names of all child journals.
25293 ** To tell if a master journal can be deleted, check to each of the
25294 ** children.  If all children are either missing or do not refer to
25295 ** a different master journal, then this master journal can be deleted.
25296 */
25297 static int pager_delmaster(Pager *pPager, const char *zMaster){
25298   sqlite3_vfs *pVfs = pPager->pVfs;
25299   int rc;
25300   int master_open = 0;
25301   sqlite3_file *pMaster;
25302   sqlite3_file *pJournal;
25303   char *zMasterJournal = 0; /* Contents of master journal file */
25304   i64 nMasterJournal;       /* Size of master journal file */
25305
25306   /* Open the master journal file exclusively in case some other process
25307   ** is running this routine also. Not that it makes too much difference.
25308   */
25309   pMaster = (sqlite3_file *)sqlite3_malloc(pVfs->szOsFile * 2);
25310   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
25311   if( !pMaster ){
25312     rc = SQLITE_NOMEM;
25313   }else{
25314     int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
25315     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
25316   }
25317   if( rc!=SQLITE_OK ) goto delmaster_out;
25318   master_open = 1;
25319
25320   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
25321   if( rc!=SQLITE_OK ) goto delmaster_out;
25322
25323   if( nMasterJournal>0 ){
25324     char *zJournal;
25325     char *zMasterPtr = 0;
25326     int nMasterPtr = pPager->pVfs->mxPathname+1;
25327
25328     /* Load the entire master journal file into space obtained from
25329     ** sqlite3_malloc() and pointed to by zMasterJournal. 
25330     */
25331     zMasterJournal = (char *)sqlite3_malloc(nMasterJournal + nMasterPtr);
25332     if( !zMasterJournal ){
25333       rc = SQLITE_NOMEM;
25334       goto delmaster_out;
25335     }
25336     zMasterPtr = &zMasterJournal[nMasterJournal];
25337     rc = sqlite3OsRead(pMaster, zMasterJournal, nMasterJournal, 0);
25338     if( rc!=SQLITE_OK ) goto delmaster_out;
25339
25340     zJournal = zMasterJournal;
25341     while( (zJournal-zMasterJournal)<nMasterJournal ){
25342       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS);
25343       if( rc!=0 && rc!=1 ){
25344         rc = SQLITE_IOERR_NOMEM;
25345         goto delmaster_out;
25346       }
25347       if( rc==1 ){
25348         /* One of the journals pointed to by the master journal exists.
25349         ** Open it and check if it points at the master journal. If
25350         ** so, return without deleting the master journal file.
25351         */
25352         int c;
25353         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
25354         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
25355         if( rc!=SQLITE_OK ){
25356           goto delmaster_out;
25357         }
25358
25359         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
25360         sqlite3OsClose(pJournal);
25361         if( rc!=SQLITE_OK ){
25362           goto delmaster_out;
25363         }
25364
25365         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
25366         if( c ){
25367           /* We have a match. Do not delete the master journal file. */
25368           goto delmaster_out;
25369         }
25370       }
25371       zJournal += (strlen(zJournal)+1);
25372     }
25373   }
25374   
25375   rc = sqlite3OsDelete(pVfs, zMaster, 0);
25376
25377 delmaster_out:
25378   if( zMasterJournal ){
25379     sqlite3_free(zMasterJournal);
25380   }  
25381   if( master_open ){
25382     sqlite3OsClose(pMaster);
25383   }
25384   sqlite3_free(pMaster);
25385   return rc;
25386 }
25387
25388
25389 static void pager_truncate_cache(Pager *pPager);
25390
25391 /*
25392 ** Truncate the main file of the given pager to the number of pages
25393 ** indicated. Also truncate the cached representation of the file.
25394 **
25395 ** Might might be the case that the file on disk is smaller than nPage.
25396 ** This can happen, for example, if we are in the middle of a transaction
25397 ** which has extended the file size and the new pages are still all held
25398 ** in cache, then an INSERT or UPDATE does a statement rollback.  Some
25399 ** operating system implementations can get confused if you try to
25400 ** truncate a file to some size that is larger than it currently is,
25401 ** so detect this case and write a single zero byte to the end of the new
25402 ** file instead.
25403 */
25404 static int pager_truncate(Pager *pPager, int nPage){
25405   int rc = SQLITE_OK;
25406   if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
25407     i64 currentSize, newSize;
25408     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
25409     newSize = pPager->pageSize*(i64)nPage;
25410     if( rc==SQLITE_OK && currentSize!=newSize ){
25411       if( currentSize>newSize ){
25412         rc = sqlite3OsTruncate(pPager->fd, newSize);
25413       }else{
25414         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
25415       }
25416     }
25417   }
25418   if( rc==SQLITE_OK ){
25419     pPager->dbSize = nPage;
25420     pager_truncate_cache(pPager);
25421   }
25422   return rc;
25423 }
25424
25425 /*
25426 ** Set the sectorSize for the given pager.
25427 **
25428 ** The sector size is at least as big as the sector size reported
25429 ** by sqlite3OsSectorSize().  The minimum sector size is 512.
25430 */
25431 static void setSectorSize(Pager *pPager){
25432   assert(pPager->fd->pMethods||pPager->tempFile);
25433   if( !pPager->tempFile ){
25434     /* Sector size doesn't matter for temporary files. Also, the file
25435     ** may not have been opened yet, in whcih case the OsSectorSize()
25436     ** call will segfault.
25437     */
25438     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
25439   }
25440   if( pPager->sectorSize<512 ){
25441     pPager->sectorSize = 512;
25442   }
25443 }
25444
25445 /*
25446 ** Playback the journal and thus restore the database file to
25447 ** the state it was in before we started making changes.  
25448 **
25449 ** The journal file format is as follows: 
25450 **
25451 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
25452 **  (2)  4 byte big-endian integer which is the number of valid page records
25453 **       in the journal.  If this value is 0xffffffff, then compute the
25454 **       number of page records from the journal size.
25455 **  (3)  4 byte big-endian integer which is the initial value for the 
25456 **       sanity checksum.
25457 **  (4)  4 byte integer which is the number of pages to truncate the
25458 **       database to during a rollback.
25459 **  (5)  4 byte big-endian integer which is the sector size.  The header
25460 **       is this many bytes in size.
25461 **  (6)  4 byte big-endian integer which is the page case.
25462 **  (7)  4 byte integer which is the number of bytes in the master journal
25463 **       name.  The value may be zero (indicate that there is no master
25464 **       journal.)
25465 **  (8)  N bytes of the master journal name.  The name will be nul-terminated
25466 **       and might be shorter than the value read from (5).  If the first byte
25467 **       of the name is \000 then there is no master journal.  The master
25468 **       journal name is stored in UTF-8.
25469 **  (9)  Zero or more pages instances, each as follows:
25470 **        +  4 byte page number.
25471 **        +  pPager->pageSize bytes of data.
25472 **        +  4 byte checksum
25473 **
25474 ** When we speak of the journal header, we mean the first 8 items above.
25475 ** Each entry in the journal is an instance of the 9th item.
25476 **
25477 ** Call the value from the second bullet "nRec".  nRec is the number of
25478 ** valid page entries in the journal.  In most cases, you can compute the
25479 ** value of nRec from the size of the journal file.  But if a power
25480 ** failure occurred while the journal was being written, it could be the
25481 ** case that the size of the journal file had already been increased but
25482 ** the extra entries had not yet made it safely to disk.  In such a case,
25483 ** the value of nRec computed from the file size would be too large.  For
25484 ** that reason, we always use the nRec value in the header.
25485 **
25486 ** If the nRec value is 0xffffffff it means that nRec should be computed
25487 ** from the file size.  This value is used when the user selects the
25488 ** no-sync option for the journal.  A power failure could lead to corruption
25489 ** in this case.  But for things like temporary table (which will be
25490 ** deleted when the power is restored) we don't care.  
25491 **
25492 ** If the file opened as the journal file is not a well-formed
25493 ** journal file then all pages up to the first corrupted page are rolled
25494 ** back (or no pages if the journal header is corrupted). The journal file
25495 ** is then deleted and SQLITE_OK returned, just as if no corruption had
25496 ** been encountered.
25497 **
25498 ** If an I/O or malloc() error occurs, the journal-file is not deleted
25499 ** and an error code is returned.
25500 */
25501 static int pager_playback(Pager *pPager, int isHot){
25502   sqlite3_vfs *pVfs = pPager->pVfs;
25503   i64 szJ;                 /* Size of the journal file in bytes */
25504   u32 nRec;                /* Number of Records in the journal */
25505   int i;                   /* Loop counter */
25506   Pgno mxPg = 0;           /* Size of the original file in pages */
25507   int rc;                  /* Result code of a subroutine */
25508   int res = 0;             /* Value returned by sqlite3OsAccess() */
25509   char *zMaster = 0;       /* Name of master journal file if any */
25510
25511   /* Figure out how many records are in the journal.  Abort early if
25512   ** the journal is empty.
25513   */
25514   assert( pPager->journalOpen );
25515   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
25516   if( rc!=SQLITE_OK || szJ==0 ){
25517     goto end_playback;
25518   }
25519
25520   /* Read the master journal name from the journal, if it is present.
25521   ** If a master journal file name is specified, but the file is not
25522   ** present on disk, then the journal is not hot and does not need to be
25523   ** played back.
25524   */
25525   zMaster = pPager->pTmpSpace;
25526   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
25527   if( rc!=SQLITE_OK || (zMaster[0] 
25528    && (res=sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS))==0 ) 
25529   ){
25530     zMaster = 0;
25531     goto end_playback;
25532   }
25533   zMaster = 0;
25534   if( res<0 ){
25535     rc = SQLITE_IOERR_NOMEM;
25536     goto end_playback;
25537   }
25538   pPager->journalOff = 0;
25539
25540   /* This loop terminates either when the readJournalHdr() call returns
25541   ** SQLITE_DONE or an IO error occurs. */
25542   while( 1 ){
25543
25544     /* Read the next journal header from the journal file.  If there are
25545     ** not enough bytes left in the journal file for a complete header, or
25546     ** it is corrupted, then a process must of failed while writing it.
25547     ** This indicates nothing more needs to be rolled back.
25548     */
25549     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
25550     if( rc!=SQLITE_OK ){ 
25551       if( rc==SQLITE_DONE ){
25552         rc = SQLITE_OK;
25553       }
25554       goto end_playback;
25555     }
25556
25557     /* If nRec is 0xffffffff, then this journal was created by a process
25558     ** working in no-sync mode. This means that the rest of the journal
25559     ** file consists of pages, there are no more journal headers. Compute
25560     ** the value of nRec based on this assumption.
25561     */
25562     if( nRec==0xffffffff ){
25563       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
25564       nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
25565     }
25566
25567     /* If nRec is 0 and this rollback is of a transaction created by this
25568     ** process and if this is the final header in the journal, then it means
25569     ** that this part of the journal was being filled but has not yet been
25570     ** synced to disk.  Compute the number of pages based on the remaining
25571     ** size of the file.
25572     **
25573     ** The third term of the test was added to fix ticket #2565.
25574     */
25575     if( nRec==0 && !isHot &&
25576         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
25577       nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
25578     }
25579
25580     /* If this is the first header read from the journal, truncate the
25581     ** database file back to its original size.
25582     */
25583     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
25584       rc = pager_truncate(pPager, mxPg);
25585       if( rc!=SQLITE_OK ){
25586         goto end_playback;
25587       }
25588     }
25589
25590     /* Copy original pages out of the journal and back into the database file.
25591     */
25592     for(i=0; i<nRec; i++){
25593       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
25594       if( rc!=SQLITE_OK ){
25595         if( rc==SQLITE_DONE ){
25596           rc = SQLITE_OK;
25597           pPager->journalOff = szJ;
25598           break;
25599         }else{
25600           goto end_playback;
25601         }
25602       }
25603     }
25604   }
25605   /*NOTREACHED*/
25606   assert( 0 );
25607
25608 end_playback:
25609   if( rc==SQLITE_OK ){
25610     zMaster = pPager->pTmpSpace;
25611     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
25612   }
25613   if( rc==SQLITE_OK ){
25614     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
25615   }
25616   if( rc==SQLITE_OK && zMaster[0] ){
25617     /* If there was a master journal and this routine will return success,
25618     ** see if it is possible to delete the master journal.
25619     */
25620     rc = pager_delmaster(pPager, zMaster);
25621   }
25622
25623   /* The Pager.sectorSize variable may have been updated while rolling
25624   ** back a journal created by a process with a different sector size
25625   ** value. Reset it to the correct value for this process.
25626   */
25627   setSectorSize(pPager);
25628   return rc;
25629 }
25630
25631 /*
25632 ** Playback the statement journal.
25633 **
25634 ** This is similar to playing back the transaction journal but with
25635 ** a few extra twists.
25636 **
25637 **    (1)  The number of pages in the database file at the start of
25638 **         the statement is stored in pPager->stmtSize, not in the
25639 **         journal file itself.
25640 **
25641 **    (2)  In addition to playing back the statement journal, also
25642 **         playback all pages of the transaction journal beginning
25643 **         at offset pPager->stmtJSize.
25644 */
25645 static int pager_stmt_playback(Pager *pPager){
25646   i64 szJ;                 /* Size of the full journal */
25647   i64 hdrOff;
25648   int nRec;                /* Number of Records */
25649   int i;                   /* Loop counter */
25650   int rc;
25651
25652   szJ = pPager->journalOff;
25653
25654   /* Set hdrOff to be the offset just after the end of the last journal
25655   ** page written before the first journal-header for this statement
25656   ** transaction was written, or the end of the file if no journal
25657   ** header was written.
25658   */
25659   hdrOff = pPager->stmtHdrOff;
25660   assert( pPager->fullSync || !hdrOff );
25661   if( !hdrOff ){
25662     hdrOff = szJ;
25663   }
25664   
25665   /* Truncate the database back to its original size.
25666   */
25667   rc = pager_truncate(pPager, pPager->stmtSize);
25668   assert( pPager->state>=PAGER_SHARED );
25669
25670   /* Figure out how many records are in the statement journal.
25671   */
25672   assert( pPager->stmtInUse && pPager->journalOpen );
25673   nRec = pPager->stmtNRec;
25674   
25675   /* Copy original pages out of the statement journal and back into the
25676   ** database file.  Note that the statement journal omits checksums from
25677   ** each record since power-failure recovery is not important to statement
25678   ** journals.
25679   */
25680   for(i=0; i<nRec; i++){
25681     i64 offset = i*(4+pPager->pageSize);
25682     rc = pager_playback_one_page(pPager, pPager->stfd, offset, 0);
25683     assert( rc!=SQLITE_DONE );
25684     if( rc!=SQLITE_OK ) goto end_stmt_playback;
25685   }
25686
25687   /* Now roll some pages back from the transaction journal. Pager.stmtJSize
25688   ** was the size of the journal file when this statement was started, so
25689   ** everything after that needs to be rolled back, either into the
25690   ** database, the memory cache, or both.
25691   **
25692   ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
25693   ** of the first journal header written during this statement transaction.
25694   */
25695   pPager->journalOff = pPager->stmtJSize;
25696   pPager->cksumInit = pPager->stmtCksum;
25697   while( pPager->journalOff < hdrOff ){
25698     rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
25699     assert( rc!=SQLITE_DONE );
25700     if( rc!=SQLITE_OK ) goto end_stmt_playback;
25701   }
25702
25703   while( pPager->journalOff < szJ ){
25704     u32 nJRec;         /* Number of Journal Records */
25705     u32 dummy;
25706     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
25707     if( rc!=SQLITE_OK ){
25708       assert( rc!=SQLITE_DONE );
25709       goto end_stmt_playback;
25710     }
25711     if( nJRec==0 ){
25712       nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
25713     }
25714     for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
25715       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
25716       assert( rc!=SQLITE_DONE );
25717       if( rc!=SQLITE_OK ) goto end_stmt_playback;
25718     }
25719   }
25720
25721   pPager->journalOff = szJ;
25722   
25723 end_stmt_playback:
25724   if( rc==SQLITE_OK) {
25725     pPager->journalOff = szJ;
25726     /* pager_reload_cache(pPager); */
25727   }
25728   return rc;
25729 }
25730
25731 /*
25732 ** Change the maximum number of in-memory pages that are allowed.
25733 */
25734 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
25735   if( mxPage>10 ){
25736     pPager->mxPage = mxPage;
25737   }else{
25738     pPager->mxPage = 10;
25739   }
25740 }
25741
25742 /*
25743 ** Adjust the robustness of the database to damage due to OS crashes
25744 ** or power failures by changing the number of syncs()s when writing
25745 ** the rollback journal.  There are three levels:
25746 **
25747 **    OFF       sqlite3OsSync() is never called.  This is the default
25748 **              for temporary and transient files.
25749 **
25750 **    NORMAL    The journal is synced once before writes begin on the
25751 **              database.  This is normally adequate protection, but
25752 **              it is theoretically possible, though very unlikely,
25753 **              that an inopertune power failure could leave the journal
25754 **              in a state which would cause damage to the database
25755 **              when it is rolled back.
25756 **
25757 **    FULL      The journal is synced twice before writes begin on the
25758 **              database (with some additional information - the nRec field
25759 **              of the journal header - being written in between the two
25760 **              syncs).  If we assume that writing a
25761 **              single disk sector is atomic, then this mode provides
25762 **              assurance that the journal will not be corrupted to the
25763 **              point of causing damage to the database during rollback.
25764 **
25765 ** Numeric values associated with these states are OFF==1, NORMAL=2,
25766 ** and FULL=3.
25767 */
25768 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
25769 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int full_fsync){
25770   pPager->noSync =  level==1 || pPager->tempFile;
25771   pPager->fullSync = level==3 && !pPager->tempFile;
25772   pPager->sync_flags = (full_fsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
25773   if( pPager->noSync ) pPager->needSync = 0;
25774 }
25775 #endif
25776
25777 /*
25778 ** The following global variable is incremented whenever the library
25779 ** attempts to open a temporary file.  This information is used for
25780 ** testing and analysis only.  
25781 */
25782 #ifdef SQLITE_TEST
25783 SQLITE_API int sqlite3_opentemp_count = 0;
25784 #endif
25785
25786 /*
25787 ** Open a temporary file. 
25788 **
25789 ** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
25790 ** other error code if we fail. The OS will automatically delete the temporary
25791 ** file when it is closed.
25792 */
25793 static int sqlite3PagerOpentemp(
25794   sqlite3_vfs *pVfs,    /* The virtual file system layer */
25795   sqlite3_file *pFile,  /* Write the file descriptor here */
25796   char *zFilename,      /* Name of the file.  Might be NULL */
25797   int vfsFlags          /* Flags passed through to the VFS */
25798 ){
25799   int rc;
25800   assert( zFilename!=0 );
25801
25802 #ifdef SQLITE_TEST
25803   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
25804 #endif
25805
25806   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
25807             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
25808   rc = sqlite3OsOpen(pVfs, zFilename, pFile, vfsFlags, 0);
25809   assert( rc!=SQLITE_OK || pFile->pMethods );
25810   return rc;
25811 }
25812
25813 /*
25814 ** Create a new page cache and put a pointer to the page cache in *ppPager.
25815 ** The file to be cached need not exist.  The file is not locked until
25816 ** the first call to sqlite3PagerGet() and is only held open until the
25817 ** last page is released using sqlite3PagerUnref().
25818 **
25819 ** If zFilename is NULL then a randomly-named temporary file is created
25820 ** and used as the file to be cached.  The file will be deleted
25821 ** automatically when it is closed.
25822 **
25823 ** If zFilename is ":memory:" then all information is held in cache.
25824 ** It is never written to disk.  This can be used to implement an
25825 ** in-memory database.
25826 */
25827 SQLITE_PRIVATE int sqlite3PagerOpen(
25828   sqlite3_vfs *pVfs,       /* The virtual file system to use */
25829   Pager **ppPager,         /* Return the Pager structure here */
25830   const char *zFilename,   /* Name of the database file to open */
25831   int nExtra,              /* Extra bytes append to each in-memory page */
25832   int flags,               /* flags controlling this file */
25833   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
25834 ){
25835   u8 *pPtr;
25836   Pager *pPager = 0;
25837   int rc = SQLITE_OK;
25838   int i;
25839   int tempFile = 0;
25840   int memDb = 0;
25841   int readOnly = 0;
25842   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
25843   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
25844   int journalFileSize = sqlite3JournalSize(pVfs);
25845   int nDefaultPage = SQLITE_DEFAULT_PAGE_SIZE;
25846   char *zPathname;
25847   int nPathname;
25848   char *zStmtJrnl;
25849   int nStmtJrnl;
25850
25851   /* The default return is a NULL pointer */
25852   *ppPager = 0;
25853
25854   /* Compute the full pathname */
25855   nPathname = pVfs->mxPathname+1;
25856   zPathname = sqlite3_malloc(nPathname*2);
25857   if( zPathname==0 ){
25858     return SQLITE_NOMEM;
25859   }
25860   if( zFilename && zFilename[0] ){
25861 #ifndef SQLITE_OMIT_MEMORYDB
25862     if( strcmp(zFilename,":memory:")==0 ){
25863       memDb = 1;
25864       zPathname[0] = 0;
25865     }else
25866 #endif
25867     {
25868       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
25869     }
25870   }else{
25871     rc = sqlite3OsGetTempname(pVfs, nPathname, zPathname);
25872   }
25873   if( rc!=SQLITE_OK ){
25874     sqlite3_free(zPathname);
25875     return rc;
25876   }
25877   nPathname = strlen(zPathname);
25878
25879   /* Put the statement journal in temporary disk space since this is
25880   ** sometimes RAM disk or other optimized storage.  Unlikely the main
25881   ** main journal file, the statement journal does not need to be 
25882   ** colocated with the database nor does it need to be persistent.
25883   */
25884   zStmtJrnl = &zPathname[nPathname+1];
25885   rc = sqlite3OsGetTempname(pVfs, pVfs->mxPathname+1, zStmtJrnl);
25886   if( rc!=SQLITE_OK ){
25887     sqlite3_free(zPathname);
25888     return rc;
25889   }
25890   nStmtJrnl = strlen(zStmtJrnl);
25891
25892   /* Allocate memory for the pager structure */
25893   pPager = sqlite3MallocZero(
25894     sizeof(*pPager) +           /* Pager structure */
25895     journalFileSize +           /* The journal file structure */ 
25896     pVfs->szOsFile * 3 +        /* The main db and two journal files */ 
25897     3*nPathname + 40 +          /* zFilename, zDirectory, zJournal */
25898     nStmtJrnl                   /* zStmtJrnl */
25899   );
25900   if( !pPager ){
25901     sqlite3_free(zPathname);
25902     return SQLITE_NOMEM;
25903   }
25904   pPtr = (u8 *)&pPager[1];
25905   pPager->vfsFlags = vfsFlags;
25906   pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
25907   pPager->stfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*1];
25908   pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*2];
25909   pPager->zFilename = (char*)&pPtr[pVfs->szOsFile*2+journalFileSize];
25910   pPager->zDirectory = &pPager->zFilename[nPathname+1];
25911   pPager->zJournal = &pPager->zDirectory[nPathname+1];
25912   pPager->zStmtJrnl = &pPager->zJournal[nPathname+10];
25913   pPager->pVfs = pVfs;
25914   memcpy(pPager->zFilename, zPathname, nPathname+1);
25915   memcpy(pPager->zStmtJrnl, zStmtJrnl, nStmtJrnl+1);
25916   sqlite3_free(zPathname);
25917
25918   /* Open the pager file.
25919   */
25920   if( zFilename && zFilename[0] && !memDb ){
25921     if( nPathname>(pVfs->mxPathname - sizeof("-journal")) ){
25922       rc = SQLITE_CANTOPEN;
25923     }else{
25924       int fout = 0;
25925       rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
25926                          pPager->vfsFlags, &fout);
25927       readOnly = (fout&SQLITE_OPEN_READONLY);
25928
25929       /* If the file was successfully opened for read/write access,
25930       ** choose a default page size in case we have to create the
25931       ** database file. The default page size is the maximum of:
25932       **
25933       **    + SQLITE_DEFAULT_PAGE_SIZE,
25934       **    + The value returned by sqlite3OsSectorSize()
25935       **    + The largest page size that can be written atomically.
25936       */
25937       if( rc==SQLITE_OK && !readOnly ){
25938         int iSectorSize = sqlite3OsSectorSize(pPager->fd);
25939         if( nDefaultPage<iSectorSize ){
25940           nDefaultPage = iSectorSize;
25941         }
25942 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
25943         {
25944           int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
25945           int ii;
25946           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
25947           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
25948           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
25949           for(ii=nDefaultPage; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
25950             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) nDefaultPage = ii;
25951           }
25952         }
25953 #endif
25954         if( nDefaultPage>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
25955           nDefaultPage = SQLITE_MAX_DEFAULT_PAGE_SIZE;
25956         }
25957       }
25958     }
25959   }else if( !memDb ){
25960     /* If a temporary file is requested, it is not opened immediately.
25961     ** In this case we accept the default page size and delay actually
25962     ** opening the file until the first call to OsWrite().
25963     */ 
25964     tempFile = 1;
25965     pPager->state = PAGER_EXCLUSIVE;
25966   }
25967
25968   if( pPager && rc==SQLITE_OK ){
25969     pPager->pTmpSpace = sqlite3MallocZero(nDefaultPage);
25970   }
25971
25972   /* If an error occured in either of the blocks above.
25973   ** Free the Pager structure and close the file.
25974   ** Since the pager is not allocated there is no need to set 
25975   ** any Pager.errMask variables.
25976   */
25977   if( !pPager || !pPager->pTmpSpace ){
25978     sqlite3OsClose(pPager->fd);
25979     sqlite3_free(pPager);
25980     return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
25981   }
25982
25983   PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename);
25984   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
25985
25986   /* Fill in Pager.zDirectory[] */
25987   memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
25988   for(i=strlen(pPager->zDirectory); i>0 && pPager->zDirectory[i-1]!='/'; i--){}
25989   if( i>0 ) pPager->zDirectory[i-1] = 0;
25990
25991   /* Fill in Pager.zJournal[] */
25992   memcpy(pPager->zJournal, pPager->zFilename, nPathname);
25993   memcpy(&pPager->zJournal[nPathname], "-journal", 9);
25994
25995   /* pPager->journalOpen = 0; */
25996   pPager->useJournal = useJournal && !memDb;
25997   pPager->noReadlock = noReadlock && readOnly;
25998   /* pPager->stmtOpen = 0; */
25999   /* pPager->stmtInUse = 0; */
26000   /* pPager->nRef = 0; */
26001   pPager->dbSize = memDb-1;
26002   pPager->pageSize = nDefaultPage;
26003   /* pPager->stmtSize = 0; */
26004   /* pPager->stmtJSize = 0; */
26005   /* pPager->nPage = 0; */
26006   pPager->mxPage = 100;
26007   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
26008   /* pPager->state = PAGER_UNLOCK; */
26009   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
26010   /* pPager->errMask = 0; */
26011   pPager->tempFile = tempFile;
26012   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
26013           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
26014   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
26015   pPager->exclusiveMode = tempFile; 
26016   pPager->memDb = memDb;
26017   pPager->readOnly = readOnly;
26018   /* pPager->needSync = 0; */
26019   pPager->noSync = pPager->tempFile || !useJournal;
26020   pPager->fullSync = (pPager->noSync?0:1);
26021   pPager->sync_flags = SQLITE_SYNC_NORMAL;
26022   /* pPager->pFirst = 0; */
26023   /* pPager->pFirstSynced = 0; */
26024   /* pPager->pLast = 0; */
26025   pPager->nExtra = FORCE_ALIGNMENT(nExtra);
26026   assert(pPager->fd->pMethods||memDb||tempFile);
26027   if( !memDb ){
26028     setSectorSize(pPager);
26029   }
26030   /* pPager->pBusyHandler = 0; */
26031   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
26032   *ppPager = pPager;
26033 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26034   pPager->iInUseMM = 0;
26035   pPager->iInUseDB = 0;
26036   if( !memDb ){
26037 #ifndef SQLITE_MUTEX_NOOP
26038     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
26039 #endif
26040     sqlite3_mutex_enter(mutex);
26041     pPager->pNext = sqlite3PagerList;
26042     if( sqlite3PagerList ){
26043       assert( sqlite3PagerList->pPrev==0 );
26044       sqlite3PagerList->pPrev = pPager;
26045     }
26046     pPager->pPrev = 0;
26047     sqlite3PagerList = pPager;
26048     sqlite3_mutex_leave(mutex);
26049   }
26050 #endif
26051   return SQLITE_OK;
26052 }
26053
26054 /*
26055 ** Set the busy handler function.
26056 */
26057 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
26058   pPager->pBusyHandler = pBusyHandler;
26059 }
26060
26061 /*
26062 ** Set the destructor for this pager.  If not NULL, the destructor is called
26063 ** when the reference count on each page reaches zero.  The destructor can
26064 ** be used to clean up information in the extra segment appended to each page.
26065 **
26066 ** The destructor is not called as a result sqlite3PagerClose().  
26067 ** Destructors are only called by sqlite3PagerUnref().
26068 */
26069 SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager *pPager, void (*xDesc)(DbPage*,int)){
26070   pPager->xDestructor = xDesc;
26071 }
26072
26073 /*
26074 ** Set the reinitializer for this pager.  If not NULL, the reinitializer
26075 ** is called when the content of a page in cache is restored to its original
26076 ** value as a result of a rollback.  The callback gives higher-level code
26077 ** an opportunity to restore the EXTRA section to agree with the restored
26078 ** page data.
26079 */
26080 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
26081   pPager->xReiniter = xReinit;
26082 }
26083
26084 /*
26085 ** Set the page size to *pPageSize. If the suggest new page size is
26086 ** inappropriate, then an alternative page size is set to that
26087 ** value before returning.
26088 */
26089 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
26090   int rc = SQLITE_OK;
26091   u16 pageSize = *pPageSize;
26092   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
26093   if( pageSize && pageSize!=pPager->pageSize 
26094    && !pPager->memDb && pPager->nRef==0 
26095   ){
26096     char *pNew = (char *)sqlite3_malloc(pageSize);
26097     if( !pNew ){
26098       rc = SQLITE_NOMEM;
26099     }else{
26100       pagerEnter(pPager);
26101       pager_reset(pPager);
26102       pPager->pageSize = pageSize;
26103       setSectorSize(pPager);
26104       sqlite3_free(pPager->pTmpSpace);
26105       pPager->pTmpSpace = pNew;
26106       pagerLeave(pPager);
26107     }
26108   }
26109   *pPageSize = pPager->pageSize;
26110   return rc;
26111 }
26112
26113 /*
26114 ** Return a pointer to the "temporary page" buffer held internally
26115 ** by the pager.  This is a buffer that is big enough to hold the
26116 ** entire content of a database page.  This buffer is used internally
26117 ** during rollback and will be overwritten whenever a rollback
26118 ** occurs.  But other modules are free to use it too, as long as
26119 ** no rollbacks are happening.
26120 */
26121 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
26122   return pPager->pTmpSpace;
26123 }
26124
26125 /*
26126 ** Attempt to set the maximum database page count if mxPage is positive. 
26127 ** Make no changes if mxPage is zero or negative.  And never reduce the
26128 ** maximum page count below the current size of the database.
26129 **
26130 ** Regardless of mxPage, return the current maximum page count.
26131 */
26132 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
26133   if( mxPage>0 ){
26134     pPager->mxPgno = mxPage;
26135   }
26136   sqlite3PagerPagecount(pPager);
26137   return pPager->mxPgno;
26138 }
26139
26140 /*
26141 ** The following set of routines are used to disable the simulated
26142 ** I/O error mechanism.  These routines are used to avoid simulated
26143 ** errors in places where we do not care about errors.
26144 **
26145 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
26146 ** and generate no code.
26147 */
26148 #ifdef SQLITE_TEST
26149 SQLITE_API extern int sqlite3_io_error_pending;
26150 SQLITE_API extern int sqlite3_io_error_hit;
26151 static int saved_cnt;
26152 void disable_simulated_io_errors(void){
26153   saved_cnt = sqlite3_io_error_pending;
26154   sqlite3_io_error_pending = -1;
26155 }
26156 void enable_simulated_io_errors(void){
26157   sqlite3_io_error_pending = saved_cnt;
26158 }
26159 #else
26160 # define disable_simulated_io_errors()
26161 # define enable_simulated_io_errors()
26162 #endif
26163
26164 /*
26165 ** Read the first N bytes from the beginning of the file into memory
26166 ** that pDest points to. 
26167 **
26168 ** No error checking is done. The rational for this is that this function 
26169 ** may be called even if the file does not exist or contain a header. In 
26170 ** these cases sqlite3OsRead() will return an error, to which the correct 
26171 ** response is to zero the memory at pDest and continue.  A real IO error 
26172 ** will presumably recur and be picked up later (Todo: Think about this).
26173 */
26174 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
26175   int rc = SQLITE_OK;
26176   memset(pDest, 0, N);
26177   assert(MEMDB||pPager->fd->pMethods||pPager->tempFile);
26178   if( pPager->fd->pMethods ){
26179     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
26180     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
26181     if( rc==SQLITE_IOERR_SHORT_READ ){
26182       rc = SQLITE_OK;
26183     }
26184   }
26185   return rc;
26186 }
26187
26188 /*
26189 ** Return the total number of pages in the disk file associated with
26190 ** pPager. 
26191 **
26192 ** If the PENDING_BYTE lies on the page directly after the end of the
26193 ** file, then consider this page part of the file too. For example, if
26194 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
26195 ** file is 4096 bytes, 5 is returned instead of 4.
26196 */
26197 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager){
26198   i64 n = 0;
26199   int rc;
26200   assert( pPager!=0 );
26201   if( pPager->errCode ){
26202     return -1;
26203   }
26204   if( pPager->dbSize>=0 ){
26205     n = pPager->dbSize;
26206   } else {
26207     assert(pPager->fd->pMethods||pPager->tempFile);
26208     if( (pPager->fd->pMethods)
26209      && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
26210       pPager->nRef++;
26211       pager_error(pPager, rc);
26212       pPager->nRef--;
26213       return -1;
26214     }
26215     if( n>0 && n<pPager->pageSize ){
26216       n = 1;
26217     }else{
26218       n /= pPager->pageSize;
26219     }
26220     if( pPager->state!=PAGER_UNLOCK ){
26221       pPager->dbSize = n;
26222     }
26223   }
26224   if( n==(PENDING_BYTE/pPager->pageSize) ){
26225     n++;
26226   }
26227   if( n>pPager->mxPgno ){
26228     pPager->mxPgno = n;
26229   }
26230   return n;
26231 }
26232
26233
26234 #ifndef SQLITE_OMIT_MEMORYDB
26235 /*
26236 ** Clear a PgHistory block
26237 */
26238 static void clearHistory(PgHistory *pHist){
26239   sqlite3_free(pHist->pOrig);
26240   sqlite3_free(pHist->pStmt);
26241   pHist->pOrig = 0;
26242   pHist->pStmt = 0;
26243 }
26244 #else
26245 #define clearHistory(x)
26246 #endif
26247
26248 /*
26249 ** Forward declaration
26250 */
26251 static int syncJournal(Pager*);
26252
26253 /*
26254 ** Unlink pPg from its hash chain. Also set the page number to 0 to indicate
26255 ** that the page is not part of any hash chain. This is required because the
26256 ** sqlite3PagerMovepage() routine can leave a page in the 
26257 ** pNextFree/pPrevFree list that is not a part of any hash-chain.
26258 */
26259 static void unlinkHashChain(Pager *pPager, PgHdr *pPg){
26260   if( pPg->pgno==0 ){
26261     assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
26262     return;
26263   }
26264   if( pPg->pNextHash ){
26265     pPg->pNextHash->pPrevHash = pPg->pPrevHash;
26266   }
26267   if( pPg->pPrevHash ){
26268     assert( pPager->aHash[pPg->pgno & (pPager->nHash-1)]!=pPg );
26269     pPg->pPrevHash->pNextHash = pPg->pNextHash;
26270   }else{
26271     int h = pPg->pgno & (pPager->nHash-1);
26272     pPager->aHash[h] = pPg->pNextHash;
26273   }
26274   if( MEMDB ){
26275     clearHistory(PGHDR_TO_HIST(pPg, pPager));
26276   }
26277   pPg->pgno = 0;
26278   pPg->pNextHash = pPg->pPrevHash = 0;
26279 }
26280
26281 /*
26282 ** Unlink a page from the free list (the list of all pages where nRef==0)
26283 ** and from its hash collision chain.
26284 */
26285 static void unlinkPage(PgHdr *pPg){
26286   Pager *pPager = pPg->pPager;
26287
26288   /* Unlink from free page list */
26289   lruListRemove(pPg);
26290
26291   /* Unlink from the pgno hash table */
26292   unlinkHashChain(pPager, pPg);
26293 }
26294
26295 /*
26296 ** This routine is used to truncate the cache when a database
26297 ** is truncated.  Drop from the cache all pages whose pgno is
26298 ** larger than pPager->dbSize and is unreferenced.
26299 **
26300 ** Referenced pages larger than pPager->dbSize are zeroed.
26301 **
26302 ** Actually, at the point this routine is called, it would be
26303 ** an error to have a referenced page.  But rather than delete
26304 ** that page and guarantee a subsequent segfault, it seems better
26305 ** to zero it and hope that we error out sanely.
26306 */
26307 static void pager_truncate_cache(Pager *pPager){
26308   PgHdr *pPg;
26309   PgHdr **ppPg;
26310   int dbSize = pPager->dbSize;
26311
26312   ppPg = &pPager->pAll;
26313   while( (pPg = *ppPg)!=0 ){
26314     if( pPg->pgno<=dbSize ){
26315       ppPg = &pPg->pNextAll;
26316     }else if( pPg->nRef>0 ){
26317       memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
26318       ppPg = &pPg->pNextAll;
26319     }else{
26320       *ppPg = pPg->pNextAll;
26321       IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
26322       PAGER_INCR(sqlite3_pager_pgfree_count);
26323       unlinkPage(pPg);
26324       makeClean(pPg);
26325       sqlite3_free(pPg->pData);
26326       sqlite3_free(pPg);
26327       pPager->nPage--;
26328     }
26329   }
26330 }
26331
26332 /*
26333 ** Try to obtain a lock on a file.  Invoke the busy callback if the lock
26334 ** is currently not available.  Repeat until the busy callback returns
26335 ** false or until the lock succeeds.
26336 **
26337 ** Return SQLITE_OK on success and an error code if we cannot obtain
26338 ** the lock.
26339 */
26340 static int pager_wait_on_lock(Pager *pPager, int locktype){
26341   int rc;
26342
26343   /* The OS lock values must be the same as the Pager lock values */
26344   assert( PAGER_SHARED==SHARED_LOCK );
26345   assert( PAGER_RESERVED==RESERVED_LOCK );
26346   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
26347
26348   /* If the file is currently unlocked then the size must be unknown */
26349   assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
26350
26351   if( pPager->state>=locktype ){
26352     rc = SQLITE_OK;
26353   }else{
26354     if( pPager->pBusyHandler ) pPager->pBusyHandler->nBusy = 0;
26355     do {
26356       rc = sqlite3OsLock(pPager->fd, locktype);
26357     }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
26358     if( rc==SQLITE_OK ){
26359       pPager->state = locktype;
26360       IOTRACE(("LOCK %p %d\n", pPager, locktype))
26361     }
26362   }
26363   return rc;
26364 }
26365
26366 /*
26367 ** Truncate the file to the number of pages specified.
26368 */
26369 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
26370   int rc;
26371   assert( pPager->state>=PAGER_SHARED || MEMDB );
26372   sqlite3PagerPagecount(pPager);
26373   if( pPager->errCode ){
26374     rc = pPager->errCode;
26375     return rc;
26376   }
26377   if( nPage>=(unsigned)pPager->dbSize ){
26378     return SQLITE_OK;
26379   }
26380   if( MEMDB ){
26381     pPager->dbSize = nPage;
26382     pager_truncate_cache(pPager);
26383     return SQLITE_OK;
26384   }
26385   pagerEnter(pPager);
26386   rc = syncJournal(pPager);
26387   pagerLeave(pPager);
26388   if( rc!=SQLITE_OK ){
26389     return rc;
26390   }
26391
26392   /* Get an exclusive lock on the database before truncating. */
26393   pagerEnter(pPager);
26394   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
26395   pagerLeave(pPager);
26396   if( rc!=SQLITE_OK ){
26397     return rc;
26398   }
26399
26400   rc = pager_truncate(pPager, nPage);
26401   return rc;
26402 }
26403
26404 /*
26405 ** Shutdown the page cache.  Free all memory and close all files.
26406 **
26407 ** If a transaction was in progress when this routine is called, that
26408 ** transaction is rolled back.  All outstanding pages are invalidated
26409 ** and their memory is freed.  Any attempt to use a page associated
26410 ** with this page cache after this function returns will likely
26411 ** result in a coredump.
26412 **
26413 ** This function always succeeds. If a transaction is active an attempt
26414 ** is made to roll it back. If an error occurs during the rollback 
26415 ** a hot journal may be left in the filesystem but no error is returned
26416 ** to the caller.
26417 */
26418 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
26419 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26420   if( !MEMDB ){
26421 #ifndef SQLITE_MUTEX_NOOP
26422     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
26423 #endif
26424     sqlite3_mutex_enter(mutex);
26425     if( pPager->pPrev ){
26426       pPager->pPrev->pNext = pPager->pNext;
26427     }else{
26428       sqlite3PagerList = pPager->pNext;
26429     }
26430     if( pPager->pNext ){
26431       pPager->pNext->pPrev = pPager->pPrev;
26432     }
26433     sqlite3_mutex_leave(mutex);
26434   }
26435 #endif
26436
26437   disable_simulated_io_errors();
26438   sqlite3FaultBeginBenign(-1);
26439   pPager->errCode = 0;
26440   pPager->exclusiveMode = 0;
26441   pager_reset(pPager);
26442   pagerUnlockAndRollback(pPager);
26443   enable_simulated_io_errors();
26444   sqlite3FaultEndBenign(-1);
26445   PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
26446   IOTRACE(("CLOSE %p\n", pPager))
26447   if( pPager->journalOpen ){
26448     sqlite3OsClose(pPager->jfd);
26449   }
26450   sqlite3BitvecDestroy(pPager->pInJournal);
26451   if( pPager->stmtOpen ){
26452     sqlite3OsClose(pPager->stfd);
26453   }
26454   sqlite3OsClose(pPager->fd);
26455   /* Temp files are automatically deleted by the OS
26456   ** if( pPager->tempFile ){
26457   **   sqlite3OsDelete(pPager->zFilename);
26458   ** }
26459   */
26460
26461   sqlite3_free(pPager->aHash);
26462   sqlite3_free(pPager->pTmpSpace);
26463   sqlite3_free(pPager);
26464   return SQLITE_OK;
26465 }
26466
26467 #if !defined(NDEBUG) || defined(SQLITE_TEST)
26468 /*
26469 ** Return the page number for the given page data.
26470 */
26471 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
26472   return p->pgno;
26473 }
26474 #endif
26475
26476 /*
26477 ** The page_ref() function increments the reference count for a page.
26478 ** If the page is currently on the freelist (the reference count is zero) then
26479 ** remove it from the freelist.
26480 **
26481 ** For non-test systems, page_ref() is a macro that calls _page_ref()
26482 ** online of the reference count is zero.  For test systems, page_ref()
26483 ** is a real function so that we can set breakpoints and trace it.
26484 */
26485 static void _page_ref(PgHdr *pPg){
26486   if( pPg->nRef==0 ){
26487     /* The page is currently on the freelist.  Remove it. */
26488     lruListRemove(pPg);
26489     pPg->pPager->nRef++;
26490   }
26491   pPg->nRef++;
26492 }
26493 #ifdef SQLITE_DEBUG
26494   static void page_ref(PgHdr *pPg){
26495     if( pPg->nRef==0 ){
26496       _page_ref(pPg);
26497     }else{
26498       pPg->nRef++;
26499     }
26500   }
26501 #else
26502 # define page_ref(P)   ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
26503 #endif
26504
26505 /*
26506 ** Increment the reference count for a page.  The input pointer is
26507 ** a reference to the page data.
26508 */
26509 SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
26510   pagerEnter(pPg->pPager);
26511   page_ref(pPg);
26512   pagerLeave(pPg->pPager);
26513   return SQLITE_OK;
26514 }
26515
26516 /*
26517 ** Sync the journal.  In other words, make sure all the pages that have
26518 ** been written to the journal have actually reached the surface of the
26519 ** disk.  It is not safe to modify the original database file until after
26520 ** the journal has been synced.  If the original database is modified before
26521 ** the journal is synced and a power failure occurs, the unsynced journal
26522 ** data would be lost and we would be unable to completely rollback the
26523 ** database changes.  Database corruption would occur.
26524 ** 
26525 ** This routine also updates the nRec field in the header of the journal.
26526 ** (See comments on the pager_playback() routine for additional information.)
26527 ** If the sync mode is FULL, two syncs will occur.  First the whole journal
26528 ** is synced, then the nRec field is updated, then a second sync occurs.
26529 **
26530 ** For temporary databases, we do not care if we are able to rollback
26531 ** after a power failure, so no sync occurs.
26532 **
26533 ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
26534 ** the database is stored, then OsSync() is never called on the journal
26535 ** file. In this case all that is required is to update the nRec field in
26536 ** the journal header.
26537 **
26538 ** This routine clears the needSync field of every page current held in
26539 ** memory.
26540 */
26541 static int syncJournal(Pager *pPager){
26542   PgHdr *pPg;
26543   int rc = SQLITE_OK;
26544
26545
26546   /* Sync the journal before modifying the main database
26547   ** (assuming there is a journal and it needs to be synced.)
26548   */
26549   if( pPager->needSync ){
26550     if( !pPager->tempFile ){
26551       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
26552       assert( pPager->journalOpen );
26553
26554       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
26555         /* Write the nRec value into the journal file header. If in
26556         ** full-synchronous mode, sync the journal first. This ensures that
26557         ** all data has really hit the disk before nRec is updated to mark
26558         ** it as a candidate for rollback.
26559         **
26560         ** This is not required if the persistent media supports the
26561         ** SAFE_APPEND property. Because in this case it is not possible 
26562         ** for garbage data to be appended to the file, the nRec field
26563         ** is populated with 0xFFFFFFFF when the journal header is written
26564         ** and never needs to be updated.
26565         */
26566         i64 jrnlOff;
26567         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
26568           PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
26569           IOTRACE(("JSYNC %p\n", pPager))
26570           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
26571           if( rc!=0 ) return rc;
26572         }
26573
26574         jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
26575         IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
26576         rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
26577         if( rc ) return rc;
26578       }
26579       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
26580         PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
26581         IOTRACE(("JSYNC %p\n", pPager))
26582         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
26583           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
26584         );
26585         if( rc!=0 ) return rc;
26586       }
26587       pPager->journalStarted = 1;
26588     }
26589     pPager->needSync = 0;
26590
26591     /* Erase the needSync flag from every page.
26592     */
26593     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
26594       pPg->needSync = 0;
26595     }
26596     lruListSetFirstSynced(pPager);
26597   }
26598
26599 #ifndef NDEBUG
26600   /* If the Pager.needSync flag is clear then the PgHdr.needSync
26601   ** flag must also be clear for all pages.  Verify that this
26602   ** invariant is true.
26603   */
26604   else{
26605     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
26606       assert( pPg->needSync==0 );
26607     }
26608     assert( pPager->lru.pFirstSynced==pPager->lru.pFirst );
26609   }
26610 #endif
26611
26612   return rc;
26613 }
26614
26615 /*
26616 ** Merge two lists of pages connected by pDirty and in pgno order.
26617 ** Do not both fixing the pPrevDirty pointers.
26618 */
26619 static PgHdr *merge_pagelist(PgHdr *pA, PgHdr *pB){
26620   PgHdr result, *pTail;
26621   pTail = &result;
26622   while( pA && pB ){
26623     if( pA->pgno<pB->pgno ){
26624       pTail->pDirty = pA;
26625       pTail = pA;
26626       pA = pA->pDirty;
26627     }else{
26628       pTail->pDirty = pB;
26629       pTail = pB;
26630       pB = pB->pDirty;
26631     }
26632   }
26633   if( pA ){
26634     pTail->pDirty = pA;
26635   }else if( pB ){
26636     pTail->pDirty = pB;
26637   }else{
26638     pTail->pDirty = 0;
26639   }
26640   return result.pDirty;
26641 }
26642
26643 /*
26644 ** Sort the list of pages in accending order by pgno.  Pages are
26645 ** connected by pDirty pointers.  The pPrevDirty pointers are
26646 ** corrupted by this sort.
26647 */
26648 #define N_SORT_BUCKET_ALLOC 25
26649 #define N_SORT_BUCKET       25
26650 #ifdef SQLITE_TEST
26651   int sqlite3_pager_n_sort_bucket = 0;
26652   #undef N_SORT_BUCKET
26653   #define N_SORT_BUCKET \
26654    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
26655 #endif
26656 static PgHdr *sort_pagelist(PgHdr *pIn){
26657   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
26658   int i;
26659   memset(a, 0, sizeof(a));
26660   while( pIn ){
26661     p = pIn;
26662     pIn = p->pDirty;
26663     p->pDirty = 0;
26664     for(i=0; i<N_SORT_BUCKET-1; i++){
26665       if( a[i]==0 ){
26666         a[i] = p;
26667         break;
26668       }else{
26669         p = merge_pagelist(a[i], p);
26670         a[i] = 0;
26671       }
26672     }
26673     if( i==N_SORT_BUCKET-1 ){
26674       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET) 
26675       ** elements in the input list. This is possible, but impractical.
26676       ** Testing this line is the point of global variable
26677       ** sqlite3_pager_n_sort_bucket.
26678       */
26679       a[i] = merge_pagelist(a[i], p);
26680     }
26681   }
26682   p = a[0];
26683   for(i=1; i<N_SORT_BUCKET; i++){
26684     p = merge_pagelist(p, a[i]);
26685   }
26686   return p;
26687 }
26688
26689 /*
26690 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
26691 ** every one of those pages out to the database file and mark them all
26692 ** as clean.
26693 */
26694 static int pager_write_pagelist(PgHdr *pList){
26695   Pager *pPager;
26696   PgHdr *p;
26697   int rc;
26698
26699   if( pList==0 ) return SQLITE_OK;
26700   pPager = pList->pPager;
26701
26702   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
26703   ** database file. If there is already an EXCLUSIVE lock, the following
26704   ** calls to sqlite3OsLock() are no-ops.
26705   **
26706   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
26707   ** through an intermediate state PENDING.   A PENDING lock prevents new
26708   ** readers from attaching to the database but is unsufficient for us to
26709   ** write.  The idea of a PENDING lock is to prevent new readers from
26710   ** coming in while we wait for existing readers to clear.
26711   **
26712   ** While the pager is in the RESERVED state, the original database file
26713   ** is unchanged and we can rollback without having to playback the
26714   ** journal into the original database file.  Once we transition to
26715   ** EXCLUSIVE, it means the database file has been changed and any rollback
26716   ** will require a journal playback.
26717   */
26718   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
26719   if( rc!=SQLITE_OK ){
26720     return rc;
26721   }
26722
26723   pList = sort_pagelist(pList);
26724   for(p=pList; p; p=p->pDirty){
26725     assert( p->dirty );
26726     p->dirty = 0;
26727   }
26728   while( pList ){
26729
26730     /* If the file has not yet been opened, open it now. */
26731     if( !pPager->fd->pMethods ){
26732       assert(pPager->tempFile);
26733       rc = sqlite3PagerOpentemp(pPager->pVfs, pPager->fd, pPager->zFilename,
26734                                 pPager->vfsFlags);
26735       if( rc ) return rc;
26736     }
26737
26738     /* If there are dirty pages in the page cache with page numbers greater
26739     ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
26740     ** make the file smaller (presumably by auto-vacuum code). Do not write
26741     ** any such pages to the file.
26742     */
26743     if( pList->pgno<=pPager->dbSize ){
26744       i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
26745       char *pData = CODEC2(pPager, PGHDR_TO_DATA(pList), pList->pgno, 6);
26746       PAGERTRACE4("STORE %d page %d hash(%08x)\n",
26747                    PAGERID(pPager), pList->pgno, pager_pagehash(pList));
26748       IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
26749       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
26750       PAGER_INCR(sqlite3_pager_writedb_count);
26751       PAGER_INCR(pPager->nWrite);
26752       if( pList->pgno==1 ){
26753         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
26754       }
26755     }
26756 #ifndef NDEBUG
26757     else{
26758       PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
26759     }
26760 #endif
26761     if( rc ) return rc;
26762 #ifdef SQLITE_CHECK_PAGES
26763     pList->pageHash = pager_pagehash(pList);
26764 #endif
26765     pList = pList->pDirty;
26766   }
26767   return SQLITE_OK;
26768 }
26769
26770 /*
26771 ** Collect every dirty page into a dirty list and
26772 ** return a pointer to the head of that list.  All pages are
26773 ** collected even if they are still in use.
26774 */
26775 static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
26776
26777 #ifndef NDEBUG
26778   /* Verify the sanity of the dirty list when we are running
26779   ** in debugging mode.  This is expensive, so do not
26780   ** do this on a normal build. */
26781   int n1 = 0;
26782   int n2 = 0;
26783   PgHdr *p;
26784   for(p=pPager->pAll; p; p=p->pNextAll){ if( p->dirty ) n1++; }
26785   for(p=pPager->pDirty; p; p=p->pDirty){ n2++; }
26786   assert( n1==n2 );
26787 #endif
26788
26789   return pPager->pDirty;
26790 }
26791
26792 /*
26793 ** Return 1 if there is a hot journal on the given pager.
26794 ** A hot journal is one that needs to be played back.
26795 **
26796 ** If the current size of the database file is 0 but a journal file
26797 ** exists, that is probably an old journal left over from a prior
26798 ** database with the same name.  Just delete the journal.
26799 **
26800 ** Return negative if unable to determine the status of the journal.
26801 **
26802 ** This routine does not open the journal file to examine its
26803 ** content.  Hence, the journal might contain the name of a master
26804 ** journal file that has been deleted, and hence not be hot.  Or
26805 ** the header of the journal might be zeroed out.  This routine
26806 ** does not discover these cases of a non-hot journal - if the
26807 ** journal file exists and is not empty this routine assumes it
26808 ** is hot.  The pager_playback() routine will discover that the
26809 ** journal file is not really hot and will no-op.
26810 */
26811 static int hasHotJournal(Pager *pPager){
26812   sqlite3_vfs *pVfs = pPager->pVfs;
26813   int rc;
26814   if( !pPager->useJournal ) return 0;
26815   if( !pPager->fd->pMethods ) return 0;
26816   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS);
26817   if( rc<=0 ){
26818     return rc;
26819   }
26820   if( sqlite3OsCheckReservedLock(pPager->fd) ){
26821     return 0;
26822   }
26823   if( sqlite3PagerPagecount(pPager)==0 ){
26824     sqlite3OsDelete(pVfs, pPager->zJournal, 0);
26825     return 0;
26826   }else{
26827     return 1;
26828   }
26829 }
26830
26831 /*
26832 ** Try to find a page in the cache that can be recycled. 
26833 **
26834 ** This routine may return SQLITE_IOERR, SQLITE_FULL or SQLITE_OK. It 
26835 ** does not set the pPager->errCode variable.
26836 */
26837 static int pager_recycle(Pager *pPager, PgHdr **ppPg){
26838   PgHdr *pPg;
26839   *ppPg = 0;
26840
26841   /* It is illegal to call this function unless the pager object
26842   ** pointed to by pPager has at least one free page (page with nRef==0).
26843   */ 
26844   assert(!MEMDB);
26845   assert(pPager->lru.pFirst);
26846
26847   /* Find a page to recycle.  Try to locate a page that does not
26848   ** require us to do an fsync() on the journal.
26849   */
26850   pPg = pPager->lru.pFirstSynced;
26851
26852   /* If we could not find a page that does not require an fsync()
26853   ** on the journal file then fsync the journal file.  This is a
26854   ** very slow operation, so we work hard to avoid it.  But sometimes
26855   ** it can't be helped.
26856   */
26857   if( pPg==0 && pPager->lru.pFirst){
26858     int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
26859     int rc = syncJournal(pPager);
26860     if( rc!=0 ){
26861       return rc;
26862     }
26863     if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
26864       /* If in full-sync mode, write a new journal header into the
26865       ** journal file. This is done to avoid ever modifying a journal
26866       ** header that is involved in the rollback of pages that have
26867       ** already been written to the database (in case the header is
26868       ** trashed when the nRec field is updated).
26869       */
26870       pPager->nRec = 0;
26871       assert( pPager->journalOff > 0 );
26872       assert( pPager->doNotSync==0 );
26873       rc = writeJournalHdr(pPager);
26874       if( rc!=0 ){
26875         return rc;
26876       }
26877     }
26878     pPg = pPager->lru.pFirst;
26879   }
26880
26881   assert( pPg->nRef==0 );
26882
26883   /* Write the page to the database file if it is dirty.
26884   */
26885   if( pPg->dirty ){
26886     int rc;
26887     assert( pPg->needSync==0 );
26888     makeClean(pPg);
26889     pPg->dirty = 1;
26890     pPg->pDirty = 0;
26891     rc = pager_write_pagelist( pPg );
26892     pPg->dirty = 0;
26893     if( rc!=SQLITE_OK ){
26894       return rc;
26895     }
26896   }
26897   assert( pPg->dirty==0 );
26898
26899   /* If the page we are recycling is marked as alwaysRollback, then
26900   ** set the global alwaysRollback flag, thus disabling the
26901   ** sqlite3PagerDontRollback() optimization for the rest of this transaction.
26902   ** It is necessary to do this because the page marked alwaysRollback
26903   ** might be reloaded at a later time but at that point we won't remember
26904   ** that is was marked alwaysRollback.  This means that all pages must
26905   ** be marked as alwaysRollback from here on out.
26906   */
26907   if( pPg->alwaysRollback ){
26908     IOTRACE(("ALWAYS_ROLLBACK %p\n", pPager))
26909     pPager->alwaysRollback = 1;
26910   }
26911
26912   /* Unlink the old page from the free list and the hash table
26913   */
26914   unlinkPage(pPg);
26915   assert( pPg->pgno==0 );
26916
26917   *ppPg = pPg;
26918   return SQLITE_OK;
26919 }
26920
26921 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
26922 /*
26923 ** This function is called to free superfluous dynamically allocated memory
26924 ** held by the pager system. Memory in use by any SQLite pager allocated
26925 ** by the current thread may be sqlite3_free()ed.
26926 **
26927 ** nReq is the number of bytes of memory required. Once this much has
26928 ** been released, the function returns. The return value is the total number 
26929 ** of bytes of memory released.
26930 */
26931 SQLITE_PRIVATE int sqlite3PagerReleaseMemory(int nReq){
26932   int nReleased = 0;          /* Bytes of memory released so far */
26933   Pager *pPager;              /* For looping over pagers */
26934   BusyHandler *savedBusy;     /* Saved copy of the busy handler */
26935   int rc = SQLITE_OK;
26936
26937   /* Acquire the memory-management mutex
26938   */
26939 #ifndef SQLITE_MUTEX_NOOP
26940   sqlite3_mutex *mutex;       /* The MEM2 mutex */
26941   mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2);
26942 #endif
26943   sqlite3_mutex_enter(mutex);
26944
26945   /* Signal all database connections that memory management wants
26946   ** to have access to the pagers.
26947   */
26948   for(pPager=sqlite3PagerList; pPager; pPager=pPager->pNext){
26949      pPager->iInUseMM = 1;
26950   }
26951
26952   while( rc==SQLITE_OK && (nReq<0 || nReleased<nReq) ){
26953     PgHdr *pPg;
26954     PgHdr *pRecycled;
26955  
26956     /* Try to find a page to recycle that does not require a sync(). If
26957     ** this is not possible, find one that does require a sync().
26958     */
26959     sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
26960     pPg = sqlite3LruPageList.pFirstSynced;
26961     while( pPg && (pPg->needSync || pPg->pPager->iInUseDB) ){
26962       pPg = pPg->gfree.pNext;
26963     }
26964     if( !pPg ){
26965       pPg = sqlite3LruPageList.pFirst;
26966       while( pPg && pPg->pPager->iInUseDB ){
26967         pPg = pPg->gfree.pNext;
26968       }
26969     }
26970     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU));
26971
26972     /* If pPg==0, then the block above has failed to find a page to
26973     ** recycle. In this case return early - no further memory will
26974     ** be released.
26975     */
26976     if( !pPg ) break;
26977
26978     pPager = pPg->pPager;
26979     assert(!pPg->needSync || pPg==pPager->lru.pFirst);
26980     assert(pPg->needSync || pPg==pPager->lru.pFirstSynced);
26981   
26982     savedBusy = pPager->pBusyHandler;
26983     pPager->pBusyHandler = 0;
26984     rc = pager_recycle(pPager, &pRecycled);
26985     pPager->pBusyHandler = savedBusy;
26986     assert(pRecycled==pPg || rc!=SQLITE_OK);
26987     if( rc==SQLITE_OK ){
26988       /* We've found a page to free. At this point the page has been 
26989       ** removed from the page hash-table, free-list and synced-list 
26990       ** (pFirstSynced). It is still in the all pages (pAll) list. 
26991       ** Remove it from this list before freeing.
26992       **
26993       ** Todo: Check the Pager.pStmt list to make sure this is Ok. It 
26994       ** probably is though.
26995       */
26996       PgHdr *pTmp;
26997       assert( pPg );
26998       if( pPg==pPager->pAll ){
26999          pPager->pAll = pPg->pNextAll;
27000       }else{
27001         for( pTmp=pPager->pAll; pTmp->pNextAll!=pPg; pTmp=pTmp->pNextAll ){}
27002         pTmp->pNextAll = pPg->pNextAll;
27003       }
27004       nReleased += (
27005           sizeof(*pPg) + pPager->pageSize
27006           + sizeof(u32) + pPager->nExtra
27007           + MEMDB*sizeof(PgHistory) 
27008       );
27009       IOTRACE(("PGFREE %p %d *\n", pPager, pPg->pgno));
27010       PAGER_INCR(sqlite3_pager_pgfree_count);
27011       sqlite3_free(pPg->pData);
27012       sqlite3_free(pPg);
27013       pPager->nPage--;
27014     }else{
27015       /* An error occured whilst writing to the database file or 
27016       ** journal in pager_recycle(). The error is not returned to the 
27017       ** caller of this function. Instead, set the Pager.errCode variable.
27018       ** The error will be returned to the user (or users, in the case 
27019       ** of a shared pager cache) of the pager for which the error occured.
27020       */
27021       assert(
27022           (rc&0xff)==SQLITE_IOERR ||
27023           rc==SQLITE_FULL ||
27024           rc==SQLITE_BUSY
27025       );
27026       assert( pPager->state>=PAGER_RESERVED );
27027       pager_error(pPager, rc);
27028     }
27029   }
27030
27031   /* Clear the memory management flags and release the mutex
27032   */
27033   for(pPager=sqlite3PagerList; pPager; pPager=pPager->pNext){
27034      pPager->iInUseMM = 0;
27035   }
27036   sqlite3_mutex_leave(mutex);
27037
27038   /* Return the number of bytes released
27039   */
27040   return nReleased;
27041 }
27042 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
27043
27044 /*
27045 ** Read the content of page pPg out of the database file.
27046 */
27047 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
27048   int rc;
27049   i64 offset;
27050   assert( MEMDB==0 );
27051   assert(pPager->fd->pMethods||pPager->tempFile);
27052   if( !pPager->fd->pMethods ){
27053     return SQLITE_IOERR_SHORT_READ;
27054   }
27055   offset = (pgno-1)*(i64)pPager->pageSize;
27056   rc = sqlite3OsRead(pPager->fd, PGHDR_TO_DATA(pPg), pPager->pageSize, offset);
27057   PAGER_INCR(sqlite3_pager_readdb_count);
27058   PAGER_INCR(pPager->nRead);
27059   IOTRACE(("PGIN %p %d\n", pPager, pgno));
27060   if( pgno==1 ){
27061     memcpy(&pPager->dbFileVers, &((u8*)PGHDR_TO_DATA(pPg))[24],
27062                                               sizeof(pPager->dbFileVers));
27063   }
27064   CODEC1(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
27065   PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
27066                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
27067   return rc;
27068 }
27069
27070
27071 /*
27072 ** This function is called to obtain the shared lock required before
27073 ** data may be read from the pager cache. If the shared lock has already
27074 ** been obtained, this function is a no-op.
27075 **
27076 ** Immediately after obtaining the shared lock (if required), this function
27077 ** checks for a hot-journal file. If one is found, an emergency rollback
27078 ** is performed immediately.
27079 */
27080 static int pagerSharedLock(Pager *pPager){
27081   int rc = SQLITE_OK;
27082   int isHot = 0;
27083
27084   /* If this database is opened for exclusive access, has no outstanding 
27085   ** page references and is in an error-state, now is the chance to clear
27086   ** the error. Discard the contents of the pager-cache and treat any
27087   ** open journal file as a hot-journal.
27088   */
27089   if( !MEMDB && pPager->exclusiveMode && pPager->nRef==0 && pPager->errCode ){
27090     if( pPager->journalOpen ){
27091       isHot = 1;
27092     }
27093     pPager->errCode = SQLITE_OK;
27094     pager_reset(pPager);
27095   }
27096
27097   /* If the pager is still in an error state, do not proceed. The error 
27098   ** state will be cleared at some point in the future when all page 
27099   ** references are dropped and the cache can be discarded.
27100   */
27101   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
27102     return pPager->errCode;
27103   }
27104
27105   if( pPager->state==PAGER_UNLOCK || isHot ){
27106     sqlite3_vfs *pVfs = pPager->pVfs;
27107     if( !MEMDB ){
27108       assert( pPager->nRef==0 );
27109       if( !pPager->noReadlock ){
27110         rc = pager_wait_on_lock(pPager, SHARED_LOCK);
27111         if( rc!=SQLITE_OK ){
27112           assert( pPager->state==PAGER_UNLOCK );
27113           return pager_error(pPager, rc);
27114         }
27115         assert( pPager->state>=SHARED_LOCK );
27116       }
27117   
27118       /* If a journal file exists, and there is no RESERVED lock on the
27119       ** database file, then it either needs to be played back or deleted.
27120       */
27121       rc = hasHotJournal(pPager);
27122       if( rc<0 ){
27123         rc = SQLITE_IOERR_NOMEM;
27124         goto failed;
27125       }
27126       if( rc==1 || isHot ){
27127         /* Get an EXCLUSIVE lock on the database file. At this point it is
27128         ** important that a RESERVED lock is not obtained on the way to the
27129         ** EXCLUSIVE lock. If it were, another process might open the
27130         ** database file, detect the RESERVED lock, and conclude that the
27131         ** database is safe to read while this process is still rolling it 
27132         ** back.
27133         ** 
27134         ** Because the intermediate RESERVED lock is not requested, the
27135         ** second process will get to this point in the code and fail to
27136         ** obtain its own EXCLUSIVE lock on the database file.
27137         */
27138         if( pPager->state<EXCLUSIVE_LOCK ){
27139           rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
27140           if( rc!=SQLITE_OK ){
27141             rc = pager_error(pPager, rc);
27142             goto failed;
27143           }
27144           pPager->state = PAGER_EXCLUSIVE;
27145         }
27146  
27147         /* Open the journal for read/write access. This is because in 
27148         ** exclusive-access mode the file descriptor will be kept open and
27149         ** possibly used for a transaction later on. On some systems, the
27150         ** OsTruncate() call used in exclusive-access mode also requires
27151         ** a read/write file handle.
27152         */
27153         if( !isHot && pPager->journalOpen==0 ){
27154           int res = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS);
27155           if( res==1 ){
27156             int fout = 0;
27157             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
27158             assert( !pPager->tempFile );
27159             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
27160             assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
27161             if( fout&SQLITE_OPEN_READONLY ){
27162               rc = SQLITE_BUSY;
27163               sqlite3OsClose(pPager->jfd);
27164             }
27165           }else if( res==0 ){
27166             /* If the journal does not exist, that means some other process
27167             ** has already rolled it back */
27168             rc = SQLITE_BUSY;
27169           }else{
27170             /* If sqlite3OsAccess() returns a negative value, that means it
27171             ** failed a memory allocation */
27172             rc = SQLITE_IOERR_NOMEM;
27173           }
27174         }
27175         if( rc!=SQLITE_OK ){
27176           if( rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_UNLOCK 
27177            && rc!=SQLITE_IOERR_NOMEM 
27178           ){
27179             rc = SQLITE_BUSY;
27180           }
27181           goto failed;
27182         }
27183         pPager->journalOpen = 1;
27184         pPager->journalStarted = 0;
27185         pPager->journalOff = 0;
27186         pPager->setMaster = 0;
27187         pPager->journalHdr = 0;
27188  
27189         /* Playback and delete the journal.  Drop the database write
27190         ** lock and reacquire the read lock.
27191         */
27192         rc = pager_playback(pPager, 1);
27193         if( rc!=SQLITE_OK ){
27194           rc = pager_error(pPager, rc);
27195           goto failed;
27196         }
27197         assert(pPager->state==PAGER_SHARED || 
27198             (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
27199         );
27200       }
27201
27202       if( pPager->pAll ){
27203         /* The shared-lock has just been acquired on the database file
27204         ** and there are already pages in the cache (from a previous
27205         ** read or write transaction).  Check to see if the database
27206         ** has been modified.  If the database has changed, flush the
27207         ** cache.
27208         **
27209         ** Database changes is detected by looking at 15 bytes beginning
27210         ** at offset 24 into the file.  The first 4 of these 16 bytes are
27211         ** a 32-bit counter that is incremented with each change.  The
27212         ** other bytes change randomly with each file change when
27213         ** a codec is in use.
27214         ** 
27215         ** There is a vanishingly small chance that a change will not be 
27216         ** detected.  The chance of an undetected change is so small that
27217         ** it can be neglected.
27218         */
27219         char dbFileVers[sizeof(pPager->dbFileVers)];
27220         sqlite3PagerPagecount(pPager);
27221
27222         if( pPager->errCode ){
27223           rc = pPager->errCode;
27224           goto failed;
27225         }
27226
27227         if( pPager->dbSize>0 ){
27228           IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
27229           rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
27230           if( rc!=SQLITE_OK ){
27231             goto failed;
27232           }
27233         }else{
27234           memset(dbFileVers, 0, sizeof(dbFileVers));
27235         }
27236
27237         if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
27238           pager_reset(pPager);
27239         }
27240       }
27241     }
27242     assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
27243     if( pPager->state==PAGER_UNLOCK ){
27244       pPager->state = PAGER_SHARED;
27245     }
27246   }
27247
27248  failed:
27249   if( rc!=SQLITE_OK ){
27250     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
27251     pager_unlock(pPager);
27252   }
27253   return rc;
27254 }
27255
27256 /*
27257 ** Allocate a PgHdr object.   Either create a new one or reuse
27258 ** an existing one that is not otherwise in use.
27259 **
27260 ** A new PgHdr structure is created if any of the following are
27261 ** true:
27262 **
27263 **     (1)  We have not exceeded our maximum allocated cache size
27264 **          as set by the "PRAGMA cache_size" command.
27265 **
27266 **     (2)  There are no unused PgHdr objects available at this time.
27267 **
27268 **     (3)  This is an in-memory database.
27269 **
27270 **     (4)  There are no PgHdr objects that do not require a journal
27271 **          file sync and a sync of the journal file is currently
27272 **          prohibited.
27273 **
27274 ** Otherwise, reuse an existing PgHdr.  In other words, reuse an
27275 ** existing PgHdr if all of the following are true:
27276 **
27277 **     (1)  We have reached or exceeded the maximum cache size
27278 **          allowed by "PRAGMA cache_size".
27279 **
27280 **     (2)  There is a PgHdr available with PgHdr->nRef==0
27281 **
27282 **     (3)  We are not in an in-memory database
27283 **
27284 **     (4)  Either there is an available PgHdr that does not need
27285 **          to be synced to disk or else disk syncing is currently
27286 **          allowed.
27287 */
27288 static int pagerAllocatePage(Pager *pPager, PgHdr **ppPg){
27289   int rc = SQLITE_OK;
27290   PgHdr *pPg;
27291   int nByteHdr;
27292
27293   /* Create a new PgHdr if any of the four conditions defined 
27294   ** above are met: */
27295   if( pPager->nPage<pPager->mxPage
27296    || pPager->lru.pFirst==0 
27297    || MEMDB
27298    || (pPager->lru.pFirstSynced==0 && pPager->doNotSync)
27299   ){
27300     void *pData;
27301     if( pPager->nPage>=pPager->nHash ){
27302       pager_resize_hash_table(pPager,
27303          pPager->nHash<256 ? 256 : pPager->nHash*2);
27304       if( pPager->nHash==0 ){
27305         rc = SQLITE_NOMEM;
27306         goto pager_allocate_out;
27307       }
27308     }
27309     pagerLeave(pPager);
27310     nByteHdr = sizeof(*pPg) + sizeof(u32) + pPager->nExtra
27311               + MEMDB*sizeof(PgHistory);
27312     pPg = sqlite3_malloc( nByteHdr );
27313     if( pPg ){
27314       pData = sqlite3_malloc( pPager->pageSize );
27315       if( pData==0 ){
27316         sqlite3_free(pPg);
27317         pPg = 0;
27318       }
27319     }
27320     pagerEnter(pPager);
27321     if( pPg==0 ){
27322       rc = SQLITE_NOMEM;
27323       goto pager_allocate_out;
27324     }
27325     memset(pPg, 0, nByteHdr);
27326     pPg->pData = pData;
27327     pPg->pPager = pPager;
27328     pPg->pNextAll = pPager->pAll;
27329     pPager->pAll = pPg;
27330     pPager->nPage++;
27331   }else{
27332     /* Recycle an existing page with a zero ref-count. */
27333     rc = pager_recycle(pPager, &pPg);
27334     if( rc==SQLITE_BUSY ){
27335       rc = SQLITE_IOERR_BLOCKED;
27336     }
27337     if( rc!=SQLITE_OK ){
27338       goto pager_allocate_out;
27339     }
27340     assert( pPager->state>=SHARED_LOCK );
27341     assert(pPg);
27342   }
27343   *ppPg = pPg;
27344
27345 pager_allocate_out:
27346   return rc;
27347 }
27348
27349 /*
27350 ** Make sure we have the content for a page.  If the page was
27351 ** previously acquired with noContent==1, then the content was
27352 ** just initialized to zeros instead of being read from disk.
27353 ** But now we need the real data off of disk.  So make sure we
27354 ** have it.  Read it in if we do not have it already.
27355 */
27356 static int pager_get_content(PgHdr *pPg){
27357   if( pPg->needRead ){
27358     int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
27359     if( rc==SQLITE_OK ){
27360       pPg->needRead = 0;
27361     }else{
27362       return rc;
27363     }
27364   }
27365   return SQLITE_OK;
27366 }
27367
27368 /*
27369 ** Acquire a page.
27370 **
27371 ** A read lock on the disk file is obtained when the first page is acquired. 
27372 ** This read lock is dropped when the last page is released.
27373 **
27374 ** This routine works for any page number greater than 0.  If the database
27375 ** file is smaller than the requested page, then no actual disk
27376 ** read occurs and the memory image of the page is initialized to
27377 ** all zeros.  The extra data appended to a page is always initialized
27378 ** to zeros the first time a page is loaded into memory.
27379 **
27380 ** The acquisition might fail for several reasons.  In all cases,
27381 ** an appropriate error code is returned and *ppPage is set to NULL.
27382 **
27383 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
27384 ** to find a page in the in-memory cache first.  If the page is not already
27385 ** in memory, this routine goes to disk to read it in whereas Lookup()
27386 ** just returns 0.  This routine acquires a read-lock the first time it
27387 ** has to go to disk, and could also playback an old journal if necessary.
27388 ** Since Lookup() never goes to disk, it never has to deal with locks
27389 ** or journal files.
27390 **
27391 ** If noContent is false, the page contents are actually read from disk.
27392 ** If noContent is true, it means that we do not care about the contents
27393 ** of the page at this time, so do not do a disk read.  Just fill in the
27394 ** page content with zeros.  But mark the fact that we have not read the
27395 ** content by setting the PgHdr.needRead flag.  Later on, if 
27396 ** sqlite3PagerWrite() is called on this page or if this routine is
27397 ** called again with noContent==0, that means that the content is needed
27398 ** and the disk read should occur at that point.
27399 */
27400 static int pagerAcquire(
27401   Pager *pPager,      /* The pager open on the database file */
27402   Pgno pgno,          /* Page number to fetch */
27403   DbPage **ppPage,    /* Write a pointer to the page here */
27404   int noContent       /* Do not bother reading content from disk if true */
27405 ){
27406   PgHdr *pPg;
27407   int rc;
27408
27409   assert( pPager->state==PAGER_UNLOCK || pPager->nRef>0 || pgno==1 );
27410
27411   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
27412   ** number greater than this, or zero, is requested.
27413   */
27414   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
27415     return SQLITE_CORRUPT_BKPT;
27416   }
27417
27418   /* Make sure we have not hit any critical errors.
27419   */ 
27420   assert( pPager!=0 );
27421   *ppPage = 0;
27422
27423   /* If this is the first page accessed, then get a SHARED lock
27424   ** on the database file. pagerSharedLock() is a no-op if 
27425   ** a database lock is already held.
27426   */
27427   rc = pagerSharedLock(pPager);
27428   if( rc!=SQLITE_OK ){
27429     return rc;
27430   }
27431   assert( pPager->state!=PAGER_UNLOCK );
27432
27433   pPg = pager_lookup(pPager, pgno);
27434   if( pPg==0 ){
27435     /* The requested page is not in the page cache. */
27436     int nMax;
27437     int h;
27438     PAGER_INCR(pPager->nMiss);
27439     rc = pagerAllocatePage(pPager, &pPg);
27440     if( rc!=SQLITE_OK ){
27441       return rc;
27442     }
27443
27444     pPg->pgno = pgno;
27445     assert( !MEMDB || pgno>pPager->stmtSize );
27446     pPg->inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno);
27447     pPg->needSync = 0;
27448
27449     makeClean(pPg);
27450     pPg->nRef = 1;
27451
27452     pPager->nRef++;
27453     if( pPager->nExtra>0 ){
27454       memset(PGHDR_TO_EXTRA(pPg, pPager), 0, pPager->nExtra);
27455     }
27456     nMax = sqlite3PagerPagecount(pPager);
27457     if( pPager->errCode ){
27458       rc = pPager->errCode;
27459       sqlite3PagerUnref(pPg);
27460       return rc;
27461     }
27462
27463     /* Populate the page with data, either by reading from the database
27464     ** file, or by setting the entire page to zero.
27465     */
27466     if( nMax<(int)pgno || MEMDB || (noContent && !pPager->alwaysRollback) ){
27467       if( pgno>pPager->mxPgno ){
27468         sqlite3PagerUnref(pPg);
27469         return SQLITE_FULL;
27470       }
27471       memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
27472       pPg->needRead = noContent && !pPager->alwaysRollback;
27473       IOTRACE(("ZERO %p %d\n", pPager, pgno));
27474     }else{
27475       rc = readDbPage(pPager, pPg, pgno);
27476       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
27477         pPg->pgno = 0;
27478         sqlite3PagerUnref(pPg);
27479         return rc;
27480       }
27481       pPg->needRead = 0;
27482     }
27483
27484     /* Link the page into the page hash table */
27485     h = pgno & (pPager->nHash-1);
27486     assert( pgno!=0 );
27487     pPg->pNextHash = pPager->aHash[h];
27488     pPager->aHash[h] = pPg;
27489     if( pPg->pNextHash ){
27490       assert( pPg->pNextHash->pPrevHash==0 );
27491       pPg->pNextHash->pPrevHash = pPg;
27492     }
27493
27494 #ifdef SQLITE_CHECK_PAGES
27495     pPg->pageHash = pager_pagehash(pPg);
27496 #endif
27497   }else{
27498     /* The requested page is in the page cache. */
27499     assert(pPager->nRef>0 || pgno==1);
27500     PAGER_INCR(pPager->nHit);
27501     if( !noContent ){
27502       rc = pager_get_content(pPg);
27503       if( rc ){
27504         return rc;
27505       }
27506     }
27507     page_ref(pPg);
27508   }
27509   *ppPage = pPg;
27510   return SQLITE_OK;
27511 }
27512 SQLITE_PRIVATE int sqlite3PagerAcquire(
27513   Pager *pPager,      /* The pager open on the database file */
27514   Pgno pgno,          /* Page number to fetch */
27515   DbPage **ppPage,    /* Write a pointer to the page here */
27516   int noContent       /* Do not bother reading content from disk if true */
27517 ){
27518   int rc;
27519   pagerEnter(pPager);
27520   rc = pagerAcquire(pPager, pgno, ppPage, noContent);
27521   pagerLeave(pPager);
27522   return rc;
27523 }
27524
27525
27526 /*
27527 ** Acquire a page if it is already in the in-memory cache.  Do
27528 ** not read the page from disk.  Return a pointer to the page,
27529 ** or 0 if the page is not in cache.
27530 **
27531 ** See also sqlite3PagerGet().  The difference between this routine
27532 ** and sqlite3PagerGet() is that _get() will go to the disk and read
27533 ** in the page if the page is not already in cache.  This routine
27534 ** returns NULL if the page is not in cache or if a disk I/O error 
27535 ** has ever happened.
27536 */
27537 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
27538   PgHdr *pPg = 0;
27539
27540   assert( pPager!=0 );
27541   assert( pgno!=0 );
27542
27543   pagerEnter(pPager);
27544   if( pPager->state==PAGER_UNLOCK ){
27545     assert( !pPager->pAll || pPager->exclusiveMode );
27546   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
27547     /* Do nothing */
27548   }else if( (pPg = pager_lookup(pPager, pgno))!=0 ){
27549     page_ref(pPg);
27550   }
27551   pagerLeave(pPager);
27552   return pPg;
27553 }
27554
27555 /*
27556 ** Release a page.
27557 **
27558 ** If the number of references to the page drop to zero, then the
27559 ** page is added to the LRU list.  When all references to all pages
27560 ** are released, a rollback occurs and the lock on the database is
27561 ** removed.
27562 */
27563 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
27564   Pager *pPager;
27565
27566   if( pPg==0 ) return SQLITE_OK;
27567   pPager = pPg->pPager;
27568
27569   /* Decrement the reference count for this page
27570   */
27571   assert( pPg->nRef>0 );
27572   pagerEnter(pPg->pPager);
27573   pPg->nRef--;
27574
27575   CHECK_PAGE(pPg);
27576
27577   /* When the number of references to a page reach 0, call the
27578   ** destructor and add the page to the freelist.
27579   */
27580   if( pPg->nRef==0 ){
27581
27582     lruListAdd(pPg);
27583     if( pPager->xDestructor ){
27584       pPager->xDestructor(pPg, pPager->pageSize);
27585     }
27586   
27587     /* When all pages reach the freelist, drop the read lock from
27588     ** the database file.
27589     */
27590     pPager->nRef--;
27591     assert( pPager->nRef>=0 );
27592     if( pPager->nRef==0 && (!pPager->exclusiveMode || pPager->journalOff>0) ){
27593       pagerUnlockAndRollback(pPager);
27594     }
27595   }
27596   pagerLeave(pPager);
27597   return SQLITE_OK;
27598 }
27599
27600 /*
27601 ** Create a journal file for pPager.  There should already be a RESERVED
27602 ** or EXCLUSIVE lock on the database file when this routine is called.
27603 **
27604 ** Return SQLITE_OK if everything.  Return an error code and release the
27605 ** write lock if anything goes wrong.
27606 */
27607 static int pager_open_journal(Pager *pPager){
27608   sqlite3_vfs *pVfs = pPager->pVfs;
27609   int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
27610
27611   int rc;
27612   assert( !MEMDB );
27613   assert( pPager->state>=PAGER_RESERVED );
27614   assert( pPager->useJournal );
27615   assert( pPager->pInJournal==0 );
27616   sqlite3PagerPagecount(pPager);
27617   pagerLeave(pPager);
27618   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
27619   pagerEnter(pPager);
27620   if( pPager->pInJournal==0 ){
27621     rc = SQLITE_NOMEM;
27622     goto failed_to_open_journal;
27623   }
27624
27625   if( pPager->journalOpen==0 ){
27626     if( pPager->tempFile ){
27627       flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
27628     }else{
27629       flags |= (SQLITE_OPEN_MAIN_JOURNAL);
27630     }
27631 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
27632     rc = sqlite3JournalOpen(
27633         pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
27634     );
27635 #else
27636     rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
27637 #endif
27638     assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
27639     pPager->journalOff = 0;
27640     pPager->setMaster = 0;
27641     pPager->journalHdr = 0;
27642     if( rc!=SQLITE_OK ){
27643       if( rc==SQLITE_NOMEM ){
27644         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
27645       }
27646       goto failed_to_open_journal;
27647     }
27648   }
27649   pPager->journalOpen = 1;
27650   pPager->journalStarted = 0;
27651   pPager->needSync = 0;
27652   pPager->alwaysRollback = 0;
27653   pPager->nRec = 0;
27654   if( pPager->errCode ){
27655     rc = pPager->errCode;
27656     goto failed_to_open_journal;
27657   }
27658   pPager->origDbSize = pPager->dbSize;
27659
27660   rc = writeJournalHdr(pPager);
27661
27662   if( pPager->stmtAutoopen && rc==SQLITE_OK ){
27663     rc = sqlite3PagerStmtBegin(pPager);
27664   }
27665   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
27666     rc = pager_end_transaction(pPager, 0);
27667     if( rc==SQLITE_OK ){
27668       rc = SQLITE_FULL;
27669     }
27670   }
27671   return rc;
27672
27673 failed_to_open_journal:
27674   sqlite3BitvecDestroy(pPager->pInJournal);
27675   pPager->pInJournal = 0;
27676   return rc;
27677 }
27678
27679 /*
27680 ** Acquire a write-lock on the database.  The lock is removed when
27681 ** the any of the following happen:
27682 **
27683 **   *  sqlite3PagerCommitPhaseTwo() is called.
27684 **   *  sqlite3PagerRollback() is called.
27685 **   *  sqlite3PagerClose() is called.
27686 **   *  sqlite3PagerUnref() is called to on every outstanding page.
27687 **
27688 ** The first parameter to this routine is a pointer to any open page of the
27689 ** database file.  Nothing changes about the page - it is used merely to
27690 ** acquire a pointer to the Pager structure and as proof that there is
27691 ** already a read-lock on the database.
27692 **
27693 ** The second parameter indicates how much space in bytes to reserve for a
27694 ** master journal file-name at the start of the journal when it is created.
27695 **
27696 ** A journal file is opened if this is not a temporary file.  For temporary
27697 ** files, the opening of the journal file is deferred until there is an
27698 ** actual need to write to the journal.
27699 **
27700 ** If the database is already reserved for writing, this routine is a no-op.
27701 **
27702 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
27703 ** immediately instead of waiting until we try to flush the cache.  The
27704 ** exFlag is ignored if a transaction is already active.
27705 */
27706 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
27707   Pager *pPager = pPg->pPager;
27708   int rc = SQLITE_OK;
27709   pagerEnter(pPager);
27710   assert( pPg->nRef>0 );
27711   assert( pPager->state!=PAGER_UNLOCK );
27712   if( pPager->state==PAGER_SHARED ){
27713     assert( pPager->pInJournal==0 );
27714     if( MEMDB ){
27715       pPager->state = PAGER_EXCLUSIVE;
27716       pPager->origDbSize = pPager->dbSize;
27717     }else{
27718       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
27719       if( rc==SQLITE_OK ){
27720         pPager->state = PAGER_RESERVED;
27721         if( exFlag ){
27722           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
27723         }
27724       }
27725       if( rc!=SQLITE_OK ){
27726         pagerLeave(pPager);
27727         return rc;
27728       }
27729       pPager->dirtyCache = 0;
27730       PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
27731       if( pPager->useJournal && !pPager->tempFile
27732              && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
27733         rc = pager_open_journal(pPager);
27734       }
27735     }
27736   }else if( pPager->journalOpen && pPager->journalOff==0 ){
27737     /* This happens when the pager was in exclusive-access mode the last
27738     ** time a (read or write) transaction was successfully concluded
27739     ** by this connection. Instead of deleting the journal file it was 
27740     ** kept open and either was truncated to 0 bytes or its header was
27741     ** overwritten with zeros.
27742     */
27743     assert( pPager->nRec==0 );
27744     assert( pPager->origDbSize==0 );
27745     assert( pPager->pInJournal==0 );
27746     sqlite3PagerPagecount(pPager);
27747     pagerLeave(pPager);
27748     pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
27749     pagerEnter(pPager);
27750     if( !pPager->pInJournal ){
27751       rc = SQLITE_NOMEM;
27752     }else{
27753       pPager->origDbSize = pPager->dbSize;
27754       rc = writeJournalHdr(pPager);
27755     }
27756   }
27757   assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
27758   pagerLeave(pPager);
27759   return rc;
27760 }
27761
27762 /*
27763 ** Make a page dirty.  Set its dirty flag and add it to the dirty
27764 ** page list.
27765 */
27766 static void makeDirty(PgHdr *pPg){
27767   if( pPg->dirty==0 ){
27768     Pager *pPager = pPg->pPager;
27769     pPg->dirty = 1;
27770     pPg->pDirty = pPager->pDirty;
27771     if( pPager->pDirty ){
27772       pPager->pDirty->pPrevDirty = pPg;
27773     }
27774     pPg->pPrevDirty = 0;
27775     pPager->pDirty = pPg;
27776   }
27777 }
27778
27779 /*
27780 ** Make a page clean.  Clear its dirty bit and remove it from the
27781 ** dirty page list.
27782 */
27783 static void makeClean(PgHdr *pPg){
27784   if( pPg->dirty ){
27785     pPg->dirty = 0;
27786     if( pPg->pDirty ){
27787       assert( pPg->pDirty->pPrevDirty==pPg );
27788       pPg->pDirty->pPrevDirty = pPg->pPrevDirty;
27789     }
27790     if( pPg->pPrevDirty ){
27791       assert( pPg->pPrevDirty->pDirty==pPg );
27792       pPg->pPrevDirty->pDirty = pPg->pDirty;
27793     }else{
27794       assert( pPg->pPager->pDirty==pPg );
27795       pPg->pPager->pDirty = pPg->pDirty;
27796     }
27797   }
27798 }
27799
27800
27801 /*
27802 ** Mark a data page as writeable.  The page is written into the journal 
27803 ** if it is not there already.  This routine must be called before making
27804 ** changes to a page.
27805 **
27806 ** The first time this routine is called, the pager creates a new
27807 ** journal and acquires a RESERVED lock on the database.  If the RESERVED
27808 ** lock could not be acquired, this routine returns SQLITE_BUSY.  The
27809 ** calling routine must check for that return value and be careful not to
27810 ** change any page data until this routine returns SQLITE_OK.
27811 **
27812 ** If the journal file could not be written because the disk is full,
27813 ** then this routine returns SQLITE_FULL and does an immediate rollback.
27814 ** All subsequent write attempts also return SQLITE_FULL until there
27815 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
27816 ** reset.
27817 */
27818 static int pager_write(PgHdr *pPg){
27819   void *pData = PGHDR_TO_DATA(pPg);
27820   Pager *pPager = pPg->pPager;
27821   int rc = SQLITE_OK;
27822
27823   /* Check for errors
27824   */
27825   if( pPager->errCode ){ 
27826     return pPager->errCode;
27827   }
27828   if( pPager->readOnly ){
27829     return SQLITE_PERM;
27830   }
27831
27832   assert( !pPager->setMaster );
27833
27834   CHECK_PAGE(pPg);
27835
27836   /* If this page was previously acquired with noContent==1, that means
27837   ** we didn't really read in the content of the page.  This can happen
27838   ** (for example) when the page is being moved to the freelist.  But
27839   ** now we are (perhaps) moving the page off of the freelist for
27840   ** reuse and we need to know its original content so that content
27841   ** can be stored in the rollback journal.  So do the read at this
27842   ** time.
27843   */
27844   rc = pager_get_content(pPg);
27845   if( rc ){
27846     return rc;
27847   }
27848
27849   /* Mark the page as dirty.  If the page has already been written
27850   ** to the journal then we can return right away.
27851   */
27852   makeDirty(pPg);
27853   if( pPg->inJournal && (pageInStatement(pPg) || pPager->stmtInUse==0) ){
27854     pPager->dirtyCache = 1;
27855     pPager->dbModified = 1;
27856   }else{
27857
27858     /* If we get this far, it means that the page needs to be
27859     ** written to the transaction journal or the ckeckpoint journal
27860     ** or both.
27861     **
27862     ** First check to see that the transaction journal exists and
27863     ** create it if it does not.
27864     */
27865     assert( pPager->state!=PAGER_UNLOCK );
27866     rc = sqlite3PagerBegin(pPg, 0);
27867     if( rc!=SQLITE_OK ){
27868       return rc;
27869     }
27870     assert( pPager->state>=PAGER_RESERVED );
27871     if( !pPager->journalOpen && pPager->useJournal
27872           && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
27873       rc = pager_open_journal(pPager);
27874       if( rc!=SQLITE_OK ) return rc;
27875     }
27876     pPager->dirtyCache = 1;
27877     pPager->dbModified = 1;
27878   
27879     /* The transaction journal now exists and we have a RESERVED or an
27880     ** EXCLUSIVE lock on the main database file.  Write the current page to
27881     ** the transaction journal if it is not there already.
27882     */
27883     if( !pPg->inJournal && (pPager->journalOpen || MEMDB) ){
27884       if( (int)pPg->pgno <= pPager->origDbSize ){
27885         if( MEMDB ){
27886           PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
27887           PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
27888           assert( pHist->pOrig==0 );
27889           pHist->pOrig = sqlite3_malloc( pPager->pageSize );
27890           if( !pHist->pOrig ){
27891             return SQLITE_NOMEM;
27892           }
27893           memcpy(pHist->pOrig, PGHDR_TO_DATA(pPg), pPager->pageSize);
27894         }else{
27895           u32 cksum;
27896           char *pData2;
27897
27898           /* We should never write to the journal file the page that
27899           ** contains the database locks.  The following assert verifies
27900           ** that we do not. */
27901           assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
27902           pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
27903           cksum = pager_cksum(pPager, (u8*)pData2);
27904           rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
27905           if( rc==SQLITE_OK ){
27906             rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
27907                                 pPager->journalOff + 4);
27908             pPager->journalOff += pPager->pageSize+4;
27909           }
27910           if( rc==SQLITE_OK ){
27911             rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
27912             pPager->journalOff += 4;
27913           }
27914           IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
27915                    pPager->journalOff, pPager->pageSize));
27916           PAGER_INCR(sqlite3_pager_writej_count);
27917           PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
27918                PAGERID(pPager), pPg->pgno, pPg->needSync, pager_pagehash(pPg));
27919
27920           /* An error has occured writing to the journal file. The 
27921           ** transaction will be rolled back by the layer above.
27922           */
27923           if( rc!=SQLITE_OK ){
27924             return rc;
27925           }
27926
27927           pPager->nRec++;
27928           assert( pPager->pInJournal!=0 );
27929           sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
27930           pPg->needSync = !pPager->noSync;
27931           if( pPager->stmtInUse ){
27932             sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
27933           }
27934         }
27935       }else{
27936         pPg->needSync = !pPager->journalStarted && !pPager->noSync;
27937         PAGERTRACE4("APPEND %d page %d needSync=%d\n",
27938                 PAGERID(pPager), pPg->pgno, pPg->needSync);
27939       }
27940       if( pPg->needSync ){
27941         pPager->needSync = 1;
27942       }
27943       pPg->inJournal = 1;
27944     }
27945   
27946     /* If the statement journal is open and the page is not in it,
27947     ** then write the current page to the statement journal.  Note that
27948     ** the statement journal format differs from the standard journal format
27949     ** in that it omits the checksums and the header.
27950     */
27951     if( pPager->stmtInUse 
27952      && !pageInStatement(pPg) 
27953      && (int)pPg->pgno<=pPager->stmtSize 
27954     ){
27955       assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
27956       if( MEMDB ){
27957         PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
27958         assert( pHist->pStmt==0 );
27959         pHist->pStmt = sqlite3_malloc( pPager->pageSize );
27960         if( pHist->pStmt ){
27961           memcpy(pHist->pStmt, PGHDR_TO_DATA(pPg), pPager->pageSize);
27962         }
27963         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
27964         page_add_to_stmt_list(pPg);
27965       }else{
27966         i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
27967         char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
27968         rc = write32bits(pPager->stfd, offset, pPg->pgno);
27969         if( rc==SQLITE_OK ){
27970           rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize, offset+4);
27971         }
27972         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
27973         if( rc!=SQLITE_OK ){
27974           return rc;
27975         }
27976         pPager->stmtNRec++;
27977         assert( pPager->pInStmt!=0 );
27978         sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
27979       }
27980     }
27981   }
27982
27983   /* Update the database size and return.
27984   */
27985   assert( pPager->state>=PAGER_SHARED );
27986   if( pPager->dbSize<(int)pPg->pgno ){
27987     pPager->dbSize = pPg->pgno;
27988     if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
27989       pPager->dbSize++;
27990     }
27991   }
27992   return rc;
27993 }
27994
27995 /*
27996 ** This function is used to mark a data-page as writable. It uses 
27997 ** pager_write() to open a journal file (if it is not already open)
27998 ** and write the page *pData to the journal.
27999 **
28000 ** The difference between this function and pager_write() is that this
28001 ** function also deals with the special case where 2 or more pages
28002 ** fit on a single disk sector. In this case all co-resident pages
28003 ** must have been written to the journal file before returning.
28004 */
28005 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
28006   int rc = SQLITE_OK;
28007
28008   PgHdr *pPg = pDbPage;
28009   Pager *pPager = pPg->pPager;
28010   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
28011
28012   pagerEnter(pPager);
28013   if( !MEMDB && nPagePerSector>1 ){
28014     Pgno nPageCount;          /* Total number of pages in database file */
28015     Pgno pg1;                 /* First page of the sector pPg is located on. */
28016     int nPage;                /* Number of pages starting at pg1 to journal */
28017     int ii;
28018     int needSync = 0;
28019
28020     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
28021     ** header to be written between the pages journaled by this function.
28022     */
28023     assert( pPager->doNotSync==0 );
28024     pPager->doNotSync = 1;
28025
28026     /* This trick assumes that both the page-size and sector-size are
28027     ** an integer power of 2. It sets variable pg1 to the identifier
28028     ** of the first page of the sector pPg is located on.
28029     */
28030     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
28031
28032     nPageCount = sqlite3PagerPagecount(pPager);
28033     if( pPg->pgno>nPageCount ){
28034       nPage = (pPg->pgno - pg1)+1;
28035     }else if( (pg1+nPagePerSector-1)>nPageCount ){
28036       nPage = nPageCount+1-pg1;
28037     }else{
28038       nPage = nPagePerSector;
28039     }
28040     assert(nPage>0);
28041     assert(pg1<=pPg->pgno);
28042     assert((pg1+nPage)>pPg->pgno);
28043
28044     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
28045       Pgno pg = pg1+ii;
28046       PgHdr *pPage;
28047       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
28048         if( pg!=PAGER_MJ_PGNO(pPager) ){
28049           rc = sqlite3PagerGet(pPager, pg, &pPage);
28050           if( rc==SQLITE_OK ){
28051             rc = pager_write(pPage);
28052             if( pPage->needSync ){
28053               needSync = 1;
28054             }
28055             sqlite3PagerUnref(pPage);
28056           }
28057         }
28058       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
28059         if( pPage->needSync ){
28060           needSync = 1;
28061         }
28062       }
28063     }
28064
28065     /* If the PgHdr.needSync flag is set for any of the nPage pages 
28066     ** starting at pg1, then it needs to be set for all of them. Because
28067     ** writing to any of these nPage pages may damage the others, the
28068     ** journal file must contain sync()ed copies of all of them
28069     ** before any of them can be written out to the database file.
28070     */
28071     if( needSync ){
28072       for(ii=0; ii<nPage && needSync; ii++){
28073         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
28074         if( pPage ) pPage->needSync = 1;
28075       }
28076       assert(pPager->needSync);
28077     }
28078
28079     assert( pPager->doNotSync==1 );
28080     pPager->doNotSync = 0;
28081   }else{
28082     rc = pager_write(pDbPage);
28083   }
28084   pagerLeave(pPager);
28085   return rc;
28086 }
28087
28088 /*
28089 ** Return TRUE if the page given in the argument was previously passed
28090 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
28091 ** to change the content of the page.
28092 */
28093 #ifndef NDEBUG
28094 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
28095   return pPg->dirty;
28096 }
28097 #endif
28098
28099 /*
28100 ** A call to this routine tells the pager that it is not necessary to
28101 ** write the information on page pPg back to the disk, even though
28102 ** that page might be marked as dirty.
28103 **
28104 ** The overlying software layer calls this routine when all of the data
28105 ** on the given page is unused.  The pager marks the page as clean so
28106 ** that it does not get written to disk.
28107 **
28108 ** Tests show that this optimization, together with the
28109 ** sqlite3PagerDontRollback() below, more than double the speed
28110 ** of large INSERT operations and quadruple the speed of large DELETEs.
28111 **
28112 ** When this routine is called, set the alwaysRollback flag to true.
28113 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
28114 ** will thereafter be ignored.  This is necessary to avoid a problem
28115 ** where a page with data is added to the freelist during one part of
28116 ** a transaction then removed from the freelist during a later part
28117 ** of the same transaction and reused for some other purpose.  When it
28118 ** is first added to the freelist, this routine is called.  When reused,
28119 ** the sqlite3PagerDontRollback() routine is called.  But because the
28120 ** page contains critical data, we still need to be sure it gets
28121 ** rolled back in spite of the sqlite3PagerDontRollback() call.
28122 */
28123 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage *pDbPage){
28124   PgHdr *pPg = pDbPage;
28125   Pager *pPager = pPg->pPager;
28126
28127   if( MEMDB ) return;
28128   pagerEnter(pPager);
28129   pPg->alwaysRollback = 1;
28130   if( pPg->dirty && !pPager->stmtInUse ){
28131     assert( pPager->state>=PAGER_SHARED );
28132     if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
28133       /* If this pages is the last page in the file and the file has grown
28134       ** during the current transaction, then do NOT mark the page as clean.
28135       ** When the database file grows, we must make sure that the last page
28136       ** gets written at least once so that the disk file will be the correct
28137       ** size. If you do not write this page and the size of the file
28138       ** on the disk ends up being too small, that can lead to database
28139       ** corruption during the next transaction.
28140       */
28141     }else{
28142       PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
28143       IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
28144       makeClean(pPg);
28145 #ifdef SQLITE_CHECK_PAGES
28146       pPg->pageHash = pager_pagehash(pPg);
28147 #endif
28148     }
28149   }
28150   pagerLeave(pPager);
28151 }
28152
28153 /*
28154 ** A call to this routine tells the pager that if a rollback occurs,
28155 ** it is not necessary to restore the data on the given page.  This
28156 ** means that the pager does not have to record the given page in the
28157 ** rollback journal.
28158 **
28159 ** If we have not yet actually read the content of this page (if
28160 ** the PgHdr.needRead flag is set) then this routine acts as a promise
28161 ** that we will never need to read the page content in the future.
28162 ** so the needRead flag can be cleared at this point.
28163 */
28164 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
28165   Pager *pPager = pPg->pPager;
28166
28167   pagerEnter(pPager);
28168   assert( pPager->state>=PAGER_RESERVED );
28169
28170   /* If the journal file is not open, or DontWrite() has been called on
28171   ** this page (DontWrite() sets the alwaysRollback flag), then this
28172   ** function is a no-op.
28173   */
28174   if( pPager->journalOpen==0 || pPg->alwaysRollback || pPager->alwaysRollback ){
28175     pagerLeave(pPager);
28176     return;
28177   }
28178   assert( !MEMDB );    /* For a memdb, pPager->journalOpen is always 0 */
28179
28180 #ifdef SQLITE_SECURE_DELETE
28181   if( pPg->inJournal || (int)pPg->pgno > pPager->origDbSize ){
28182     return;
28183   }
28184 #endif
28185
28186   /* If SECURE_DELETE is disabled, then there is no way that this
28187   ** routine can be called on a page for which sqlite3PagerDontWrite()
28188   ** has not been previously called during the same transaction.
28189   ** And if DontWrite() has previously been called, the following
28190   ** conditions must be met.
28191   */
28192   assert( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize );
28193
28194   assert( pPager->pInJournal!=0 );
28195   sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
28196   pPg->inJournal = 1;
28197   pPg->needRead = 0;
28198   if( pPager->stmtInUse ){
28199     assert( pPager->stmtSize >= pPager->origDbSize );
28200     sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
28201   }
28202   PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
28203   IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
28204   pagerLeave(pPager);
28205 }
28206
28207
28208 /*
28209 ** This routine is called to increment the database file change-counter,
28210 ** stored at byte 24 of the pager file.
28211 */
28212 static int pager_incr_changecounter(Pager *pPager, int isDirect){
28213   PgHdr *pPgHdr;
28214   u32 change_counter;
28215   int rc = SQLITE_OK;
28216
28217   if( !pPager->changeCountDone ){
28218     /* Open page 1 of the file for writing. */
28219     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
28220     if( rc!=SQLITE_OK ) return rc;
28221
28222     if( !isDirect ){
28223       rc = sqlite3PagerWrite(pPgHdr);
28224       if( rc!=SQLITE_OK ){
28225         sqlite3PagerUnref(pPgHdr);
28226         return rc;
28227       }
28228     }
28229
28230     /* Increment the value just read and write it back to byte 24. */
28231     change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
28232     change_counter++;
28233     put32bits(((char*)PGHDR_TO_DATA(pPgHdr))+24, change_counter);
28234
28235     if( isDirect && pPager->fd->pMethods ){
28236       const void *zBuf = PGHDR_TO_DATA(pPgHdr);
28237       rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
28238     }
28239
28240     /* Release the page reference. */
28241     sqlite3PagerUnref(pPgHdr);
28242     pPager->changeCountDone = 1;
28243   }
28244   return rc;
28245 }
28246
28247 /*
28248 ** Sync the pager file to disk.
28249 */
28250 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
28251   int rc;
28252   pagerEnter(pPager);
28253   rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
28254   pagerLeave(pPager);
28255   return rc;
28256 }
28257
28258 /*
28259 ** Sync the database file for the pager pPager. zMaster points to the name
28260 ** of a master journal file that should be written into the individual
28261 ** journal file. zMaster may be NULL, which is interpreted as no master
28262 ** journal (a single database transaction).
28263 **
28264 ** This routine ensures that the journal is synced, all dirty pages written
28265 ** to the database file and the database file synced. The only thing that
28266 ** remains to commit the transaction is to delete the journal file (or
28267 ** master journal file if specified).
28268 **
28269 ** Note that if zMaster==NULL, this does not overwrite a previous value
28270 ** passed to an sqlite3PagerCommitPhaseOne() call.
28271 **
28272 ** If parameter nTrunc is non-zero, then the pager file is truncated to
28273 ** nTrunc pages (this is used by auto-vacuum databases).
28274 **
28275 ** If the final parameter - noSync - is true, then the database file itself
28276 ** is not synced. The caller must call sqlite3PagerSync() directly to
28277 ** sync the database file before calling CommitPhaseTwo() to delete the
28278 ** journal file in this case.
28279 */
28280 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
28281   Pager *pPager, 
28282   const char *zMaster, 
28283   Pgno nTrunc,
28284   int noSync
28285 ){
28286   int rc = SQLITE_OK;
28287
28288   /* If no changes have been made, we can leave the transaction early.
28289   */
28290   if( pPager->dbModified==0 &&
28291         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
28292           pPager->exclusiveMode!=0) ){
28293     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
28294     return SQLITE_OK;
28295   }
28296
28297   PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
28298       pPager->zFilename, zMaster, nTrunc);
28299   pagerEnter(pPager);
28300
28301   /* If this is an in-memory db, or no pages have been written to, or this
28302   ** function has already been called, it is a no-op.
28303   */
28304   if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
28305     PgHdr *pPg;
28306
28307 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
28308     /* The atomic-write optimization can be used if all of the
28309     ** following are true:
28310     **
28311     **    + The file-system supports the atomic-write property for
28312     **      blocks of size page-size, and
28313     **    + This commit is not part of a multi-file transaction, and
28314     **    + Exactly one page has been modified and store in the journal file.
28315     **
28316     ** If the optimization can be used, then the journal file will never
28317     ** be created for this transaction.
28318     */
28319     int useAtomicWrite = (
28320         !zMaster && 
28321         pPager->journalOpen &&
28322         pPager->journalOff==jrnlBufferSize(pPager) && 
28323         nTrunc==0 && 
28324         (0==pPager->pDirty || 0==pPager->pDirty->pDirty)
28325     );
28326     assert( pPager->journalOpen || pPager->journalMode==PAGER_JOURNALMODE_OFF );
28327     if( useAtomicWrite ){
28328       /* Update the nRec field in the journal file. */
28329       int offset = pPager->journalHdr + sizeof(aJournalMagic);
28330       assert(pPager->nRec==1);
28331       rc = write32bits(pPager->jfd, offset, pPager->nRec);
28332
28333       /* Update the db file change counter. The following call will modify
28334       ** the in-memory representation of page 1 to include the updated
28335       ** change counter and then write page 1 directly to the database
28336       ** file. Because of the atomic-write property of the host file-system, 
28337       ** this is safe.
28338       */
28339       if( rc==SQLITE_OK ){
28340         rc = pager_incr_changecounter(pPager, 1);
28341       }
28342     }else{
28343       rc = sqlite3JournalCreate(pPager->jfd);
28344     }
28345
28346     if( !useAtomicWrite && rc==SQLITE_OK )
28347 #endif
28348
28349     /* If a master journal file name has already been written to the
28350     ** journal file, then no sync is required. This happens when it is
28351     ** written, then the process fails to upgrade from a RESERVED to an
28352     ** EXCLUSIVE lock. The next time the process tries to commit the
28353     ** transaction the m-j name will have already been written.
28354     */
28355     if( !pPager->setMaster ){
28356       rc = pager_incr_changecounter(pPager, 0);
28357       if( rc!=SQLITE_OK ) goto sync_exit;
28358 #ifndef SQLITE_OMIT_AUTOVACUUM
28359       if( nTrunc!=0 ){
28360         /* If this transaction has made the database smaller, then all pages
28361         ** being discarded by the truncation must be written to the journal
28362         ** file.
28363         */
28364         Pgno i;
28365         int iSkip = PAGER_MJ_PGNO(pPager);
28366         for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
28367           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
28368             rc = sqlite3PagerGet(pPager, i, &pPg);
28369             if( rc!=SQLITE_OK ) goto sync_exit;
28370             rc = sqlite3PagerWrite(pPg);
28371             sqlite3PagerUnref(pPg);
28372             if( rc!=SQLITE_OK ) goto sync_exit;
28373           }
28374         } 
28375       }
28376 #endif
28377       rc = writeMasterJournal(pPager, zMaster);
28378       if( rc!=SQLITE_OK ) goto sync_exit;
28379       rc = syncJournal(pPager);
28380     }
28381     if( rc!=SQLITE_OK ) goto sync_exit;
28382
28383 #ifndef SQLITE_OMIT_AUTOVACUUM
28384     if( nTrunc!=0 ){
28385       rc = sqlite3PagerTruncate(pPager, nTrunc);
28386       if( rc!=SQLITE_OK ) goto sync_exit;
28387     }
28388 #endif
28389
28390     /* Write all dirty pages to the database file */
28391     pPg = pager_get_all_dirty_pages(pPager);
28392     rc = pager_write_pagelist(pPg);
28393     if( rc!=SQLITE_OK ){
28394       assert( rc!=SQLITE_IOERR_BLOCKED );
28395       /* The error might have left the dirty list all fouled up here,
28396       ** but that does not matter because if the if the dirty list did
28397       ** get corrupted, then the transaction will roll back and
28398       ** discard the dirty list.  There is an assert in
28399       ** pager_get_all_dirty_pages() that verifies that no attempt
28400       ** is made to use an invalid dirty list.
28401       */
28402       goto sync_exit;
28403     }
28404     pPager->pDirty = 0;
28405
28406     /* Sync the database file. */
28407     if( !pPager->noSync && !noSync ){
28408       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
28409     }
28410     IOTRACE(("DBSYNC %p\n", pPager))
28411
28412     pPager->state = PAGER_SYNCED;
28413   }else if( MEMDB && nTrunc!=0 ){
28414     rc = sqlite3PagerTruncate(pPager, nTrunc);
28415   }
28416
28417 sync_exit:
28418   if( rc==SQLITE_IOERR_BLOCKED ){
28419     /* pager_incr_changecounter() may attempt to obtain an exclusive
28420      * lock to spill the cache and return IOERR_BLOCKED. But since 
28421      * there is no chance the cache is inconsistent, it is
28422      * better to return SQLITE_BUSY.
28423      */
28424     rc = SQLITE_BUSY;
28425   }
28426   pagerLeave(pPager);
28427   return rc;
28428 }
28429
28430
28431 /*
28432 ** Commit all changes to the database and release the write lock.
28433 **
28434 ** If the commit fails for any reason, a rollback attempt is made
28435 ** and an error code is returned.  If the commit worked, SQLITE_OK
28436 ** is returned.
28437 */
28438 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
28439   int rc;
28440   PgHdr *pPg;
28441
28442   if( pPager->errCode ){
28443     return pPager->errCode;
28444   }
28445   if( pPager->state<PAGER_RESERVED ){
28446     return SQLITE_ERROR;
28447   }
28448   if( pPager->dbModified==0 &&
28449         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
28450           pPager->exclusiveMode!=0) ){
28451     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
28452     return SQLITE_OK;
28453   }
28454   pagerEnter(pPager);
28455   PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
28456   if( MEMDB ){
28457     pPg = pager_get_all_dirty_pages(pPager);
28458     while( pPg ){
28459       PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
28460       clearHistory(pHist);
28461       pPg->dirty = 0;
28462       pPg->inJournal = 0;
28463       pHist->inStmt = 0;
28464       pPg->needSync = 0;
28465       pHist->pPrevStmt = pHist->pNextStmt = 0;
28466       pPg = pPg->pDirty;
28467     }
28468     pPager->pDirty = 0;
28469 #ifndef NDEBUG
28470     for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
28471       PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
28472       assert( !pPg->alwaysRollback );
28473       assert( !pHist->pOrig );
28474       assert( !pHist->pStmt );
28475     }
28476 #endif
28477     pPager->pStmt = 0;
28478     pPager->state = PAGER_SHARED;
28479     pagerLeave(pPager);
28480     return SQLITE_OK;
28481   }
28482   assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
28483   rc = pager_end_transaction(pPager, pPager->setMaster);
28484   rc = pager_error(pPager, rc);
28485   pagerLeave(pPager);
28486   return rc;
28487 }
28488
28489 /*
28490 ** Rollback all changes.  The database falls back to PAGER_SHARED mode.
28491 ** All in-memory cache pages revert to their original data contents.
28492 ** The journal is deleted.
28493 **
28494 ** This routine cannot fail unless some other process is not following
28495 ** the correct locking protocol or unless some other
28496 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
28497 ** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
28498 ** codes are returned for all these occasions.  Otherwise,
28499 ** SQLITE_OK is returned.
28500 */
28501 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
28502   int rc;
28503   PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
28504   if( MEMDB ){
28505     PgHdr *p;
28506     for(p=pPager->pAll; p; p=p->pNextAll){
28507       PgHistory *pHist;
28508       assert( !p->alwaysRollback );
28509       if( !p->dirty ){
28510         assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pOrig );
28511         assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pStmt );
28512         continue;
28513       }
28514
28515       pHist = PGHDR_TO_HIST(p, pPager);
28516       if( pHist->pOrig ){
28517         memcpy(PGHDR_TO_DATA(p), pHist->pOrig, pPager->pageSize);
28518         PAGERTRACE3("ROLLBACK-PAGE %d of %d\n", p->pgno, PAGERID(pPager));
28519       }else{
28520         PAGERTRACE3("PAGE %d is clean on %d\n", p->pgno, PAGERID(pPager));
28521       }
28522       clearHistory(pHist);
28523       p->dirty = 0;
28524       p->inJournal = 0;
28525       pHist->inStmt = 0;
28526       pHist->pPrevStmt = pHist->pNextStmt = 0;
28527       if( pPager->xReiniter ){
28528         pPager->xReiniter(p, pPager->pageSize);
28529       }
28530     }
28531     pPager->pDirty = 0;
28532     pPager->pStmt = 0;
28533     pPager->dbSize = pPager->origDbSize;
28534     pager_truncate_cache(pPager);
28535     pPager->stmtInUse = 0;
28536     pPager->state = PAGER_SHARED;
28537     return SQLITE_OK;
28538   }
28539
28540   pagerEnter(pPager);
28541   if( !pPager->dirtyCache || !pPager->journalOpen ){
28542     rc = pager_end_transaction(pPager, pPager->setMaster);
28543     pagerLeave(pPager);
28544     return rc;
28545   }
28546
28547   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
28548     if( pPager->state>=PAGER_EXCLUSIVE ){
28549       pager_playback(pPager, 0);
28550     }
28551     pagerLeave(pPager);
28552     return pPager->errCode;
28553   }
28554   if( pPager->state==PAGER_RESERVED ){
28555     int rc2;
28556     rc = pager_playback(pPager, 0);
28557     rc2 = pager_end_transaction(pPager, pPager->setMaster);
28558     if( rc==SQLITE_OK ){
28559       rc = rc2;
28560     }
28561   }else{
28562     rc = pager_playback(pPager, 0);
28563   }
28564   /* pager_reset(pPager); */
28565   pPager->dbSize = -1;
28566
28567   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
28568   ** cache. So call pager_error() on the way out to make any error 
28569   ** persistent.
28570   */
28571   rc = pager_error(pPager, rc);
28572   pagerLeave(pPager);
28573   return rc;
28574 }
28575
28576 /*
28577 ** Return TRUE if the database file is opened read-only.  Return FALSE
28578 ** if the database is (in theory) writable.
28579 */
28580 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager *pPager){
28581   return pPager->readOnly;
28582 }
28583
28584 /*
28585 ** Return the number of references to the pager.
28586 */
28587 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
28588   return pPager->nRef;
28589 }
28590
28591 #ifdef SQLITE_TEST
28592 /*
28593 ** This routine is used for testing and analysis only.
28594 */
28595 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
28596   static int a[11];
28597   a[0] = pPager->nRef;
28598   a[1] = pPager->nPage;
28599   a[2] = pPager->mxPage;
28600   a[3] = pPager->dbSize;
28601   a[4] = pPager->state;
28602   a[5] = pPager->errCode;
28603   a[6] = pPager->nHit;
28604   a[7] = pPager->nMiss;
28605   a[8] = 0;  /* Used to be pPager->nOvfl */
28606   a[9] = pPager->nRead;
28607   a[10] = pPager->nWrite;
28608   return a;
28609 }
28610 #endif
28611
28612 /*
28613 ** Set the statement rollback point.
28614 **
28615 ** This routine should be called with the transaction journal already
28616 ** open.  A new statement journal is created that can be used to rollback
28617 ** changes of a single SQL command within a larger transaction.
28618 */
28619 static int pagerStmtBegin(Pager *pPager){
28620   int rc;
28621   assert( !pPager->stmtInUse );
28622   assert( pPager->state>=PAGER_SHARED );
28623   assert( pPager->dbSize>=0 );
28624   PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
28625   if( MEMDB ){
28626     pPager->stmtInUse = 1;
28627     pPager->stmtSize = pPager->dbSize;
28628     return SQLITE_OK;
28629   }
28630   if( !pPager->journalOpen ){
28631     pPager->stmtAutoopen = 1;
28632     return SQLITE_OK;
28633   }
28634   assert( pPager->journalOpen );
28635   pagerLeave(pPager);
28636   assert( pPager->pInStmt==0 );
28637   pPager->pInStmt = sqlite3BitvecCreate(pPager->dbSize);
28638   pagerEnter(pPager);
28639   if( pPager->pInStmt==0 ){
28640     /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
28641     return SQLITE_NOMEM;
28642   }
28643   pPager->stmtJSize = pPager->journalOff;
28644   pPager->stmtSize = pPager->dbSize;
28645   pPager->stmtHdrOff = 0;
28646   pPager->stmtCksum = pPager->cksumInit;
28647   if( !pPager->stmtOpen ){
28648     rc = sqlite3PagerOpentemp(pPager->pVfs, pPager->stfd, pPager->zStmtJrnl,
28649                               SQLITE_OPEN_SUBJOURNAL);
28650     if( rc ){
28651       goto stmt_begin_failed;
28652     }
28653     pPager->stmtOpen = 1;
28654     pPager->stmtNRec = 0;
28655   }
28656   pPager->stmtInUse = 1;
28657   return SQLITE_OK;
28658  
28659 stmt_begin_failed:
28660   if( pPager->pInStmt ){
28661     sqlite3BitvecDestroy(pPager->pInStmt);
28662     pPager->pInStmt = 0;
28663   }
28664   return rc;
28665 }
28666 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager *pPager){
28667   int rc;
28668   pagerEnter(pPager);
28669   rc = pagerStmtBegin(pPager);
28670   pagerLeave(pPager);
28671   return rc;
28672 }
28673
28674 /*
28675 ** Commit a statement.
28676 */
28677 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager *pPager){
28678   pagerEnter(pPager);
28679   if( pPager->stmtInUse ){
28680     PgHdr *pPg, *pNext;
28681     PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
28682     if( !MEMDB ){
28683       /* sqlite3OsTruncate(pPager->stfd, 0); */
28684       sqlite3BitvecDestroy(pPager->pInStmt);
28685       pPager->pInStmt = 0;
28686     }else{
28687       for(pPg=pPager->pStmt; pPg; pPg=pNext){
28688         PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
28689         pNext = pHist->pNextStmt;
28690         assert( pHist->inStmt );
28691         pHist->inStmt = 0;
28692         pHist->pPrevStmt = pHist->pNextStmt = 0;
28693         sqlite3_free(pHist->pStmt);
28694         pHist->pStmt = 0;
28695       }
28696     }
28697     pPager->stmtNRec = 0;
28698     pPager->stmtInUse = 0;
28699     pPager->pStmt = 0;
28700   }
28701   pPager->stmtAutoopen = 0;
28702   pagerLeave(pPager);
28703   return SQLITE_OK;
28704 }
28705
28706 /*
28707 ** Rollback a statement.
28708 */
28709 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager *pPager){
28710   int rc;
28711   pagerEnter(pPager);
28712   if( pPager->stmtInUse ){
28713     PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
28714     if( MEMDB ){
28715       PgHdr *pPg;
28716       PgHistory *pHist;
28717       for(pPg=pPager->pStmt; pPg; pPg=pHist->pNextStmt){
28718         pHist = PGHDR_TO_HIST(pPg, pPager);
28719         if( pHist->pStmt ){
28720           memcpy(PGHDR_TO_DATA(pPg), pHist->pStmt, pPager->pageSize);
28721           sqlite3_free(pHist->pStmt);
28722           pHist->pStmt = 0;
28723         }
28724       }
28725       pPager->dbSize = pPager->stmtSize;
28726       pager_truncate_cache(pPager);
28727       rc = SQLITE_OK;
28728     }else{
28729       rc = pager_stmt_playback(pPager);
28730     }
28731     sqlite3PagerStmtCommit(pPager);
28732   }else{
28733     rc = SQLITE_OK;
28734   }
28735   pPager->stmtAutoopen = 0;
28736   pagerLeave(pPager);
28737   return rc;
28738 }
28739
28740 /*
28741 ** Return the full pathname of the database file.
28742 */
28743 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
28744   return pPager->zFilename;
28745 }
28746
28747 /*
28748 ** Return the VFS structure for the pager.
28749 */
28750 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
28751   return pPager->pVfs;
28752 }
28753
28754 /*
28755 ** Return the file handle for the database file associated
28756 ** with the pager.  This might return NULL if the file has
28757 ** not yet been opened.
28758 */
28759 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
28760   return pPager->fd;
28761 }
28762
28763 /*
28764 ** Return the directory of the database file.
28765 */
28766 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
28767   return pPager->zDirectory;
28768 }
28769
28770 /*
28771 ** Return the full pathname of the journal file.
28772 */
28773 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
28774   return pPager->zJournal;
28775 }
28776
28777 /*
28778 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
28779 ** if fsync()s are executed normally.
28780 */
28781 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
28782   return pPager->noSync;
28783 }
28784
28785 #ifdef SQLITE_HAS_CODEC
28786 /*
28787 ** Set the codec for this pager
28788 */
28789 SQLITE_PRIVATE void sqlite3PagerSetCodec(
28790   Pager *pPager,
28791   void *(*xCodec)(void*,void*,Pgno,int),
28792   void *pCodecArg
28793 ){
28794   pPager->xCodec = xCodec;
28795   pPager->pCodecArg = pCodecArg;
28796 }
28797 #endif
28798
28799 #ifndef SQLITE_OMIT_AUTOVACUUM
28800 /*
28801 ** Move the page pPg to location pgno in the file.
28802 **
28803 ** There must be no references to the page previously located at
28804 ** pgno (which we call pPgOld) though that page is allowed to be
28805 ** in cache.  If the page previous located at pgno is not already
28806 ** in the rollback journal, it is not put there by by this routine.
28807 **
28808 ** References to the page pPg remain valid. Updating any
28809 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
28810 ** allocated along with the page) is the responsibility of the caller.
28811 **
28812 ** A transaction must be active when this routine is called. It used to be
28813 ** required that a statement transaction was not active, but this restriction
28814 ** has been removed (CREATE INDEX needs to move a page when a statement
28815 ** transaction is active).
28816 */
28817 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno){
28818   PgHdr *pPgOld;  /* The page being overwritten. */
28819   int h;
28820   Pgno needSyncPgno = 0;
28821
28822   pagerEnter(pPager);
28823   assert( pPg->nRef>0 );
28824
28825   PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
28826       PAGERID(pPager), pPg->pgno, pPg->needSync, pgno);
28827   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
28828
28829   pager_get_content(pPg);
28830   if( pPg->needSync ){
28831     needSyncPgno = pPg->pgno;
28832     assert( pPg->inJournal || (int)pgno>pPager->origDbSize );
28833     assert( pPg->dirty );
28834     assert( pPager->needSync );
28835   }
28836
28837   /* Unlink pPg from its hash-chain */
28838   unlinkHashChain(pPager, pPg);
28839
28840   /* If the cache contains a page with page-number pgno, remove it
28841   ** from its hash chain. Also, if the PgHdr.needSync was set for 
28842   ** page pgno before the 'move' operation, it needs to be retained 
28843   ** for the page moved there.
28844   */
28845   pPg->needSync = 0;
28846   pPgOld = pager_lookup(pPager, pgno);
28847   if( pPgOld ){
28848     assert( pPgOld->nRef==0 );
28849     unlinkHashChain(pPager, pPgOld);
28850     makeClean(pPgOld);
28851     pPg->needSync = pPgOld->needSync;
28852   }else{
28853     pPg->needSync = 0;
28854   }
28855   pPg->inJournal = sqlite3BitvecTest(pPager->pInJournal, pgno);
28856
28857   /* Change the page number for pPg and insert it into the new hash-chain. */
28858   assert( pgno!=0 );
28859   pPg->pgno = pgno;
28860   h = pgno & (pPager->nHash-1);
28861   if( pPager->aHash[h] ){
28862     assert( pPager->aHash[h]->pPrevHash==0 );
28863     pPager->aHash[h]->pPrevHash = pPg;
28864   }
28865   pPg->pNextHash = pPager->aHash[h];
28866   pPager->aHash[h] = pPg;
28867   pPg->pPrevHash = 0;
28868
28869   makeDirty(pPg);
28870   pPager->dirtyCache = 1;
28871   pPager->dbModified = 1;
28872
28873   if( needSyncPgno ){
28874     /* If needSyncPgno is non-zero, then the journal file needs to be 
28875     ** sync()ed before any data is written to database file page needSyncPgno.
28876     ** Currently, no such page exists in the page-cache and the 
28877     ** Pager.pInJournal bit has been set. This needs to be remedied by loading
28878     ** the page into the pager-cache and setting the PgHdr.needSync flag.
28879     **
28880     ** If the attempt to load the page into the page-cache fails, (due
28881     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
28882     ** array. Otherwise, if the page is loaded and written again in
28883     ** this transaction, it may be written to the database file before
28884     ** it is synced into the journal file. This way, it may end up in
28885     ** the journal file twice, but that is not a problem.
28886     **
28887     ** The sqlite3PagerGet() call may cause the journal to sync. So make
28888     ** sure the Pager.needSync flag is set too.
28889     */
28890     int rc;
28891     PgHdr *pPgHdr;
28892     assert( pPager->needSync );
28893     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
28894     if( rc!=SQLITE_OK ){
28895       if( pPager->pInJournal && (int)needSyncPgno<=pPager->origDbSize ){
28896         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
28897       }
28898       pagerLeave(pPager);
28899       return rc;
28900     }
28901     pPager->needSync = 1;
28902     pPgHdr->needSync = 1;
28903     pPgHdr->inJournal = 1;
28904     makeDirty(pPgHdr);
28905     sqlite3PagerUnref(pPgHdr);
28906   }
28907
28908   pagerLeave(pPager);
28909   return SQLITE_OK;
28910 }
28911 #endif
28912
28913 /*
28914 ** Return a pointer to the data for the specified page.
28915 */
28916 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
28917   return PGHDR_TO_DATA(pPg);
28918 }
28919
28920 /*
28921 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
28922 ** allocated along with the specified page.
28923 */
28924 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
28925   Pager *pPager = pPg->pPager;
28926   return (pPager?PGHDR_TO_EXTRA(pPg, pPager):0);
28927 }
28928
28929 /*
28930 ** Get/set the locking-mode for this pager. Parameter eMode must be one
28931 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
28932 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
28933 ** the locking-mode is set to the value specified.
28934 **
28935 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
28936 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
28937 ** locking-mode.
28938 */
28939 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
28940   assert( eMode==PAGER_LOCKINGMODE_QUERY
28941             || eMode==PAGER_LOCKINGMODE_NORMAL
28942             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
28943   assert( PAGER_LOCKINGMODE_QUERY<0 );
28944   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
28945   if( eMode>=0 && !pPager->tempFile ){
28946     pPager->exclusiveMode = eMode;
28947   }
28948   return (int)pPager->exclusiveMode;
28949 }
28950
28951 /*
28952 ** Get/set the journal-mode for this pager. Parameter eMode must be one
28953 ** of PAGER_JOURNALMODE_QUERY, PAGER_JOURNALMODE_DELETE or 
28954 ** PAGER_JOURNALMODE_PERSIST. If the parameter is not _QUERY, then
28955 ** the journal-mode is set to the value specified.
28956 **
28957 ** The returned value is either PAGER_JOURNALMODE_DELETE or
28958 ** PAGER_JOURNALMODE_PERSIST, indicating the current (possibly updated)
28959 ** journal-mode.
28960 */
28961 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
28962   assert( eMode==PAGER_JOURNALMODE_QUERY
28963             || eMode==PAGER_JOURNALMODE_DELETE
28964             || eMode==PAGER_JOURNALMODE_PERSIST
28965             || eMode==PAGER_JOURNALMODE_OFF );
28966   assert( PAGER_JOURNALMODE_QUERY<0 );
28967   assert( PAGER_JOURNALMODE_DELETE>=0 && PAGER_JOURNALMODE_PERSIST>=0 );
28968   if( eMode>=0 ){
28969     pPager->journalMode = eMode;
28970   }
28971   return (int)pPager->journalMode;
28972 }
28973
28974 #ifdef SQLITE_TEST
28975 /*
28976 ** Print a listing of all referenced pages and their ref count.
28977 */
28978 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager *pPager){
28979   PgHdr *pPg;
28980   for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
28981     if( pPg->nRef<=0 ) continue;
28982     sqlite3DebugPrintf("PAGE %3d addr=%p nRef=%d\n", 
28983        pPg->pgno, PGHDR_TO_DATA(pPg), pPg->nRef);
28984   }
28985 }
28986 #endif
28987
28988 #endif /* SQLITE_OMIT_DISKIO */
28989
28990 /************** End of pager.c ***********************************************/
28991 /************** Begin file btmutex.c *****************************************/
28992 /*
28993 ** 2007 August 27
28994 **
28995 ** The author disclaims copyright to this source code.  In place of
28996 ** a legal notice, here is a blessing:
28997 **
28998 **    May you do good and not evil.
28999 **    May you find forgiveness for yourself and forgive others.
29000 **    May you share freely, never taking more than you give.
29001 **
29002 *************************************************************************
29003 **
29004 ** $Id: btmutex.c,v 1.9 2008/01/23 12:52:41 drh Exp $
29005 **
29006 ** This file contains code used to implement mutexes on Btree objects.
29007 ** This code really belongs in btree.c.  But btree.c is getting too
29008 ** big and we want to break it down some.  This packaged seemed like
29009 ** a good breakout.
29010 */
29011 /************** Include btreeInt.h in the middle of btmutex.c ****************/
29012 /************** Begin file btreeInt.h ****************************************/
29013 /*
29014 ** 2004 April 6
29015 **
29016 ** The author disclaims copyright to this source code.  In place of
29017 ** a legal notice, here is a blessing:
29018 **
29019 **    May you do good and not evil.
29020 **    May you find forgiveness for yourself and forgive others.
29021 **    May you share freely, never taking more than you give.
29022 **
29023 *************************************************************************
29024 ** $Id: btreeInt.h,v 1.21 2008/04/24 19:15:10 shane Exp $
29025 **
29026 ** This file implements a external (disk-based) database using BTrees.
29027 ** For a detailed discussion of BTrees, refer to
29028 **
29029 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
29030 **     "Sorting And Searching", pages 473-480. Addison-Wesley
29031 **     Publishing Company, Reading, Massachusetts.
29032 **
29033 ** The basic idea is that each page of the file contains N database
29034 ** entries and N+1 pointers to subpages.
29035 **
29036 **   ----------------------------------------------------------------
29037 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
29038 **   ----------------------------------------------------------------
29039 **
29040 ** All of the keys on the page that Ptr(0) points to have values less
29041 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
29042 ** values greater than Key(0) and less than Key(1).  All of the keys
29043 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
29044 ** so forth.
29045 **
29046 ** Finding a particular key requires reading O(log(M)) pages from the 
29047 ** disk where M is the number of entries in the tree.
29048 **
29049 ** In this implementation, a single file can hold one or more separate 
29050 ** BTrees.  Each BTree is identified by the index of its root page.  The
29051 ** key and data for any entry are combined to form the "payload".  A
29052 ** fixed amount of payload can be carried directly on the database
29053 ** page.  If the payload is larger than the preset amount then surplus
29054 ** bytes are stored on overflow pages.  The payload for an entry
29055 ** and the preceding pointer are combined to form a "Cell".  Each 
29056 ** page has a small header which contains the Ptr(N) pointer and other
29057 ** information such as the size of key and data.
29058 **
29059 ** FORMAT DETAILS
29060 **
29061 ** The file is divided into pages.  The first page is called page 1,
29062 ** the second is page 2, and so forth.  A page number of zero indicates
29063 ** "no such page".  The page size can be anything between 512 and 65536.
29064 ** Each page can be either a btree page, a freelist page or an overflow
29065 ** page.
29066 **
29067 ** The first page is always a btree page.  The first 100 bytes of the first
29068 ** page contain a special header (the "file header") that describes the file.
29069 ** The format of the file header is as follows:
29070 **
29071 **   OFFSET   SIZE    DESCRIPTION
29072 **      0      16     Header string: "SQLite format 3\000"
29073 **     16       2     Page size in bytes.  
29074 **     18       1     File format write version
29075 **     19       1     File format read version
29076 **     20       1     Bytes of unused space at the end of each page
29077 **     21       1     Max embedded payload fraction
29078 **     22       1     Min embedded payload fraction
29079 **     23       1     Min leaf payload fraction
29080 **     24       4     File change counter
29081 **     28       4     Reserved for future use
29082 **     32       4     First freelist page
29083 **     36       4     Number of freelist pages in the file
29084 **     40      60     15 4-byte meta values passed to higher layers
29085 **
29086 ** All of the integer values are big-endian (most significant byte first).
29087 **
29088 ** The file change counter is incremented when the database is changed
29089 ** This counter allows other processes to know when the file has changed
29090 ** and thus when they need to flush their cache.
29091 **
29092 ** The max embedded payload fraction is the amount of the total usable
29093 ** space in a page that can be consumed by a single cell for standard
29094 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
29095 ** is to limit the maximum cell size so that at least 4 cells will fit
29096 ** on one page.  Thus the default max embedded payload fraction is 64.
29097 **
29098 ** If the payload for a cell is larger than the max payload, then extra
29099 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
29100 ** as many bytes as possible are moved into the overflow pages without letting
29101 ** the cell size drop below the min embedded payload fraction.
29102 **
29103 ** The min leaf payload fraction is like the min embedded payload fraction
29104 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
29105 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
29106 ** not specified in the header.
29107 **
29108 ** Each btree pages is divided into three sections:  The header, the
29109 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
29110 ** file header that occurs before the page header.
29111 **
29112 **      |----------------|
29113 **      | file header    |   100 bytes.  Page 1 only.
29114 **      |----------------|
29115 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
29116 **      |----------------|
29117 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
29118 **      | array          |   |  Grows downward
29119 **      |                |   v
29120 **      |----------------|
29121 **      | unallocated    |
29122 **      | space          |
29123 **      |----------------|   ^  Grows upwards
29124 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
29125 **      | area           |   |  and free space fragments.
29126 **      |----------------|
29127 **
29128 ** The page headers looks like this:
29129 **
29130 **   OFFSET   SIZE     DESCRIPTION
29131 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
29132 **      1       2      byte offset to the first freeblock
29133 **      3       2      number of cells on this page
29134 **      5       2      first byte of the cell content area
29135 **      7       1      number of fragmented free bytes
29136 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
29137 **
29138 ** The flags define the format of this btree page.  The leaf flag means that
29139 ** this page has no children.  The zerodata flag means that this page carries
29140 ** only keys and no data.  The intkey flag means that the key is a integer
29141 ** which is stored in the key size entry of the cell header rather than in
29142 ** the payload area.
29143 **
29144 ** The cell pointer array begins on the first byte after the page header.
29145 ** The cell pointer array contains zero or more 2-byte numbers which are
29146 ** offsets from the beginning of the page to the cell content in the cell
29147 ** content area.  The cell pointers occur in sorted order.  The system strives
29148 ** to keep free space after the last cell pointer so that new cells can
29149 ** be easily added without having to defragment the page.
29150 **
29151 ** Cell content is stored at the very end of the page and grows toward the
29152 ** beginning of the page.
29153 **
29154 ** Unused space within the cell content area is collected into a linked list of
29155 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
29156 ** to the first freeblock is given in the header.  Freeblocks occur in
29157 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
29158 ** any group of 3 or fewer unused bytes in the cell content area cannot
29159 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
29160 ** a fragment.  The total number of bytes in all fragments is recorded.
29161 ** in the page header at offset 7.
29162 **
29163 **    SIZE    DESCRIPTION
29164 **      2     Byte offset of the next freeblock
29165 **      2     Bytes in this freeblock
29166 **
29167 ** Cells are of variable length.  Cells are stored in the cell content area at
29168 ** the end of the page.  Pointers to the cells are in the cell pointer array
29169 ** that immediately follows the page header.  Cells is not necessarily
29170 ** contiguous or in order, but cell pointers are contiguous and in order.
29171 **
29172 ** Cell content makes use of variable length integers.  A variable
29173 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
29174 ** byte are used.  The integer consists of all bytes that have bit 8 set and
29175 ** the first byte with bit 8 clear.  The most significant byte of the integer
29176 ** appears first.  A variable-length integer may not be more than 9 bytes long.
29177 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
29178 ** allows a 64-bit integer to be encoded in 9 bytes.
29179 **
29180 **    0x00                      becomes  0x00000000
29181 **    0x7f                      becomes  0x0000007f
29182 **    0x81 0x00                 becomes  0x00000080
29183 **    0x82 0x00                 becomes  0x00000100
29184 **    0x80 0x7f                 becomes  0x0000007f
29185 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
29186 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
29187 **
29188 ** Variable length integers are used for rowids and to hold the number of
29189 ** bytes of key and data in a btree cell.
29190 **
29191 ** The content of a cell looks like this:
29192 **
29193 **    SIZE    DESCRIPTION
29194 **      4     Page number of the left child. Omitted if leaf flag is set.
29195 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
29196 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
29197 **      *     Payload
29198 **      4     First page of the overflow chain.  Omitted if no overflow
29199 **
29200 ** Overflow pages form a linked list.  Each page except the last is completely
29201 ** filled with data (pagesize - 4 bytes).  The last page can have as little
29202 ** as 1 byte of data.
29203 **
29204 **    SIZE    DESCRIPTION
29205 **      4     Page number of next overflow page
29206 **      *     Data
29207 **
29208 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
29209 ** file header points to the first in a linked list of trunk page.  Each trunk
29210 ** page points to multiple leaf pages.  The content of a leaf page is
29211 ** unspecified.  A trunk page looks like this:
29212 **
29213 **    SIZE    DESCRIPTION
29214 **      4     Page number of next trunk page
29215 **      4     Number of leaf pointers on this page
29216 **      *     zero or more pages numbers of leaves
29217 */
29218
29219 /* Round up a number to the next larger multiple of 8.  This is used
29220 ** to force 8-byte alignment on 64-bit architectures.
29221 */
29222 #define ROUND8(x)   ((x+7)&~7)
29223
29224
29225 /* The following value is the maximum cell size assuming a maximum page
29226 ** size give above.
29227 */
29228 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
29229
29230 /* The maximum number of cells on a single page of the database.  This
29231 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
29232 ** plus 2 bytes for the index to the cell in the page header).  Such
29233 ** small cells will be rare, but they are possible.
29234 */
29235 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
29236
29237 /* Forward declarations */
29238 typedef struct MemPage MemPage;
29239 typedef struct BtLock BtLock;
29240
29241 /*
29242 ** This is a magic string that appears at the beginning of every
29243 ** SQLite database in order to identify the file as a real database.
29244 **
29245 ** You can change this value at compile-time by specifying a
29246 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
29247 ** header must be exactly 16 bytes including the zero-terminator so
29248 ** the string itself should be 15 characters long.  If you change
29249 ** the header, then your custom library will not be able to read 
29250 ** databases generated by the standard tools and the standard tools
29251 ** will not be able to read databases created by your custom library.
29252 */
29253 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
29254 #  define SQLITE_FILE_HEADER "SQLite format 3"
29255 #endif
29256
29257 /*
29258 ** Page type flags.  An ORed combination of these flags appear as the
29259 ** first byte of on-disk image of every BTree page.
29260 */
29261 #define PTF_INTKEY    0x01
29262 #define PTF_ZERODATA  0x02
29263 #define PTF_LEAFDATA  0x04
29264 #define PTF_LEAF      0x08
29265
29266 /*
29267 ** As each page of the file is loaded into memory, an instance of the following
29268 ** structure is appended and initialized to zero.  This structure stores
29269 ** information about the page that is decoded from the raw file page.
29270 **
29271 ** The pParent field points back to the parent page.  This allows us to
29272 ** walk up the BTree from any leaf to the root.  Care must be taken to
29273 ** unref() the parent page pointer when this page is no longer referenced.
29274 ** The pageDestructor() routine handles that chore.
29275 **
29276 ** Access to all fields of this structure is controlled by the mutex
29277 ** stored in MemPage.pBt->mutex.
29278 */
29279 struct MemPage {
29280   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
29281   u8 idxShift;         /* True if Cell indices have changed */
29282   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
29283   u8 intKey;           /* True if intkey flag is set */
29284   u8 leaf;             /* True if leaf flag is set */
29285   u8 zeroData;         /* True if table stores keys only */
29286   u8 leafData;         /* True if tables stores data on leaves only */
29287   u8 hasData;          /* True if this page stores data */
29288   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
29289   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
29290   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
29291   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
29292   u16 cellOffset;      /* Index in aData of first cell pointer */
29293   u16 idxParent;       /* Index in parent of this node */
29294   u16 nFree;           /* Number of free bytes on the page */
29295   u16 nCell;           /* Number of cells on this page, local and ovfl */
29296   struct _OvflCell {   /* Cells that will not fit on aData[] */
29297     u8 *pCell;          /* Pointers to the body of the overflow cell */
29298     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
29299   } aOvfl[5];
29300   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
29301   u8 *aData;           /* Pointer to disk image of the page data */
29302   DbPage *pDbPage;     /* Pager page handle */
29303   Pgno pgno;           /* Page number for this page */
29304   MemPage *pParent;    /* The parent of this page.  NULL for root */
29305 };
29306
29307 /*
29308 ** The in-memory image of a disk page has the auxiliary information appended
29309 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
29310 ** that extra information.
29311 */
29312 #define EXTRA_SIZE sizeof(MemPage)
29313
29314 /* A Btree handle
29315 **
29316 ** A database connection contains a pointer to an instance of
29317 ** this object for every database file that it has open.  This structure
29318 ** is opaque to the database connection.  The database connection cannot
29319 ** see the internals of this structure and only deals with pointers to
29320 ** this structure.
29321 **
29322 ** For some database files, the same underlying database cache might be 
29323 ** shared between multiple connections.  In that case, each contection
29324 ** has it own pointer to this object.  But each instance of this object
29325 ** points to the same BtShared object.  The database cache and the
29326 ** schema associated with the database file are all contained within
29327 ** the BtShared object.
29328 **
29329 ** All fields in this structure are accessed under sqlite3.mutex.
29330 ** The pBt pointer itself may not be changed while there exists cursors 
29331 ** in the referenced BtShared that point back to this Btree since those
29332 ** cursors have to do go through this Btree to find their BtShared and
29333 ** they often do so without holding sqlite3.mutex.
29334 */
29335 struct Btree {
29336   sqlite3 *db;       /* The database connection holding this btree */
29337   BtShared *pBt;     /* Sharable content of this btree */
29338   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
29339   u8 sharable;       /* True if we can share pBt with another db */
29340   u8 locked;         /* True if db currently has pBt locked */
29341   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
29342   Btree *pNext;      /* List of other sharable Btrees from the same db */
29343   Btree *pPrev;      /* Back pointer of the same list */
29344 };
29345
29346 /*
29347 ** Btree.inTrans may take one of the following values.
29348 **
29349 ** If the shared-data extension is enabled, there may be multiple users
29350 ** of the Btree structure. At most one of these may open a write transaction,
29351 ** but any number may have active read transactions.
29352 */
29353 #define TRANS_NONE  0
29354 #define TRANS_READ  1
29355 #define TRANS_WRITE 2
29356
29357 /*
29358 ** An instance of this object represents a single database file.
29359 ** 
29360 ** A single database file can be in use as the same time by two
29361 ** or more database connections.  When two or more connections are
29362 ** sharing the same database file, each connection has it own
29363 ** private Btree object for the file and each of those Btrees points
29364 ** to this one BtShared object.  BtShared.nRef is the number of
29365 ** connections currently sharing this database file.
29366 **
29367 ** Fields in this structure are accessed under the BtShared.mutex
29368 ** mutex, except for nRef and pNext which are accessed under the
29369 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
29370 ** may not be modified once it is initially set as long as nRef>0.
29371 ** The pSchema field may be set once under BtShared.mutex and
29372 ** thereafter is unchanged as long as nRef>0.
29373 */
29374 struct BtShared {
29375   Pager *pPager;        /* The page cache */
29376   sqlite3 *db;          /* Database connection currently using this Btree */
29377   BtCursor *pCursor;    /* A list of all open cursors */
29378   MemPage *pPage1;      /* First page of the database */
29379   u8 inStmt;            /* True if we are in a statement subtransaction */
29380   u8 readOnly;          /* True if the underlying file is readonly */
29381   u8 maxEmbedFrac;      /* Maximum payload as % of total page size */
29382   u8 minEmbedFrac;      /* Minimum payload as % of total page size */
29383   u8 minLeafFrac;       /* Minimum leaf payload as % of total page size */
29384   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
29385 #ifndef SQLITE_OMIT_AUTOVACUUM
29386   u8 autoVacuum;        /* True if auto-vacuum is enabled */
29387   u8 incrVacuum;        /* True if incr-vacuum is enabled */
29388   Pgno nTrunc;          /* Non-zero if the db will be truncated (incr vacuum) */
29389 #endif
29390   u16 pageSize;         /* Total number of bytes on a page */
29391   u16 usableSize;       /* Number of usable bytes on each page */
29392   int maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
29393   int minLocal;         /* Minimum local payload in non-LEAFDATA tables */
29394   int maxLeaf;          /* Maximum local payload in a LEAFDATA table */
29395   int minLeaf;          /* Minimum local payload in a LEAFDATA table */
29396   u8 inTransaction;     /* Transaction state */
29397   int nTransaction;     /* Number of open transactions (read + write) */
29398   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
29399   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
29400   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
29401   BusyHandler busyHdr;  /* The busy handler for this btree */
29402 #ifndef SQLITE_OMIT_SHARED_CACHE
29403   int nRef;             /* Number of references to this structure */
29404   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
29405   BtLock *pLock;        /* List of locks held on this shared-btree struct */
29406   Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
29407 #endif
29408   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
29409 };
29410
29411 /*
29412 ** An instance of the following structure is used to hold information
29413 ** about a cell.  The parseCellPtr() function fills in this structure
29414 ** based on information extract from the raw disk page.
29415 */
29416 typedef struct CellInfo CellInfo;
29417 struct CellInfo {
29418   u8 *pCell;     /* Pointer to the start of cell content */
29419   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
29420   u32 nData;     /* Number of bytes of data */
29421   u32 nPayload;  /* Total amount of payload */
29422   u16 nHeader;   /* Size of the cell content header in bytes */
29423   u16 nLocal;    /* Amount of payload held locally */
29424   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
29425   u16 nSize;     /* Size of the cell content on the main b-tree page */
29426 };
29427
29428 /*
29429 ** A cursor is a pointer to a particular entry within a particular
29430 ** b-tree within a database file.
29431 **
29432 ** The entry is identified by its MemPage and the index in
29433 ** MemPage.aCell[] of the entry.
29434 **
29435 ** When a single database file can shared by two more database connections,
29436 ** but cursors cannot be shared.  Each cursor is associated with a
29437 ** particular database connection identified BtCursor.pBtree.db.
29438 **
29439 ** Fields in this structure are accessed under the BtShared.mutex
29440 ** found at self->pBt->mutex. 
29441 */
29442 struct BtCursor {
29443   Btree *pBtree;            /* The Btree to which this cursor belongs */
29444   BtShared *pBt;            /* The BtShared this cursor points to */
29445   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
29446   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
29447   Pgno pgnoRoot;            /* The root page of this tree */
29448   MemPage *pPage;           /* Page that contains the entry */
29449   int idx;                  /* Index of the entry in pPage->aCell[] */
29450   CellInfo info;            /* A parse of the cell we are pointing at */
29451   u8 wrFlag;                /* True if writable */
29452   u8 atLast;                /* Cursor pointing to the last entry */
29453   u8 validNKey;             /* True if info.nKey is valid */
29454   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
29455   void *pKey;      /* Saved key that was cursor's last known position */
29456   i64 nKey;        /* Size of pKey, or last integer key */
29457   int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
29458 #ifndef SQLITE_OMIT_INCRBLOB
29459   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
29460   Pgno *aOverflow;          /* Cache of overflow page locations */
29461 #endif
29462 };
29463
29464 /*
29465 ** Potential values for BtCursor.eState.
29466 **
29467 ** CURSOR_VALID:
29468 **   Cursor points to a valid entry. getPayload() etc. may be called.
29469 **
29470 ** CURSOR_INVALID:
29471 **   Cursor does not point to a valid entry. This can happen (for example) 
29472 **   because the table is empty or because BtreeCursorFirst() has not been
29473 **   called.
29474 **
29475 ** CURSOR_REQUIRESEEK:
29476 **   The table that this cursor was opened on still exists, but has been 
29477 **   modified since the cursor was last used. The cursor position is saved
29478 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
29479 **   this state, restoreOrClearCursorPosition() can be called to attempt to
29480 **   seek the cursor to the saved position.
29481 **
29482 ** CURSOR_FAULT:
29483 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
29484 **   on a different connection that shares the BtShared cache with this
29485 **   cursor.  The error has left the cache in an inconsistent state.
29486 **   Do nothing else with this cursor.  Any attempt to use the cursor
29487 **   should return the error code stored in BtCursor.skip
29488 */
29489 #define CURSOR_INVALID           0
29490 #define CURSOR_VALID             1
29491 #define CURSOR_REQUIRESEEK       2
29492 #define CURSOR_FAULT             3
29493
29494 /*
29495 ** The TRACE macro will print high-level status information about the
29496 ** btree operation when the global variable sqlite3BtreeTrace is
29497 ** enabled.
29498 */
29499 #if SQLITE_TEST
29500 # define TRACE(X)   if( sqlite3BtreeTrace ){ printf X; fflush(stdout); }
29501 #else
29502 # define TRACE(X)
29503 #endif
29504
29505 /* The database page the PENDING_BYTE occupies. This page is never used.
29506 ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
29507 ** should possibly be consolidated (presumably in pager.h).
29508 **
29509 ** If disk I/O is omitted (meaning that the database is stored purely
29510 ** in memory) then there is no pending byte.
29511 */
29512 #ifdef SQLITE_OMIT_DISKIO
29513 # define PENDING_BYTE_PAGE(pBt)  0x7fffffff
29514 #else
29515 # define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
29516 #endif
29517
29518 /*
29519 ** A linked list of the following structures is stored at BtShared.pLock.
29520 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
29521 ** is opened on the table with root page BtShared.iTable. Locks are removed
29522 ** from this list when a transaction is committed or rolled back, or when
29523 ** a btree handle is closed.
29524 */
29525 struct BtLock {
29526   Btree *pBtree;        /* Btree handle holding this lock */
29527   Pgno iTable;          /* Root page of table */
29528   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
29529   BtLock *pNext;        /* Next in BtShared.pLock list */
29530 };
29531
29532 /* Candidate values for BtLock.eLock */
29533 #define READ_LOCK     1
29534 #define WRITE_LOCK    2
29535
29536 /*
29537 ** These macros define the location of the pointer-map entry for a 
29538 ** database page. The first argument to each is the number of usable
29539 ** bytes on each page of the database (often 1024). The second is the
29540 ** page number to look up in the pointer map.
29541 **
29542 ** PTRMAP_PAGENO returns the database page number of the pointer-map
29543 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
29544 ** the offset of the requested map entry.
29545 **
29546 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
29547 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
29548 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
29549 ** this test.
29550 */
29551 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
29552 #define PTRMAP_PTROFFSET(pBt, pgno) (5*(pgno-ptrmapPageno(pBt, pgno)-1))
29553 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
29554
29555 /*
29556 ** The pointer map is a lookup table that identifies the parent page for
29557 ** each child page in the database file.  The parent page is the page that
29558 ** contains a pointer to the child.  Every page in the database contains
29559 ** 0 or 1 parent pages.  (In this context 'database page' refers
29560 ** to any page that is not part of the pointer map itself.)  Each pointer map
29561 ** entry consists of a single byte 'type' and a 4 byte parent page number.
29562 ** The PTRMAP_XXX identifiers below are the valid types.
29563 **
29564 ** The purpose of the pointer map is to facility moving pages from one
29565 ** position in the file to another as part of autovacuum.  When a page
29566 ** is moved, the pointer in its parent must be updated to point to the
29567 ** new location.  The pointer map is used to locate the parent page quickly.
29568 **
29569 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
29570 **                  used in this case.
29571 **
29572 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
29573 **                  is not used in this case.
29574 **
29575 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
29576 **                   overflow pages. The page number identifies the page that
29577 **                   contains the cell with a pointer to this overflow page.
29578 **
29579 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
29580 **                   overflow pages. The page-number identifies the previous
29581 **                   page in the overflow page list.
29582 **
29583 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
29584 **               identifies the parent page in the btree.
29585 */
29586 #define PTRMAP_ROOTPAGE 1
29587 #define PTRMAP_FREEPAGE 2
29588 #define PTRMAP_OVERFLOW1 3
29589 #define PTRMAP_OVERFLOW2 4
29590 #define PTRMAP_BTREE 5
29591
29592 /* A bunch of assert() statements to check the transaction state variables
29593 ** of handle p (type Btree*) are internally consistent.
29594 */
29595 #define btreeIntegrity(p) \
29596   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
29597   assert( p->pBt->inTransaction>=p->inTrans ); 
29598
29599
29600 /*
29601 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
29602 ** if the database supports auto-vacuum or not. Because it is used
29603 ** within an expression that is an argument to another macro 
29604 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
29605 ** So, this macro is defined instead.
29606 */
29607 #ifndef SQLITE_OMIT_AUTOVACUUM
29608 #define ISAUTOVACUUM (pBt->autoVacuum)
29609 #else
29610 #define ISAUTOVACUUM 0
29611 #endif
29612
29613
29614 /*
29615 ** This structure is passed around through all the sanity checking routines
29616 ** in order to keep track of some global state information.
29617 */
29618 typedef struct IntegrityCk IntegrityCk;
29619 struct IntegrityCk {
29620   BtShared *pBt;    /* The tree being checked out */
29621   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
29622   int nPage;        /* Number of pages in the database */
29623   int *anRef;       /* Number of times each page is referenced */
29624   int mxErr;        /* Stop accumulating errors when this reaches zero */
29625   char *zErrMsg;    /* An error message.  NULL if no errors seen. */
29626   int nErr;         /* Number of messages written to zErrMsg so far */
29627 };
29628
29629 /*
29630 ** Read or write a two- and four-byte big-endian integer values.
29631 */
29632 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
29633 #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
29634 #define get4byte sqlite3Get4byte
29635 #define put4byte sqlite3Put4byte
29636
29637 /*
29638 ** Internal routines that should be accessed by the btree layer only.
29639 */
29640 SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
29641 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
29642 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
29643 SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
29644 #ifdef SQLITE_TEST
29645 SQLITE_PRIVATE u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell);
29646 #endif
29647 SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur);
29648 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
29649 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
29650 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage);
29651 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
29652
29653 /************** End of btreeInt.h ********************************************/
29654 /************** Continuing where we left off in btmutex.c ********************/
29655 #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
29656
29657
29658 /*
29659 ** Enter a mutex on the given BTree object.
29660 **
29661 ** If the object is not sharable, then no mutex is ever required
29662 ** and this routine is a no-op.  The underlying mutex is non-recursive.
29663 ** But we keep a reference count in Btree.wantToLock so the behavior
29664 ** of this interface is recursive.
29665 **
29666 ** To avoid deadlocks, multiple Btrees are locked in the same order
29667 ** by all database connections.  The p->pNext is a list of other
29668 ** Btrees belonging to the same database connection as the p Btree
29669 ** which need to be locked after p.  If we cannot get a lock on
29670 ** p, then first unlock all of the others on p->pNext, then wait
29671 ** for the lock to become available on p, then relock all of the
29672 ** subsequent Btrees that desire a lock.
29673 */
29674 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
29675   Btree *pLater;
29676
29677   /* Some basic sanity checking on the Btree.  The list of Btrees
29678   ** connected by pNext and pPrev should be in sorted order by
29679   ** Btree.pBt value. All elements of the list should belong to
29680   ** the same connection. Only shared Btrees are on the list. */
29681   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
29682   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
29683   assert( p->pNext==0 || p->pNext->db==p->db );
29684   assert( p->pPrev==0 || p->pPrev->db==p->db );
29685   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
29686
29687   /* Check for locking consistency */
29688   assert( !p->locked || p->wantToLock>0 );
29689   assert( p->sharable || p->wantToLock==0 );
29690
29691   /* We should already hold a lock on the database connection */
29692   assert( sqlite3_mutex_held(p->db->mutex) );
29693
29694   if( !p->sharable ) return;
29695   p->wantToLock++;
29696   if( p->locked ) return;
29697
29698 #ifndef SQLITE_MUTEX_NOOP
29699   /* In most cases, we should be able to acquire the lock we
29700   ** want without having to go throught the ascending lock
29701   ** procedure that follows.  Just be sure not to block.
29702   */
29703   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
29704     p->locked = 1;
29705     return;
29706   }
29707
29708   /* To avoid deadlock, first release all locks with a larger
29709   ** BtShared address.  Then acquire our lock.  Then reacquire
29710   ** the other BtShared locks that we used to hold in ascending
29711   ** order.
29712   */
29713   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
29714     assert( pLater->sharable );
29715     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
29716     assert( !pLater->locked || pLater->wantToLock>0 );
29717     if( pLater->locked ){
29718       sqlite3_mutex_leave(pLater->pBt->mutex);
29719       pLater->locked = 0;
29720     }
29721   }
29722   sqlite3_mutex_enter(p->pBt->mutex);
29723   p->locked = 1;
29724   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
29725     if( pLater->wantToLock ){
29726       sqlite3_mutex_enter(pLater->pBt->mutex);
29727       pLater->locked = 1;
29728     }
29729   }
29730 #endif /* SQLITE_MUTEX_NOOP */
29731 }
29732
29733 /*
29734 ** Exit the recursive mutex on a Btree.
29735 */
29736 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
29737   if( p->sharable ){
29738     assert( p->wantToLock>0 );
29739     p->wantToLock--;
29740     if( p->wantToLock==0 ){
29741       assert( p->locked );
29742       sqlite3_mutex_leave(p->pBt->mutex);
29743       p->locked = 0;
29744     }
29745   }
29746 }
29747
29748 #ifndef NDEBUG
29749 /*
29750 ** Return true if the BtShared mutex is held on the btree.  
29751 **
29752 ** This routine makes no determination one why or another if the
29753 ** database connection mutex is held.
29754 **
29755 ** This routine is used only from within assert() statements.
29756 */
29757 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
29758   return (p->sharable==0 ||
29759              (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
29760 }
29761 #endif
29762
29763
29764 #ifndef SQLITE_OMIT_INCRBLOB
29765 /*
29766 ** Enter and leave a mutex on a Btree given a cursor owned by that
29767 ** Btree.  These entry points are used by incremental I/O and can be
29768 ** omitted if that module is not used.
29769 */
29770 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
29771   sqlite3BtreeEnter(pCur->pBtree);
29772 }
29773 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
29774   sqlite3BtreeLeave(pCur->pBtree);
29775 }
29776 #endif /* SQLITE_OMIT_INCRBLOB */
29777
29778
29779 /*
29780 ** Enter the mutex on every Btree associated with a database
29781 ** connection.  This is needed (for example) prior to parsing
29782 ** a statement since we will be comparing table and column names
29783 ** against all schemas and we do not want those schemas being
29784 ** reset out from under us.
29785 **
29786 ** There is a corresponding leave-all procedures.
29787 **
29788 ** Enter the mutexes in accending order by BtShared pointer address
29789 ** to avoid the possibility of deadlock when two threads with
29790 ** two or more btrees in common both try to lock all their btrees
29791 ** at the same instant.
29792 */
29793 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
29794   int i;
29795   Btree *p, *pLater;
29796   assert( sqlite3_mutex_held(db->mutex) );
29797   for(i=0; i<db->nDb; i++){
29798     p = db->aDb[i].pBt;
29799     if( p && p->sharable ){
29800       p->wantToLock++;
29801       if( !p->locked ){
29802         assert( p->wantToLock==1 );
29803         while( p->pPrev ) p = p->pPrev;
29804         while( p->locked && p->pNext ) p = p->pNext;
29805         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
29806           if( pLater->locked ){
29807             sqlite3_mutex_leave(pLater->pBt->mutex);
29808             pLater->locked = 0;
29809           }
29810         }
29811         while( p ){
29812           sqlite3_mutex_enter(p->pBt->mutex);
29813           p->locked++;
29814           p = p->pNext;
29815         }
29816       }
29817     }
29818   }
29819 }
29820 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
29821   int i;
29822   Btree *p;
29823   assert( sqlite3_mutex_held(db->mutex) );
29824   for(i=0; i<db->nDb; i++){
29825     p = db->aDb[i].pBt;
29826     if( p && p->sharable ){
29827       assert( p->wantToLock>0 );
29828       p->wantToLock--;
29829       if( p->wantToLock==0 ){
29830         assert( p->locked );
29831         sqlite3_mutex_leave(p->pBt->mutex);
29832         p->locked = 0;
29833       }
29834     }
29835   }
29836 }
29837
29838 #ifndef NDEBUG
29839 /*
29840 ** Return true if the current thread holds the database connection
29841 ** mutex and all required BtShared mutexes.
29842 **
29843 ** This routine is used inside assert() statements only.
29844 */
29845 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
29846   int i;
29847   if( !sqlite3_mutex_held(db->mutex) ){
29848     return 0;
29849   }
29850   for(i=0; i<db->nDb; i++){
29851     Btree *p;
29852     p = db->aDb[i].pBt;
29853     if( p && p->sharable &&
29854          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
29855       return 0;
29856     }
29857   }
29858   return 1;
29859 }
29860 #endif /* NDEBUG */
29861
29862 /*
29863 ** Potentially dd a new Btree pointer to a BtreeMutexArray.
29864 ** Really only add the Btree if it can possibly be shared with
29865 ** another database connection.
29866 **
29867 ** The Btrees are kept in sorted order by pBtree->pBt.  That
29868 ** way when we go to enter all the mutexes, we can enter them
29869 ** in order without every having to backup and retry and without
29870 ** worrying about deadlock.
29871 **
29872 ** The number of shared btrees will always be small (usually 0 or 1)
29873 ** so an insertion sort is an adequate algorithm here.
29874 */
29875 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
29876   int i, j;
29877   BtShared *pBt;
29878   if( pBtree==0 || pBtree->sharable==0 ) return;
29879 #ifndef NDEBUG
29880   {
29881     for(i=0; i<pArray->nMutex; i++){
29882       assert( pArray->aBtree[i]!=pBtree );
29883     }
29884   }
29885 #endif
29886   assert( pArray->nMutex>=0 );
29887   assert( pArray->nMutex<sizeof(pArray->aBtree)/sizeof(pArray->aBtree[0])-1 );
29888   pBt = pBtree->pBt;
29889   for(i=0; i<pArray->nMutex; i++){
29890     assert( pArray->aBtree[i]!=pBtree );
29891     if( pArray->aBtree[i]->pBt>pBt ){
29892       for(j=pArray->nMutex; j>i; j--){
29893         pArray->aBtree[j] = pArray->aBtree[j-1];
29894       }
29895       pArray->aBtree[i] = pBtree;
29896       pArray->nMutex++;
29897       return;
29898     }
29899   }
29900   pArray->aBtree[pArray->nMutex++] = pBtree;
29901 }
29902
29903 /*
29904 ** Enter the mutex of every btree in the array.  This routine is
29905 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
29906 ** exited at the end of the same function.
29907 */
29908 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
29909   int i;
29910   for(i=0; i<pArray->nMutex; i++){
29911     Btree *p = pArray->aBtree[i];
29912     /* Some basic sanity checking */
29913     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
29914     assert( !p->locked || p->wantToLock>0 );
29915
29916     /* We should already hold a lock on the database connection */
29917     assert( sqlite3_mutex_held(p->db->mutex) );
29918
29919     p->wantToLock++;
29920     if( !p->locked && p->sharable ){
29921       sqlite3_mutex_enter(p->pBt->mutex);
29922       p->locked = 1;
29923     }
29924   }
29925 }
29926
29927 /*
29928 ** Leave the mutex of every btree in the group.
29929 */
29930 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
29931   int i;
29932   for(i=0; i<pArray->nMutex; i++){
29933     Btree *p = pArray->aBtree[i];
29934     /* Some basic sanity checking */
29935     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
29936     assert( p->locked || !p->sharable );
29937     assert( p->wantToLock>0 );
29938
29939     /* We should already hold a lock on the database connection */
29940     assert( sqlite3_mutex_held(p->db->mutex) );
29941
29942     p->wantToLock--;
29943     if( p->wantToLock==0 && p->locked ){
29944       sqlite3_mutex_leave(p->pBt->mutex);
29945       p->locked = 0;
29946     }
29947   }
29948 }
29949
29950
29951 #endif  /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
29952
29953 /************** End of btmutex.c *********************************************/
29954 /************** Begin file btree.c *******************************************/
29955 /*
29956 ** 2004 April 6
29957 **
29958 ** The author disclaims copyright to this source code.  In place of
29959 ** a legal notice, here is a blessing:
29960 **
29961 **    May you do good and not evil.
29962 **    May you find forgiveness for yourself and forgive others.
29963 **    May you share freely, never taking more than you give.
29964 **
29965 *************************************************************************
29966 ** $Id: btree.c,v 1.458 2008/05/09 16:57:51 danielk1977 Exp $
29967 **
29968 ** This file implements a external (disk-based) database using BTrees.
29969 ** See the header comment on "btreeInt.h" for additional information.
29970 ** Including a description of file format and an overview of operation.
29971 */
29972
29973 /*
29974 ** The header string that appears at the beginning of every
29975 ** SQLite database.
29976 */
29977 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
29978
29979 /*
29980 ** Set this global variable to 1 to enable tracing using the TRACE
29981 ** macro.
29982 */
29983 #if SQLITE_TEST
29984 int sqlite3BtreeTrace=0;  /* True to enable tracing */
29985 #endif
29986
29987
29988
29989 #ifndef SQLITE_OMIT_SHARED_CACHE
29990 /*
29991 ** A flag to indicate whether or not shared cache is enabled.  Also,
29992 ** a list of BtShared objects that are eligible for participation
29993 ** in shared cache.  The variables have file scope during normal builds,
29994 ** but the test harness needs to access these variables so we make them
29995 ** global for test builds.
29996 */
29997 #ifdef SQLITE_TEST
29998 SQLITE_PRIVATE BtShared *sqlite3SharedCacheList = 0;
29999 SQLITE_PRIVATE int sqlite3SharedCacheEnabled = 0;
30000 #else
30001 static BtShared *sqlite3SharedCacheList = 0;
30002 static int sqlite3SharedCacheEnabled = 0;
30003 #endif
30004 #endif /* SQLITE_OMIT_SHARED_CACHE */
30005
30006 #ifndef SQLITE_OMIT_SHARED_CACHE
30007 /*
30008 ** Enable or disable the shared pager and schema features.
30009 **
30010 ** This routine has no effect on existing database connections.
30011 ** The shared cache setting effects only future calls to
30012 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
30013 */
30014 SQLITE_API int sqlite3_enable_shared_cache(int enable){
30015   sqlite3SharedCacheEnabled = enable;
30016   return SQLITE_OK;
30017 }
30018 #endif
30019
30020
30021 /*
30022 ** Forward declaration
30023 */
30024 static int checkReadLocks(Btree*,Pgno,BtCursor*);
30025
30026
30027 #ifdef SQLITE_OMIT_SHARED_CACHE
30028   /*
30029   ** The functions queryTableLock(), lockTable() and unlockAllTables()
30030   ** manipulate entries in the BtShared.pLock linked list used to store
30031   ** shared-cache table level locks. If the library is compiled with the
30032   ** shared-cache feature disabled, then there is only ever one user
30033   ** of each BtShared structure and so this locking is not necessary. 
30034   ** So define the lock related functions as no-ops.
30035   */
30036   #define queryTableLock(a,b,c) SQLITE_OK
30037   #define lockTable(a,b,c) SQLITE_OK
30038   #define unlockAllTables(a)
30039 #endif
30040
30041 #ifndef SQLITE_OMIT_SHARED_CACHE
30042 /*
30043 ** Query to see if btree handle p may obtain a lock of type eLock 
30044 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
30045 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
30046 ** SQLITE_LOCKED if not.
30047 */
30048 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
30049   BtShared *pBt = p->pBt;
30050   BtLock *pIter;
30051
30052   assert( sqlite3BtreeHoldsMutex(p) );
30053   
30054   /* This is a no-op if the shared-cache is not enabled */
30055   if( !p->sharable ){
30056     return SQLITE_OK;
30057   }
30058
30059   /* If some other connection is holding an exclusive lock, the
30060   ** requested lock may not be obtained.
30061   */
30062   if( pBt->pExclusive && pBt->pExclusive!=p ){
30063     return SQLITE_LOCKED;
30064   }
30065
30066   /* This (along with lockTable()) is where the ReadUncommitted flag is
30067   ** dealt with. If the caller is querying for a read-lock and the flag is
30068   ** set, it is unconditionally granted - even if there are write-locks
30069   ** on the table. If a write-lock is requested, the ReadUncommitted flag
30070   ** is not considered.
30071   **
30072   ** In function lockTable(), if a read-lock is demanded and the 
30073   ** ReadUncommitted flag is set, no entry is added to the locks list 
30074   ** (BtShared.pLock).
30075   **
30076   ** To summarize: If the ReadUncommitted flag is set, then read cursors do
30077   ** not create or respect table locks. The locking procedure for a 
30078   ** write-cursor does not change.
30079   */
30080   if( 
30081     !p->db || 
30082     0==(p->db->flags&SQLITE_ReadUncommitted) || 
30083     eLock==WRITE_LOCK ||
30084     iTab==MASTER_ROOT
30085   ){
30086     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
30087       if( pIter->pBtree!=p && pIter->iTable==iTab && 
30088           (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
30089         return SQLITE_LOCKED;
30090       }
30091     }
30092   }
30093   return SQLITE_OK;
30094 }
30095 #endif /* !SQLITE_OMIT_SHARED_CACHE */
30096
30097 #ifndef SQLITE_OMIT_SHARED_CACHE
30098 /*
30099 ** Add a lock on the table with root-page iTable to the shared-btree used
30100 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
30101 ** WRITE_LOCK.
30102 **
30103 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
30104 ** SQLITE_NOMEM may also be returned.
30105 */
30106 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
30107   BtShared *pBt = p->pBt;
30108   BtLock *pLock = 0;
30109   BtLock *pIter;
30110
30111   assert( sqlite3BtreeHoldsMutex(p) );
30112
30113   /* This is a no-op if the shared-cache is not enabled */
30114   if( !p->sharable ){
30115     return SQLITE_OK;
30116   }
30117
30118   assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
30119
30120   /* If the read-uncommitted flag is set and a read-lock is requested,
30121   ** return early without adding an entry to the BtShared.pLock list. See
30122   ** comment in function queryTableLock() for more info on handling 
30123   ** the ReadUncommitted flag.
30124   */
30125   if( 
30126     (p->db) && 
30127     (p->db->flags&SQLITE_ReadUncommitted) && 
30128     (eLock==READ_LOCK) &&
30129     iTable!=MASTER_ROOT
30130   ){
30131     return SQLITE_OK;
30132   }
30133
30134   /* First search the list for an existing lock on this table. */
30135   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
30136     if( pIter->iTable==iTable && pIter->pBtree==p ){
30137       pLock = pIter;
30138       break;
30139     }
30140   }
30141
30142   /* If the above search did not find a BtLock struct associating Btree p
30143   ** with table iTable, allocate one and link it into the list.
30144   */
30145   if( !pLock ){
30146     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
30147     if( !pLock ){
30148       return SQLITE_NOMEM;
30149     }
30150     pLock->iTable = iTable;
30151     pLock->pBtree = p;
30152     pLock->pNext = pBt->pLock;
30153     pBt->pLock = pLock;
30154   }
30155
30156   /* Set the BtLock.eLock variable to the maximum of the current lock
30157   ** and the requested lock. This means if a write-lock was already held
30158   ** and a read-lock requested, we don't incorrectly downgrade the lock.
30159   */
30160   assert( WRITE_LOCK>READ_LOCK );
30161   if( eLock>pLock->eLock ){
30162     pLock->eLock = eLock;
30163   }
30164
30165   return SQLITE_OK;
30166 }
30167 #endif /* !SQLITE_OMIT_SHARED_CACHE */
30168
30169 #ifndef SQLITE_OMIT_SHARED_CACHE
30170 /*
30171 ** Release all the table locks (locks obtained via calls to the lockTable()
30172 ** procedure) held by Btree handle p.
30173 */
30174 static void unlockAllTables(Btree *p){
30175   BtShared *pBt = p->pBt;
30176   BtLock **ppIter = &pBt->pLock;
30177
30178   assert( sqlite3BtreeHoldsMutex(p) );
30179   assert( p->sharable || 0==*ppIter );
30180
30181   while( *ppIter ){
30182     BtLock *pLock = *ppIter;
30183     assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
30184     if( pLock->pBtree==p ){
30185       *ppIter = pLock->pNext;
30186       sqlite3_free(pLock);
30187     }else{
30188       ppIter = &pLock->pNext;
30189     }
30190   }
30191
30192   if( pBt->pExclusive==p ){
30193     pBt->pExclusive = 0;
30194   }
30195 }
30196 #endif /* SQLITE_OMIT_SHARED_CACHE */
30197
30198 static void releasePage(MemPage *pPage);  /* Forward reference */
30199
30200 /*
30201 ** Verify that the cursor holds a mutex on the BtShared
30202 */
30203 #ifndef NDEBUG
30204 static int cursorHoldsMutex(BtCursor *p){
30205   return sqlite3_mutex_held(p->pBt->mutex);
30206 }
30207 #endif
30208
30209
30210 #ifndef SQLITE_OMIT_INCRBLOB
30211 /*
30212 ** Invalidate the overflow page-list cache for cursor pCur, if any.
30213 */
30214 static void invalidateOverflowCache(BtCursor *pCur){
30215   assert( cursorHoldsMutex(pCur) );
30216   sqlite3_free(pCur->aOverflow);
30217   pCur->aOverflow = 0;
30218 }
30219
30220 /*
30221 ** Invalidate the overflow page-list cache for all cursors opened
30222 ** on the shared btree structure pBt.
30223 */
30224 static void invalidateAllOverflowCache(BtShared *pBt){
30225   BtCursor *p;
30226   assert( sqlite3_mutex_held(pBt->mutex) );
30227   for(p=pBt->pCursor; p; p=p->pNext){
30228     invalidateOverflowCache(p);
30229   }
30230 }
30231 #else
30232   #define invalidateOverflowCache(x)
30233   #define invalidateAllOverflowCache(x)
30234 #endif
30235
30236 /*
30237 ** Save the current cursor position in the variables BtCursor.nKey 
30238 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
30239 */
30240 static int saveCursorPosition(BtCursor *pCur){
30241   int rc;
30242
30243   assert( CURSOR_VALID==pCur->eState );
30244   assert( 0==pCur->pKey );
30245   assert( cursorHoldsMutex(pCur) );
30246
30247   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
30248
30249   /* If this is an intKey table, then the above call to BtreeKeySize()
30250   ** stores the integer key in pCur->nKey. In this case this value is
30251   ** all that is required. Otherwise, if pCur is not open on an intKey
30252   ** table, then malloc space for and store the pCur->nKey bytes of key 
30253   ** data.
30254   */
30255   if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
30256     void *pKey = sqlite3_malloc(pCur->nKey);
30257     if( pKey ){
30258       rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
30259       if( rc==SQLITE_OK ){
30260         pCur->pKey = pKey;
30261       }else{
30262         sqlite3_free(pKey);
30263       }
30264     }else{
30265       rc = SQLITE_NOMEM;
30266     }
30267   }
30268   assert( !pCur->pPage->intKey || !pCur->pKey );
30269
30270   if( rc==SQLITE_OK ){
30271     releasePage(pCur->pPage);
30272     pCur->pPage = 0;
30273     pCur->eState = CURSOR_REQUIRESEEK;
30274   }
30275
30276   invalidateOverflowCache(pCur);
30277   return rc;
30278 }
30279
30280 /*
30281 ** Save the positions of all cursors except pExcept open on the table 
30282 ** with root-page iRoot. Usually, this is called just before cursor
30283 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
30284 */
30285 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
30286   BtCursor *p;
30287   assert( sqlite3_mutex_held(pBt->mutex) );
30288   assert( pExcept==0 || pExcept->pBt==pBt );
30289   for(p=pBt->pCursor; p; p=p->pNext){
30290     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
30291         p->eState==CURSOR_VALID ){
30292       int rc = saveCursorPosition(p);
30293       if( SQLITE_OK!=rc ){
30294         return rc;
30295       }
30296     }
30297   }
30298   return SQLITE_OK;
30299 }
30300
30301 /*
30302 ** Clear the current cursor position.
30303 */
30304 static void clearCursorPosition(BtCursor *pCur){
30305   assert( cursorHoldsMutex(pCur) );
30306   sqlite3_free(pCur->pKey);
30307   pCur->pKey = 0;
30308   pCur->eState = CURSOR_INVALID;
30309 }
30310
30311 /*
30312 ** Restore the cursor to the position it was in (or as close to as possible)
30313 ** when saveCursorPosition() was called. Note that this call deletes the 
30314 ** saved position info stored by saveCursorPosition(), so there can be
30315 ** at most one effective restoreOrClearCursorPosition() call after each 
30316 ** saveCursorPosition().
30317 **
30318 ** If the second argument argument - doSeek - is false, then instead of 
30319 ** returning the cursor to its saved position, any saved position is deleted
30320 ** and the cursor state set to CURSOR_INVALID.
30321 */
30322 SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
30323   int rc;
30324   assert( cursorHoldsMutex(pCur) );
30325   assert( pCur->eState>=CURSOR_REQUIRESEEK );
30326   if( pCur->eState==CURSOR_FAULT ){
30327     return pCur->skip;
30328   }
30329 #ifndef SQLITE_OMIT_INCRBLOB
30330   if( pCur->isIncrblobHandle ){
30331     return SQLITE_ABORT;
30332   }
30333 #endif
30334   pCur->eState = CURSOR_INVALID;
30335   rc = sqlite3BtreeMoveto(pCur, pCur->pKey, 0, pCur->nKey, 0, &pCur->skip);
30336   if( rc==SQLITE_OK ){
30337     sqlite3_free(pCur->pKey);
30338     pCur->pKey = 0;
30339     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
30340   }
30341   return rc;
30342 }
30343
30344 #define restoreOrClearCursorPosition(p) \
30345   (p->eState>=CURSOR_REQUIRESEEK ? \
30346          sqlite3BtreeRestoreOrClearCursorPosition(p) : \
30347          SQLITE_OK)
30348
30349 #ifndef SQLITE_OMIT_AUTOVACUUM
30350 /*
30351 ** Given a page number of a regular database page, return the page
30352 ** number for the pointer-map page that contains the entry for the
30353 ** input page number.
30354 */
30355 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
30356   int nPagesPerMapPage, iPtrMap, ret;
30357   assert( sqlite3_mutex_held(pBt->mutex) );
30358   nPagesPerMapPage = (pBt->usableSize/5)+1;
30359   iPtrMap = (pgno-2)/nPagesPerMapPage;
30360   ret = (iPtrMap*nPagesPerMapPage) + 2; 
30361   if( ret==PENDING_BYTE_PAGE(pBt) ){
30362     ret++;
30363   }
30364   return ret;
30365 }
30366
30367 /*
30368 ** Write an entry into the pointer map.
30369 **
30370 ** This routine updates the pointer map entry for page number 'key'
30371 ** so that it maps to type 'eType' and parent page number 'pgno'.
30372 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
30373 */
30374 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
30375   DbPage *pDbPage;  /* The pointer map page */
30376   u8 *pPtrmap;      /* The pointer map data */
30377   Pgno iPtrmap;     /* The pointer map page number */
30378   int offset;       /* Offset in pointer map page */
30379   int rc;
30380
30381   assert( sqlite3_mutex_held(pBt->mutex) );
30382   /* The master-journal page number must never be used as a pointer map page */
30383   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
30384
30385   assert( pBt->autoVacuum );
30386   if( key==0 ){
30387     return SQLITE_CORRUPT_BKPT;
30388   }
30389   iPtrmap = PTRMAP_PAGENO(pBt, key);
30390   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
30391   if( rc!=SQLITE_OK ){
30392     return rc;
30393   }
30394   offset = PTRMAP_PTROFFSET(pBt, key);
30395   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
30396
30397   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
30398     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
30399     rc = sqlite3PagerWrite(pDbPage);
30400     if( rc==SQLITE_OK ){
30401       pPtrmap[offset] = eType;
30402       put4byte(&pPtrmap[offset+1], parent);
30403     }
30404   }
30405
30406   sqlite3PagerUnref(pDbPage);
30407   return rc;
30408 }
30409
30410 /*
30411 ** Read an entry from the pointer map.
30412 **
30413 ** This routine retrieves the pointer map entry for page 'key', writing
30414 ** the type and parent page number to *pEType and *pPgno respectively.
30415 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
30416 */
30417 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
30418   DbPage *pDbPage;   /* The pointer map page */
30419   int iPtrmap;       /* Pointer map page index */
30420   u8 *pPtrmap;       /* Pointer map page data */
30421   int offset;        /* Offset of entry in pointer map */
30422   int rc;
30423
30424   assert( sqlite3_mutex_held(pBt->mutex) );
30425
30426   iPtrmap = PTRMAP_PAGENO(pBt, key);
30427   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
30428   if( rc!=0 ){
30429     return rc;
30430   }
30431   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
30432
30433   offset = PTRMAP_PTROFFSET(pBt, key);
30434   assert( pEType!=0 );
30435   *pEType = pPtrmap[offset];
30436   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
30437
30438   sqlite3PagerUnref(pDbPage);
30439   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
30440   return SQLITE_OK;
30441 }
30442
30443 #endif /* SQLITE_OMIT_AUTOVACUUM */
30444
30445 /*
30446 ** Given a btree page and a cell index (0 means the first cell on
30447 ** the page, 1 means the second cell, and so forth) return a pointer
30448 ** to the cell content.
30449 **
30450 ** This routine works only for pages that do not contain overflow cells.
30451 */
30452 #define findCell(pPage, iCell) \
30453   ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
30454 #ifdef SQLITE_TEST
30455 SQLITE_PRIVATE u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
30456   assert( iCell>=0 );
30457   assert( iCell<get2byte(&pPage->aData[pPage->hdrOffset+3]) );
30458   return findCell(pPage, iCell);
30459 }
30460 #endif
30461
30462 /*
30463 ** This a more complex version of sqlite3BtreeFindCell() that works for
30464 ** pages that do contain overflow cells.  See insert
30465 */
30466 static u8 *findOverflowCell(MemPage *pPage, int iCell){
30467   int i;
30468   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30469   for(i=pPage->nOverflow-1; i>=0; i--){
30470     int k;
30471     struct _OvflCell *pOvfl;
30472     pOvfl = &pPage->aOvfl[i];
30473     k = pOvfl->idx;
30474     if( k<=iCell ){
30475       if( k==iCell ){
30476         return pOvfl->pCell;
30477       }
30478       iCell--;
30479     }
30480   }
30481   return findCell(pPage, iCell);
30482 }
30483
30484 /*
30485 ** Parse a cell content block and fill in the CellInfo structure.  There
30486 ** are two versions of this function.  sqlite3BtreeParseCell() takes a 
30487 ** cell index as the second argument and sqlite3BtreeParseCellPtr() 
30488 ** takes a pointer to the body of the cell as its second argument.
30489 **
30490 ** Within this file, the parseCell() macro can be called instead of
30491 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
30492 */
30493 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
30494   MemPage *pPage,         /* Page containing the cell */
30495   u8 *pCell,              /* Pointer to the cell text. */
30496   CellInfo *pInfo         /* Fill in this structure */
30497 ){
30498   int n;                  /* Number bytes in cell content header */
30499   u32 nPayload;           /* Number of bytes of cell payload */
30500
30501   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30502
30503   pInfo->pCell = pCell;
30504   assert( pPage->leaf==0 || pPage->leaf==1 );
30505   n = pPage->childPtrSize;
30506   assert( n==4-4*pPage->leaf );
30507   if( pPage->hasData ){
30508     n += getVarint32(&pCell[n], nPayload);
30509   }else{
30510     nPayload = 0;
30511   }
30512   pInfo->nData = nPayload;
30513   if( pPage->intKey ){
30514     n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
30515   }else{
30516     u32 x;
30517     n += getVarint32(&pCell[n], x);
30518     pInfo->nKey = x;
30519     nPayload += x;
30520   }
30521   pInfo->nPayload = nPayload;
30522   pInfo->nHeader = n;
30523   if( nPayload<=pPage->maxLocal ){
30524     /* This is the (easy) common case where the entire payload fits
30525     ** on the local page.  No overflow is required.
30526     */
30527     int nSize;          /* Total size of cell content in bytes */
30528     pInfo->nLocal = nPayload;
30529     pInfo->iOverflow = 0;
30530     nSize = nPayload + n;
30531     if( nSize<4 ){
30532       nSize = 4;        /* Minimum cell size is 4 */
30533     }
30534     pInfo->nSize = nSize;
30535   }else{
30536     /* If the payload will not fit completely on the local page, we have
30537     ** to decide how much to store locally and how much to spill onto
30538     ** overflow pages.  The strategy is to minimize the amount of unused
30539     ** space on overflow pages while keeping the amount of local storage
30540     ** in between minLocal and maxLocal.
30541     **
30542     ** Warning:  changing the way overflow payload is distributed in any
30543     ** way will result in an incompatible file format.
30544     */
30545     int minLocal;  /* Minimum amount of payload held locally */
30546     int maxLocal;  /* Maximum amount of payload held locally */
30547     int surplus;   /* Overflow payload available for local storage */
30548
30549     minLocal = pPage->minLocal;
30550     maxLocal = pPage->maxLocal;
30551     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
30552     if( surplus <= maxLocal ){
30553       pInfo->nLocal = surplus;
30554     }else{
30555       pInfo->nLocal = minLocal;
30556     }
30557     pInfo->iOverflow = pInfo->nLocal + n;
30558     pInfo->nSize = pInfo->iOverflow + 4;
30559   }
30560 }
30561 #define parseCell(pPage, iCell, pInfo) \
30562   sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
30563 SQLITE_PRIVATE void sqlite3BtreeParseCell(
30564   MemPage *pPage,         /* Page containing the cell */
30565   int iCell,              /* The cell index.  First cell is 0 */
30566   CellInfo *pInfo         /* Fill in this structure */
30567 ){
30568   parseCell(pPage, iCell, pInfo);
30569 }
30570
30571 /*
30572 ** Compute the total number of bytes that a Cell needs in the cell
30573 ** data area of the btree-page.  The return number includes the cell
30574 ** data header and the local payload, but not any overflow page or
30575 ** the space used by the cell pointer.
30576 */
30577 #ifndef NDEBUG
30578 static u16 cellSize(MemPage *pPage, int iCell){
30579   CellInfo info;
30580   sqlite3BtreeParseCell(pPage, iCell, &info);
30581   return info.nSize;
30582 }
30583 #endif
30584 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
30585   CellInfo info;
30586   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
30587   return info.nSize;
30588 }
30589
30590 #ifndef SQLITE_OMIT_AUTOVACUUM
30591 /*
30592 ** If the cell pCell, part of page pPage contains a pointer
30593 ** to an overflow page, insert an entry into the pointer-map
30594 ** for the overflow page.
30595 */
30596 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
30597   if( pCell ){
30598     CellInfo info;
30599     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
30600     assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
30601     if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
30602       Pgno ovfl = get4byte(&pCell[info.iOverflow]);
30603       return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
30604     }
30605   }
30606   return SQLITE_OK;
30607 }
30608 /*
30609 ** If the cell with index iCell on page pPage contains a pointer
30610 ** to an overflow page, insert an entry into the pointer-map
30611 ** for the overflow page.
30612 */
30613 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
30614   u8 *pCell;
30615   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30616   pCell = findOverflowCell(pPage, iCell);
30617   return ptrmapPutOvflPtr(pPage, pCell);
30618 }
30619 #endif
30620
30621
30622 /*
30623 ** Defragment the page given.  All Cells are moved to the
30624 ** end of the page and all free space is collected into one
30625 ** big FreeBlk that occurs in between the header and cell
30626 ** pointer array and the cell content area.
30627 */
30628 static int defragmentPage(MemPage *pPage){
30629   int i;                     /* Loop counter */
30630   int pc;                    /* Address of a i-th cell */
30631   int addr;                  /* Offset of first byte after cell pointer array */
30632   int hdr;                   /* Offset to the page header */
30633   int size;                  /* Size of a cell */
30634   int usableSize;            /* Number of usable bytes on a page */
30635   int cellOffset;            /* Offset to the cell pointer array */
30636   int brk;                   /* Offset to the cell content area */
30637   int nCell;                 /* Number of cells on the page */
30638   unsigned char *data;       /* The page data */
30639   unsigned char *temp;       /* Temp area for cell content */
30640
30641   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
30642   assert( pPage->pBt!=0 );
30643   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
30644   assert( pPage->nOverflow==0 );
30645   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30646   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
30647   data = pPage->aData;
30648   hdr = pPage->hdrOffset;
30649   cellOffset = pPage->cellOffset;
30650   nCell = pPage->nCell;
30651   assert( nCell==get2byte(&data[hdr+3]) );
30652   usableSize = pPage->pBt->usableSize;
30653   brk = get2byte(&data[hdr+5]);
30654   memcpy(&temp[brk], &data[brk], usableSize - brk);
30655   brk = usableSize;
30656   for(i=0; i<nCell; i++){
30657     u8 *pAddr;     /* The i-th cell pointer */
30658     pAddr = &data[cellOffset + i*2];
30659     pc = get2byte(pAddr);
30660     assert( pc<pPage->pBt->usableSize );
30661     size = cellSizePtr(pPage, &temp[pc]);
30662     brk -= size;
30663     memcpy(&data[brk], &temp[pc], size);
30664     put2byte(pAddr, brk);
30665   }
30666   assert( brk>=cellOffset+2*nCell );
30667   put2byte(&data[hdr+5], brk);
30668   data[hdr+1] = 0;
30669   data[hdr+2] = 0;
30670   data[hdr+7] = 0;
30671   addr = cellOffset+2*nCell;
30672   memset(&data[addr], 0, brk-addr);
30673   return SQLITE_OK;
30674 }
30675
30676 /*
30677 ** Allocate nByte bytes of space on a page.
30678 **
30679 ** Return the index into pPage->aData[] of the first byte of
30680 ** the new allocation. Or return 0 if there is not enough free
30681 ** space on the page to satisfy the allocation request.
30682 **
30683 ** If the page contains nBytes of free space but does not contain
30684 ** nBytes of contiguous free space, then this routine automatically
30685 ** calls defragementPage() to consolidate all free space before 
30686 ** allocating the new chunk.
30687 */
30688 static int allocateSpace(MemPage *pPage, int nByte){
30689   int addr, pc, hdr;
30690   int size;
30691   int nFrag;
30692   int top;
30693   int nCell;
30694   int cellOffset;
30695   unsigned char *data;
30696   
30697   data = pPage->aData;
30698   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
30699   assert( pPage->pBt );
30700   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30701   if( nByte<4 ) nByte = 4;
30702   if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
30703   pPage->nFree -= nByte;
30704   hdr = pPage->hdrOffset;
30705
30706   nFrag = data[hdr+7];
30707   if( nFrag<60 ){
30708     /* Search the freelist looking for a slot big enough to satisfy the
30709     ** space request. */
30710     addr = hdr+1;
30711     while( (pc = get2byte(&data[addr]))>0 ){
30712       size = get2byte(&data[pc+2]);
30713       if( size>=nByte ){
30714         if( size<nByte+4 ){
30715           memcpy(&data[addr], &data[pc], 2);
30716           data[hdr+7] = nFrag + size - nByte;
30717           return pc;
30718         }else{
30719           put2byte(&data[pc+2], size-nByte);
30720           return pc + size - nByte;
30721         }
30722       }
30723       addr = pc;
30724     }
30725   }
30726
30727   /* Allocate memory from the gap in between the cell pointer array
30728   ** and the cell content area.
30729   */
30730   top = get2byte(&data[hdr+5]);
30731   nCell = get2byte(&data[hdr+3]);
30732   cellOffset = pPage->cellOffset;
30733   if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
30734     if( defragmentPage(pPage) ) return 0;
30735     top = get2byte(&data[hdr+5]);
30736   }
30737   top -= nByte;
30738   assert( cellOffset + 2*nCell <= top );
30739   put2byte(&data[hdr+5], top);
30740   return top;
30741 }
30742
30743 /*
30744 ** Return a section of the pPage->aData to the freelist.
30745 ** The first byte of the new free block is pPage->aDisk[start]
30746 ** and the size of the block is "size" bytes.
30747 **
30748 ** Most of the effort here is involved in coalesing adjacent
30749 ** free blocks into a single big free block.
30750 */
30751 static void freeSpace(MemPage *pPage, int start, int size){
30752   int addr, pbegin, hdr;
30753   unsigned char *data = pPage->aData;
30754
30755   assert( pPage->pBt!=0 );
30756   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
30757   assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
30758   assert( (start + size)<=pPage->pBt->usableSize );
30759   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30760   if( size<4 ) size = 4;
30761
30762 #ifdef SQLITE_SECURE_DELETE
30763   /* Overwrite deleted information with zeros when the SECURE_DELETE 
30764   ** option is enabled at compile-time */
30765   memset(&data[start], 0, size);
30766 #endif
30767
30768   /* Add the space back into the linked list of freeblocks */
30769   hdr = pPage->hdrOffset;
30770   addr = hdr + 1;
30771   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
30772     assert( pbegin<=pPage->pBt->usableSize-4 );
30773     assert( pbegin>addr );
30774     addr = pbegin;
30775   }
30776   assert( pbegin<=pPage->pBt->usableSize-4 );
30777   assert( pbegin>addr || pbegin==0 );
30778   put2byte(&data[addr], start);
30779   put2byte(&data[start], pbegin);
30780   put2byte(&data[start+2], size);
30781   pPage->nFree += size;
30782
30783   /* Coalesce adjacent free blocks */
30784   addr = pPage->hdrOffset + 1;
30785   while( (pbegin = get2byte(&data[addr]))>0 ){
30786     int pnext, psize;
30787     assert( pbegin>addr );
30788     assert( pbegin<=pPage->pBt->usableSize-4 );
30789     pnext = get2byte(&data[pbegin]);
30790     psize = get2byte(&data[pbegin+2]);
30791     if( pbegin + psize + 3 >= pnext && pnext>0 ){
30792       int frag = pnext - (pbegin+psize);
30793       assert( frag<=data[pPage->hdrOffset+7] );
30794       data[pPage->hdrOffset+7] -= frag;
30795       put2byte(&data[pbegin], get2byte(&data[pnext]));
30796       put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
30797     }else{
30798       addr = pbegin;
30799     }
30800   }
30801
30802   /* If the cell content area begins with a freeblock, remove it. */
30803   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
30804     int top;
30805     pbegin = get2byte(&data[hdr+1]);
30806     memcpy(&data[hdr+1], &data[pbegin], 2);
30807     top = get2byte(&data[hdr+5]);
30808     put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
30809   }
30810 }
30811
30812 /*
30813 ** Decode the flags byte (the first byte of the header) for a page
30814 ** and initialize fields of the MemPage structure accordingly.
30815 */
30816 static void decodeFlags(MemPage *pPage, int flagByte){
30817   BtShared *pBt;     /* A copy of pPage->pBt */
30818
30819   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
30820   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
30821   pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
30822   pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
30823   pPage->leaf = (flagByte & PTF_LEAF)!=0;
30824   pPage->childPtrSize = 4*(pPage->leaf==0);
30825   pBt = pPage->pBt;
30826   if( flagByte & PTF_LEAFDATA ){
30827     pPage->leafData = 1;
30828     pPage->maxLocal = pBt->maxLeaf;
30829     pPage->minLocal = pBt->minLeaf;
30830   }else{
30831     pPage->leafData = 0;
30832     pPage->maxLocal = pBt->maxLocal;
30833     pPage->minLocal = pBt->minLocal;
30834   }
30835   pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
30836 }
30837
30838 /*
30839 ** Initialize the auxiliary information for a disk block.
30840 **
30841 ** The pParent parameter must be a pointer to the MemPage which
30842 ** is the parent of the page being initialized.  The root of a
30843 ** BTree has no parent and so for that page, pParent==NULL.
30844 **
30845 ** Return SQLITE_OK on success.  If we see that the page does
30846 ** not contain a well-formed database page, then return 
30847 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
30848 ** guarantee that the page is well-formed.  It only shows that
30849 ** we failed to detect any corruption.
30850 */
30851 SQLITE_PRIVATE int sqlite3BtreeInitPage(
30852   MemPage *pPage,        /* The page to be initialized */
30853   MemPage *pParent       /* The parent.  Might be NULL */
30854 ){
30855   int pc;            /* Address of a freeblock within pPage->aData[] */
30856   int hdr;           /* Offset to beginning of page header */
30857   u8 *data;          /* Equal to pPage->aData */
30858   BtShared *pBt;        /* The main btree structure */
30859   int usableSize;    /* Amount of usable space on each page */
30860   int cellOffset;    /* Offset from start of page to first cell pointer */
30861   int nFree;         /* Number of unused bytes on the page */
30862   int top;           /* First byte of the cell content area */
30863
30864   pBt = pPage->pBt;
30865   assert( pBt!=0 );
30866   assert( pParent==0 || pParent->pBt==pBt );
30867   assert( sqlite3_mutex_held(pBt->mutex) );
30868   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
30869   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
30870   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
30871   if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
30872     /* The parent page should never change unless the file is corrupt */
30873     return SQLITE_CORRUPT_BKPT;
30874   }
30875   if( pPage->isInit ) return SQLITE_OK;
30876   if( pPage->pParent==0 && pParent!=0 ){
30877     pPage->pParent = pParent;
30878     sqlite3PagerRef(pParent->pDbPage);
30879   }
30880   hdr = pPage->hdrOffset;
30881   data = pPage->aData;
30882   decodeFlags(pPage, data[hdr]);
30883   pPage->nOverflow = 0;
30884   pPage->idxShift = 0;
30885   usableSize = pBt->usableSize;
30886   pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
30887   top = get2byte(&data[hdr+5]);
30888   pPage->nCell = get2byte(&data[hdr+3]);
30889   if( pPage->nCell>MX_CELL(pBt) ){
30890     /* To many cells for a single page.  The page must be corrupt */
30891     return SQLITE_CORRUPT_BKPT;
30892   }
30893   if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
30894     /* All pages must have at least one cell, except for root pages */
30895     return SQLITE_CORRUPT_BKPT;
30896   }
30897
30898   /* Compute the total free space on the page */
30899   pc = get2byte(&data[hdr+1]);
30900   nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
30901   while( pc>0 ){
30902     int next, size;
30903     if( pc>usableSize-4 ){
30904       /* Free block is off the page */
30905       return SQLITE_CORRUPT_BKPT; 
30906     }
30907     next = get2byte(&data[pc]);
30908     size = get2byte(&data[pc+2]);
30909     if( next>0 && next<=pc+size+3 ){
30910       /* Free blocks must be in accending order */
30911       return SQLITE_CORRUPT_BKPT; 
30912     }
30913     nFree += size;
30914     pc = next;
30915   }
30916   pPage->nFree = nFree;
30917   if( nFree>=usableSize ){
30918     /* Free space cannot exceed total page size */
30919     return SQLITE_CORRUPT_BKPT; 
30920   }
30921
30922   pPage->isInit = 1;
30923   return SQLITE_OK;
30924 }
30925
30926 /*
30927 ** Set up a raw page so that it looks like a database page holding
30928 ** no entries.
30929 */
30930 static void zeroPage(MemPage *pPage, int flags){
30931   unsigned char *data = pPage->aData;
30932   BtShared *pBt = pPage->pBt;
30933   int hdr = pPage->hdrOffset;
30934   int first;
30935
30936   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
30937   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
30938   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
30939   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
30940   assert( sqlite3_mutex_held(pBt->mutex) );
30941   memset(&data[hdr], 0, pBt->usableSize - hdr);
30942   data[hdr] = flags;
30943   first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
30944   memset(&data[hdr+1], 0, 4);
30945   data[hdr+7] = 0;
30946   put2byte(&data[hdr+5], pBt->usableSize);
30947   pPage->nFree = pBt->usableSize - first;
30948   decodeFlags(pPage, flags);
30949   pPage->hdrOffset = hdr;
30950   pPage->cellOffset = first;
30951   pPage->nOverflow = 0;
30952   pPage->idxShift = 0;
30953   pPage->nCell = 0;
30954   pPage->isInit = 1;
30955 }
30956
30957 /*
30958 ** Get a page from the pager.  Initialize the MemPage.pBt and
30959 ** MemPage.aData elements if needed.
30960 **
30961 ** If the noContent flag is set, it means that we do not care about
30962 ** the content of the page at this time.  So do not go to the disk
30963 ** to fetch the content.  Just fill in the content with zeros for now.
30964 ** If in the future we call sqlite3PagerWrite() on this page, that
30965 ** means we have started to be concerned about content and the disk
30966 ** read should occur at that point.
30967 */
30968 SQLITE_PRIVATE int sqlite3BtreeGetPage(
30969   BtShared *pBt,       /* The btree */
30970   Pgno pgno,           /* Number of the page to fetch */
30971   MemPage **ppPage,    /* Return the page in this parameter */
30972   int noContent        /* Do not load page content if true */
30973 ){
30974   int rc;
30975   MemPage *pPage;
30976   DbPage *pDbPage;
30977
30978   assert( sqlite3_mutex_held(pBt->mutex) );
30979   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
30980   if( rc ) return rc;
30981   pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
30982   pPage->aData = sqlite3PagerGetData(pDbPage);
30983   pPage->pDbPage = pDbPage;
30984   pPage->pBt = pBt;
30985   pPage->pgno = pgno;
30986   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
30987   *ppPage = pPage;
30988   return SQLITE_OK;
30989 }
30990
30991 /*
30992 ** Get a page from the pager and initialize it.  This routine
30993 ** is just a convenience wrapper around separate calls to
30994 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
30995 */
30996 static int getAndInitPage(
30997   BtShared *pBt,          /* The database file */
30998   Pgno pgno,           /* Number of the page to get */
30999   MemPage **ppPage,    /* Write the page pointer here */
31000   MemPage *pParent     /* Parent of the page */
31001 ){
31002   int rc;
31003   assert( sqlite3_mutex_held(pBt->mutex) );
31004   if( pgno==0 ){
31005     return SQLITE_CORRUPT_BKPT; 
31006   }
31007   rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
31008   if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
31009     rc = sqlite3BtreeInitPage(*ppPage, pParent);
31010     if( rc!=SQLITE_OK ){
31011       releasePage(*ppPage);
31012       *ppPage = 0;
31013     }
31014   }
31015   return rc;
31016 }
31017
31018 /*
31019 ** Release a MemPage.  This should be called once for each prior
31020 ** call to sqlite3BtreeGetPage.
31021 */
31022 static void releasePage(MemPage *pPage){
31023   if( pPage ){
31024     assert( pPage->aData );
31025     assert( pPage->pBt );
31026     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
31027     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
31028     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
31029     sqlite3PagerUnref(pPage->pDbPage);
31030   }
31031 }
31032
31033 /*
31034 ** This routine is called when the reference count for a page
31035 ** reaches zero.  We need to unref the pParent pointer when that
31036 ** happens.
31037 */
31038 static void pageDestructor(DbPage *pData, int pageSize){
31039   MemPage *pPage;
31040   assert( (pageSize & 7)==0 );
31041   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
31042   assert( pPage->isInit==0 || sqlite3_mutex_held(pPage->pBt->mutex) );
31043   if( pPage->pParent ){
31044     MemPage *pParent = pPage->pParent;
31045     assert( pParent->pBt==pPage->pBt );
31046     pPage->pParent = 0;
31047     releasePage(pParent);
31048   }
31049   pPage->isInit = 0;
31050 }
31051
31052 /*
31053 ** During a rollback, when the pager reloads information into the cache
31054 ** so that the cache is restored to its original state at the start of
31055 ** the transaction, for each page restored this routine is called.
31056 **
31057 ** This routine needs to reset the extra data section at the end of the
31058 ** page to agree with the restored data.
31059 */
31060 static void pageReinit(DbPage *pData, int pageSize){
31061   MemPage *pPage;
31062   assert( (pageSize & 7)==0 );
31063   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
31064   if( pPage->isInit ){
31065     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
31066     pPage->isInit = 0;
31067     sqlite3BtreeInitPage(pPage, pPage->pParent);
31068   }
31069 }
31070
31071 /*
31072 ** Invoke the busy handler for a btree.
31073 */
31074 static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
31075   BtShared *pBt = (BtShared*)pArg;
31076   assert( pBt->db );
31077   assert( sqlite3_mutex_held(pBt->db->mutex) );
31078   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
31079 }
31080
31081 /*
31082 ** Open a database file.
31083 ** 
31084 ** zFilename is the name of the database file.  If zFilename is NULL
31085 ** a new database with a random name is created.  This randomly named
31086 ** database file will be deleted when sqlite3BtreeClose() is called.
31087 ** If zFilename is ":memory:" then an in-memory database is created
31088 ** that is automatically destroyed when it is closed.
31089 */
31090 SQLITE_PRIVATE int sqlite3BtreeOpen(
31091   const char *zFilename,  /* Name of the file containing the BTree database */
31092   sqlite3 *db,            /* Associated database handle */
31093   Btree **ppBtree,        /* Pointer to new Btree object written here */
31094   int flags,              /* Options */
31095   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
31096 ){
31097   sqlite3_vfs *pVfs;      /* The VFS to use for this btree */
31098   BtShared *pBt = 0;      /* Shared part of btree structure */
31099   Btree *p;               /* Handle to return */
31100   int rc = SQLITE_OK;
31101   int nReserve;
31102   unsigned char zDbHeader[100];
31103
31104   /* Set the variable isMemdb to true for an in-memory database, or 
31105   ** false for a file-based database. This symbol is only required if
31106   ** either of the shared-data or autovacuum features are compiled 
31107   ** into the library.
31108   */
31109 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
31110   #ifdef SQLITE_OMIT_MEMORYDB
31111     const int isMemdb = 0;
31112   #else
31113     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
31114   #endif
31115 #endif
31116
31117   assert( db!=0 );
31118   assert( sqlite3_mutex_held(db->mutex) );
31119
31120   pVfs = db->pVfs;
31121   p = sqlite3MallocZero(sizeof(Btree));
31122   if( !p ){
31123     return SQLITE_NOMEM;
31124   }
31125   p->inTrans = TRANS_NONE;
31126   p->db = db;
31127
31128 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
31129   /*
31130   ** If this Btree is a candidate for shared cache, try to find an
31131   ** existing BtShared object that we can share with
31132   */
31133   if( (flags & BTREE_PRIVATE)==0
31134    && isMemdb==0
31135    && (db->flags & SQLITE_Vtab)==0
31136    && zFilename && zFilename[0]
31137   ){
31138     if( sqlite3SharedCacheEnabled ){
31139       int nFullPathname = pVfs->mxPathname+1;
31140       char *zFullPathname = (char *)sqlite3_malloc(nFullPathname);
31141       sqlite3_mutex *mutexShared;
31142       p->sharable = 1;
31143       if( db ){
31144         db->flags |= SQLITE_SharedCache;
31145       }
31146       if( !zFullPathname ){
31147         sqlite3_free(p);
31148         return SQLITE_NOMEM;
31149       }
31150       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
31151       mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
31152       sqlite3_mutex_enter(mutexShared);
31153       for(pBt=sqlite3SharedCacheList; pBt; pBt=pBt->pNext){
31154         assert( pBt->nRef>0 );
31155         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
31156                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
31157           p->pBt = pBt;
31158           pBt->nRef++;
31159           break;
31160         }
31161       }
31162       sqlite3_mutex_leave(mutexShared);
31163       sqlite3_free(zFullPathname);
31164     }
31165 #ifdef SQLITE_DEBUG
31166     else{
31167       /* In debug mode, we mark all persistent databases as sharable
31168       ** even when they are not.  This exercises the locking code and
31169       ** gives more opportunity for asserts(sqlite3_mutex_held())
31170       ** statements to find locking problems.
31171       */
31172       p->sharable = 1;
31173     }
31174 #endif
31175   }
31176 #endif
31177   if( pBt==0 ){
31178     /*
31179     ** The following asserts make sure that structures used by the btree are
31180     ** the right size.  This is to guard against size changes that result
31181     ** when compiling on a different architecture.
31182     */
31183     assert( sizeof(i64)==8 || sizeof(i64)==4 );
31184     assert( sizeof(u64)==8 || sizeof(u64)==4 );
31185     assert( sizeof(u32)==4 );
31186     assert( sizeof(u16)==2 );
31187     assert( sizeof(Pgno)==4 );
31188   
31189     pBt = sqlite3MallocZero( sizeof(*pBt) );
31190     if( pBt==0 ){
31191       rc = SQLITE_NOMEM;
31192       goto btree_open_out;
31193     }
31194     pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
31195     pBt->busyHdr.pArg = pBt;
31196     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
31197                           EXTRA_SIZE, flags, vfsFlags);
31198     if( rc==SQLITE_OK ){
31199       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
31200     }
31201     if( rc!=SQLITE_OK ){
31202       goto btree_open_out;
31203     }
31204     sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
31205     p->pBt = pBt;
31206   
31207     sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
31208     sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
31209     pBt->pCursor = 0;
31210     pBt->pPage1 = 0;
31211     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
31212     pBt->pageSize = get2byte(&zDbHeader[16]);
31213     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
31214          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
31215       pBt->pageSize = 0;
31216       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
31217       pBt->maxEmbedFrac = 64;   /* 25% */
31218       pBt->minEmbedFrac = 32;   /* 12.5% */
31219       pBt->minLeafFrac = 32;    /* 12.5% */
31220 #ifndef SQLITE_OMIT_AUTOVACUUM
31221       /* If the magic name ":memory:" will create an in-memory database, then
31222       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
31223       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
31224       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
31225       ** regular file-name. In this case the auto-vacuum applies as per normal.
31226       */
31227       if( zFilename && !isMemdb ){
31228         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
31229         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
31230       }
31231 #endif
31232       nReserve = 0;
31233     }else{
31234       nReserve = zDbHeader[20];
31235       pBt->maxEmbedFrac = zDbHeader[21];
31236       pBt->minEmbedFrac = zDbHeader[22];
31237       pBt->minLeafFrac = zDbHeader[23];
31238       pBt->pageSizeFixed = 1;
31239 #ifndef SQLITE_OMIT_AUTOVACUUM
31240       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
31241       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
31242 #endif
31243     }
31244     pBt->usableSize = pBt->pageSize - nReserve;
31245     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
31246     sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
31247    
31248 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
31249     /* Add the new BtShared object to the linked list sharable BtShareds.
31250     */
31251     if( p->sharable ){
31252       sqlite3_mutex *mutexShared;
31253       pBt->nRef = 1;
31254       mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
31255       if( SQLITE_THREADSAFE ){
31256         pBt->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
31257         if( pBt->mutex==0 ){
31258           rc = SQLITE_NOMEM;
31259           db->mallocFailed = 0;
31260           goto btree_open_out;
31261         }
31262       }
31263       sqlite3_mutex_enter(mutexShared);
31264       pBt->pNext = sqlite3SharedCacheList;
31265       sqlite3SharedCacheList = pBt;
31266       sqlite3_mutex_leave(mutexShared);
31267     }
31268 #endif
31269   }
31270
31271 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
31272   /* If the new Btree uses a sharable pBtShared, then link the new
31273   ** Btree into the list of all sharable Btrees for the same connection.
31274   ** The list is kept in ascending order by pBt address.
31275   */
31276   if( p->sharable ){
31277     int i;
31278     Btree *pSib;
31279     for(i=0; i<db->nDb; i++){
31280       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
31281         while( pSib->pPrev ){ pSib = pSib->pPrev; }
31282         if( p->pBt<pSib->pBt ){
31283           p->pNext = pSib;
31284           p->pPrev = 0;
31285           pSib->pPrev = p;
31286         }else{
31287           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
31288             pSib = pSib->pNext;
31289           }
31290           p->pNext = pSib->pNext;
31291           p->pPrev = pSib;
31292           if( p->pNext ){
31293             p->pNext->pPrev = p;
31294           }
31295           pSib->pNext = p;
31296         }
31297         break;
31298       }
31299     }
31300   }
31301 #endif
31302   *ppBtree = p;
31303
31304 btree_open_out:
31305   if( rc!=SQLITE_OK ){
31306     if( pBt && pBt->pPager ){
31307       sqlite3PagerClose(pBt->pPager);
31308     }
31309     sqlite3_free(pBt);
31310     sqlite3_free(p);
31311     *ppBtree = 0;
31312   }
31313   return rc;
31314 }
31315
31316 /*
31317 ** Decrement the BtShared.nRef counter.  When it reaches zero,
31318 ** remove the BtShared structure from the sharing list.  Return
31319 ** true if the BtShared.nRef counter reaches zero and return
31320 ** false if it is still positive.
31321 */
31322 static int removeFromSharingList(BtShared *pBt){
31323 #ifndef SQLITE_OMIT_SHARED_CACHE
31324   sqlite3_mutex *pMaster;
31325   BtShared *pList;
31326   int removed = 0;
31327
31328   assert( sqlite3_mutex_notheld(pBt->mutex) );
31329   pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
31330   sqlite3_mutex_enter(pMaster);
31331   pBt->nRef--;
31332   if( pBt->nRef<=0 ){
31333     if( sqlite3SharedCacheList==pBt ){
31334       sqlite3SharedCacheList = pBt->pNext;
31335     }else{
31336       pList = sqlite3SharedCacheList;
31337       while( pList && pList->pNext!=pBt ){
31338         pList=pList->pNext;
31339       }
31340       if( pList ){
31341         pList->pNext = pBt->pNext;
31342       }
31343     }
31344     if( SQLITE_THREADSAFE ){
31345       sqlite3_mutex_free(pBt->mutex);
31346     }
31347     removed = 1;
31348   }
31349   sqlite3_mutex_leave(pMaster);
31350   return removed;
31351 #else
31352   return 1;
31353 #endif
31354 }
31355
31356 /*
31357 ** Close an open database and invalidate all cursors.
31358 */
31359 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
31360   BtShared *pBt = p->pBt;
31361   BtCursor *pCur;
31362
31363   /* Close all cursors opened via this handle.  */
31364   assert( sqlite3_mutex_held(p->db->mutex) );
31365   sqlite3BtreeEnter(p);
31366   pBt->db = p->db;
31367   pCur = pBt->pCursor;
31368   while( pCur ){
31369     BtCursor *pTmp = pCur;
31370     pCur = pCur->pNext;
31371     if( pTmp->pBtree==p ){
31372       sqlite3BtreeCloseCursor(pTmp);
31373     }
31374   }
31375
31376   /* Rollback any active transaction and free the handle structure.
31377   ** The call to sqlite3BtreeRollback() drops any table-locks held by
31378   ** this handle.
31379   */
31380   sqlite3BtreeRollback(p);
31381   sqlite3BtreeLeave(p);
31382
31383   /* If there are still other outstanding references to the shared-btree
31384   ** structure, return now. The remainder of this procedure cleans 
31385   ** up the shared-btree.
31386   */
31387   assert( p->wantToLock==0 && p->locked==0 );
31388   if( !p->sharable || removeFromSharingList(pBt) ){
31389     /* The pBt is no longer on the sharing list, so we can access
31390     ** it without having to hold the mutex.
31391     **
31392     ** Clean out and delete the BtShared object.
31393     */
31394     assert( !pBt->pCursor );
31395     sqlite3PagerClose(pBt->pPager);
31396     if( pBt->xFreeSchema && pBt->pSchema ){
31397       pBt->xFreeSchema(pBt->pSchema);
31398     }
31399     sqlite3_free(pBt->pSchema);
31400     sqlite3_free(pBt->pTmpSpace);
31401     sqlite3_free(pBt);
31402   }
31403
31404 #ifndef SQLITE_OMIT_SHARED_CACHE
31405   assert( p->wantToLock==0 );
31406   assert( p->locked==0 );
31407   if( p->pPrev ) p->pPrev->pNext = p->pNext;
31408   if( p->pNext ) p->pNext->pPrev = p->pPrev;
31409 #endif
31410
31411   sqlite3_free(p);
31412   return SQLITE_OK;
31413 }
31414
31415 /*
31416 ** Change the limit on the number of pages allowed in the cache.
31417 **
31418 ** The maximum number of cache pages is set to the absolute
31419 ** value of mxPage.  If mxPage is negative, the pager will
31420 ** operate asynchronously - it will not stop to do fsync()s
31421 ** to insure data is written to the disk surface before
31422 ** continuing.  Transactions still work if synchronous is off,
31423 ** and the database cannot be corrupted if this program
31424 ** crashes.  But if the operating system crashes or there is
31425 ** an abrupt power failure when synchronous is off, the database
31426 ** could be left in an inconsistent and unrecoverable state.
31427 ** Synchronous is on by default so database corruption is not
31428 ** normally a worry.
31429 */
31430 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
31431   BtShared *pBt = p->pBt;
31432   assert( sqlite3_mutex_held(p->db->mutex) );
31433   sqlite3BtreeEnter(p);
31434   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
31435   sqlite3BtreeLeave(p);
31436   return SQLITE_OK;
31437 }
31438
31439 /*
31440 ** Change the way data is synced to disk in order to increase or decrease
31441 ** how well the database resists damage due to OS crashes and power
31442 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
31443 ** there is a high probability of damage)  Level 2 is the default.  There
31444 ** is a very low but non-zero probability of damage.  Level 3 reduces the
31445 ** probability of damage to near zero but with a write performance reduction.
31446 */
31447 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
31448 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
31449   BtShared *pBt = p->pBt;
31450   assert( sqlite3_mutex_held(p->db->mutex) );
31451   sqlite3BtreeEnter(p);
31452   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
31453   sqlite3BtreeLeave(p);
31454   return SQLITE_OK;
31455 }
31456 #endif
31457
31458 /*
31459 ** Return TRUE if the given btree is set to safety level 1.  In other
31460 ** words, return TRUE if no sync() occurs on the disk files.
31461 */
31462 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
31463   BtShared *pBt = p->pBt;
31464   int rc;
31465   assert( sqlite3_mutex_held(p->db->mutex) );  
31466   sqlite3BtreeEnter(p);
31467   assert( pBt && pBt->pPager );
31468   rc = sqlite3PagerNosync(pBt->pPager);
31469   sqlite3BtreeLeave(p);
31470   return rc;
31471 }
31472
31473 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
31474 /*
31475 ** Change the default pages size and the number of reserved bytes per page.
31476 **
31477 ** The page size must be a power of 2 between 512 and 65536.  If the page
31478 ** size supplied does not meet this constraint then the page size is not
31479 ** changed.
31480 **
31481 ** Page sizes are constrained to be a power of two so that the region
31482 ** of the database file used for locking (beginning at PENDING_BYTE,
31483 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
31484 ** at the beginning of a page.
31485 **
31486 ** If parameter nReserve is less than zero, then the number of reserved
31487 ** bytes per page is left unchanged.
31488 */
31489 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
31490   int rc = SQLITE_OK;
31491   BtShared *pBt = p->pBt;
31492   sqlite3BtreeEnter(p);
31493   if( pBt->pageSizeFixed ){
31494     sqlite3BtreeLeave(p);
31495     return SQLITE_READONLY;
31496   }
31497   if( nReserve<0 ){
31498     nReserve = pBt->pageSize - pBt->usableSize;
31499   }
31500   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
31501         ((pageSize-1)&pageSize)==0 ){
31502     assert( (pageSize & 7)==0 );
31503     assert( !pBt->pPage1 && !pBt->pCursor );
31504     pBt->pageSize = pageSize;
31505     sqlite3_free(pBt->pTmpSpace);
31506     pBt->pTmpSpace = 0;
31507     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
31508   }
31509   pBt->usableSize = pBt->pageSize - nReserve;
31510   sqlite3BtreeLeave(p);
31511   return rc;
31512 }
31513
31514 /*
31515 ** Return the currently defined page size
31516 */
31517 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
31518   return p->pBt->pageSize;
31519 }
31520 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
31521   int n;
31522   sqlite3BtreeEnter(p);
31523   n = p->pBt->pageSize - p->pBt->usableSize;
31524   sqlite3BtreeLeave(p);
31525   return n;
31526 }
31527
31528 /*
31529 ** Set the maximum page count for a database if mxPage is positive.
31530 ** No changes are made if mxPage is 0 or negative.
31531 ** Regardless of the value of mxPage, return the maximum page count.
31532 */
31533 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
31534   int n;
31535   sqlite3BtreeEnter(p);
31536   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
31537   sqlite3BtreeLeave(p);
31538   return n;
31539 }
31540 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
31541
31542 /*
31543 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
31544 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
31545 ** is disabled. The default value for the auto-vacuum property is 
31546 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
31547 */
31548 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
31549 #ifdef SQLITE_OMIT_AUTOVACUUM
31550   return SQLITE_READONLY;
31551 #else
31552   BtShared *pBt = p->pBt;
31553   int rc = SQLITE_OK;
31554   int av = (autoVacuum?1:0);
31555
31556   sqlite3BtreeEnter(p);
31557   if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
31558     rc = SQLITE_READONLY;
31559   }else{
31560     pBt->autoVacuum = av;
31561   }
31562   sqlite3BtreeLeave(p);
31563   return rc;
31564 #endif
31565 }
31566
31567 /*
31568 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
31569 ** enabled 1 is returned. Otherwise 0.
31570 */
31571 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
31572 #ifdef SQLITE_OMIT_AUTOVACUUM
31573   return BTREE_AUTOVACUUM_NONE;
31574 #else
31575   int rc;
31576   sqlite3BtreeEnter(p);
31577   rc = (
31578     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
31579     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
31580     BTREE_AUTOVACUUM_INCR
31581   );
31582   sqlite3BtreeLeave(p);
31583   return rc;
31584 #endif
31585 }
31586
31587
31588 /*
31589 ** Get a reference to pPage1 of the database file.  This will
31590 ** also acquire a readlock on that file.
31591 **
31592 ** SQLITE_OK is returned on success.  If the file is not a
31593 ** well-formed database file, then SQLITE_CORRUPT is returned.
31594 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
31595 ** is returned if we run out of memory. 
31596 */
31597 static int lockBtree(BtShared *pBt){
31598   int rc;
31599   MemPage *pPage1;
31600   int nPage;
31601
31602   assert( sqlite3_mutex_held(pBt->mutex) );
31603   if( pBt->pPage1 ) return SQLITE_OK;
31604   rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
31605   if( rc!=SQLITE_OK ) return rc;
31606
31607   /* Do some checking to help insure the file we opened really is
31608   ** a valid database file. 
31609   */
31610   rc = SQLITE_NOTADB;
31611   nPage = sqlite3PagerPagecount(pBt->pPager);
31612   if( nPage<0 ){
31613     rc = SQLITE_IOERR;
31614     goto page1_init_failed;
31615   }else if( nPage>0 ){
31616     int pageSize;
31617     int usableSize;
31618     u8 *page1 = pPage1->aData;
31619     if( memcmp(page1, zMagicHeader, 16)!=0 ){
31620       goto page1_init_failed;
31621     }
31622     if( page1[18]>1 ){
31623       pBt->readOnly = 1;
31624     }
31625     if( page1[19]>1 ){
31626       goto page1_init_failed;
31627     }
31628     pageSize = get2byte(&page1[16]);
31629     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
31630         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
31631     ){
31632       goto page1_init_failed;
31633     }
31634     assert( (pageSize & 7)==0 );
31635     usableSize = pageSize - page1[20];
31636     if( pageSize!=pBt->pageSize ){
31637       /* After reading the first page of the database assuming a page size
31638       ** of BtShared.pageSize, we have discovered that the page-size is
31639       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
31640       ** zero and return SQLITE_OK. The caller will call this function
31641       ** again with the correct page-size.
31642       */
31643       releasePage(pPage1);
31644       pBt->usableSize = usableSize;
31645       pBt->pageSize = pageSize;
31646       sqlite3_free(pBt->pTmpSpace);
31647       pBt->pTmpSpace = 0;
31648       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
31649       return SQLITE_OK;
31650     }
31651     if( usableSize<500 ){
31652       goto page1_init_failed;
31653     }
31654     pBt->pageSize = pageSize;
31655     pBt->usableSize = usableSize;
31656     pBt->maxEmbedFrac = page1[21];
31657     pBt->minEmbedFrac = page1[22];
31658     pBt->minLeafFrac = page1[23];
31659 #ifndef SQLITE_OMIT_AUTOVACUUM
31660     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
31661     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
31662 #endif
31663   }
31664
31665   /* maxLocal is the maximum amount of payload to store locally for
31666   ** a cell.  Make sure it is small enough so that at least minFanout
31667   ** cells can will fit on one page.  We assume a 10-byte page header.
31668   ** Besides the payload, the cell must store:
31669   **     2-byte pointer to the cell
31670   **     4-byte child pointer
31671   **     9-byte nKey value
31672   **     4-byte nData value
31673   **     4-byte overflow page pointer
31674   ** So a cell consists of a 2-byte poiner, a header which is as much as
31675   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
31676   ** page pointer.
31677   */
31678   pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
31679   pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
31680   pBt->maxLeaf = pBt->usableSize - 35;
31681   pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
31682   if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
31683     goto page1_init_failed;
31684   }
31685   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
31686   pBt->pPage1 = pPage1;
31687   return SQLITE_OK;
31688
31689 page1_init_failed:
31690   releasePage(pPage1);
31691   pBt->pPage1 = 0;
31692   return rc;
31693 }
31694
31695 /*
31696 ** This routine works like lockBtree() except that it also invokes the
31697 ** busy callback if there is lock contention.
31698 */
31699 static int lockBtreeWithRetry(Btree *pRef){
31700   int rc = SQLITE_OK;
31701
31702   assert( sqlite3BtreeHoldsMutex(pRef) );
31703   if( pRef->inTrans==TRANS_NONE ){
31704     u8 inTransaction = pRef->pBt->inTransaction;
31705     btreeIntegrity(pRef);
31706     rc = sqlite3BtreeBeginTrans(pRef, 0);
31707     pRef->pBt->inTransaction = inTransaction;
31708     pRef->inTrans = TRANS_NONE;
31709     if( rc==SQLITE_OK ){
31710       pRef->pBt->nTransaction--;
31711     }
31712     btreeIntegrity(pRef);
31713   }
31714   return rc;
31715 }
31716        
31717
31718 /*
31719 ** If there are no outstanding cursors and we are not in the middle
31720 ** of a transaction but there is a read lock on the database, then
31721 ** this routine unrefs the first page of the database file which 
31722 ** has the effect of releasing the read lock.
31723 **
31724 ** If there are any outstanding cursors, this routine is a no-op.
31725 **
31726 ** If there is a transaction in progress, this routine is a no-op.
31727 */
31728 static void unlockBtreeIfUnused(BtShared *pBt){
31729   assert( sqlite3_mutex_held(pBt->mutex) );
31730   if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
31731     if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
31732       assert( pBt->pPage1->aData );
31733 #if 0
31734       if( pBt->pPage1->aData==0 ){
31735         MemPage *pPage = pBt->pPage1;
31736         pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
31737         pPage->pBt = pBt;
31738         pPage->pgno = 1;
31739       }
31740 #endif
31741       releasePage(pBt->pPage1);
31742     }
31743     pBt->pPage1 = 0;
31744     pBt->inStmt = 0;
31745   }
31746 }
31747
31748 /*
31749 ** Create a new database by initializing the first page of the
31750 ** file.
31751 */
31752 static int newDatabase(BtShared *pBt){
31753   MemPage *pP1;
31754   unsigned char *data;
31755   int rc;
31756
31757   assert( sqlite3_mutex_held(pBt->mutex) );
31758   if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
31759   pP1 = pBt->pPage1;
31760   assert( pP1!=0 );
31761   data = pP1->aData;
31762   rc = sqlite3PagerWrite(pP1->pDbPage);
31763   if( rc ) return rc;
31764   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
31765   assert( sizeof(zMagicHeader)==16 );
31766   put2byte(&data[16], pBt->pageSize);
31767   data[18] = 1;
31768   data[19] = 1;
31769   data[20] = pBt->pageSize - pBt->usableSize;
31770   data[21] = pBt->maxEmbedFrac;
31771   data[22] = pBt->minEmbedFrac;
31772   data[23] = pBt->minLeafFrac;
31773   memset(&data[24], 0, 100-24);
31774   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
31775   pBt->pageSizeFixed = 1;
31776 #ifndef SQLITE_OMIT_AUTOVACUUM
31777   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
31778   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
31779   put4byte(&data[36 + 4*4], pBt->autoVacuum);
31780   put4byte(&data[36 + 7*4], pBt->incrVacuum);
31781 #endif
31782   return SQLITE_OK;
31783 }
31784
31785 /*
31786 ** Attempt to start a new transaction. A write-transaction
31787 ** is started if the second argument is nonzero, otherwise a read-
31788 ** transaction.  If the second argument is 2 or more and exclusive
31789 ** transaction is started, meaning that no other process is allowed
31790 ** to access the database.  A preexisting transaction may not be
31791 ** upgraded to exclusive by calling this routine a second time - the
31792 ** exclusivity flag only works for a new transaction.
31793 **
31794 ** A write-transaction must be started before attempting any 
31795 ** changes to the database.  None of the following routines 
31796 ** will work unless a transaction is started first:
31797 **
31798 **      sqlite3BtreeCreateTable()
31799 **      sqlite3BtreeCreateIndex()
31800 **      sqlite3BtreeClearTable()
31801 **      sqlite3BtreeDropTable()
31802 **      sqlite3BtreeInsert()
31803 **      sqlite3BtreeDelete()
31804 **      sqlite3BtreeUpdateMeta()
31805 **
31806 ** If an initial attempt to acquire the lock fails because of lock contention
31807 ** and the database was previously unlocked, then invoke the busy handler
31808 ** if there is one.  But if there was previously a read-lock, do not
31809 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
31810 ** returned when there is already a read-lock in order to avoid a deadlock.
31811 **
31812 ** Suppose there are two processes A and B.  A has a read lock and B has
31813 ** a reserved lock.  B tries to promote to exclusive but is blocked because
31814 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
31815 ** One or the other of the two processes must give way or there can be
31816 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
31817 ** when A already has a read lock, we encourage A to give up and let B
31818 ** proceed.
31819 */
31820 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
31821   BtShared *pBt = p->pBt;
31822   int rc = SQLITE_OK;
31823
31824   sqlite3BtreeEnter(p);
31825   pBt->db = p->db;
31826   btreeIntegrity(p);
31827
31828   /* If the btree is already in a write-transaction, or it
31829   ** is already in a read-transaction and a read-transaction
31830   ** is requested, this is a no-op.
31831   */
31832   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
31833     goto trans_begun;
31834   }
31835
31836   /* Write transactions are not possible on a read-only database */
31837   if( pBt->readOnly && wrflag ){
31838     rc = SQLITE_READONLY;
31839     goto trans_begun;
31840   }
31841
31842   /* If another database handle has already opened a write transaction 
31843   ** on this shared-btree structure and a second write transaction is
31844   ** requested, return SQLITE_BUSY.
31845   */
31846   if( pBt->inTransaction==TRANS_WRITE && wrflag ){
31847     rc = SQLITE_BUSY;
31848     goto trans_begun;
31849   }
31850
31851 #ifndef SQLITE_OMIT_SHARED_CACHE
31852   if( wrflag>1 ){
31853     BtLock *pIter;
31854     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
31855       if( pIter->pBtree!=p ){
31856         rc = SQLITE_BUSY;
31857         goto trans_begun;
31858       }
31859     }
31860   }
31861 #endif
31862
31863   do {
31864     if( pBt->pPage1==0 ){
31865       do{
31866         rc = lockBtree(pBt);
31867       }while( pBt->pPage1==0 && rc==SQLITE_OK );
31868     }
31869
31870     if( rc==SQLITE_OK && wrflag ){
31871       if( pBt->readOnly ){
31872         rc = SQLITE_READONLY;
31873       }else{
31874         rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
31875         if( rc==SQLITE_OK ){
31876           rc = newDatabase(pBt);
31877         }
31878       }
31879     }
31880   
31881     if( rc==SQLITE_OK ){
31882       if( wrflag ) pBt->inStmt = 0;
31883     }else{
31884       unlockBtreeIfUnused(pBt);
31885     }
31886   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
31887           sqlite3BtreeInvokeBusyHandler(pBt, 0) );
31888
31889   if( rc==SQLITE_OK ){
31890     if( p->inTrans==TRANS_NONE ){
31891       pBt->nTransaction++;
31892     }
31893     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
31894     if( p->inTrans>pBt->inTransaction ){
31895       pBt->inTransaction = p->inTrans;
31896     }
31897 #ifndef SQLITE_OMIT_SHARED_CACHE
31898     if( wrflag>1 ){
31899       assert( !pBt->pExclusive );
31900       pBt->pExclusive = p;
31901     }
31902 #endif
31903   }
31904
31905
31906 trans_begun:
31907   btreeIntegrity(p);
31908   sqlite3BtreeLeave(p);
31909   return rc;
31910 }
31911
31912 #ifndef SQLITE_OMIT_AUTOVACUUM
31913
31914 /*
31915 ** Set the pointer-map entries for all children of page pPage. Also, if
31916 ** pPage contains cells that point to overflow pages, set the pointer
31917 ** map entries for the overflow pages as well.
31918 */
31919 static int setChildPtrmaps(MemPage *pPage){
31920   int i;                             /* Counter variable */
31921   int nCell;                         /* Number of cells in page pPage */
31922   int rc;                            /* Return code */
31923   BtShared *pBt = pPage->pBt;
31924   int isInitOrig = pPage->isInit;
31925   Pgno pgno = pPage->pgno;
31926
31927   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
31928   rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
31929   if( rc!=SQLITE_OK ){
31930     goto set_child_ptrmaps_out;
31931   }
31932   nCell = pPage->nCell;
31933
31934   for(i=0; i<nCell; i++){
31935     u8 *pCell = findCell(pPage, i);
31936
31937     rc = ptrmapPutOvflPtr(pPage, pCell);
31938     if( rc!=SQLITE_OK ){
31939       goto set_child_ptrmaps_out;
31940     }
31941
31942     if( !pPage->leaf ){
31943       Pgno childPgno = get4byte(pCell);
31944       rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
31945       if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
31946     }
31947   }
31948
31949   if( !pPage->leaf ){
31950     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
31951     rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
31952   }
31953
31954 set_child_ptrmaps_out:
31955   pPage->isInit = isInitOrig;
31956   return rc;
31957 }
31958
31959 /*
31960 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
31961 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
31962 ** iTo. Parameter eType describes the type of pointer to be modified, as 
31963 ** follows:
31964 **
31965 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
31966 **                   page of pPage.
31967 **
31968 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
31969 **                   page pointed to by one of the cells on pPage.
31970 **
31971 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
31972 **                   overflow page in the list.
31973 */
31974 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
31975   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
31976   if( eType==PTRMAP_OVERFLOW2 ){
31977     /* The pointer is always the first 4 bytes of the page in this case.  */
31978     if( get4byte(pPage->aData)!=iFrom ){
31979       return SQLITE_CORRUPT_BKPT;
31980     }
31981     put4byte(pPage->aData, iTo);
31982   }else{
31983     int isInitOrig = pPage->isInit;
31984     int i;
31985     int nCell;
31986
31987     sqlite3BtreeInitPage(pPage, 0);
31988     nCell = pPage->nCell;
31989
31990     for(i=0; i<nCell; i++){
31991       u8 *pCell = findCell(pPage, i);
31992       if( eType==PTRMAP_OVERFLOW1 ){
31993         CellInfo info;
31994         sqlite3BtreeParseCellPtr(pPage, pCell, &info);
31995         if( info.iOverflow ){
31996           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
31997             put4byte(&pCell[info.iOverflow], iTo);
31998             break;
31999           }
32000         }
32001       }else{
32002         if( get4byte(pCell)==iFrom ){
32003           put4byte(pCell, iTo);
32004           break;
32005         }
32006       }
32007     }
32008   
32009     if( i==nCell ){
32010       if( eType!=PTRMAP_BTREE || 
32011           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
32012         return SQLITE_CORRUPT_BKPT;
32013       }
32014       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
32015     }
32016
32017     pPage->isInit = isInitOrig;
32018   }
32019   return SQLITE_OK;
32020 }
32021
32022
32023 /*
32024 ** Move the open database page pDbPage to location iFreePage in the 
32025 ** database. The pDbPage reference remains valid.
32026 */
32027 static int relocatePage(
32028   BtShared *pBt,           /* Btree */
32029   MemPage *pDbPage,        /* Open page to move */
32030   u8 eType,                /* Pointer map 'type' entry for pDbPage */
32031   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
32032   Pgno iFreePage           /* The location to move pDbPage to */
32033 ){
32034   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
32035   Pgno iDbPage = pDbPage->pgno;
32036   Pager *pPager = pBt->pPager;
32037   int rc;
32038
32039   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
32040       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
32041   assert( sqlite3_mutex_held(pBt->mutex) );
32042   assert( pDbPage->pBt==pBt );
32043
32044   /* Move page iDbPage from its current location to page number iFreePage */
32045   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
32046       iDbPage, iFreePage, iPtrPage, eType));
32047   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
32048   if( rc!=SQLITE_OK ){
32049     return rc;
32050   }
32051   pDbPage->pgno = iFreePage;
32052
32053   /* If pDbPage was a btree-page, then it may have child pages and/or cells
32054   ** that point to overflow pages. The pointer map entries for all these
32055   ** pages need to be changed.
32056   **
32057   ** If pDbPage is an overflow page, then the first 4 bytes may store a
32058   ** pointer to a subsequent overflow page. If this is the case, then
32059   ** the pointer map needs to be updated for the subsequent overflow page.
32060   */
32061   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
32062     rc = setChildPtrmaps(pDbPage);
32063     if( rc!=SQLITE_OK ){
32064       return rc;
32065     }
32066   }else{
32067     Pgno nextOvfl = get4byte(pDbPage->aData);
32068     if( nextOvfl!=0 ){
32069       rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
32070       if( rc!=SQLITE_OK ){
32071         return rc;
32072       }
32073     }
32074   }
32075
32076   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
32077   ** that it points at iFreePage. Also fix the pointer map entry for
32078   ** iPtrPage.
32079   */
32080   if( eType!=PTRMAP_ROOTPAGE ){
32081     rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
32082     if( rc!=SQLITE_OK ){
32083       return rc;
32084     }
32085     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
32086     if( rc!=SQLITE_OK ){
32087       releasePage(pPtrPage);
32088       return rc;
32089     }
32090     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
32091     releasePage(pPtrPage);
32092     if( rc==SQLITE_OK ){
32093       rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
32094     }
32095   }
32096   return rc;
32097 }
32098
32099 /* Forward declaration required by incrVacuumStep(). */
32100 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
32101
32102 /*
32103 ** Perform a single step of an incremental-vacuum. If successful,
32104 ** return SQLITE_OK. If there is no work to do (and therefore no
32105 ** point in calling this function again), return SQLITE_DONE.
32106 **
32107 ** More specificly, this function attempts to re-organize the 
32108 ** database so that the last page of the file currently in use
32109 ** is no longer in use.
32110 **
32111 ** If the nFin parameter is non-zero, the implementation assumes
32112 ** that the caller will keep calling incrVacuumStep() until
32113 ** it returns SQLITE_DONE or an error, and that nFin is the
32114 ** number of pages the database file will contain after this 
32115 ** process is complete.
32116 */
32117 static int incrVacuumStep(BtShared *pBt, Pgno nFin){
32118   Pgno iLastPg;             /* Last page in the database */
32119   Pgno nFreeList;           /* Number of pages still on the free-list */
32120
32121   assert( sqlite3_mutex_held(pBt->mutex) );
32122   iLastPg = pBt->nTrunc;
32123   if( iLastPg==0 ){
32124     iLastPg = sqlite3PagerPagecount(pBt->pPager);
32125   }
32126
32127   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
32128     int rc;
32129     u8 eType;
32130     Pgno iPtrPage;
32131
32132     nFreeList = get4byte(&pBt->pPage1->aData[36]);
32133     if( nFreeList==0 || nFin==iLastPg ){
32134       return SQLITE_DONE;
32135     }
32136
32137     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
32138     if( rc!=SQLITE_OK ){
32139       return rc;
32140     }
32141     if( eType==PTRMAP_ROOTPAGE ){
32142       return SQLITE_CORRUPT_BKPT;
32143     }
32144
32145     if( eType==PTRMAP_FREEPAGE ){
32146       if( nFin==0 ){
32147         /* Remove the page from the files free-list. This is not required
32148         ** if nFin is non-zero. In that case, the free-list will be
32149         ** truncated to zero after this function returns, so it doesn't 
32150         ** matter if it still contains some garbage entries.
32151         */
32152         Pgno iFreePg;
32153         MemPage *pFreePg;
32154         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
32155         if( rc!=SQLITE_OK ){
32156           return rc;
32157         }
32158         assert( iFreePg==iLastPg );
32159         releasePage(pFreePg);
32160       }
32161     } else {
32162       Pgno iFreePg;             /* Index of free page to move pLastPg to */
32163       MemPage *pLastPg;
32164
32165       rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
32166       if( rc!=SQLITE_OK ){
32167         return rc;
32168       }
32169
32170       /* If nFin is zero, this loop runs exactly once and page pLastPg
32171       ** is swapped with the first free page pulled off the free list.
32172       **
32173       ** On the other hand, if nFin is greater than zero, then keep
32174       ** looping until a free-page located within the first nFin pages
32175       ** of the file is found.
32176       */
32177       do {
32178         MemPage *pFreePg;
32179         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
32180         if( rc!=SQLITE_OK ){
32181           releasePage(pLastPg);
32182           return rc;
32183         }
32184         releasePage(pFreePg);
32185       }while( nFin!=0 && iFreePg>nFin );
32186       assert( iFreePg<iLastPg );
32187       
32188       rc = sqlite3PagerWrite(pLastPg->pDbPage);
32189       if( rc==SQLITE_OK ){
32190         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
32191       }
32192       releasePage(pLastPg);
32193       if( rc!=SQLITE_OK ){
32194         return rc;
32195       }
32196     }
32197   }
32198
32199   pBt->nTrunc = iLastPg - 1;
32200   while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
32201     pBt->nTrunc--;
32202   }
32203   return SQLITE_OK;
32204 }
32205
32206 /*
32207 ** A write-transaction must be opened before calling this function.
32208 ** It performs a single unit of work towards an incremental vacuum.
32209 **
32210 ** If the incremental vacuum is finished after this function has run,
32211 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
32212 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
32213 */
32214 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
32215   int rc;
32216   BtShared *pBt = p->pBt;
32217
32218   sqlite3BtreeEnter(p);
32219   pBt->db = p->db;
32220   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
32221   if( !pBt->autoVacuum ){
32222     rc = SQLITE_DONE;
32223   }else{
32224     invalidateAllOverflowCache(pBt);
32225     rc = incrVacuumStep(pBt, 0);
32226   }
32227   sqlite3BtreeLeave(p);
32228   return rc;
32229 }
32230
32231 /*
32232 ** This routine is called prior to sqlite3PagerCommit when a transaction
32233 ** is commited for an auto-vacuum database.
32234 **
32235 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
32236 ** the database file should be truncated to during the commit process. 
32237 ** i.e. the database has been reorganized so that only the first *pnTrunc
32238 ** pages are in use.
32239 */
32240 static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
32241   int rc = SQLITE_OK;
32242   Pager *pPager = pBt->pPager;
32243 #ifndef NDEBUG
32244   int nRef = sqlite3PagerRefcount(pPager);
32245 #endif
32246
32247   assert( sqlite3_mutex_held(pBt->mutex) );
32248   invalidateAllOverflowCache(pBt);
32249   assert(pBt->autoVacuum);
32250   if( !pBt->incrVacuum ){
32251     Pgno nFin = 0;
32252
32253     if( pBt->nTrunc==0 ){
32254       Pgno nFree;
32255       Pgno nPtrmap;
32256       const int pgsz = pBt->pageSize;
32257       Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
32258
32259       if( PTRMAP_ISPAGE(pBt, nOrig) ){
32260         return SQLITE_CORRUPT_BKPT;
32261       }
32262       if( nOrig==PENDING_BYTE_PAGE(pBt) ){
32263         nOrig--;
32264       }
32265       nFree = get4byte(&pBt->pPage1->aData[36]);
32266       nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
32267       nFin = nOrig - nFree - nPtrmap;
32268       if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
32269         nFin--;
32270       }
32271       while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
32272         nFin--;
32273       }
32274     }
32275
32276     while( rc==SQLITE_OK ){
32277       rc = incrVacuumStep(pBt, nFin);
32278     }
32279     if( rc==SQLITE_DONE ){
32280       assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
32281       rc = SQLITE_OK;
32282       if( pBt->nTrunc && nFin ){
32283         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
32284         put4byte(&pBt->pPage1->aData[32], 0);
32285         put4byte(&pBt->pPage1->aData[36], 0);
32286         pBt->nTrunc = nFin;
32287       }
32288     }
32289     if( rc!=SQLITE_OK ){
32290       sqlite3PagerRollback(pPager);
32291     }
32292   }
32293
32294   if( rc==SQLITE_OK ){
32295     *pnTrunc = pBt->nTrunc;
32296     pBt->nTrunc = 0;
32297   }
32298   assert( nRef==sqlite3PagerRefcount(pPager) );
32299   return rc;
32300 }
32301
32302 #endif
32303
32304 /*
32305 ** This routine does the first phase of a two-phase commit.  This routine
32306 ** causes a rollback journal to be created (if it does not already exist)
32307 ** and populated with enough information so that if a power loss occurs
32308 ** the database can be restored to its original state by playing back
32309 ** the journal.  Then the contents of the journal are flushed out to
32310 ** the disk.  After the journal is safely on oxide, the changes to the
32311 ** database are written into the database file and flushed to oxide.
32312 ** At the end of this call, the rollback journal still exists on the
32313 ** disk and we are still holding all locks, so the transaction has not
32314 ** committed.  See sqlite3BtreeCommit() for the second phase of the
32315 ** commit process.
32316 **
32317 ** This call is a no-op if no write-transaction is currently active on pBt.
32318 **
32319 ** Otherwise, sync the database file for the btree pBt. zMaster points to
32320 ** the name of a master journal file that should be written into the
32321 ** individual journal file, or is NULL, indicating no master journal file 
32322 ** (single database transaction).
32323 **
32324 ** When this is called, the master journal should already have been
32325 ** created, populated with this journal pointer and synced to disk.
32326 **
32327 ** Once this is routine has returned, the only thing required to commit
32328 ** the write-transaction for this database file is to delete the journal.
32329 */
32330 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
32331   int rc = SQLITE_OK;
32332   if( p->inTrans==TRANS_WRITE ){
32333     BtShared *pBt = p->pBt;
32334     Pgno nTrunc = 0;
32335     sqlite3BtreeEnter(p);
32336     pBt->db = p->db;
32337 #ifndef SQLITE_OMIT_AUTOVACUUM
32338     if( pBt->autoVacuum ){
32339       rc = autoVacuumCommit(pBt, &nTrunc); 
32340       if( rc!=SQLITE_OK ){
32341         sqlite3BtreeLeave(p);
32342         return rc;
32343       }
32344     }
32345 #endif
32346     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
32347     sqlite3BtreeLeave(p);
32348   }
32349   return rc;
32350 }
32351
32352 /*
32353 ** Commit the transaction currently in progress.
32354 **
32355 ** This routine implements the second phase of a 2-phase commit.  The
32356 ** sqlite3BtreeSync() routine does the first phase and should be invoked
32357 ** prior to calling this routine.  The sqlite3BtreeSync() routine did
32358 ** all the work of writing information out to disk and flushing the
32359 ** contents so that they are written onto the disk platter.  All this
32360 ** routine has to do is delete or truncate the rollback journal
32361 ** (which causes the transaction to commit) and drop locks.
32362 **
32363 ** This will release the write lock on the database file.  If there
32364 ** are no active cursors, it also releases the read lock.
32365 */
32366 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
32367   BtShared *pBt = p->pBt;
32368
32369   sqlite3BtreeEnter(p);
32370   pBt->db = p->db;
32371   btreeIntegrity(p);
32372
32373   /* If the handle has a write-transaction open, commit the shared-btrees 
32374   ** transaction and set the shared state to TRANS_READ.
32375   */
32376   if( p->inTrans==TRANS_WRITE ){
32377     int rc;
32378     assert( pBt->inTransaction==TRANS_WRITE );
32379     assert( pBt->nTransaction>0 );
32380     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
32381     if( rc!=SQLITE_OK ){
32382       sqlite3BtreeLeave(p);
32383       return rc;
32384     }
32385     pBt->inTransaction = TRANS_READ;
32386     pBt->inStmt = 0;
32387   }
32388   unlockAllTables(p);
32389
32390   /* If the handle has any kind of transaction open, decrement the transaction
32391   ** count of the shared btree. If the transaction count reaches 0, set
32392   ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
32393   ** will unlock the pager.
32394   */
32395   if( p->inTrans!=TRANS_NONE ){
32396     pBt->nTransaction--;
32397     if( 0==pBt->nTransaction ){
32398       pBt->inTransaction = TRANS_NONE;
32399     }
32400   }
32401
32402   /* Set the handles current transaction state to TRANS_NONE and unlock
32403   ** the pager if this call closed the only read or write transaction.
32404   */
32405   p->inTrans = TRANS_NONE;
32406   unlockBtreeIfUnused(pBt);
32407
32408   btreeIntegrity(p);
32409   sqlite3BtreeLeave(p);
32410   return SQLITE_OK;
32411 }
32412
32413 /*
32414 ** Do both phases of a commit.
32415 */
32416 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
32417   int rc;
32418   sqlite3BtreeEnter(p);
32419   rc = sqlite3BtreeCommitPhaseOne(p, 0);
32420   if( rc==SQLITE_OK ){
32421     rc = sqlite3BtreeCommitPhaseTwo(p);
32422   }
32423   sqlite3BtreeLeave(p);
32424   return rc;
32425 }
32426
32427 #ifndef NDEBUG
32428 /*
32429 ** Return the number of write-cursors open on this handle. This is for use
32430 ** in assert() expressions, so it is only compiled if NDEBUG is not
32431 ** defined.
32432 **
32433 ** For the purposes of this routine, a write-cursor is any cursor that
32434 ** is capable of writing to the databse.  That means the cursor was
32435 ** originally opened for writing and the cursor has not be disabled
32436 ** by having its state changed to CURSOR_FAULT.
32437 */
32438 static int countWriteCursors(BtShared *pBt){
32439   BtCursor *pCur;
32440   int r = 0;
32441   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
32442     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
32443   }
32444   return r;
32445 }
32446 #endif
32447
32448 /*
32449 ** This routine sets the state to CURSOR_FAULT and the error
32450 ** code to errCode for every cursor on BtShared that pBtree
32451 ** references.
32452 **
32453 ** Every cursor is tripped, including cursors that belong
32454 ** to other database connections that happen to be sharing
32455 ** the cache with pBtree.
32456 **
32457 ** This routine gets called when a rollback occurs.
32458 ** All cursors using the same cache must be tripped
32459 ** to prevent them from trying to use the btree after
32460 ** the rollback.  The rollback may have deleted tables
32461 ** or moved root pages, so it is not sufficient to
32462 ** save the state of the cursor.  The cursor must be
32463 ** invalidated.
32464 */
32465 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
32466   BtCursor *p;
32467   sqlite3BtreeEnter(pBtree);
32468   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
32469     clearCursorPosition(p);
32470     p->eState = CURSOR_FAULT;
32471     p->skip = errCode;
32472   }
32473   sqlite3BtreeLeave(pBtree);
32474 }
32475
32476 /*
32477 ** Rollback the transaction in progress.  All cursors will be
32478 ** invalided by this operation.  Any attempt to use a cursor
32479 ** that was open at the beginning of this operation will result
32480 ** in an error.
32481 **
32482 ** This will release the write lock on the database file.  If there
32483 ** are no active cursors, it also releases the read lock.
32484 */
32485 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
32486   int rc;
32487   BtShared *pBt = p->pBt;
32488   MemPage *pPage1;
32489
32490   sqlite3BtreeEnter(p);
32491   pBt->db = p->db;
32492   rc = saveAllCursors(pBt, 0, 0);
32493 #ifndef SQLITE_OMIT_SHARED_CACHE
32494   if( rc!=SQLITE_OK ){
32495     /* This is a horrible situation. An IO or malloc() error occured whilst
32496     ** trying to save cursor positions. If this is an automatic rollback (as
32497     ** the result of a constraint, malloc() failure or IO error) then 
32498     ** the cache may be internally inconsistent (not contain valid trees) so
32499     ** we cannot simply return the error to the caller. Instead, abort 
32500     ** all queries that may be using any of the cursors that failed to save.
32501     */
32502     sqlite3BtreeTripAllCursors(p, rc);
32503   }
32504 #endif
32505   btreeIntegrity(p);
32506   unlockAllTables(p);
32507
32508   if( p->inTrans==TRANS_WRITE ){
32509     int rc2;
32510
32511 #ifndef SQLITE_OMIT_AUTOVACUUM
32512     pBt->nTrunc = 0;
32513 #endif
32514
32515     assert( TRANS_WRITE==pBt->inTransaction );
32516     rc2 = sqlite3PagerRollback(pBt->pPager);
32517     if( rc2!=SQLITE_OK ){
32518       rc = rc2;
32519     }
32520
32521     /* The rollback may have destroyed the pPage1->aData value.  So
32522     ** call sqlite3BtreeGetPage() on page 1 again to make
32523     ** sure pPage1->aData is set correctly. */
32524     if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
32525       releasePage(pPage1);
32526     }
32527     assert( countWriteCursors(pBt)==0 );
32528     pBt->inTransaction = TRANS_READ;
32529   }
32530
32531   if( p->inTrans!=TRANS_NONE ){
32532     assert( pBt->nTransaction>0 );
32533     pBt->nTransaction--;
32534     if( 0==pBt->nTransaction ){
32535       pBt->inTransaction = TRANS_NONE;
32536     }
32537   }
32538
32539   p->inTrans = TRANS_NONE;
32540   pBt->inStmt = 0;
32541   unlockBtreeIfUnused(pBt);
32542
32543   btreeIntegrity(p);
32544   sqlite3BtreeLeave(p);
32545   return rc;
32546 }
32547
32548 /*
32549 ** Start a statement subtransaction.  The subtransaction can
32550 ** can be rolled back independently of the main transaction.
32551 ** You must start a transaction before starting a subtransaction.
32552 ** The subtransaction is ended automatically if the main transaction
32553 ** commits or rolls back.
32554 **
32555 ** Only one subtransaction may be active at a time.  It is an error to try
32556 ** to start a new subtransaction if another subtransaction is already active.
32557 **
32558 ** Statement subtransactions are used around individual SQL statements
32559 ** that are contained within a BEGIN...COMMIT block.  If a constraint
32560 ** error occurs within the statement, the effect of that one statement
32561 ** can be rolled back without having to rollback the entire transaction.
32562 */
32563 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
32564   int rc;
32565   BtShared *pBt = p->pBt;
32566   sqlite3BtreeEnter(p);
32567   pBt->db = p->db;
32568   if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
32569     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
32570   }else{
32571     assert( pBt->inTransaction==TRANS_WRITE );
32572     rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
32573     pBt->inStmt = 1;
32574   }
32575   sqlite3BtreeLeave(p);
32576   return rc;
32577 }
32578
32579
32580 /*
32581 ** Commit the statment subtransaction currently in progress.  If no
32582 ** subtransaction is active, this is a no-op.
32583 */
32584 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
32585   int rc;
32586   BtShared *pBt = p->pBt;
32587   sqlite3BtreeEnter(p);
32588   pBt->db = p->db;
32589   if( pBt->inStmt && !pBt->readOnly ){
32590     rc = sqlite3PagerStmtCommit(pBt->pPager);
32591   }else{
32592     rc = SQLITE_OK;
32593   }
32594   pBt->inStmt = 0;
32595   sqlite3BtreeLeave(p);
32596   return rc;
32597 }
32598
32599 /*
32600 ** Rollback the active statement subtransaction.  If no subtransaction
32601 ** is active this routine is a no-op.
32602 **
32603 ** All cursors will be invalidated by this operation.  Any attempt
32604 ** to use a cursor that was open at the beginning of this operation
32605 ** will result in an error.
32606 */
32607 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
32608   int rc = SQLITE_OK;
32609   BtShared *pBt = p->pBt;
32610   sqlite3BtreeEnter(p);
32611   pBt->db = p->db;
32612   if( pBt->inStmt && !pBt->readOnly ){
32613     rc = sqlite3PagerStmtRollback(pBt->pPager);
32614     assert( countWriteCursors(pBt)==0 );
32615     pBt->inStmt = 0;
32616   }
32617   sqlite3BtreeLeave(p);
32618   return rc;
32619 }
32620
32621 /*
32622 ** Create a new cursor for the BTree whose root is on the page
32623 ** iTable.  The act of acquiring a cursor gets a read lock on 
32624 ** the database file.
32625 **
32626 ** If wrFlag==0, then the cursor can only be used for reading.
32627 ** If wrFlag==1, then the cursor can be used for reading or for
32628 ** writing if other conditions for writing are also met.  These
32629 ** are the conditions that must be met in order for writing to
32630 ** be allowed:
32631 **
32632 ** 1:  The cursor must have been opened with wrFlag==1
32633 **
32634 ** 2:  Other database connections that share the same pager cache
32635 **     but which are not in the READ_UNCOMMITTED state may not have
32636 **     cursors open with wrFlag==0 on the same table.  Otherwise
32637 **     the changes made by this write cursor would be visible to
32638 **     the read cursors in the other database connection.
32639 **
32640 ** 3:  The database must be writable (not on read-only media)
32641 **
32642 ** 4:  There must be an active transaction.
32643 **
32644 ** No checking is done to make sure that page iTable really is the
32645 ** root page of a b-tree.  If it is not, then the cursor acquired
32646 ** will not work correctly.
32647 */
32648 static int btreeCursor(
32649   Btree *p,                              /* The btree */
32650   int iTable,                            /* Root page of table to open */
32651   int wrFlag,                            /* 1 to write. 0 read-only */
32652   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
32653   BtCursor *pCur                         /* Space for new cursor */
32654 ){
32655   int rc;
32656   BtShared *pBt = p->pBt;
32657
32658   assert( sqlite3BtreeHoldsMutex(p) );
32659   if( wrFlag ){
32660     if( pBt->readOnly ){
32661       return SQLITE_READONLY;
32662     }
32663     if( checkReadLocks(p, iTable, 0) ){
32664       return SQLITE_LOCKED;
32665     }
32666   }
32667
32668   if( pBt->pPage1==0 ){
32669     rc = lockBtreeWithRetry(p);
32670     if( rc!=SQLITE_OK ){
32671       return rc;
32672     }
32673     if( pBt->readOnly && wrFlag ){
32674       return SQLITE_READONLY;
32675     }
32676   }
32677   pCur->pgnoRoot = (Pgno)iTable;
32678   if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
32679     rc = SQLITE_EMPTY;
32680     goto create_cursor_exception;
32681   }
32682   rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
32683   if( rc!=SQLITE_OK ){
32684     goto create_cursor_exception;
32685   }
32686
32687   /* Now that no other errors can occur, finish filling in the BtCursor
32688   ** variables, link the cursor into the BtShared list and set *ppCur (the
32689   ** output argument to this function).
32690   */
32691   pCur->pKeyInfo = pKeyInfo;
32692   pCur->pBtree = p;
32693   pCur->pBt = pBt;
32694   pCur->wrFlag = wrFlag;
32695   pCur->pNext = pBt->pCursor;
32696   if( pCur->pNext ){
32697     pCur->pNext->pPrev = pCur;
32698   }
32699   pBt->pCursor = pCur;
32700   pCur->eState = CURSOR_INVALID;
32701
32702   return SQLITE_OK;
32703
32704 create_cursor_exception:
32705   if( pCur ){
32706     releasePage(pCur->pPage);
32707   }
32708   unlockBtreeIfUnused(pBt);
32709   return rc;
32710 }
32711 SQLITE_PRIVATE int sqlite3BtreeCursor(
32712   Btree *p,                                   /* The btree */
32713   int iTable,                                 /* Root page of table to open */
32714   int wrFlag,                                 /* 1 to write. 0 read-only */
32715   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
32716   BtCursor *pCur                              /* Write new cursor here */
32717 ){
32718   int rc;
32719   sqlite3BtreeEnter(p);
32720   p->pBt->db = p->db;
32721   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
32722   sqlite3BtreeLeave(p);
32723   return rc;
32724 }
32725 SQLITE_PRIVATE int sqlite3BtreeCursorSize(){
32726   return sizeof(BtCursor);
32727 }
32728
32729
32730
32731 /*
32732 ** Close a cursor.  The read lock on the database file is released
32733 ** when the last cursor is closed.
32734 */
32735 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
32736   Btree *pBtree = pCur->pBtree;
32737   if( pBtree ){
32738     BtShared *pBt = pCur->pBt;
32739     sqlite3BtreeEnter(pBtree);
32740     pBt->db = pBtree->db;
32741     clearCursorPosition(pCur);
32742     if( pCur->pPrev ){
32743       pCur->pPrev->pNext = pCur->pNext;
32744     }else{
32745       pBt->pCursor = pCur->pNext;
32746     }
32747     if( pCur->pNext ){
32748       pCur->pNext->pPrev = pCur->pPrev;
32749     }
32750     releasePage(pCur->pPage);
32751     unlockBtreeIfUnused(pBt);
32752     invalidateOverflowCache(pCur);
32753     /* sqlite3_free(pCur); */
32754     sqlite3BtreeLeave(pBtree);
32755   }
32756   return SQLITE_OK;
32757 }
32758
32759 /*
32760 ** Make a temporary cursor by filling in the fields of pTempCur.
32761 ** The temporary cursor is not on the cursor list for the Btree.
32762 */
32763 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
32764   assert( cursorHoldsMutex(pCur) );
32765   memcpy(pTempCur, pCur, sizeof(*pCur));
32766   pTempCur->pNext = 0;
32767   pTempCur->pPrev = 0;
32768   if( pTempCur->pPage ){
32769     sqlite3PagerRef(pTempCur->pPage->pDbPage);
32770   }
32771 }
32772
32773 /*
32774 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
32775 ** function above.
32776 */
32777 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
32778   assert( cursorHoldsMutex(pCur) );
32779   if( pCur->pPage ){
32780     sqlite3PagerUnref(pCur->pPage->pDbPage);
32781   }
32782 }
32783
32784 /*
32785 ** Make sure the BtCursor* given in the argument has a valid
32786 ** BtCursor.info structure.  If it is not already valid, call
32787 ** sqlite3BtreeParseCell() to fill it in.
32788 **
32789 ** BtCursor.info is a cache of the information in the current cell.
32790 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
32791 **
32792 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
32793 ** compiler to crash when getCellInfo() is implemented as a macro.
32794 ** But there is a measureable speed advantage to using the macro on gcc
32795 ** (when less compiler optimizations like -Os or -O0 are used and the
32796 ** compiler is not doing agressive inlining.)  So we use a real function
32797 ** for MSVC and a macro for everything else.  Ticket #2457.
32798 */
32799 #ifndef NDEBUG
32800   static void assertCellInfo(BtCursor *pCur){
32801     CellInfo info;
32802     memset(&info, 0, sizeof(info));
32803     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
32804     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
32805   }
32806 #else
32807   #define assertCellInfo(x)
32808 #endif
32809 #ifdef _MSC_VER
32810   /* Use a real function in MSVC to work around bugs in that compiler. */
32811   static void getCellInfo(BtCursor *pCur){
32812     if( pCur->info.nSize==0 ){
32813       sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
32814       pCur->validNKey = 1;
32815     }else{
32816       assertCellInfo(pCur);
32817     }
32818   }
32819 #else /* if not _MSC_VER */
32820   /* Use a macro in all other compilers so that the function is inlined */
32821 #define getCellInfo(pCur)                                               \
32822   if( pCur->info.nSize==0 ){                                            \
32823     sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);         \
32824     pCur->validNKey = 1;                                                \
32825   }else{                                                                \
32826     assertCellInfo(pCur);                                               \
32827   }
32828 #endif /* _MSC_VER */
32829
32830 /*
32831 ** Set *pSize to the size of the buffer needed to hold the value of
32832 ** the key for the current entry.  If the cursor is not pointing
32833 ** to a valid entry, *pSize is set to 0. 
32834 **
32835 ** For a table with the INTKEY flag set, this routine returns the key
32836 ** itself, not the number of bytes in the key.
32837 */
32838 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
32839   int rc;
32840
32841   assert( cursorHoldsMutex(pCur) );
32842   rc = restoreOrClearCursorPosition(pCur);
32843   if( rc==SQLITE_OK ){
32844     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
32845     if( pCur->eState==CURSOR_INVALID ){
32846       *pSize = 0;
32847     }else{
32848       getCellInfo(pCur);
32849       *pSize = pCur->info.nKey;
32850     }
32851   }
32852   return rc;
32853 }
32854
32855 /*
32856 ** Set *pSize to the number of bytes of data in the entry the
32857 ** cursor currently points to.  Always return SQLITE_OK.
32858 ** Failure is not possible.  If the cursor is not currently
32859 ** pointing to an entry (which can happen, for example, if
32860 ** the database is empty) then *pSize is set to 0.
32861 */
32862 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
32863   int rc;
32864
32865   assert( cursorHoldsMutex(pCur) );
32866   rc = restoreOrClearCursorPosition(pCur);
32867   if( rc==SQLITE_OK ){
32868     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
32869     if( pCur->eState==CURSOR_INVALID ){
32870       /* Not pointing at a valid entry - set *pSize to 0. */
32871       *pSize = 0;
32872     }else{
32873       getCellInfo(pCur);
32874       *pSize = pCur->info.nData;
32875     }
32876   }
32877   return rc;
32878 }
32879
32880 /*
32881 ** Given the page number of an overflow page in the database (parameter
32882 ** ovfl), this function finds the page number of the next page in the 
32883 ** linked list of overflow pages. If possible, it uses the auto-vacuum
32884 ** pointer-map data instead of reading the content of page ovfl to do so. 
32885 **
32886 ** If an error occurs an SQLite error code is returned. Otherwise:
32887 **
32888 ** Unless pPgnoNext is NULL, the page number of the next overflow 
32889 ** page in the linked list is written to *pPgnoNext. If page ovfl
32890 ** is the last page in its linked list, *pPgnoNext is set to zero. 
32891 **
32892 ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
32893 ** for page ovfl. The underlying pager page may have been requested
32894 ** with the noContent flag set, so the page data accessable via
32895 ** this handle may not be trusted.
32896 */
32897 static int getOverflowPage(
32898   BtShared *pBt, 
32899   Pgno ovfl,                   /* Overflow page */
32900   MemPage **ppPage,            /* OUT: MemPage handle */
32901   Pgno *pPgnoNext              /* OUT: Next overflow page number */
32902 ){
32903   Pgno next = 0;
32904   int rc;
32905
32906   assert( sqlite3_mutex_held(pBt->mutex) );
32907   /* One of these must not be NULL. Otherwise, why call this function? */
32908   assert(ppPage || pPgnoNext);
32909
32910   /* If pPgnoNext is NULL, then this function is being called to obtain
32911   ** a MemPage* reference only. No page-data is required in this case.
32912   */
32913   if( !pPgnoNext ){
32914     return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
32915   }
32916
32917 #ifndef SQLITE_OMIT_AUTOVACUUM
32918   /* Try to find the next page in the overflow list using the
32919   ** autovacuum pointer-map pages. Guess that the next page in 
32920   ** the overflow list is page number (ovfl+1). If that guess turns 
32921   ** out to be wrong, fall back to loading the data of page 
32922   ** number ovfl to determine the next page number.
32923   */
32924   if( pBt->autoVacuum ){
32925     Pgno pgno;
32926     Pgno iGuess = ovfl+1;
32927     u8 eType;
32928
32929     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
32930       iGuess++;
32931     }
32932
32933     if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
32934       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
32935       if( rc!=SQLITE_OK ){
32936         return rc;
32937       }
32938       if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
32939         next = iGuess;
32940       }
32941     }
32942   }
32943 #endif
32944
32945   if( next==0 || ppPage ){
32946     MemPage *pPage = 0;
32947
32948     rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
32949     assert(rc==SQLITE_OK || pPage==0);
32950     if( next==0 && rc==SQLITE_OK ){
32951       next = get4byte(pPage->aData);
32952     }
32953
32954     if( ppPage ){
32955       *ppPage = pPage;
32956     }else{
32957       releasePage(pPage);
32958     }
32959   }
32960   *pPgnoNext = next;
32961
32962   return rc;
32963 }
32964
32965 /*
32966 ** Copy data from a buffer to a page, or from a page to a buffer.
32967 **
32968 ** pPayload is a pointer to data stored on database page pDbPage.
32969 ** If argument eOp is false, then nByte bytes of data are copied
32970 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
32971 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
32972 ** of data are copied from the buffer pBuf to pPayload.
32973 **
32974 ** SQLITE_OK is returned on success, otherwise an error code.
32975 */
32976 static int copyPayload(
32977   void *pPayload,           /* Pointer to page data */
32978   void *pBuf,               /* Pointer to buffer */
32979   int nByte,                /* Number of bytes to copy */
32980   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
32981   DbPage *pDbPage           /* Page containing pPayload */
32982 ){
32983   if( eOp ){
32984     /* Copy data from buffer to page (a write operation) */
32985     int rc = sqlite3PagerWrite(pDbPage);
32986     if( rc!=SQLITE_OK ){
32987       return rc;
32988     }
32989     memcpy(pPayload, pBuf, nByte);
32990   }else{
32991     /* Copy data from page to buffer (a read operation) */
32992     memcpy(pBuf, pPayload, nByte);
32993   }
32994   return SQLITE_OK;
32995 }
32996
32997 /*
32998 ** This function is used to read or overwrite payload information
32999 ** for the entry that the pCur cursor is pointing to. If the eOp
33000 ** parameter is 0, this is a read operation (data copied into
33001 ** buffer pBuf). If it is non-zero, a write (data copied from
33002 ** buffer pBuf).
33003 **
33004 ** A total of "amt" bytes are read or written beginning at "offset".
33005 ** Data is read to or from the buffer pBuf.
33006 **
33007 ** This routine does not make a distinction between key and data.
33008 ** It just reads or writes bytes from the payload area.  Data might 
33009 ** appear on the main page or be scattered out on multiple overflow 
33010 ** pages.
33011 **
33012 ** If the BtCursor.isIncrblobHandle flag is set, and the current
33013 ** cursor entry uses one or more overflow pages, this function
33014 ** allocates space for and lazily popluates the overflow page-list 
33015 ** cache array (BtCursor.aOverflow). Subsequent calls use this
33016 ** cache to make seeking to the supplied offset more efficient.
33017 **
33018 ** Once an overflow page-list cache has been allocated, it may be
33019 ** invalidated if some other cursor writes to the same table, or if
33020 ** the cursor is moved to a different row. Additionally, in auto-vacuum
33021 ** mode, the following events may invalidate an overflow page-list cache.
33022 **
33023 **   * An incremental vacuum,
33024 **   * A commit in auto_vacuum="full" mode,
33025 **   * Creating a table (may require moving an overflow page).
33026 */
33027 static int accessPayload(
33028   BtCursor *pCur,      /* Cursor pointing to entry to read from */
33029   int offset,          /* Begin reading this far into payload */
33030   int amt,             /* Read this many bytes */
33031   unsigned char *pBuf, /* Write the bytes into this buffer */ 
33032   int skipKey,         /* offset begins at data if this is true */
33033   int eOp              /* zero to read. non-zero to write. */
33034 ){
33035   unsigned char *aPayload;
33036   int rc = SQLITE_OK;
33037   u32 nKey;
33038   int iIdx = 0;
33039   MemPage *pPage = pCur->pPage;     /* Btree page of current cursor entry */
33040   BtShared *pBt;                   /* Btree this cursor belongs to */
33041
33042   assert( pPage );
33043   assert( pCur->eState==CURSOR_VALID );
33044   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
33045   assert( offset>=0 );
33046   assert( cursorHoldsMutex(pCur) );
33047
33048   getCellInfo(pCur);
33049   aPayload = pCur->info.pCell + pCur->info.nHeader;
33050   nKey = (pPage->intKey ? 0 : pCur->info.nKey);
33051
33052   if( skipKey ){
33053     offset += nKey;
33054   }
33055   if( offset+amt > nKey+pCur->info.nData ){
33056     /* Trying to read or write past the end of the data is an error */
33057     return SQLITE_ERROR;
33058   }
33059
33060   /* Check if data must be read/written to/from the btree page itself. */
33061   if( offset<pCur->info.nLocal ){
33062     int a = amt;
33063     if( a+offset>pCur->info.nLocal ){
33064       a = pCur->info.nLocal - offset;
33065     }
33066     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
33067     offset = 0;
33068     pBuf += a;
33069     amt -= a;
33070   }else{
33071     offset -= pCur->info.nLocal;
33072   }
33073
33074   pBt = pCur->pBt;
33075   if( rc==SQLITE_OK && amt>0 ){
33076     const int ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
33077     Pgno nextPage;
33078
33079     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
33080
33081 #ifndef SQLITE_OMIT_INCRBLOB
33082     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
33083     ** has not been allocated, allocate it now. The array is sized at
33084     ** one entry for each overflow page in the overflow chain. The
33085     ** page number of the first overflow page is stored in aOverflow[0],
33086     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
33087     ** (the cache is lazily populated).
33088     */
33089     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
33090       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
33091       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
33092       if( nOvfl && !pCur->aOverflow ){
33093         rc = SQLITE_NOMEM;
33094       }
33095     }
33096
33097     /* If the overflow page-list cache has been allocated and the
33098     ** entry for the first required overflow page is valid, skip
33099     ** directly to it.
33100     */
33101     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
33102       iIdx = (offset/ovflSize);
33103       nextPage = pCur->aOverflow[iIdx];
33104       offset = (offset%ovflSize);
33105     }
33106 #endif
33107
33108     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
33109
33110 #ifndef SQLITE_OMIT_INCRBLOB
33111       /* If required, populate the overflow page-list cache. */
33112       if( pCur->aOverflow ){
33113         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
33114         pCur->aOverflow[iIdx] = nextPage;
33115       }
33116 #endif
33117
33118       if( offset>=ovflSize ){
33119         /* The only reason to read this page is to obtain the page
33120         ** number for the next page in the overflow chain. The page
33121         ** data is not required. So first try to lookup the overflow
33122         ** page-list cache, if any, then fall back to the getOverflowPage()
33123         ** function.
33124         */
33125 #ifndef SQLITE_OMIT_INCRBLOB
33126         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
33127           nextPage = pCur->aOverflow[iIdx+1];
33128         } else 
33129 #endif
33130           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
33131         offset -= ovflSize;
33132       }else{
33133         /* Need to read this page properly. It contains some of the
33134         ** range of data that is being read (eOp==0) or written (eOp!=0).
33135         */
33136         DbPage *pDbPage;
33137         int a = amt;
33138         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
33139         if( rc==SQLITE_OK ){
33140           aPayload = sqlite3PagerGetData(pDbPage);
33141           nextPage = get4byte(aPayload);
33142           if( a + offset > ovflSize ){
33143             a = ovflSize - offset;
33144           }
33145           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
33146           sqlite3PagerUnref(pDbPage);
33147           offset = 0;
33148           amt -= a;
33149           pBuf += a;
33150         }
33151       }
33152     }
33153   }
33154
33155   if( rc==SQLITE_OK && amt>0 ){
33156     return SQLITE_CORRUPT_BKPT;
33157   }
33158   return rc;
33159 }
33160
33161 /*
33162 ** Read part of the key associated with cursor pCur.  Exactly
33163 ** "amt" bytes will be transfered into pBuf[].  The transfer
33164 ** begins at "offset".
33165 **
33166 ** Return SQLITE_OK on success or an error code if anything goes
33167 ** wrong.  An error is returned if "offset+amt" is larger than
33168 ** the available payload.
33169 */
33170 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
33171   int rc;
33172
33173   assert( cursorHoldsMutex(pCur) );
33174   rc = restoreOrClearCursorPosition(pCur);
33175   if( rc==SQLITE_OK ){
33176     assert( pCur->eState==CURSOR_VALID );
33177     assert( pCur->pPage!=0 );
33178     if( pCur->pPage->intKey ){
33179       return SQLITE_CORRUPT_BKPT;
33180     }
33181     assert( pCur->pPage->intKey==0 );
33182     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
33183     rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
33184   }
33185   return rc;
33186 }
33187
33188 /*
33189 ** Read part of the data associated with cursor pCur.  Exactly
33190 ** "amt" bytes will be transfered into pBuf[].  The transfer
33191 ** begins at "offset".
33192 **
33193 ** Return SQLITE_OK on success or an error code if anything goes
33194 ** wrong.  An error is returned if "offset+amt" is larger than
33195 ** the available payload.
33196 */
33197 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
33198   int rc;
33199
33200   assert( cursorHoldsMutex(pCur) );
33201   rc = restoreOrClearCursorPosition(pCur);
33202   if( rc==SQLITE_OK ){
33203     assert( pCur->eState==CURSOR_VALID );
33204     assert( pCur->pPage!=0 );
33205     assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
33206     rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
33207   }
33208   return rc;
33209 }
33210
33211 /*
33212 ** Return a pointer to payload information from the entry that the 
33213 ** pCur cursor is pointing to.  The pointer is to the beginning of
33214 ** the key if skipKey==0 and it points to the beginning of data if
33215 ** skipKey==1.  The number of bytes of available key/data is written
33216 ** into *pAmt.  If *pAmt==0, then the value returned will not be
33217 ** a valid pointer.
33218 **
33219 ** This routine is an optimization.  It is common for the entire key
33220 ** and data to fit on the local page and for there to be no overflow
33221 ** pages.  When that is so, this routine can be used to access the
33222 ** key and data without making a copy.  If the key and/or data spills
33223 ** onto overflow pages, then accessPayload() must be used to reassembly
33224 ** the key/data and copy it into a preallocated buffer.
33225 **
33226 ** The pointer returned by this routine looks directly into the cached
33227 ** page of the database.  The data might change or move the next time
33228 ** any btree routine is called.
33229 */
33230 static const unsigned char *fetchPayload(
33231   BtCursor *pCur,      /* Cursor pointing to entry to read from */
33232   int *pAmt,           /* Write the number of available bytes here */
33233   int skipKey          /* read beginning at data if this is true */
33234 ){
33235   unsigned char *aPayload;
33236   MemPage *pPage;
33237   u32 nKey;
33238   int nLocal;
33239
33240   assert( pCur!=0 && pCur->pPage!=0 );
33241   assert( pCur->eState==CURSOR_VALID );
33242   assert( cursorHoldsMutex(pCur) );
33243   pPage = pCur->pPage;
33244   assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
33245   getCellInfo(pCur);
33246   aPayload = pCur->info.pCell;
33247   aPayload += pCur->info.nHeader;
33248   if( pPage->intKey ){
33249     nKey = 0;
33250   }else{
33251     nKey = pCur->info.nKey;
33252   }
33253   if( skipKey ){
33254     aPayload += nKey;
33255     nLocal = pCur->info.nLocal - nKey;
33256   }else{
33257     nLocal = pCur->info.nLocal;
33258     if( nLocal>nKey ){
33259       nLocal = nKey;
33260     }
33261   }
33262   *pAmt = nLocal;
33263   return aPayload;
33264 }
33265
33266
33267 /*
33268 ** For the entry that cursor pCur is point to, return as
33269 ** many bytes of the key or data as are available on the local
33270 ** b-tree page.  Write the number of available bytes into *pAmt.
33271 **
33272 ** The pointer returned is ephemeral.  The key/data may move
33273 ** or be destroyed on the next call to any Btree routine,
33274 ** including calls from other threads against the same cache.
33275 ** Hence, a mutex on the BtShared should be held prior to calling
33276 ** this routine.
33277 **
33278 ** These routines is used to get quick access to key and data
33279 ** in the common case where no overflow pages are used.
33280 */
33281 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
33282   assert( cursorHoldsMutex(pCur) );
33283   if( pCur->eState==CURSOR_VALID ){
33284     return (const void*)fetchPayload(pCur, pAmt, 0);
33285   }
33286   return 0;
33287 }
33288 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
33289   assert( cursorHoldsMutex(pCur) );
33290   if( pCur->eState==CURSOR_VALID ){
33291     return (const void*)fetchPayload(pCur, pAmt, 1);
33292   }
33293   return 0;
33294 }
33295
33296
33297 /*
33298 ** Move the cursor down to a new child page.  The newPgno argument is the
33299 ** page number of the child page to move to.
33300 */
33301 static int moveToChild(BtCursor *pCur, u32 newPgno){
33302   int rc;
33303   MemPage *pNewPage;
33304   MemPage *pOldPage;
33305   BtShared *pBt = pCur->pBt;
33306
33307   assert( cursorHoldsMutex(pCur) );
33308   assert( pCur->eState==CURSOR_VALID );
33309   rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
33310   if( rc ) return rc;
33311   pNewPage->idxParent = pCur->idx;
33312   pOldPage = pCur->pPage;
33313   pOldPage->idxShift = 0;
33314   releasePage(pOldPage);
33315   pCur->pPage = pNewPage;
33316   pCur->idx = 0;
33317   pCur->info.nSize = 0;
33318   pCur->validNKey = 0;
33319   if( pNewPage->nCell<1 ){
33320     return SQLITE_CORRUPT_BKPT;
33321   }
33322   return SQLITE_OK;
33323 }
33324
33325 /*
33326 ** Return true if the page is the virtual root of its table.
33327 **
33328 ** The virtual root page is the root page for most tables.  But
33329 ** for the table rooted on page 1, sometime the real root page
33330 ** is empty except for the right-pointer.  In such cases the
33331 ** virtual root page is the page that the right-pointer of page
33332 ** 1 is pointing to.
33333 */
33334 SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage){
33335   MemPage *pParent;
33336
33337   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
33338   pParent = pPage->pParent;
33339   if( pParent==0 ) return 1;
33340   if( pParent->pgno>1 ) return 0;
33341   if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
33342   return 0;
33343 }
33344
33345 /*
33346 ** Move the cursor up to the parent page.
33347 **
33348 ** pCur->idx is set to the cell index that contains the pointer
33349 ** to the page we are coming from.  If we are coming from the
33350 ** right-most child page then pCur->idx is set to one more than
33351 ** the largest cell index.
33352 */
33353 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
33354   MemPage *pParent;
33355   MemPage *pPage;
33356   int idxParent;
33357
33358   assert( cursorHoldsMutex(pCur) );
33359   assert( pCur->eState==CURSOR_VALID );
33360   pPage = pCur->pPage;
33361   assert( pPage!=0 );
33362   assert( !sqlite3BtreeIsRootPage(pPage) );
33363   pParent = pPage->pParent;
33364   assert( pParent!=0 );
33365   idxParent = pPage->idxParent;
33366   sqlite3PagerRef(pParent->pDbPage);
33367   releasePage(pPage);
33368   pCur->pPage = pParent;
33369   pCur->info.nSize = 0;
33370   pCur->validNKey = 0;
33371   assert( pParent->idxShift==0 );
33372   pCur->idx = idxParent;
33373 }
33374
33375 /*
33376 ** Move the cursor to the root page
33377 */
33378 static int moveToRoot(BtCursor *pCur){
33379   MemPage *pRoot;
33380   int rc = SQLITE_OK;
33381   Btree *p = pCur->pBtree;
33382   BtShared *pBt = p->pBt;
33383
33384   assert( cursorHoldsMutex(pCur) );
33385   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
33386   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
33387   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
33388   if( pCur->eState>=CURSOR_REQUIRESEEK ){
33389     if( pCur->eState==CURSOR_FAULT ){
33390       return pCur->skip;
33391     }
33392     clearCursorPosition(pCur);
33393   }
33394   pRoot = pCur->pPage;
33395   if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
33396     assert( pRoot->isInit );
33397   }else{
33398     if( 
33399       SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
33400     ){
33401       pCur->eState = CURSOR_INVALID;
33402       return rc;
33403     }
33404     releasePage(pCur->pPage);
33405     pCur->pPage = pRoot;
33406   }
33407   pCur->idx = 0;
33408   pCur->info.nSize = 0;
33409   pCur->atLast = 0;
33410   pCur->validNKey = 0;
33411   if( pRoot->nCell==0 && !pRoot->leaf ){
33412     Pgno subpage;
33413     assert( pRoot->pgno==1 );
33414     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
33415     assert( subpage>0 );
33416     pCur->eState = CURSOR_VALID;
33417     rc = moveToChild(pCur, subpage);
33418   }
33419   pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
33420   return rc;
33421 }
33422
33423 /*
33424 ** Move the cursor down to the left-most leaf entry beneath the
33425 ** entry to which it is currently pointing.
33426 **
33427 ** The left-most leaf is the one with the smallest key - the first
33428 ** in ascending order.
33429 */
33430 static int moveToLeftmost(BtCursor *pCur){
33431   Pgno pgno;
33432   int rc = SQLITE_OK;
33433   MemPage *pPage;
33434
33435   assert( cursorHoldsMutex(pCur) );
33436   assert( pCur->eState==CURSOR_VALID );
33437   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
33438     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
33439     pgno = get4byte(findCell(pPage, pCur->idx));
33440     rc = moveToChild(pCur, pgno);
33441   }
33442   return rc;
33443 }
33444
33445 /*
33446 ** Move the cursor down to the right-most leaf entry beneath the
33447 ** page to which it is currently pointing.  Notice the difference
33448 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
33449 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
33450 ** finds the right-most entry beneath the *page*.
33451 **
33452 ** The right-most entry is the one with the largest key - the last
33453 ** key in ascending order.
33454 */
33455 static int moveToRightmost(BtCursor *pCur){
33456   Pgno pgno;
33457   int rc = SQLITE_OK;
33458   MemPage *pPage;
33459
33460   assert( cursorHoldsMutex(pCur) );
33461   assert( pCur->eState==CURSOR_VALID );
33462   while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
33463     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
33464     pCur->idx = pPage->nCell;
33465     rc = moveToChild(pCur, pgno);
33466   }
33467   if( rc==SQLITE_OK ){
33468     pCur->idx = pPage->nCell - 1;
33469     pCur->info.nSize = 0;
33470     pCur->validNKey = 0;
33471   }
33472   return SQLITE_OK;
33473 }
33474
33475 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
33476 ** on success.  Set *pRes to 0 if the cursor actually points to something
33477 ** or set *pRes to 1 if the table is empty.
33478 */
33479 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
33480   int rc;
33481
33482   assert( cursorHoldsMutex(pCur) );
33483   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
33484   rc = moveToRoot(pCur);
33485   if( rc==SQLITE_OK ){
33486     if( pCur->eState==CURSOR_INVALID ){
33487       assert( pCur->pPage->nCell==0 );
33488       *pRes = 1;
33489       rc = SQLITE_OK;
33490     }else{
33491       assert( pCur->pPage->nCell>0 );
33492       *pRes = 0;
33493       rc = moveToLeftmost(pCur);
33494     }
33495   }
33496   return rc;
33497 }
33498
33499 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
33500 ** on success.  Set *pRes to 0 if the cursor actually points to something
33501 ** or set *pRes to 1 if the table is empty.
33502 */
33503 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
33504   int rc;
33505  
33506   assert( cursorHoldsMutex(pCur) );
33507   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
33508   rc = moveToRoot(pCur);
33509   if( rc==SQLITE_OK ){
33510     if( CURSOR_INVALID==pCur->eState ){
33511       assert( pCur->pPage->nCell==0 );
33512       *pRes = 1;
33513     }else{
33514       assert( pCur->eState==CURSOR_VALID );
33515       *pRes = 0;
33516       rc = moveToRightmost(pCur);
33517       getCellInfo(pCur);
33518       pCur->atLast = rc==SQLITE_OK;
33519     }
33520   }
33521   return rc;
33522 }
33523
33524 /* Move the cursor so that it points to an entry near the key 
33525 ** specified by pKey/nKey/pUnKey. Return a success code.
33526 **
33527 ** For INTKEY tables, only the nKey parameter is used.  pKey 
33528 ** and pUnKey must be NULL.  For index tables, either pUnKey
33529 ** must point to a key that has already been unpacked, or else
33530 ** pKey/nKey describes a blob containing the key.
33531 **
33532 ** If an exact match is not found, then the cursor is always
33533 ** left pointing at a leaf page which would hold the entry if it
33534 ** were present.  The cursor might point to an entry that comes
33535 ** before or after the key.
33536 **
33537 ** The result of comparing the key with the entry to which the
33538 ** cursor is written to *pRes if pRes!=NULL.  The meaning of
33539 ** this value is as follows:
33540 **
33541 **     *pRes<0      The cursor is left pointing at an entry that
33542 **                  is smaller than pKey or if the table is empty
33543 **                  and the cursor is therefore left point to nothing.
33544 **
33545 **     *pRes==0     The cursor is left pointing at an entry that
33546 **                  exactly matches pKey.
33547 **
33548 **     *pRes>0      The cursor is left pointing at an entry that
33549 **                  is larger than pKey.
33550 **
33551 */
33552 SQLITE_PRIVATE int sqlite3BtreeMoveto(
33553   BtCursor *pCur,        /* The cursor to be moved */
33554   const void *pKey,      /* The key content for indices.  Not used by tables */
33555   UnpackedRecord *pUnKey,/* Unpacked version of pKey */
33556   i64 nKey,              /* Size of pKey.  Or the key for tables */
33557   int biasRight,         /* If true, bias the search to the high end */
33558   int *pRes              /* Search result flag */
33559 ){
33560   int rc;
33561   char aSpace[200];
33562
33563   assert( cursorHoldsMutex(pCur) );
33564   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
33565
33566   /* If the cursor is already positioned at the point we are trying
33567   ** to move to, then just return without doing any work */
33568   if( pCur->eState==CURSOR_VALID && pCur->validNKey && pCur->pPage->intKey ){
33569     if( pCur->info.nKey==nKey ){
33570       *pRes = 0;
33571       return SQLITE_OK;
33572     }
33573     if( pCur->atLast && pCur->info.nKey<nKey ){
33574       *pRes = -1;
33575       return SQLITE_OK;
33576     }
33577   }
33578
33579
33580   rc = moveToRoot(pCur);
33581   if( rc ){
33582     return rc;
33583   }
33584   assert( pCur->pPage );
33585   assert( pCur->pPage->isInit );
33586   if( pCur->eState==CURSOR_INVALID ){
33587     *pRes = -1;
33588     assert( pCur->pPage->nCell==0 );
33589     return SQLITE_OK;
33590   }
33591   if( pCur->pPage->intKey ){
33592     /* We are given an SQL table to search.  The key is the integer
33593     ** rowid contained in nKey.  pKey and pUnKey should both be NULL */
33594     assert( pUnKey==0 );
33595     assert( pKey==0 );
33596   }else if( pUnKey==0 ){
33597     /* We are to search an SQL index using a key encoded as a blob.
33598     ** The blob is found at pKey and is nKey bytes in length.  Unpack
33599     ** this key so that we can use it. */
33600     assert( pKey!=0 );
33601     pUnKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
33602                                    aSpace, sizeof(aSpace));
33603     if( pUnKey==0 ) return SQLITE_NOMEM;
33604   }else{
33605     /* We are to search an SQL index using a key that is already unpacked
33606     ** and handed to us in pUnKey. */
33607     assert( pKey==0 );
33608   }
33609   for(;;){
33610     int lwr, upr;
33611     Pgno chldPg;
33612     MemPage *pPage = pCur->pPage;
33613     int c = -1;  /* pRes return if table is empty must be -1 */
33614     lwr = 0;
33615     upr = pPage->nCell-1;
33616     if( !pPage->intKey && pUnKey==0 ){
33617       rc = SQLITE_CORRUPT_BKPT;
33618       goto moveto_finish;
33619     }
33620     if( biasRight ){
33621       pCur->idx = upr;
33622     }else{
33623       pCur->idx = (upr+lwr)/2;
33624     }
33625     if( lwr<=upr ) for(;;){
33626       void *pCellKey;
33627       i64 nCellKey;
33628       pCur->info.nSize = 0;
33629       pCur->validNKey = 1;
33630       if( pPage->intKey ){
33631         u8 *pCell;
33632         pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
33633         if( pPage->hasData ){
33634           u32 dummy;
33635           pCell += getVarint32(pCell, dummy);
33636         }
33637         getVarint(pCell, (u64*)&nCellKey);
33638         if( nCellKey==nKey ){
33639           c = 0;
33640         }else if( nCellKey<nKey ){
33641           c = -1;
33642         }else{
33643           assert( nCellKey>nKey );
33644           c = +1;
33645         }
33646       }else{
33647         int available;
33648         pCellKey = (void *)fetchPayload(pCur, &available, 0);
33649         nCellKey = pCur->info.nKey;
33650         if( available>=nCellKey ){
33651           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pUnKey);
33652         }else{
33653           pCellKey = sqlite3_malloc( nCellKey );
33654           if( pCellKey==0 ){
33655             rc = SQLITE_NOMEM;
33656             goto moveto_finish;
33657           }
33658           rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
33659           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pUnKey);
33660           sqlite3_free(pCellKey);
33661           if( rc ) goto moveto_finish;
33662         }
33663       }
33664       if( c==0 ){
33665         pCur->info.nKey = nCellKey;
33666         if( pPage->leafData && !pPage->leaf ){
33667           lwr = pCur->idx;
33668           upr = lwr - 1;
33669           break;
33670         }else{
33671           if( pRes ) *pRes = 0;
33672           rc = SQLITE_OK;
33673           goto moveto_finish;
33674         }
33675       }
33676       if( c<0 ){
33677         lwr = pCur->idx+1;
33678       }else{
33679         upr = pCur->idx-1;
33680       }
33681       if( lwr>upr ){
33682         pCur->info.nKey = nCellKey;
33683         break;
33684       }
33685       pCur->idx = (lwr+upr)/2;
33686     }
33687     assert( lwr==upr+1 );
33688     assert( pPage->isInit );
33689     if( pPage->leaf ){
33690       chldPg = 0;
33691     }else if( lwr>=pPage->nCell ){
33692       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
33693     }else{
33694       chldPg = get4byte(findCell(pPage, lwr));
33695     }
33696     if( chldPg==0 ){
33697       assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
33698       if( pRes ) *pRes = c;
33699       rc = SQLITE_OK;
33700       goto moveto_finish;
33701     }
33702     pCur->idx = lwr;
33703     pCur->info.nSize = 0;
33704     pCur->validNKey = 0;
33705     rc = moveToChild(pCur, chldPg);
33706     if( rc ) goto moveto_finish;
33707   }
33708 moveto_finish:
33709   if( pKey ){
33710     /* If we created our own unpacked key at the top of this
33711     ** procedure, then destroy that key before returning. */
33712     sqlite3VdbeDeleteUnpackedRecord(pUnKey);
33713   }
33714   return rc;
33715 }
33716
33717
33718 /*
33719 ** Return TRUE if the cursor is not pointing at an entry of the table.
33720 **
33721 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
33722 ** past the last entry in the table or sqlite3BtreePrev() moves past
33723 ** the first entry.  TRUE is also returned if the table is empty.
33724 */
33725 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
33726   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
33727   ** have been deleted? This API will need to change to return an error code
33728   ** as well as the boolean result value.
33729   */
33730   return (CURSOR_VALID!=pCur->eState);
33731 }
33732
33733 /*
33734 ** Return the database connection handle for a cursor.
33735 */
33736 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
33737   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
33738   return pCur->pBtree->db;
33739 }
33740
33741 /*
33742 ** Advance the cursor to the next entry in the database.  If
33743 ** successful then set *pRes=0.  If the cursor
33744 ** was already pointing to the last entry in the database before
33745 ** this routine was called, then set *pRes=1.
33746 */
33747 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
33748   int rc;
33749   MemPage *pPage;
33750
33751   assert( cursorHoldsMutex(pCur) );
33752   rc = restoreOrClearCursorPosition(pCur);
33753   if( rc!=SQLITE_OK ){
33754     return rc;
33755   }
33756   assert( pRes!=0 );
33757   pPage = pCur->pPage;
33758   if( CURSOR_INVALID==pCur->eState ){
33759     *pRes = 1;
33760     return SQLITE_OK;
33761   }
33762   if( pCur->skip>0 ){
33763     pCur->skip = 0;
33764     *pRes = 0;
33765     return SQLITE_OK;
33766   }
33767   pCur->skip = 0;
33768
33769   assert( pPage->isInit );
33770   assert( pCur->idx<pPage->nCell );
33771
33772   pCur->idx++;
33773   pCur->info.nSize = 0;
33774   pCur->validNKey = 0;
33775   if( pCur->idx>=pPage->nCell ){
33776     if( !pPage->leaf ){
33777       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
33778       if( rc ) return rc;
33779       rc = moveToLeftmost(pCur);
33780       *pRes = 0;
33781       return rc;
33782     }
33783     do{
33784       if( sqlite3BtreeIsRootPage(pPage) ){
33785         *pRes = 1;
33786         pCur->eState = CURSOR_INVALID;
33787         return SQLITE_OK;
33788       }
33789       sqlite3BtreeMoveToParent(pCur);
33790       pPage = pCur->pPage;
33791     }while( pCur->idx>=pPage->nCell );
33792     *pRes = 0;
33793     if( pPage->leafData ){
33794       rc = sqlite3BtreeNext(pCur, pRes);
33795     }else{
33796       rc = SQLITE_OK;
33797     }
33798     return rc;
33799   }
33800   *pRes = 0;
33801   if( pPage->leaf ){
33802     return SQLITE_OK;
33803   }
33804   rc = moveToLeftmost(pCur);
33805   return rc;
33806 }
33807
33808
33809 /*
33810 ** Step the cursor to the back to the previous entry in the database.  If
33811 ** successful then set *pRes=0.  If the cursor
33812 ** was already pointing to the first entry in the database before
33813 ** this routine was called, then set *pRes=1.
33814 */
33815 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
33816   int rc;
33817   Pgno pgno;
33818   MemPage *pPage;
33819
33820   assert( cursorHoldsMutex(pCur) );
33821   rc = restoreOrClearCursorPosition(pCur);
33822   if( rc!=SQLITE_OK ){
33823     return rc;
33824   }
33825   pCur->atLast = 0;
33826   if( CURSOR_INVALID==pCur->eState ){
33827     *pRes = 1;
33828     return SQLITE_OK;
33829   }
33830   if( pCur->skip<0 ){
33831     pCur->skip = 0;
33832     *pRes = 0;
33833     return SQLITE_OK;
33834   }
33835   pCur->skip = 0;
33836
33837   pPage = pCur->pPage;
33838   assert( pPage->isInit );
33839   assert( pCur->idx>=0 );
33840   if( !pPage->leaf ){
33841     pgno = get4byte( findCell(pPage, pCur->idx) );
33842     rc = moveToChild(pCur, pgno);
33843     if( rc ){
33844       return rc;
33845     }
33846     rc = moveToRightmost(pCur);
33847   }else{
33848     while( pCur->idx==0 ){
33849       if( sqlite3BtreeIsRootPage(pPage) ){
33850         pCur->eState = CURSOR_INVALID;
33851         *pRes = 1;
33852         return SQLITE_OK;
33853       }
33854       sqlite3BtreeMoveToParent(pCur);
33855       pPage = pCur->pPage;
33856     }
33857     pCur->idx--;
33858     pCur->info.nSize = 0;
33859     pCur->validNKey = 0;
33860     if( pPage->leafData && !pPage->leaf ){
33861       rc = sqlite3BtreePrevious(pCur, pRes);
33862     }else{
33863       rc = SQLITE_OK;
33864     }
33865   }
33866   *pRes = 0;
33867   return rc;
33868 }
33869
33870 /*
33871 ** Allocate a new page from the database file.
33872 **
33873 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
33874 ** has already been called on the new page.)  The new page has also
33875 ** been referenced and the calling routine is responsible for calling
33876 ** sqlite3PagerUnref() on the new page when it is done.
33877 **
33878 ** SQLITE_OK is returned on success.  Any other return value indicates
33879 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
33880 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
33881 **
33882 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
33883 ** locate a page close to the page number "nearby".  This can be used in an
33884 ** attempt to keep related pages close to each other in the database file,
33885 ** which in turn can make database access faster.
33886 **
33887 ** If the "exact" parameter is not 0, and the page-number nearby exists 
33888 ** anywhere on the free-list, then it is guarenteed to be returned. This
33889 ** is only used by auto-vacuum databases when allocating a new table.
33890 */
33891 static int allocateBtreePage(
33892   BtShared *pBt, 
33893   MemPage **ppPage, 
33894   Pgno *pPgno, 
33895   Pgno nearby,
33896   u8 exact
33897 ){
33898   MemPage *pPage1;
33899   int rc;
33900   int n;     /* Number of pages on the freelist */
33901   int k;     /* Number of leaves on the trunk of the freelist */
33902   MemPage *pTrunk = 0;
33903   MemPage *pPrevTrunk = 0;
33904
33905   assert( sqlite3_mutex_held(pBt->mutex) );
33906   pPage1 = pBt->pPage1;
33907   n = get4byte(&pPage1->aData[36]);
33908   if( n>0 ){
33909     /* There are pages on the freelist.  Reuse one of those pages. */
33910     Pgno iTrunk;
33911     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
33912     
33913     /* If the 'exact' parameter was true and a query of the pointer-map
33914     ** shows that the page 'nearby' is somewhere on the free-list, then
33915     ** the entire-list will be searched for that page.
33916     */
33917 #ifndef SQLITE_OMIT_AUTOVACUUM
33918     if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){
33919       u8 eType;
33920       assert( nearby>0 );
33921       assert( pBt->autoVacuum );
33922       rc = ptrmapGet(pBt, nearby, &eType, 0);
33923       if( rc ) return rc;
33924       if( eType==PTRMAP_FREEPAGE ){
33925         searchList = 1;
33926       }
33927       *pPgno = nearby;
33928     }
33929 #endif
33930
33931     /* Decrement the free-list count by 1. Set iTrunk to the index of the
33932     ** first free-list trunk page. iPrevTrunk is initially 1.
33933     */
33934     rc = sqlite3PagerWrite(pPage1->pDbPage);
33935     if( rc ) return rc;
33936     put4byte(&pPage1->aData[36], n-1);
33937
33938     /* The code within this loop is run only once if the 'searchList' variable
33939     ** is not true. Otherwise, it runs once for each trunk-page on the
33940     ** free-list until the page 'nearby' is located.
33941     */
33942     do {
33943       pPrevTrunk = pTrunk;
33944       if( pPrevTrunk ){
33945         iTrunk = get4byte(&pPrevTrunk->aData[0]);
33946       }else{
33947         iTrunk = get4byte(&pPage1->aData[32]);
33948       }
33949       rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
33950       if( rc ){
33951         pTrunk = 0;
33952         goto end_allocate_page;
33953       }
33954
33955       k = get4byte(&pTrunk->aData[4]);
33956       if( k==0 && !searchList ){
33957         /* The trunk has no leaves and the list is not being searched. 
33958         ** So extract the trunk page itself and use it as the newly 
33959         ** allocated page */
33960         assert( pPrevTrunk==0 );
33961         rc = sqlite3PagerWrite(pTrunk->pDbPage);
33962         if( rc ){
33963           goto end_allocate_page;
33964         }
33965         *pPgno = iTrunk;
33966         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
33967         *ppPage = pTrunk;
33968         pTrunk = 0;
33969         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
33970       }else if( k>pBt->usableSize/4 - 8 ){
33971         /* Value of k is out of range.  Database corruption */
33972         rc = SQLITE_CORRUPT_BKPT;
33973         goto end_allocate_page;
33974 #ifndef SQLITE_OMIT_AUTOVACUUM
33975       }else if( searchList && nearby==iTrunk ){
33976         /* The list is being searched and this trunk page is the page
33977         ** to allocate, regardless of whether it has leaves.
33978         */
33979         assert( *pPgno==iTrunk );
33980         *ppPage = pTrunk;
33981         searchList = 0;
33982         rc = sqlite3PagerWrite(pTrunk->pDbPage);
33983         if( rc ){
33984           goto end_allocate_page;
33985         }
33986         if( k==0 ){
33987           if( !pPrevTrunk ){
33988             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
33989           }else{
33990             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
33991           }
33992         }else{
33993           /* The trunk page is required by the caller but it contains 
33994           ** pointers to free-list leaves. The first leaf becomes a trunk
33995           ** page in this case.
33996           */
33997           MemPage *pNewTrunk;
33998           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
33999           rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
34000           if( rc!=SQLITE_OK ){
34001             goto end_allocate_page;
34002           }
34003           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
34004           if( rc!=SQLITE_OK ){
34005             releasePage(pNewTrunk);
34006             goto end_allocate_page;
34007           }
34008           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
34009           put4byte(&pNewTrunk->aData[4], k-1);
34010           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
34011           releasePage(pNewTrunk);
34012           if( !pPrevTrunk ){
34013             put4byte(&pPage1->aData[32], iNewTrunk);
34014           }else{
34015             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
34016             if( rc ){
34017               goto end_allocate_page;
34018             }
34019             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
34020           }
34021         }
34022         pTrunk = 0;
34023         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
34024 #endif
34025       }else{
34026         /* Extract a leaf from the trunk */
34027         int closest;
34028         Pgno iPage;
34029         unsigned char *aData = pTrunk->aData;
34030         rc = sqlite3PagerWrite(pTrunk->pDbPage);
34031         if( rc ){
34032           goto end_allocate_page;
34033         }
34034         if( nearby>0 ){
34035           int i, dist;
34036           closest = 0;
34037           dist = get4byte(&aData[8]) - nearby;
34038           if( dist<0 ) dist = -dist;
34039           for(i=1; i<k; i++){
34040             int d2 = get4byte(&aData[8+i*4]) - nearby;
34041             if( d2<0 ) d2 = -d2;
34042             if( d2<dist ){
34043               closest = i;
34044               dist = d2;
34045             }
34046           }
34047         }else{
34048           closest = 0;
34049         }
34050
34051         iPage = get4byte(&aData[8+closest*4]);
34052         if( !searchList || iPage==nearby ){
34053           *pPgno = iPage;
34054           if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
34055             /* Free page off the end of the file */
34056             rc = SQLITE_CORRUPT_BKPT;
34057             goto end_allocate_page;
34058           }
34059           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
34060                  ": %d more free pages\n",
34061                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
34062           if( closest<k-1 ){
34063             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
34064           }
34065           put4byte(&aData[4], k-1);
34066           rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
34067           if( rc==SQLITE_OK ){
34068             sqlite3PagerDontRollback((*ppPage)->pDbPage);
34069             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
34070             if( rc!=SQLITE_OK ){
34071               releasePage(*ppPage);
34072             }
34073           }
34074           searchList = 0;
34075         }
34076       }
34077       releasePage(pPrevTrunk);
34078       pPrevTrunk = 0;
34079     }while( searchList );
34080   }else{
34081     /* There are no pages on the freelist, so create a new page at the
34082     ** end of the file */
34083     *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
34084
34085 #ifndef SQLITE_OMIT_AUTOVACUUM
34086     if( pBt->nTrunc ){
34087       /* An incr-vacuum has already run within this transaction. So the
34088       ** page to allocate is not from the physical end of the file, but
34089       ** at pBt->nTrunc. 
34090       */
34091       *pPgno = pBt->nTrunc+1;
34092       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
34093         (*pPgno)++;
34094       }
34095     }
34096     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
34097       /* If *pPgno refers to a pointer-map page, allocate two new pages
34098       ** at the end of the file instead of one. The first allocated page
34099       ** becomes a new pointer-map page, the second is used by the caller.
34100       */
34101       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
34102       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
34103       (*pPgno)++;
34104       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
34105     }
34106     if( pBt->nTrunc ){
34107       pBt->nTrunc = *pPgno;
34108     }
34109 #endif
34110
34111     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
34112     rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
34113     if( rc ) return rc;
34114     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
34115     if( rc!=SQLITE_OK ){
34116       releasePage(*ppPage);
34117     }
34118     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
34119   }
34120
34121   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
34122
34123 end_allocate_page:
34124   releasePage(pTrunk);
34125   releasePage(pPrevTrunk);
34126   return rc;
34127 }
34128
34129 /*
34130 ** Add a page of the database file to the freelist.
34131 **
34132 ** sqlite3PagerUnref() is NOT called for pPage.
34133 */
34134 static int freePage(MemPage *pPage){
34135   BtShared *pBt = pPage->pBt;
34136   MemPage *pPage1 = pBt->pPage1;
34137   int rc, n, k;
34138
34139   /* Prepare the page for freeing */
34140   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34141   assert( pPage->pgno>1 );
34142   pPage->isInit = 0;
34143   releasePage(pPage->pParent);
34144   pPage->pParent = 0;
34145
34146   /* Increment the free page count on pPage1 */
34147   rc = sqlite3PagerWrite(pPage1->pDbPage);
34148   if( rc ) return rc;
34149   n = get4byte(&pPage1->aData[36]);
34150   put4byte(&pPage1->aData[36], n+1);
34151
34152 #ifdef SQLITE_SECURE_DELETE
34153   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
34154   ** always fully overwrite deleted information with zeros.
34155   */
34156   rc = sqlite3PagerWrite(pPage->pDbPage);
34157   if( rc ) return rc;
34158   memset(pPage->aData, 0, pPage->pBt->pageSize);
34159 #endif
34160
34161 #ifndef SQLITE_OMIT_AUTOVACUUM
34162   /* If the database supports auto-vacuum, write an entry in the pointer-map
34163   ** to indicate that the page is free.
34164   */
34165   if( pBt->autoVacuum ){
34166     rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
34167     if( rc ) return rc;
34168   }
34169 #endif
34170
34171   if( n==0 ){
34172     /* This is the first free page */
34173     rc = sqlite3PagerWrite(pPage->pDbPage);
34174     if( rc ) return rc;
34175     memset(pPage->aData, 0, 8);
34176     put4byte(&pPage1->aData[32], pPage->pgno);
34177     TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
34178   }else{
34179     /* Other free pages already exist.  Retrive the first trunk page
34180     ** of the freelist and find out how many leaves it has. */
34181     MemPage *pTrunk;
34182     rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
34183     if( rc ) return rc;
34184     k = get4byte(&pTrunk->aData[4]);
34185     if( k>=pBt->usableSize/4 - 8 ){
34186       /* The trunk is full.  Turn the page being freed into a new
34187       ** trunk page with no leaves. */
34188       rc = sqlite3PagerWrite(pPage->pDbPage);
34189       if( rc==SQLITE_OK ){
34190         put4byte(pPage->aData, pTrunk->pgno);
34191         put4byte(&pPage->aData[4], 0);
34192         put4byte(&pPage1->aData[32], pPage->pgno);
34193         TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
34194                 pPage->pgno, pTrunk->pgno));
34195       }
34196     }else if( k<0 ){
34197       rc = SQLITE_CORRUPT;
34198     }else{
34199       /* Add the newly freed page as a leaf on the current trunk */
34200       rc = sqlite3PagerWrite(pTrunk->pDbPage);
34201       if( rc==SQLITE_OK ){
34202         put4byte(&pTrunk->aData[4], k+1);
34203         put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
34204 #ifndef SQLITE_SECURE_DELETE
34205         sqlite3PagerDontWrite(pPage->pDbPage);
34206 #endif
34207       }
34208       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
34209     }
34210     releasePage(pTrunk);
34211   }
34212   return rc;
34213 }
34214
34215 /*
34216 ** Free any overflow pages associated with the given Cell.
34217 */
34218 static int clearCell(MemPage *pPage, unsigned char *pCell){
34219   BtShared *pBt = pPage->pBt;
34220   CellInfo info;
34221   Pgno ovflPgno;
34222   int rc;
34223   int nOvfl;
34224   int ovflPageSize;
34225
34226   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34227   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34228   if( info.iOverflow==0 ){
34229     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
34230   }
34231   ovflPgno = get4byte(&pCell[info.iOverflow]);
34232   ovflPageSize = pBt->usableSize - 4;
34233   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
34234   assert( ovflPgno==0 || nOvfl>0 );
34235   while( nOvfl-- ){
34236     MemPage *pOvfl;
34237     if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
34238       return SQLITE_CORRUPT_BKPT;
34239     }
34240
34241     rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
34242     if( rc ) return rc;
34243     rc = freePage(pOvfl);
34244     sqlite3PagerUnref(pOvfl->pDbPage);
34245     if( rc ) return rc;
34246   }
34247   return SQLITE_OK;
34248 }
34249
34250 /*
34251 ** Create the byte sequence used to represent a cell on page pPage
34252 ** and write that byte sequence into pCell[].  Overflow pages are
34253 ** allocated and filled in as necessary.  The calling procedure
34254 ** is responsible for making sure sufficient space has been allocated
34255 ** for pCell[].
34256 **
34257 ** Note that pCell does not necessary need to point to the pPage->aData
34258 ** area.  pCell might point to some temporary storage.  The cell will
34259 ** be constructed in this temporary area then copied into pPage->aData
34260 ** later.
34261 */
34262 static int fillInCell(
34263   MemPage *pPage,                /* The page that contains the cell */
34264   unsigned char *pCell,          /* Complete text of the cell */
34265   const void *pKey, i64 nKey,    /* The key */
34266   const void *pData,int nData,   /* The data */
34267   int nZero,                     /* Extra zero bytes to append to pData */
34268   int *pnSize                    /* Write cell size here */
34269 ){
34270   int nPayload;
34271   const u8 *pSrc;
34272   int nSrc, n, rc;
34273   int spaceLeft;
34274   MemPage *pOvfl = 0;
34275   MemPage *pToRelease = 0;
34276   unsigned char *pPrior;
34277   unsigned char *pPayload;
34278   BtShared *pBt = pPage->pBt;
34279   Pgno pgnoOvfl = 0;
34280   int nHeader;
34281   CellInfo info;
34282
34283   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34284
34285   /* Fill in the header. */
34286   nHeader = 0;
34287   if( !pPage->leaf ){
34288     nHeader += 4;
34289   }
34290   if( pPage->hasData ){
34291     nHeader += putVarint(&pCell[nHeader], nData+nZero);
34292   }else{
34293     nData = nZero = 0;
34294   }
34295   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
34296   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34297   assert( info.nHeader==nHeader );
34298   assert( info.nKey==nKey );
34299   assert( info.nData==nData+nZero );
34300   
34301   /* Fill in the payload */
34302   nPayload = nData + nZero;
34303   if( pPage->intKey ){
34304     pSrc = pData;
34305     nSrc = nData;
34306     nData = 0;
34307   }else{
34308     nPayload += nKey;
34309     pSrc = pKey;
34310     nSrc = nKey;
34311   }
34312   *pnSize = info.nSize;
34313   spaceLeft = info.nLocal;
34314   pPayload = &pCell[nHeader];
34315   pPrior = &pCell[info.iOverflow];
34316
34317   while( nPayload>0 ){
34318     if( spaceLeft==0 ){
34319       int isExact = 0;
34320 #ifndef SQLITE_OMIT_AUTOVACUUM
34321       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
34322       if( pBt->autoVacuum ){
34323         do{
34324           pgnoOvfl++;
34325         } while( 
34326           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
34327         );
34328         if( pgnoOvfl>1 ){
34329           /* isExact = 1; */
34330         }
34331       }
34332 #endif
34333       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
34334 #ifndef SQLITE_OMIT_AUTOVACUUM
34335       /* If the database supports auto-vacuum, and the second or subsequent
34336       ** overflow page is being allocated, add an entry to the pointer-map
34337       ** for that page now. 
34338       **
34339       ** If this is the first overflow page, then write a partial entry 
34340       ** to the pointer-map. If we write nothing to this pointer-map slot,
34341       ** then the optimistic overflow chain processing in clearCell()
34342       ** may misinterpret the uninitialised values and delete the
34343       ** wrong pages from the database.
34344       */
34345       if( pBt->autoVacuum && rc==SQLITE_OK ){
34346         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
34347         rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
34348         if( rc ){
34349           releasePage(pOvfl);
34350         }
34351       }
34352 #endif
34353       if( rc ){
34354         releasePage(pToRelease);
34355         return rc;
34356       }
34357       put4byte(pPrior, pgnoOvfl);
34358       releasePage(pToRelease);
34359       pToRelease = pOvfl;
34360       pPrior = pOvfl->aData;
34361       put4byte(pPrior, 0);
34362       pPayload = &pOvfl->aData[4];
34363       spaceLeft = pBt->usableSize - 4;
34364     }
34365     n = nPayload;
34366     if( n>spaceLeft ) n = spaceLeft;
34367     if( nSrc>0 ){
34368       if( n>nSrc ) n = nSrc;
34369       assert( pSrc );
34370       memcpy(pPayload, pSrc, n);
34371     }else{
34372       memset(pPayload, 0, n);
34373     }
34374     nPayload -= n;
34375     pPayload += n;
34376     pSrc += n;
34377     nSrc -= n;
34378     spaceLeft -= n;
34379     if( nSrc==0 ){
34380       nSrc = nData;
34381       pSrc = pData;
34382     }
34383   }
34384   releasePage(pToRelease);
34385   return SQLITE_OK;
34386 }
34387
34388 /*
34389 ** Change the MemPage.pParent pointer on the page whose number is
34390 ** given in the second argument so that MemPage.pParent holds the
34391 ** pointer in the third argument.
34392 */
34393 static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
34394   MemPage *pThis;
34395   DbPage *pDbPage;
34396
34397   assert( sqlite3_mutex_held(pBt->mutex) );
34398   assert( pNewParent!=0 );
34399   if( pgno==0 ) return SQLITE_OK;
34400   assert( pBt->pPager!=0 );
34401   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
34402   if( pDbPage ){
34403     pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
34404     if( pThis->isInit ){
34405       assert( pThis->aData==sqlite3PagerGetData(pDbPage) );
34406       if( pThis->pParent!=pNewParent ){
34407         if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
34408         pThis->pParent = pNewParent;
34409         sqlite3PagerRef(pNewParent->pDbPage);
34410       }
34411       pThis->idxParent = idx;
34412     }
34413     sqlite3PagerUnref(pDbPage);
34414   }
34415
34416 #ifndef SQLITE_OMIT_AUTOVACUUM
34417   if( pBt->autoVacuum ){
34418     return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
34419   }
34420 #endif
34421   return SQLITE_OK;
34422 }
34423
34424
34425
34426 /*
34427 ** Change the pParent pointer of all children of pPage to point back
34428 ** to pPage.
34429 **
34430 ** In other words, for every child of pPage, invoke reparentPage()
34431 ** to make sure that each child knows that pPage is its parent.
34432 **
34433 ** This routine gets called after you memcpy() one page into
34434 ** another.
34435 */
34436 static int reparentChildPages(MemPage *pPage){
34437   int i;
34438   BtShared *pBt = pPage->pBt;
34439   int rc = SQLITE_OK;
34440
34441   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34442   if( pPage->leaf ) return SQLITE_OK;
34443
34444   for(i=0; i<pPage->nCell; i++){
34445     u8 *pCell = findCell(pPage, i);
34446     rc = reparentPage(pBt, get4byte(pCell), pPage, i);
34447     if( rc!=SQLITE_OK ) return rc;
34448   }
34449   rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]), 
34450                     pPage, i);
34451   pPage->idxShift = 0;
34452   return rc;
34453 }
34454
34455 /*
34456 ** Remove the i-th cell from pPage.  This routine effects pPage only.
34457 ** The cell content is not freed or deallocated.  It is assumed that
34458 ** the cell content has been copied someplace else.  This routine just
34459 ** removes the reference to the cell from pPage.
34460 **
34461 ** "sz" must be the number of bytes in the cell.
34462 */
34463 static void dropCell(MemPage *pPage, int idx, int sz){
34464   int i;          /* Loop counter */
34465   int pc;         /* Offset to cell content of cell being deleted */
34466   u8 *data;       /* pPage->aData */
34467   u8 *ptr;        /* Used to move bytes around within data[] */
34468
34469   assert( idx>=0 && idx<pPage->nCell );
34470   assert( sz==cellSize(pPage, idx) );
34471   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34472   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34473   data = pPage->aData;
34474   ptr = &data[pPage->cellOffset + 2*idx];
34475   pc = get2byte(ptr);
34476   assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
34477   freeSpace(pPage, pc, sz);
34478   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
34479     ptr[0] = ptr[2];
34480     ptr[1] = ptr[3];
34481   }
34482   pPage->nCell--;
34483   put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
34484   pPage->nFree += 2;
34485   pPage->idxShift = 1;
34486 }
34487
34488 /*
34489 ** Insert a new cell on pPage at cell index "i".  pCell points to the
34490 ** content of the cell.
34491 **
34492 ** If the cell content will fit on the page, then put it there.  If it
34493 ** will not fit, then make a copy of the cell content into pTemp if
34494 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
34495 ** in pPage->aOvfl[] and make it point to the cell content (either
34496 ** in pTemp or the original pCell) and also record its index. 
34497 ** Allocating a new entry in pPage->aCell[] implies that 
34498 ** pPage->nOverflow is incremented.
34499 **
34500 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
34501 ** cell. The caller will overwrite them after this function returns. If
34502 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
34503 ** (but pCell+nSkip is always valid).
34504 */
34505 static int insertCell(
34506   MemPage *pPage,   /* Page into which we are copying */
34507   int i,            /* New cell becomes the i-th cell of the page */
34508   u8 *pCell,        /* Content of the new cell */
34509   int sz,           /* Bytes of content in pCell */
34510   u8 *pTemp,        /* Temp storage space for pCell, if needed */
34511   u8 nSkip          /* Do not write the first nSkip bytes of the cell */
34512 ){
34513   int idx;          /* Where to write new cell content in data[] */
34514   int j;            /* Loop counter */
34515   int top;          /* First byte of content for any cell in data[] */
34516   int end;          /* First byte past the last cell pointer in data[] */
34517   int ins;          /* Index in data[] where new cell pointer is inserted */
34518   int hdr;          /* Offset into data[] of the page header */
34519   int cellOffset;   /* Address of first cell pointer in data[] */
34520   u8 *data;         /* The content of the whole page */
34521   u8 *ptr;          /* Used for moving information around in data[] */
34522
34523   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
34524   assert( sz==cellSizePtr(pPage, pCell) );
34525   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34526   if( pPage->nOverflow || sz+2>pPage->nFree ){
34527     if( pTemp ){
34528       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
34529       pCell = pTemp;
34530     }
34531     j = pPage->nOverflow++;
34532     assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
34533     pPage->aOvfl[j].pCell = pCell;
34534     pPage->aOvfl[j].idx = i;
34535     pPage->nFree = 0;
34536   }else{
34537     int rc = sqlite3PagerWrite(pPage->pDbPage);
34538     if( rc!=SQLITE_OK ){
34539       return rc;
34540     }
34541     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34542     data = pPage->aData;
34543     hdr = pPage->hdrOffset;
34544     top = get2byte(&data[hdr+5]);
34545     cellOffset = pPage->cellOffset;
34546     end = cellOffset + 2*pPage->nCell + 2;
34547     ins = cellOffset + 2*i;
34548     if( end > top - sz ){
34549       rc = defragmentPage(pPage);
34550       if( rc!=SQLITE_OK ) return rc;
34551       top = get2byte(&data[hdr+5]);
34552       assert( end + sz <= top );
34553     }
34554     idx = allocateSpace(pPage, sz);
34555     assert( idx>0 );
34556     assert( end <= get2byte(&data[hdr+5]) );
34557     pPage->nCell++;
34558     pPage->nFree -= 2;
34559     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
34560     for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
34561       ptr[0] = ptr[-2];
34562       ptr[1] = ptr[-1];
34563     }
34564     put2byte(&data[ins], idx);
34565     put2byte(&data[hdr+3], pPage->nCell);
34566     pPage->idxShift = 1;
34567 #ifndef SQLITE_OMIT_AUTOVACUUM
34568     if( pPage->pBt->autoVacuum ){
34569       /* The cell may contain a pointer to an overflow page. If so, write
34570       ** the entry for the overflow page into the pointer map.
34571       */
34572       CellInfo info;
34573       sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34574       assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
34575       if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
34576         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
34577         rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
34578         if( rc!=SQLITE_OK ) return rc;
34579       }
34580     }
34581 #endif
34582   }
34583
34584   return SQLITE_OK;
34585 }
34586
34587 /*
34588 ** Add a list of cells to a page.  The page should be initially empty.
34589 ** The cells are guaranteed to fit on the page.
34590 */
34591 static void assemblePage(
34592   MemPage *pPage,   /* The page to be assemblied */
34593   int nCell,        /* The number of cells to add to this page */
34594   u8 **apCell,      /* Pointers to cell bodies */
34595   u16 *aSize        /* Sizes of the cells */
34596 ){
34597   int i;            /* Loop counter */
34598   int totalSize;    /* Total size of all cells */
34599   int hdr;          /* Index of page header */
34600   int cellptr;      /* Address of next cell pointer */
34601   int cellbody;     /* Address of next cell body */
34602   u8 *data;         /* Data for the page */
34603
34604   assert( pPage->nOverflow==0 );
34605   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34606   totalSize = 0;
34607   for(i=0; i<nCell; i++){
34608     totalSize += aSize[i];
34609   }
34610   assert( totalSize+2*nCell<=pPage->nFree );
34611   assert( pPage->nCell==0 );
34612   cellptr = pPage->cellOffset;
34613   data = pPage->aData;
34614   hdr = pPage->hdrOffset;
34615   put2byte(&data[hdr+3], nCell);
34616   if( nCell ){
34617     cellbody = allocateSpace(pPage, totalSize);
34618     assert( cellbody>0 );
34619     assert( pPage->nFree >= 2*nCell );
34620     pPage->nFree -= 2*nCell;
34621     for(i=0; i<nCell; i++){
34622       put2byte(&data[cellptr], cellbody);
34623       memcpy(&data[cellbody], apCell[i], aSize[i]);
34624       cellptr += 2;
34625       cellbody += aSize[i];
34626     }
34627     assert( cellbody==pPage->pBt->usableSize );
34628   }
34629   pPage->nCell = nCell;
34630 }
34631
34632 /*
34633 ** The following parameters determine how many adjacent pages get involved
34634 ** in a balancing operation.  NN is the number of neighbors on either side
34635 ** of the page that participate in the balancing operation.  NB is the
34636 ** total number of pages that participate, including the target page and
34637 ** NN neighbors on either side.
34638 **
34639 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
34640 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
34641 ** in exchange for a larger degradation in INSERT and UPDATE performance.
34642 ** The value of NN appears to give the best results overall.
34643 */
34644 #define NN 1             /* Number of neighbors on either side of pPage */
34645 #define NB (NN*2+1)      /* Total pages involved in the balance */
34646
34647 /* Forward reference */
34648 static int balance(MemPage*, int);
34649
34650 #ifndef SQLITE_OMIT_QUICKBALANCE
34651 /*
34652 ** This version of balance() handles the common special case where
34653 ** a new entry is being inserted on the extreme right-end of the
34654 ** tree, in other words, when the new entry will become the largest
34655 ** entry in the tree.
34656 **
34657 ** Instead of trying balance the 3 right-most leaf pages, just add
34658 ** a new page to the right-hand side and put the one new entry in
34659 ** that page.  This leaves the right side of the tree somewhat
34660 ** unbalanced.  But odds are that we will be inserting new entries
34661 ** at the end soon afterwards so the nearly empty page will quickly
34662 ** fill up.  On average.
34663 **
34664 ** pPage is the leaf page which is the right-most page in the tree.
34665 ** pParent is its parent.  pPage must have a single overflow entry
34666 ** which is also the right-most entry on the page.
34667 */
34668 static int balance_quick(MemPage *pPage, MemPage *pParent){
34669   int rc;
34670   MemPage *pNew;
34671   Pgno pgnoNew;
34672   u8 *pCell;
34673   u16 szCell;
34674   CellInfo info;
34675   BtShared *pBt = pPage->pBt;
34676   int parentIdx = pParent->nCell;   /* pParent new divider cell index */
34677   int parentSize;                   /* Size of new divider cell */
34678   u8 parentCell[64];                /* Space for the new divider cell */
34679
34680   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34681
34682   /* Allocate a new page. Insert the overflow cell from pPage
34683   ** into it. Then remove the overflow cell from pPage.
34684   */
34685   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
34686   if( rc!=SQLITE_OK ){
34687     return rc;
34688   }
34689   pCell = pPage->aOvfl[0].pCell;
34690   szCell = cellSizePtr(pPage, pCell);
34691   zeroPage(pNew, pPage->aData[0]);
34692   assemblePage(pNew, 1, &pCell, &szCell);
34693   pPage->nOverflow = 0;
34694
34695   /* Set the parent of the newly allocated page to pParent. */
34696   pNew->pParent = pParent;
34697   sqlite3PagerRef(pParent->pDbPage);
34698
34699   /* pPage is currently the right-child of pParent. Change this
34700   ** so that the right-child is the new page allocated above and
34701   ** pPage is the next-to-right child. 
34702   */
34703   assert( pPage->nCell>0 );
34704   pCell = findCell(pPage, pPage->nCell-1);
34705   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34706   rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
34707   if( rc!=SQLITE_OK ){
34708     return rc;
34709   }
34710   assert( parentSize<64 );
34711   rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
34712   if( rc!=SQLITE_OK ){
34713     return rc;
34714   }
34715   put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
34716   put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
34717
34718 #ifndef SQLITE_OMIT_AUTOVACUUM
34719   /* If this is an auto-vacuum database, update the pointer map
34720   ** with entries for the new page, and any pointer from the 
34721   ** cell on the page to an overflow page.
34722   */
34723   if( pBt->autoVacuum ){
34724     rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
34725     if( rc==SQLITE_OK ){
34726       rc = ptrmapPutOvfl(pNew, 0);
34727     }
34728     if( rc!=SQLITE_OK ){
34729       releasePage(pNew);
34730       return rc;
34731     }
34732   }
34733 #endif
34734
34735   /* Release the reference to the new page and balance the parent page,
34736   ** in case the divider cell inserted caused it to become overfull.
34737   */
34738   releasePage(pNew);
34739   return balance(pParent, 0);
34740 }
34741 #endif /* SQLITE_OMIT_QUICKBALANCE */
34742
34743 /*
34744 ** This routine redistributes Cells on pPage and up to NN*2 siblings
34745 ** of pPage so that all pages have about the same amount of free space.
34746 ** Usually NN siblings on either side of pPage is used in the balancing,
34747 ** though more siblings might come from one side if pPage is the first
34748 ** or last child of its parent.  If pPage has fewer than 2*NN siblings
34749 ** (something which can only happen if pPage is the root page or a 
34750 ** child of root) then all available siblings participate in the balancing.
34751 **
34752 ** The number of siblings of pPage might be increased or decreased by one or
34753 ** two in an effort to keep pages nearly full but not over full. The root page
34754 ** is special and is allowed to be nearly empty. If pPage is 
34755 ** the root page, then the depth of the tree might be increased
34756 ** or decreased by one, as necessary, to keep the root page from being
34757 ** overfull or completely empty.
34758 **
34759 ** Note that when this routine is called, some of the Cells on pPage
34760 ** might not actually be stored in pPage->aData[].  This can happen
34761 ** if the page is overfull.  Part of the job of this routine is to
34762 ** make sure all Cells for pPage once again fit in pPage->aData[].
34763 **
34764 ** In the course of balancing the siblings of pPage, the parent of pPage
34765 ** might become overfull or underfull.  If that happens, then this routine
34766 ** is called recursively on the parent.
34767 **
34768 ** If this routine fails for any reason, it might leave the database
34769 ** in a corrupted state.  So if this routine fails, the database should
34770 ** be rolled back.
34771 */
34772 static int balance_nonroot(MemPage *pPage){
34773   MemPage *pParent;            /* The parent of pPage */
34774   BtShared *pBt;               /* The whole database */
34775   int nCell = 0;               /* Number of cells in apCell[] */
34776   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
34777   int nOld;                    /* Number of pages in apOld[] */
34778   int nNew;                    /* Number of pages in apNew[] */
34779   int nDiv;                    /* Number of cells in apDiv[] */
34780   int i, j, k;                 /* Loop counters */
34781   int idx;                     /* Index of pPage in pParent->aCell[] */
34782   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
34783   int rc;                      /* The return code */
34784   int leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
34785   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
34786   int usableSpace;             /* Bytes in pPage beyond the header */
34787   int pageFlags;               /* Value of pPage->aData[0] */
34788   int subtotal;                /* Subtotal of bytes in cells on one page */
34789   int iSpace = 0;              /* First unused byte of aSpace[] */
34790   MemPage *apOld[NB];          /* pPage and up to two siblings */
34791   Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
34792   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
34793   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
34794   Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
34795   u8 *apDiv[NB];               /* Divider cells in pParent */
34796   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
34797   int szNew[NB+2];             /* Combined size of cells place on i-th page */
34798   u8 **apCell = 0;             /* All cells begin balanced */
34799   u16 *szCell;                 /* Local size of all cells in apCell[] */
34800   u8 *aCopy[NB];               /* Space for holding data of apCopy[] */
34801   u8 *aSpace;                  /* Space to hold copies of dividers cells */
34802 #ifndef SQLITE_OMIT_AUTOVACUUM
34803   u8 *aFrom = 0;
34804 #endif
34805
34806   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34807
34808   /* 
34809   ** Find the parent page.
34810   */
34811   assert( pPage->isInit );
34812   assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
34813   pBt = pPage->pBt;
34814   pParent = pPage->pParent;
34815   assert( pParent );
34816   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
34817     return rc;
34818   }
34819   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
34820
34821 #ifndef SQLITE_OMIT_QUICKBALANCE
34822   /*
34823   ** A special case:  If a new entry has just been inserted into a
34824   ** table (that is, a btree with integer keys and all data at the leaves)
34825   ** and the new entry is the right-most entry in the tree (it has the
34826   ** largest key) then use the special balance_quick() routine for
34827   ** balancing.  balance_quick() is much faster and results in a tighter
34828   ** packing of data in the common case.
34829   */
34830   if( pPage->leaf &&
34831       pPage->intKey &&
34832       pPage->leafData &&
34833       pPage->nOverflow==1 &&
34834       pPage->aOvfl[0].idx==pPage->nCell &&
34835       pPage->pParent->pgno!=1 &&
34836       get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
34837   ){
34838     /*
34839     ** TODO: Check the siblings to the left of pPage. It may be that
34840     ** they are not full and no new page is required.
34841     */
34842     return balance_quick(pPage, pParent);
34843   }
34844 #endif
34845
34846   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
34847     return rc;
34848   }
34849
34850   /*
34851   ** Find the cell in the parent page whose left child points back
34852   ** to pPage.  The "idx" variable is the index of that cell.  If pPage
34853   ** is the rightmost child of pParent then set idx to pParent->nCell 
34854   */
34855   if( pParent->idxShift ){
34856     Pgno pgno;
34857     pgno = pPage->pgno;
34858     assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
34859     for(idx=0; idx<pParent->nCell; idx++){
34860       if( get4byte(findCell(pParent, idx))==pgno ){
34861         break;
34862       }
34863     }
34864     assert( idx<pParent->nCell
34865              || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
34866   }else{
34867     idx = pPage->idxParent;
34868   }
34869
34870   /*
34871   ** Initialize variables so that it will be safe to jump
34872   ** directly to balance_cleanup at any moment.
34873   */
34874   nOld = nNew = 0;
34875   sqlite3PagerRef(pParent->pDbPage);
34876
34877   /*
34878   ** Find sibling pages to pPage and the cells in pParent that divide
34879   ** the siblings.  An attempt is made to find NN siblings on either
34880   ** side of pPage.  More siblings are taken from one side, however, if
34881   ** pPage there are fewer than NN siblings on the other side.  If pParent
34882   ** has NB or fewer children then all children of pParent are taken.
34883   */
34884   nxDiv = idx - NN;
34885   if( nxDiv + NB > pParent->nCell ){
34886     nxDiv = pParent->nCell - NB + 1;
34887   }
34888   if( nxDiv<0 ){
34889     nxDiv = 0;
34890   }
34891   nDiv = 0;
34892   for(i=0, k=nxDiv; i<NB; i++, k++){
34893     if( k<pParent->nCell ){
34894       apDiv[i] = findCell(pParent, k);
34895       nDiv++;
34896       assert( !pParent->leaf );
34897       pgnoOld[i] = get4byte(apDiv[i]);
34898     }else if( k==pParent->nCell ){
34899       pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
34900     }else{
34901       break;
34902     }
34903     rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
34904     if( rc ) goto balance_cleanup;
34905     apOld[i]->idxParent = k;
34906     apCopy[i] = 0;
34907     assert( i==nOld );
34908     nOld++;
34909     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
34910   }
34911
34912   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
34913   ** alignment */
34914   nMaxCells = (nMaxCells + 3)&~3;
34915
34916   /*
34917   ** Allocate space for memory structures
34918   */
34919   apCell = sqlite3_malloc( 
34920        nMaxCells*sizeof(u8*)                       /* apCell */
34921      + nMaxCells*sizeof(u16)                       /* szCell */
34922      + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB  /* aCopy */
34923      + pBt->pageSize*5                             /* aSpace */
34924      + (ISAUTOVACUUM ? nMaxCells : 0)              /* aFrom */
34925   );
34926   if( apCell==0 ){
34927     rc = SQLITE_NOMEM;
34928     goto balance_cleanup;
34929   }
34930   szCell = (u16*)&apCell[nMaxCells];
34931   aCopy[0] = (u8*)&szCell[nMaxCells];
34932   assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
34933   for(i=1; i<NB; i++){
34934     aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
34935     assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
34936   }
34937   aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
34938   assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
34939 #ifndef SQLITE_OMIT_AUTOVACUUM
34940   if( pBt->autoVacuum ){
34941     aFrom = &aSpace[5*pBt->pageSize];
34942   }
34943 #endif
34944   
34945   /*
34946   ** Make copies of the content of pPage and its siblings into aOld[].
34947   ** The rest of this function will use data from the copies rather
34948   ** that the original pages since the original pages will be in the
34949   ** process of being overwritten.
34950   */
34951   for(i=0; i<nOld; i++){
34952     MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
34953     memcpy(p, apOld[i], sizeof(MemPage));
34954     p->aData = (void*)&p[1];
34955     memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
34956   }
34957
34958   /*
34959   ** Load pointers to all cells on sibling pages and the divider cells
34960   ** into the local apCell[] array.  Make copies of the divider cells
34961   ** into space obtained form aSpace[] and remove the the divider Cells
34962   ** from pParent.
34963   **
34964   ** If the siblings are on leaf pages, then the child pointers of the
34965   ** divider cells are stripped from the cells before they are copied
34966   ** into aSpace[].  In this way, all cells in apCell[] are without
34967   ** child pointers.  If siblings are not leaves, then all cell in
34968   ** apCell[] include child pointers.  Either way, all cells in apCell[]
34969   ** are alike.
34970   **
34971   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
34972   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
34973   */
34974   nCell = 0;
34975   leafCorrection = pPage->leaf*4;
34976   leafData = pPage->leafData && pPage->leaf;
34977   for(i=0; i<nOld; i++){
34978     MemPage *pOld = apCopy[i];
34979     int limit = pOld->nCell+pOld->nOverflow;
34980     for(j=0; j<limit; j++){
34981       assert( nCell<nMaxCells );
34982       apCell[nCell] = findOverflowCell(pOld, j);
34983       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
34984 #ifndef SQLITE_OMIT_AUTOVACUUM
34985       if( pBt->autoVacuum ){
34986         int a;
34987         aFrom[nCell] = i;
34988         for(a=0; a<pOld->nOverflow; a++){
34989           if( pOld->aOvfl[a].pCell==apCell[nCell] ){
34990             aFrom[nCell] = 0xFF;
34991             break;
34992           }
34993         }
34994       }
34995 #endif
34996       nCell++;
34997     }
34998     if( i<nOld-1 ){
34999       u16 sz = cellSizePtr(pParent, apDiv[i]);
35000       if( leafData ){
35001         /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
35002         ** are duplicates of keys on the child pages.  We need to remove
35003         ** the divider cells from pParent, but the dividers cells are not
35004         ** added to apCell[] because they are duplicates of child cells.
35005         */
35006         dropCell(pParent, nxDiv, sz);
35007       }else{
35008         u8 *pTemp;
35009         assert( nCell<nMaxCells );
35010         szCell[nCell] = sz;
35011         pTemp = &aSpace[iSpace];
35012         iSpace += sz;
35013         assert( iSpace<=pBt->pageSize*5 );
35014         memcpy(pTemp, apDiv[i], sz);
35015         apCell[nCell] = pTemp+leafCorrection;
35016 #ifndef SQLITE_OMIT_AUTOVACUUM
35017         if( pBt->autoVacuum ){
35018           aFrom[nCell] = 0xFF;
35019         }
35020 #endif
35021         dropCell(pParent, nxDiv, sz);
35022         szCell[nCell] -= leafCorrection;
35023         assert( get4byte(pTemp)==pgnoOld[i] );
35024         if( !pOld->leaf ){
35025           assert( leafCorrection==0 );
35026           /* The right pointer of the child page pOld becomes the left
35027           ** pointer of the divider cell */
35028           memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
35029         }else{
35030           assert( leafCorrection==4 );
35031           if( szCell[nCell]<4 ){
35032             /* Do not allow any cells smaller than 4 bytes. */
35033             szCell[nCell] = 4;
35034           }
35035         }
35036         nCell++;
35037       }
35038     }
35039   }
35040
35041   /*
35042   ** Figure out the number of pages needed to hold all nCell cells.
35043   ** Store this number in "k".  Also compute szNew[] which is the total
35044   ** size of all cells on the i-th page and cntNew[] which is the index
35045   ** in apCell[] of the cell that divides page i from page i+1.  
35046   ** cntNew[k] should equal nCell.
35047   **
35048   ** Values computed by this block:
35049   **
35050   **           k: The total number of sibling pages
35051   **    szNew[i]: Spaced used on the i-th sibling page.
35052   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
35053   **              the right of the i-th sibling page.
35054   ** usableSpace: Number of bytes of space available on each sibling.
35055   ** 
35056   */
35057   usableSpace = pBt->usableSize - 12 + leafCorrection;
35058   for(subtotal=k=i=0; i<nCell; i++){
35059     assert( i<nMaxCells );
35060     subtotal += szCell[i] + 2;
35061     if( subtotal > usableSpace ){
35062       szNew[k] = subtotal - szCell[i];
35063       cntNew[k] = i;
35064       if( leafData ){ i--; }
35065       subtotal = 0;
35066       k++;
35067     }
35068   }
35069   szNew[k] = subtotal;
35070   cntNew[k] = nCell;
35071   k++;
35072
35073   /*
35074   ** The packing computed by the previous block is biased toward the siblings
35075   ** on the left side.  The left siblings are always nearly full, while the
35076   ** right-most sibling might be nearly empty.  This block of code attempts
35077   ** to adjust the packing of siblings to get a better balance.
35078   **
35079   ** This adjustment is more than an optimization.  The packing above might
35080   ** be so out of balance as to be illegal.  For example, the right-most
35081   ** sibling might be completely empty.  This adjustment is not optional.
35082   */
35083   for(i=k-1; i>0; i--){
35084     int szRight = szNew[i];  /* Size of sibling on the right */
35085     int szLeft = szNew[i-1]; /* Size of sibling on the left */
35086     int r;              /* Index of right-most cell in left sibling */
35087     int d;              /* Index of first cell to the left of right sibling */
35088
35089     r = cntNew[i-1] - 1;
35090     d = r + 1 - leafData;
35091     assert( d<nMaxCells );
35092     assert( r<nMaxCells );
35093     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
35094       szRight += szCell[d] + 2;
35095       szLeft -= szCell[r] + 2;
35096       cntNew[i-1]--;
35097       r = cntNew[i-1] - 1;
35098       d = r + 1 - leafData;
35099     }
35100     szNew[i] = szRight;
35101     szNew[i-1] = szLeft;
35102   }
35103
35104   /* Either we found one or more cells (cntnew[0])>0) or we are the
35105   ** a virtual root page.  A virtual root page is when the real root
35106   ** page is page 1 and we are the only child of that page.
35107   */
35108   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
35109
35110   /*
35111   ** Allocate k new pages.  Reuse old pages where possible.
35112   */
35113   assert( pPage->pgno>1 );
35114   pageFlags = pPage->aData[0];
35115   for(i=0; i<k; i++){
35116     MemPage *pNew;
35117     if( i<nOld ){
35118       pNew = apNew[i] = apOld[i];
35119       pgnoNew[i] = pgnoOld[i];
35120       apOld[i] = 0;
35121       rc = sqlite3PagerWrite(pNew->pDbPage);
35122       nNew++;
35123       if( rc ) goto balance_cleanup;
35124     }else{
35125       assert( i>0 );
35126       rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
35127       if( rc ) goto balance_cleanup;
35128       apNew[i] = pNew;
35129       nNew++;
35130     }
35131     zeroPage(pNew, pageFlags);
35132   }
35133
35134   /* Free any old pages that were not reused as new pages.
35135   */
35136   while( i<nOld ){
35137     rc = freePage(apOld[i]);
35138     if( rc ) goto balance_cleanup;
35139     releasePage(apOld[i]);
35140     apOld[i] = 0;
35141     i++;
35142   }
35143
35144   /*
35145   ** Put the new pages in accending order.  This helps to
35146   ** keep entries in the disk file in order so that a scan
35147   ** of the table is a linear scan through the file.  That
35148   ** in turn helps the operating system to deliver pages
35149   ** from the disk more rapidly.
35150   **
35151   ** An O(n^2) insertion sort algorithm is used, but since
35152   ** n is never more than NB (a small constant), that should
35153   ** not be a problem.
35154   **
35155   ** When NB==3, this one optimization makes the database
35156   ** about 25% faster for large insertions and deletions.
35157   */
35158   for(i=0; i<k-1; i++){
35159     int minV = pgnoNew[i];
35160     int minI = i;
35161     for(j=i+1; j<k; j++){
35162       if( pgnoNew[j]<(unsigned)minV ){
35163         minI = j;
35164         minV = pgnoNew[j];
35165       }
35166     }
35167     if( minI>i ){
35168       int t;
35169       MemPage *pT;
35170       t = pgnoNew[i];
35171       pT = apNew[i];
35172       pgnoNew[i] = pgnoNew[minI];
35173       apNew[i] = apNew[minI];
35174       pgnoNew[minI] = t;
35175       apNew[minI] = pT;
35176     }
35177   }
35178   TRACE(("BALANCE: old: %d %d %d  new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
35179     pgnoOld[0], 
35180     nOld>=2 ? pgnoOld[1] : 0,
35181     nOld>=3 ? pgnoOld[2] : 0,
35182     pgnoNew[0], szNew[0],
35183     nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
35184     nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
35185     nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
35186     nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
35187
35188   /*
35189   ** Evenly distribute the data in apCell[] across the new pages.
35190   ** Insert divider cells into pParent as necessary.
35191   */
35192   j = 0;
35193   for(i=0; i<nNew; i++){
35194     /* Assemble the new sibling page. */
35195     MemPage *pNew = apNew[i];
35196     assert( j<nMaxCells );
35197     assert( pNew->pgno==pgnoNew[i] );
35198     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
35199     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
35200     assert( pNew->nOverflow==0 );
35201
35202 #ifndef SQLITE_OMIT_AUTOVACUUM
35203     /* If this is an auto-vacuum database, update the pointer map entries
35204     ** that point to the siblings that were rearranged. These can be: left
35205     ** children of cells, the right-child of the page, or overflow pages
35206     ** pointed to by cells.
35207     */
35208     if( pBt->autoVacuum ){
35209       for(k=j; k<cntNew[i]; k++){
35210         assert( k<nMaxCells );
35211         if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
35212           rc = ptrmapPutOvfl(pNew, k-j);
35213           if( rc!=SQLITE_OK ){
35214             goto balance_cleanup;
35215           }
35216         }
35217       }
35218     }
35219 #endif
35220
35221     j = cntNew[i];
35222
35223     /* If the sibling page assembled above was not the right-most sibling,
35224     ** insert a divider cell into the parent page.
35225     */
35226     if( i<nNew-1 && j<nCell ){
35227       u8 *pCell;
35228       u8 *pTemp;
35229       int sz;
35230
35231       assert( j<nMaxCells );
35232       pCell = apCell[j];
35233       sz = szCell[j] + leafCorrection;
35234       if( !pNew->leaf ){
35235         memcpy(&pNew->aData[8], pCell, 4);
35236         pTemp = 0;
35237       }else if( leafData ){
35238         /* If the tree is a leaf-data tree, and the siblings are leaves, 
35239         ** then there is no divider cell in apCell[]. Instead, the divider 
35240         ** cell consists of the integer key for the right-most cell of 
35241         ** the sibling-page assembled above only.
35242         */
35243         CellInfo info;
35244         j--;
35245         sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
35246         pCell = &aSpace[iSpace];
35247         fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
35248         iSpace += sz;
35249         assert( iSpace<=pBt->pageSize*5 );
35250         pTemp = 0;
35251       }else{
35252         pCell -= 4;
35253         pTemp = &aSpace[iSpace];
35254         iSpace += sz;
35255         assert( iSpace<=pBt->pageSize*5 );
35256         /* Obscure case for non-leaf-data trees: If the cell at pCell was
35257         ** previously stored on a leaf node, and its reported size was 4
35258         ** bytes, then it may actually be smaller than this 
35259         ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
35260         ** any cell). But it is important to pass the correct size to 
35261         ** insertCell(), so reparse the cell now.
35262         **
35263         ** Note that this can never happen in an SQLite data file, as all
35264         ** cells are at least 4 bytes. It only happens in b-trees used
35265         ** to evaluate "IN (SELECT ...)" and similar clauses.
35266         */
35267         if( szCell[j]==4 ){
35268           assert(leafCorrection==4);
35269           sz = cellSizePtr(pParent, pCell);
35270         }
35271       }
35272       rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
35273       if( rc!=SQLITE_OK ) goto balance_cleanup;
35274       put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
35275 #ifndef SQLITE_OMIT_AUTOVACUUM
35276       /* If this is an auto-vacuum database, and not a leaf-data tree,
35277       ** then update the pointer map with an entry for the overflow page
35278       ** that the cell just inserted points to (if any).
35279       */
35280       if( pBt->autoVacuum && !leafData ){
35281         rc = ptrmapPutOvfl(pParent, nxDiv);
35282         if( rc!=SQLITE_OK ){
35283           goto balance_cleanup;
35284         }
35285       }
35286 #endif
35287       j++;
35288       nxDiv++;
35289     }
35290   }
35291   assert( j==nCell );
35292   assert( nOld>0 );
35293   assert( nNew>0 );
35294   if( (pageFlags & PTF_LEAF)==0 ){
35295     memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
35296   }
35297   if( nxDiv==pParent->nCell+pParent->nOverflow ){
35298     /* Right-most sibling is the right-most child of pParent */
35299     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
35300   }else{
35301     /* Right-most sibling is the left child of the first entry in pParent
35302     ** past the right-most divider entry */
35303     put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
35304   }
35305
35306   /*
35307   ** Reparent children of all cells.
35308   */
35309   for(i=0; i<nNew; i++){
35310     rc = reparentChildPages(apNew[i]);
35311     if( rc!=SQLITE_OK ) goto balance_cleanup;
35312   }
35313   rc = reparentChildPages(pParent);
35314   if( rc!=SQLITE_OK ) goto balance_cleanup;
35315
35316   /*
35317   ** Balance the parent page.  Note that the current page (pPage) might
35318   ** have been added to the freelist so it might no longer be initialized.
35319   ** But the parent page will always be initialized.
35320   */
35321   assert( pParent->isInit );
35322   rc = balance(pParent, 0);
35323   
35324   /*
35325   ** Cleanup before returning.
35326   */
35327 balance_cleanup:
35328   sqlite3_free(apCell);
35329   for(i=0; i<nOld; i++){
35330     releasePage(apOld[i]);
35331   }
35332   for(i=0; i<nNew; i++){
35333     releasePage(apNew[i]);
35334   }
35335   releasePage(pParent);
35336   TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
35337           pPage->pgno, nOld, nNew, nCell));
35338   return rc;
35339 }
35340
35341 /*
35342 ** This routine is called for the root page of a btree when the root
35343 ** page contains no cells.  This is an opportunity to make the tree
35344 ** shallower by one level.
35345 */
35346 static int balance_shallower(MemPage *pPage){
35347   MemPage *pChild;             /* The only child page of pPage */
35348   Pgno pgnoChild;              /* Page number for pChild */
35349   int rc = SQLITE_OK;          /* Return code from subprocedures */
35350   BtShared *pBt;                  /* The main BTree structure */
35351   int mxCellPerPage;           /* Maximum number of cells per page */
35352   u8 **apCell;                 /* All cells from pages being balanced */
35353   u16 *szCell;                 /* Local size of all cells */
35354
35355   assert( pPage->pParent==0 );
35356   assert( pPage->nCell==0 );
35357   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35358   pBt = pPage->pBt;
35359   mxCellPerPage = MX_CELL(pBt);
35360   apCell = sqlite3_malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
35361   if( apCell==0 ) return SQLITE_NOMEM;
35362   szCell = (u16*)&apCell[mxCellPerPage];
35363   if( pPage->leaf ){
35364     /* The table is completely empty */
35365     TRACE(("BALANCE: empty table %d\n", pPage->pgno));
35366   }else{
35367     /* The root page is empty but has one child.  Transfer the
35368     ** information from that one child into the root page if it 
35369     ** will fit.  This reduces the depth of the tree by one.
35370     **
35371     ** If the root page is page 1, it has less space available than
35372     ** its child (due to the 100 byte header that occurs at the beginning
35373     ** of the database fle), so it might not be able to hold all of the 
35374     ** information currently contained in the child.  If this is the 
35375     ** case, then do not do the transfer.  Leave page 1 empty except
35376     ** for the right-pointer to the child page.  The child page becomes
35377     ** the virtual root of the tree.
35378     */
35379     pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
35380     assert( pgnoChild>0 );
35381     assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
35382     rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
35383     if( rc ) goto end_shallow_balance;
35384     if( pPage->pgno==1 ){
35385       rc = sqlite3BtreeInitPage(pChild, pPage);
35386       if( rc ) goto end_shallow_balance;
35387       assert( pChild->nOverflow==0 );
35388       if( pChild->nFree>=100 ){
35389         /* The child information will fit on the root page, so do the
35390         ** copy */
35391         int i;
35392         zeroPage(pPage, pChild->aData[0]);
35393         for(i=0; i<pChild->nCell; i++){
35394           apCell[i] = findCell(pChild,i);
35395           szCell[i] = cellSizePtr(pChild, apCell[i]);
35396         }
35397         assemblePage(pPage, pChild->nCell, apCell, szCell);
35398         /* Copy the right-pointer of the child to the parent. */
35399         put4byte(&pPage->aData[pPage->hdrOffset+8], 
35400             get4byte(&pChild->aData[pChild->hdrOffset+8]));
35401         freePage(pChild);
35402         TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
35403       }else{
35404         /* The child has more information that will fit on the root.
35405         ** The tree is already balanced.  Do nothing. */
35406         TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
35407       }
35408     }else{
35409       memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
35410       pPage->isInit = 0;
35411       pPage->pParent = 0;
35412       rc = sqlite3BtreeInitPage(pPage, 0);
35413       assert( rc==SQLITE_OK );
35414       freePage(pChild);
35415       TRACE(("BALANCE: transfer child %d into root %d\n",
35416               pChild->pgno, pPage->pgno));
35417     }
35418     rc = reparentChildPages(pPage);
35419     assert( pPage->nOverflow==0 );
35420 #ifndef SQLITE_OMIT_AUTOVACUUM
35421     if( pBt->autoVacuum ){
35422       int i;
35423       for(i=0; i<pPage->nCell; i++){ 
35424         rc = ptrmapPutOvfl(pPage, i);
35425         if( rc!=SQLITE_OK ){
35426           goto end_shallow_balance;
35427         }
35428       }
35429     }
35430 #endif
35431     releasePage(pChild);
35432   }
35433 end_shallow_balance:
35434   sqlite3_free(apCell);
35435   return rc;
35436 }
35437
35438
35439 /*
35440 ** The root page is overfull
35441 **
35442 ** When this happens, Create a new child page and copy the
35443 ** contents of the root into the child.  Then make the root
35444 ** page an empty page with rightChild pointing to the new
35445 ** child.   Finally, call balance_internal() on the new child
35446 ** to cause it to split.
35447 */
35448 static int balance_deeper(MemPage *pPage){
35449   int rc;             /* Return value from subprocedures */
35450   MemPage *pChild;    /* Pointer to a new child page */
35451   Pgno pgnoChild;     /* Page number of the new child page */
35452   BtShared *pBt;         /* The BTree */
35453   int usableSize;     /* Total usable size of a page */
35454   u8 *data;           /* Content of the parent page */
35455   u8 *cdata;          /* Content of the child page */
35456   int hdr;            /* Offset to page header in parent */
35457   int brk;            /* Offset to content of first cell in parent */
35458
35459   assert( pPage->pParent==0 );
35460   assert( pPage->nOverflow>0 );
35461   pBt = pPage->pBt;
35462   assert( sqlite3_mutex_held(pBt->mutex) );
35463   rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
35464   if( rc ) return rc;
35465   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
35466   usableSize = pBt->usableSize;
35467   data = pPage->aData;
35468   hdr = pPage->hdrOffset;
35469   brk = get2byte(&data[hdr+5]);
35470   cdata = pChild->aData;
35471   memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
35472   memcpy(&cdata[brk], &data[brk], usableSize-brk);
35473   assert( pChild->isInit==0 );
35474   rc = sqlite3BtreeInitPage(pChild, pPage);
35475   if( rc ) goto balancedeeper_out;
35476   memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
35477   pChild->nOverflow = pPage->nOverflow;
35478   if( pChild->nOverflow ){
35479     pChild->nFree = 0;
35480   }
35481   assert( pChild->nCell==pPage->nCell );
35482   zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
35483   put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
35484   TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
35485 #ifndef SQLITE_OMIT_AUTOVACUUM
35486   if( pBt->autoVacuum ){
35487     int i;
35488     rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
35489     if( rc ) goto balancedeeper_out;
35490     for(i=0; i<pChild->nCell; i++){
35491       rc = ptrmapPutOvfl(pChild, i);
35492       if( rc!=SQLITE_OK ){
35493         return rc;
35494       }
35495     }
35496   }
35497 #endif
35498   rc = balance_nonroot(pChild);
35499
35500 balancedeeper_out:
35501   releasePage(pChild);
35502   return rc;
35503 }
35504
35505 /*
35506 ** Decide if the page pPage needs to be balanced.  If balancing is
35507 ** required, call the appropriate balancing routine.
35508 */
35509 static int balance(MemPage *pPage, int insert){
35510   int rc = SQLITE_OK;
35511   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35512   if( pPage->pParent==0 ){
35513     rc = sqlite3PagerWrite(pPage->pDbPage);
35514     if( rc==SQLITE_OK && pPage->nOverflow>0 ){
35515       rc = balance_deeper(pPage);
35516     }
35517     if( rc==SQLITE_OK && pPage->nCell==0 ){
35518       rc = balance_shallower(pPage);
35519     }
35520   }else{
35521     if( pPage->nOverflow>0 || 
35522         (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
35523       rc = balance_nonroot(pPage);
35524     }
35525   }
35526   return rc;
35527 }
35528
35529 /*
35530 ** This routine checks all cursors that point to table pgnoRoot.
35531 ** If any of those cursors were opened with wrFlag==0 in a different
35532 ** database connection (a database connection that shares the pager
35533 ** cache with the current connection) and that other connection 
35534 ** is not in the ReadUncommmitted state, then this routine returns 
35535 ** SQLITE_LOCKED.
35536 **
35537 ** In addition to checking for read-locks (where a read-lock 
35538 ** means a cursor opened with wrFlag==0) this routine also moves
35539 ** all write cursors so that they are pointing to the 
35540 ** first Cell on the root page.  This is necessary because an insert 
35541 ** or delete might change the number of cells on a page or delete
35542 ** a page entirely and we do not want to leave any cursors 
35543 ** pointing to non-existant pages or cells.
35544 */
35545 static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
35546   BtCursor *p;
35547   BtShared *pBt = pBtree->pBt;
35548   sqlite3 *db = pBtree->db;
35549   assert( sqlite3BtreeHoldsMutex(pBtree) );
35550   for(p=pBt->pCursor; p; p=p->pNext){
35551     if( p==pExclude ) continue;
35552     if( p->eState!=CURSOR_VALID ) continue;
35553     if( p->pgnoRoot!=pgnoRoot ) continue;
35554     if( p->wrFlag==0 ){
35555       sqlite3 *dbOther = p->pBtree->db;
35556       if( dbOther==0 ||
35557          (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
35558         return SQLITE_LOCKED;
35559       }
35560     }else if( p->pPage->pgno!=p->pgnoRoot ){
35561       moveToRoot(p);
35562     }
35563   }
35564   return SQLITE_OK;
35565 }
35566
35567 /*
35568 ** Make sure pBt->pTmpSpace points to an allocation of 
35569 ** MX_CELL_SIZE(pBt) bytes.
35570 */
35571 static void allocateTempSpace(BtShared *pBt){
35572   if( !pBt->pTmpSpace ){
35573     pBt->pTmpSpace = sqlite3_malloc(MX_CELL_SIZE(pBt));
35574   }
35575 }
35576
35577 /*
35578 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
35579 ** and the data is given by (pData,nData).  The cursor is used only to
35580 ** define what table the record should be inserted into.  The cursor
35581 ** is left pointing at a random location.
35582 **
35583 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
35584 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
35585 */
35586 SQLITE_PRIVATE int sqlite3BtreeInsert(
35587   BtCursor *pCur,                /* Insert data into the table of this cursor */
35588   const void *pKey, i64 nKey,    /* The key of the new record */
35589   const void *pData, int nData,  /* The data of the new record */
35590   int nZero,                     /* Number of extra 0 bytes to append to data */
35591   int appendBias                 /* True if this is likely an append */
35592 ){
35593   int rc;
35594   int loc;
35595   int szNew;
35596   MemPage *pPage;
35597   Btree *p = pCur->pBtree;
35598   BtShared *pBt = p->pBt;
35599   unsigned char *oldCell;
35600   unsigned char *newCell = 0;
35601
35602   assert( cursorHoldsMutex(pCur) );
35603   if( pBt->inTransaction!=TRANS_WRITE ){
35604     /* Must start a transaction before doing an insert */
35605     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
35606     return rc;
35607   }
35608   assert( !pBt->readOnly );
35609   if( !pCur->wrFlag ){
35610     return SQLITE_PERM;   /* Cursor not open for writing */
35611   }
35612   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
35613     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
35614   }
35615   if( pCur->eState==CURSOR_FAULT ){
35616     return pCur->skip;
35617   }
35618
35619   /* Save the positions of any other cursors open on this table */
35620   clearCursorPosition(pCur);
35621   if( 
35622     SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
35623     SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, 0, nKey, appendBias, &loc))
35624   ){
35625     return rc;
35626   }
35627
35628   pPage = pCur->pPage;
35629   assert( pPage->intKey || nKey>=0 );
35630   assert( pPage->leaf || !pPage->leafData );
35631   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
35632           pCur->pgnoRoot, nKey, nData, pPage->pgno,
35633           loc==0 ? "overwrite" : "new entry"));
35634   assert( pPage->isInit );
35635   allocateTempSpace(pBt);
35636   newCell = pBt->pTmpSpace;
35637   if( newCell==0 ) return SQLITE_NOMEM;
35638   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
35639   if( rc ) goto end_insert;
35640   assert( szNew==cellSizePtr(pPage, newCell) );
35641   assert( szNew<=MX_CELL_SIZE(pBt) );
35642   if( loc==0 && CURSOR_VALID==pCur->eState ){
35643     u16 szOld;
35644     assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
35645     rc = sqlite3PagerWrite(pPage->pDbPage);
35646     if( rc ){
35647       goto end_insert;
35648     }
35649     oldCell = findCell(pPage, pCur->idx);
35650     if( !pPage->leaf ){
35651       memcpy(newCell, oldCell, 4);
35652     }
35653     szOld = cellSizePtr(pPage, oldCell);
35654     rc = clearCell(pPage, oldCell);
35655     if( rc ) goto end_insert;
35656     dropCell(pPage, pCur->idx, szOld);
35657   }else if( loc<0 && pPage->nCell>0 ){
35658     assert( pPage->leaf );
35659     pCur->idx++;
35660     pCur->info.nSize = 0;
35661     pCur->validNKey = 0;
35662   }else{
35663     assert( pPage->leaf );
35664   }
35665   rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
35666   if( rc!=SQLITE_OK ) goto end_insert;
35667   rc = balance(pPage, 1);
35668   /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
35669   /* fflush(stdout); */
35670   if( rc==SQLITE_OK ){
35671     moveToRoot(pCur);
35672   }
35673 end_insert:
35674   return rc;
35675 }
35676
35677 /*
35678 ** Delete the entry that the cursor is pointing to.  The cursor
35679 ** is left pointing at a random location.
35680 */
35681 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
35682   MemPage *pPage = pCur->pPage;
35683   unsigned char *pCell;
35684   int rc;
35685   Pgno pgnoChild = 0;
35686   Btree *p = pCur->pBtree;
35687   BtShared *pBt = p->pBt;
35688
35689   assert( cursorHoldsMutex(pCur) );
35690   assert( pPage->isInit );
35691   if( pBt->inTransaction!=TRANS_WRITE ){
35692     /* Must start a transaction before doing a delete */
35693     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
35694     return rc;
35695   }
35696   assert( !pBt->readOnly );
35697   if( pCur->eState==CURSOR_FAULT ){
35698     return pCur->skip;
35699   }
35700   if( pCur->idx >= pPage->nCell ){
35701     return SQLITE_ERROR;  /* The cursor is not pointing to anything */
35702   }
35703   if( !pCur->wrFlag ){
35704     return SQLITE_PERM;   /* Did not open this cursor for writing */
35705   }
35706   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
35707     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
35708   }
35709
35710   /* Restore the current cursor position (a no-op if the cursor is not in 
35711   ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
35712   ** open on the same table. Then call sqlite3PagerWrite() on the page
35713   ** that the entry will be deleted from.
35714   */
35715   if( 
35716     (rc = restoreOrClearCursorPosition(pCur))!=0 ||
35717     (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
35718     (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
35719   ){
35720     return rc;
35721   }
35722
35723   /* Locate the cell within its page and leave pCell pointing to the
35724   ** data. The clearCell() call frees any overflow pages associated with the
35725   ** cell. The cell itself is still intact.
35726   */
35727   pCell = findCell(pPage, pCur->idx);
35728   if( !pPage->leaf ){
35729     pgnoChild = get4byte(pCell);
35730   }
35731   rc = clearCell(pPage, pCell);
35732   if( rc ){
35733     return rc;
35734   }
35735
35736   if( !pPage->leaf ){
35737     /*
35738     ** The entry we are about to delete is not a leaf so if we do not
35739     ** do something we will leave a hole on an internal page.
35740     ** We have to fill the hole by moving in a cell from a leaf.  The
35741     ** next Cell after the one to be deleted is guaranteed to exist and
35742     ** to be a leaf so we can use it.
35743     */
35744     BtCursor leafCur;
35745     unsigned char *pNext;
35746     int notUsed;
35747     unsigned char *tempCell = 0;
35748     assert( !pPage->leafData );
35749     sqlite3BtreeGetTempCursor(pCur, &leafCur);
35750     rc = sqlite3BtreeNext(&leafCur, &notUsed);
35751     if( rc==SQLITE_OK ){
35752       rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
35753     }
35754     if( rc==SQLITE_OK ){
35755       u16 szNext;
35756       TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
35757          pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
35758       dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
35759       pNext = findCell(leafCur.pPage, leafCur.idx);
35760       szNext = cellSizePtr(leafCur.pPage, pNext);
35761       assert( MX_CELL_SIZE(pBt)>=szNext+4 );
35762       allocateTempSpace(pBt);
35763       tempCell = pBt->pTmpSpace;
35764       if( tempCell==0 ){
35765         rc = SQLITE_NOMEM;
35766       }
35767       if( rc==SQLITE_OK ){
35768         rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
35769       }
35770       if( rc==SQLITE_OK ){
35771         put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
35772         rc = balance(pPage, 0);
35773       }
35774       if( rc==SQLITE_OK ){
35775         dropCell(leafCur.pPage, leafCur.idx, szNext);
35776         rc = balance(leafCur.pPage, 0);
35777       }
35778     }
35779     sqlite3BtreeReleaseTempCursor(&leafCur);
35780   }else{
35781     TRACE(("DELETE: table=%d delete from leaf %d\n",
35782        pCur->pgnoRoot, pPage->pgno));
35783     dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
35784     rc = balance(pPage, 0);
35785   }
35786   if( rc==SQLITE_OK ){
35787     moveToRoot(pCur);
35788   }
35789   return rc;
35790 }
35791
35792 /*
35793 ** Create a new BTree table.  Write into *piTable the page
35794 ** number for the root page of the new table.
35795 **
35796 ** The type of type is determined by the flags parameter.  Only the
35797 ** following values of flags are currently in use.  Other values for
35798 ** flags might not work:
35799 **
35800 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
35801 **     BTREE_ZERODATA                  Used for SQL indices
35802 */
35803 static int btreeCreateTable(Btree *p, int *piTable, int flags){
35804   BtShared *pBt = p->pBt;
35805   MemPage *pRoot;
35806   Pgno pgnoRoot;
35807   int rc;
35808
35809   assert( sqlite3BtreeHoldsMutex(p) );
35810   if( pBt->inTransaction!=TRANS_WRITE ){
35811     /* Must start a transaction first */
35812     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
35813     return rc;
35814   }
35815   assert( !pBt->readOnly );
35816
35817 #ifdef SQLITE_OMIT_AUTOVACUUM
35818   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
35819   if( rc ){
35820     return rc;
35821   }
35822 #else
35823   if( pBt->autoVacuum ){
35824     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
35825     MemPage *pPageMove; /* The page to move to. */
35826
35827     /* Creating a new table may probably require moving an existing database
35828     ** to make room for the new tables root page. In case this page turns
35829     ** out to be an overflow page, delete all overflow page-map caches
35830     ** held by open cursors.
35831     */
35832     invalidateAllOverflowCache(pBt);
35833
35834     /* Read the value of meta[3] from the database to determine where the
35835     ** root page of the new table should go. meta[3] is the largest root-page
35836     ** created so far, so the new root-page is (meta[3]+1).
35837     */
35838     rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
35839     if( rc!=SQLITE_OK ){
35840       return rc;
35841     }
35842     pgnoRoot++;
35843
35844     /* The new root-page may not be allocated on a pointer-map page, or the
35845     ** PENDING_BYTE page.
35846     */
35847     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
35848         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
35849       pgnoRoot++;
35850     }
35851     assert( pgnoRoot>=3 );
35852
35853     /* Allocate a page. The page that currently resides at pgnoRoot will
35854     ** be moved to the allocated page (unless the allocated page happens
35855     ** to reside at pgnoRoot).
35856     */
35857     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
35858     if( rc!=SQLITE_OK ){
35859       return rc;
35860     }
35861
35862     if( pgnoMove!=pgnoRoot ){
35863       /* pgnoRoot is the page that will be used for the root-page of
35864       ** the new table (assuming an error did not occur). But we were
35865       ** allocated pgnoMove. If required (i.e. if it was not allocated
35866       ** by extending the file), the current page at position pgnoMove
35867       ** is already journaled.
35868       */
35869       u8 eType;
35870       Pgno iPtrPage;
35871
35872       releasePage(pPageMove);
35873
35874       /* Move the page currently at pgnoRoot to pgnoMove. */
35875       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
35876       if( rc!=SQLITE_OK ){
35877         return rc;
35878       }
35879       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
35880       if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
35881         releasePage(pRoot);
35882         return rc;
35883       }
35884       assert( eType!=PTRMAP_ROOTPAGE );
35885       assert( eType!=PTRMAP_FREEPAGE );
35886       rc = sqlite3PagerWrite(pRoot->pDbPage);
35887       if( rc!=SQLITE_OK ){
35888         releasePage(pRoot);
35889         return rc;
35890       }
35891       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
35892       releasePage(pRoot);
35893
35894       /* Obtain the page at pgnoRoot */
35895       if( rc!=SQLITE_OK ){
35896         return rc;
35897       }
35898       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
35899       if( rc!=SQLITE_OK ){
35900         return rc;
35901       }
35902       rc = sqlite3PagerWrite(pRoot->pDbPage);
35903       if( rc!=SQLITE_OK ){
35904         releasePage(pRoot);
35905         return rc;
35906       }
35907     }else{
35908       pRoot = pPageMove;
35909     } 
35910
35911     /* Update the pointer-map and meta-data with the new root-page number. */
35912     rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
35913     if( rc ){
35914       releasePage(pRoot);
35915       return rc;
35916     }
35917     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
35918     if( rc ){
35919       releasePage(pRoot);
35920       return rc;
35921     }
35922
35923   }else{
35924     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
35925     if( rc ) return rc;
35926   }
35927 #endif
35928   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
35929   zeroPage(pRoot, flags | PTF_LEAF);
35930   sqlite3PagerUnref(pRoot->pDbPage);
35931   *piTable = (int)pgnoRoot;
35932   return SQLITE_OK;
35933 }
35934 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
35935   int rc;
35936   sqlite3BtreeEnter(p);
35937   p->pBt->db = p->db;
35938   rc = btreeCreateTable(p, piTable, flags);
35939   sqlite3BtreeLeave(p);
35940   return rc;
35941 }
35942
35943 /*
35944 ** Erase the given database page and all its children.  Return
35945 ** the page to the freelist.
35946 */
35947 static int clearDatabasePage(
35948   BtShared *pBt,           /* The BTree that contains the table */
35949   Pgno pgno,            /* Page number to clear */
35950   MemPage *pParent,     /* Parent page.  NULL for the root */
35951   int freePageFlag      /* Deallocate page if true */
35952 ){
35953   MemPage *pPage = 0;
35954   int rc;
35955   unsigned char *pCell;
35956   int i;
35957
35958   assert( sqlite3_mutex_held(pBt->mutex) );
35959   if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
35960     return SQLITE_CORRUPT_BKPT;
35961   }
35962
35963   rc = getAndInitPage(pBt, pgno, &pPage, pParent);
35964   if( rc ) goto cleardatabasepage_out;
35965   for(i=0; i<pPage->nCell; i++){
35966     pCell = findCell(pPage, i);
35967     if( !pPage->leaf ){
35968       rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
35969       if( rc ) goto cleardatabasepage_out;
35970     }
35971     rc = clearCell(pPage, pCell);
35972     if( rc ) goto cleardatabasepage_out;
35973   }
35974   if( !pPage->leaf ){
35975     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
35976     if( rc ) goto cleardatabasepage_out;
35977   }
35978   if( freePageFlag ){
35979     rc = freePage(pPage);
35980   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
35981     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
35982   }
35983
35984 cleardatabasepage_out:
35985   releasePage(pPage);
35986   return rc;
35987 }
35988
35989 /*
35990 ** Delete all information from a single table in the database.  iTable is
35991 ** the page number of the root of the table.  After this routine returns,
35992 ** the root page is empty, but still exists.
35993 **
35994 ** This routine will fail with SQLITE_LOCKED if there are any open
35995 ** read cursors on the table.  Open write cursors are moved to the
35996 ** root of the table.
35997 */
35998 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable){
35999   int rc;
36000   BtShared *pBt = p->pBt;
36001   sqlite3BtreeEnter(p);
36002   pBt->db = p->db;
36003   if( p->inTrans!=TRANS_WRITE ){
36004     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
36005   }else if( (rc = checkReadLocks(p, iTable, 0))!=SQLITE_OK ){
36006     /* nothing to do */
36007   }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
36008     /* nothing to do */
36009   }else{
36010     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
36011   }
36012   sqlite3BtreeLeave(p);
36013   return rc;
36014 }
36015
36016 /*
36017 ** Erase all information in a table and add the root of the table to
36018 ** the freelist.  Except, the root of the principle table (the one on
36019 ** page 1) is never added to the freelist.
36020 **
36021 ** This routine will fail with SQLITE_LOCKED if there are any open
36022 ** cursors on the table.
36023 **
36024 ** If AUTOVACUUM is enabled and the page at iTable is not the last
36025 ** root page in the database file, then the last root page 
36026 ** in the database file is moved into the slot formerly occupied by
36027 ** iTable and that last slot formerly occupied by the last root page
36028 ** is added to the freelist instead of iTable.  In this say, all
36029 ** root pages are kept at the beginning of the database file, which
36030 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
36031 ** page number that used to be the last root page in the file before
36032 ** the move.  If no page gets moved, *piMoved is set to 0.
36033 ** The last root page is recorded in meta[3] and the value of
36034 ** meta[3] is updated by this procedure.
36035 */
36036 static int btreeDropTable(Btree *p, int iTable, int *piMoved){
36037   int rc;
36038   MemPage *pPage = 0;
36039   BtShared *pBt = p->pBt;
36040
36041   assert( sqlite3BtreeHoldsMutex(p) );
36042   if( p->inTrans!=TRANS_WRITE ){
36043     return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
36044   }
36045
36046   /* It is illegal to drop a table if any cursors are open on the
36047   ** database. This is because in auto-vacuum mode the backend may
36048   ** need to move another root-page to fill a gap left by the deleted
36049   ** root page. If an open cursor was using this page a problem would 
36050   ** occur.
36051   */
36052   if( pBt->pCursor ){
36053     return SQLITE_LOCKED;
36054   }
36055
36056   rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
36057   if( rc ) return rc;
36058   rc = sqlite3BtreeClearTable(p, iTable);
36059   if( rc ){
36060     releasePage(pPage);
36061     return rc;
36062   }
36063
36064   *piMoved = 0;
36065
36066   if( iTable>1 ){
36067 #ifdef SQLITE_OMIT_AUTOVACUUM
36068     rc = freePage(pPage);
36069     releasePage(pPage);
36070 #else
36071     if( pBt->autoVacuum ){
36072       Pgno maxRootPgno;
36073       rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
36074       if( rc!=SQLITE_OK ){
36075         releasePage(pPage);
36076         return rc;
36077       }
36078
36079       if( iTable==maxRootPgno ){
36080         /* If the table being dropped is the table with the largest root-page
36081         ** number in the database, put the root page on the free list. 
36082         */
36083         rc = freePage(pPage);
36084         releasePage(pPage);
36085         if( rc!=SQLITE_OK ){
36086           return rc;
36087         }
36088       }else{
36089         /* The table being dropped does not have the largest root-page
36090         ** number in the database. So move the page that does into the 
36091         ** gap left by the deleted root-page.
36092         */
36093         MemPage *pMove;
36094         releasePage(pPage);
36095         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
36096         if( rc!=SQLITE_OK ){
36097           return rc;
36098         }
36099         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
36100         releasePage(pMove);
36101         if( rc!=SQLITE_OK ){
36102           return rc;
36103         }
36104         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
36105         if( rc!=SQLITE_OK ){
36106           return rc;
36107         }
36108         rc = freePage(pMove);
36109         releasePage(pMove);
36110         if( rc!=SQLITE_OK ){
36111           return rc;
36112         }
36113         *piMoved = maxRootPgno;
36114       }
36115
36116       /* Set the new 'max-root-page' value in the database header. This
36117       ** is the old value less one, less one more if that happens to
36118       ** be a root-page number, less one again if that is the
36119       ** PENDING_BYTE_PAGE.
36120       */
36121       maxRootPgno--;
36122       if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
36123         maxRootPgno--;
36124       }
36125       if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
36126         maxRootPgno--;
36127       }
36128       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
36129
36130       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
36131     }else{
36132       rc = freePage(pPage);
36133       releasePage(pPage);
36134     }
36135 #endif
36136   }else{
36137     /* If sqlite3BtreeDropTable was called on page 1. */
36138     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
36139     releasePage(pPage);
36140   }
36141   return rc;  
36142 }
36143 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
36144   int rc;
36145   sqlite3BtreeEnter(p);
36146   p->pBt->db = p->db;
36147   rc = btreeDropTable(p, iTable, piMoved);
36148   sqlite3BtreeLeave(p);
36149   return rc;
36150 }
36151
36152
36153 /*
36154 ** Read the meta-information out of a database file.  Meta[0]
36155 ** is the number of free pages currently in the database.  Meta[1]
36156 ** through meta[15] are available for use by higher layers.  Meta[0]
36157 ** is read-only, the others are read/write.
36158 ** 
36159 ** The schema layer numbers meta values differently.  At the schema
36160 ** layer (and the SetCookie and ReadCookie opcodes) the number of
36161 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
36162 */
36163 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
36164   DbPage *pDbPage;
36165   int rc;
36166   unsigned char *pP1;
36167   BtShared *pBt = p->pBt;
36168
36169   sqlite3BtreeEnter(p);
36170   pBt->db = p->db;
36171
36172   /* Reading a meta-data value requires a read-lock on page 1 (and hence
36173   ** the sqlite_master table. We grab this lock regardless of whether or
36174   ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
36175   ** 1 is treated as a special case by queryTableLock() and lockTable()).
36176   */
36177   rc = queryTableLock(p, 1, READ_LOCK);
36178   if( rc!=SQLITE_OK ){
36179     sqlite3BtreeLeave(p);
36180     return rc;
36181   }
36182
36183   assert( idx>=0 && idx<=15 );
36184   rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
36185   if( rc ){
36186     sqlite3BtreeLeave(p);
36187     return rc;
36188   }
36189   pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
36190   *pMeta = get4byte(&pP1[36 + idx*4]);
36191   sqlite3PagerUnref(pDbPage);
36192
36193   /* If autovacuumed is disabled in this build but we are trying to 
36194   ** access an autovacuumed database, then make the database readonly. 
36195   */
36196 #ifdef SQLITE_OMIT_AUTOVACUUM
36197   if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
36198 #endif
36199
36200   /* Grab the read-lock on page 1. */
36201   rc = lockTable(p, 1, READ_LOCK);
36202   sqlite3BtreeLeave(p);
36203   return rc;
36204 }
36205
36206 /*
36207 ** Write meta-information back into the database.  Meta[0] is
36208 ** read-only and may not be written.
36209 */
36210 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
36211   BtShared *pBt = p->pBt;
36212   unsigned char *pP1;
36213   int rc;
36214   assert( idx>=1 && idx<=15 );
36215   sqlite3BtreeEnter(p);
36216   pBt->db = p->db;
36217   if( p->inTrans!=TRANS_WRITE ){
36218     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
36219   }else{
36220     assert( pBt->pPage1!=0 );
36221     pP1 = pBt->pPage1->aData;
36222     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
36223     if( rc==SQLITE_OK ){
36224       put4byte(&pP1[36 + idx*4], iMeta);
36225 #ifndef SQLITE_OMIT_AUTOVACUUM
36226       if( idx==7 ){
36227         assert( pBt->autoVacuum || iMeta==0 );
36228         assert( iMeta==0 || iMeta==1 );
36229         pBt->incrVacuum = iMeta;
36230       }
36231 #endif
36232     }
36233   }
36234   sqlite3BtreeLeave(p);
36235   return rc;
36236 }
36237
36238 /*
36239 ** Return the flag byte at the beginning of the page that the cursor
36240 ** is currently pointing to.
36241 */
36242 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
36243   /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
36244   ** restoreOrClearCursorPosition() here.
36245   */
36246   MemPage *pPage;
36247   restoreOrClearCursorPosition(pCur);
36248   pPage = pCur->pPage;
36249   assert( cursorHoldsMutex(pCur) );
36250   assert( pPage->pBt==pCur->pBt );
36251   return pPage ? pPage->aData[pPage->hdrOffset] : 0;
36252 }
36253
36254
36255 /*
36256 ** Return the pager associated with a BTree.  This routine is used for
36257 ** testing and debugging only.
36258 */
36259 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
36260   return p->pBt->pPager;
36261 }
36262
36263 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
36264 /*
36265 ** Append a message to the error message string.
36266 */
36267 static void checkAppendMsg(
36268   IntegrityCk *pCheck,
36269   char *zMsg1,
36270   const char *zFormat,
36271   ...
36272 ){
36273   va_list ap;
36274   char *zMsg2;
36275   if( !pCheck->mxErr ) return;
36276   pCheck->mxErr--;
36277   pCheck->nErr++;
36278   va_start(ap, zFormat);
36279   zMsg2 = sqlite3VMPrintf(0, zFormat, ap);
36280   va_end(ap);
36281   if( zMsg1==0 ) zMsg1 = "";
36282   if( pCheck->zErrMsg ){
36283     char *zOld = pCheck->zErrMsg;
36284     pCheck->zErrMsg = 0;
36285     sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
36286     sqlite3_free(zOld);
36287   }else{
36288     sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
36289   }
36290   sqlite3_free(zMsg2);
36291 }
36292 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
36293
36294 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
36295 /*
36296 ** Add 1 to the reference count for page iPage.  If this is the second
36297 ** reference to the page, add an error message to pCheck->zErrMsg.
36298 ** Return 1 if there are 2 ore more references to the page and 0 if
36299 ** if this is the first reference to the page.
36300 **
36301 ** Also check that the page number is in bounds.
36302 */
36303 static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
36304   if( iPage==0 ) return 1;
36305   if( iPage>pCheck->nPage || iPage<0 ){
36306     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
36307     return 1;
36308   }
36309   if( pCheck->anRef[iPage]==1 ){
36310     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
36311     return 1;
36312   }
36313   return  (pCheck->anRef[iPage]++)>1;
36314 }
36315
36316 #ifndef SQLITE_OMIT_AUTOVACUUM
36317 /*
36318 ** Check that the entry in the pointer-map for page iChild maps to 
36319 ** page iParent, pointer type ptrType. If not, append an error message
36320 ** to pCheck.
36321 */
36322 static void checkPtrmap(
36323   IntegrityCk *pCheck,   /* Integrity check context */
36324   Pgno iChild,           /* Child page number */
36325   u8 eType,              /* Expected pointer map type */
36326   Pgno iParent,          /* Expected pointer map parent page number */
36327   char *zContext         /* Context description (used for error msg) */
36328 ){
36329   int rc;
36330   u8 ePtrmapType;
36331   Pgno iPtrmapParent;
36332
36333   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
36334   if( rc!=SQLITE_OK ){
36335     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
36336     return;
36337   }
36338
36339   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
36340     checkAppendMsg(pCheck, zContext, 
36341       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
36342       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
36343   }
36344 }
36345 #endif
36346
36347 /*
36348 ** Check the integrity of the freelist or of an overflow page list.
36349 ** Verify that the number of pages on the list is N.
36350 */
36351 static void checkList(
36352   IntegrityCk *pCheck,  /* Integrity checking context */
36353   int isFreeList,       /* True for a freelist.  False for overflow page list */
36354   int iPage,            /* Page number for first page in the list */
36355   int N,                /* Expected number of pages in the list */
36356   char *zContext        /* Context for error messages */
36357 ){
36358   int i;
36359   int expected = N;
36360   int iFirst = iPage;
36361   while( N-- > 0 && pCheck->mxErr ){
36362     DbPage *pOvflPage;
36363     unsigned char *pOvflData;
36364     if( iPage<1 ){
36365       checkAppendMsg(pCheck, zContext,
36366          "%d of %d pages missing from overflow list starting at %d",
36367           N+1, expected, iFirst);
36368       break;
36369     }
36370     if( checkRef(pCheck, iPage, zContext) ) break;
36371     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
36372       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
36373       break;
36374     }
36375     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
36376     if( isFreeList ){
36377       int n = get4byte(&pOvflData[4]);
36378 #ifndef SQLITE_OMIT_AUTOVACUUM
36379       if( pCheck->pBt->autoVacuum ){
36380         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
36381       }
36382 #endif
36383       if( n>pCheck->pBt->usableSize/4-8 ){
36384         checkAppendMsg(pCheck, zContext,
36385            "freelist leaf count too big on page %d", iPage);
36386         N--;
36387       }else{
36388         for(i=0; i<n; i++){
36389           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
36390 #ifndef SQLITE_OMIT_AUTOVACUUM
36391           if( pCheck->pBt->autoVacuum ){
36392             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
36393           }
36394 #endif
36395           checkRef(pCheck, iFreePage, zContext);
36396         }
36397         N -= n;
36398       }
36399     }
36400 #ifndef SQLITE_OMIT_AUTOVACUUM
36401     else{
36402       /* If this database supports auto-vacuum and iPage is not the last
36403       ** page in this overflow list, check that the pointer-map entry for
36404       ** the following page matches iPage.
36405       */
36406       if( pCheck->pBt->autoVacuum && N>0 ){
36407         i = get4byte(pOvflData);
36408         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
36409       }
36410     }
36411 #endif
36412     iPage = get4byte(pOvflData);
36413     sqlite3PagerUnref(pOvflPage);
36414   }
36415 }
36416 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
36417
36418 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
36419 /*
36420 ** Do various sanity checks on a single page of a tree.  Return
36421 ** the tree depth.  Root pages return 0.  Parents of root pages
36422 ** return 1, and so forth.
36423 ** 
36424 ** These checks are done:
36425 **
36426 **      1.  Make sure that cells and freeblocks do not overlap
36427 **          but combine to completely cover the page.
36428 **  NO  2.  Make sure cell keys are in order.
36429 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
36430 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
36431 **      5.  Check the integrity of overflow pages.
36432 **      6.  Recursively call checkTreePage on all children.
36433 **      7.  Verify that the depth of all children is the same.
36434 **      8.  Make sure this page is at least 33% full or else it is
36435 **          the root of the tree.
36436 */
36437 static int checkTreePage(
36438   IntegrityCk *pCheck,  /* Context for the sanity check */
36439   int iPage,            /* Page number of the page to check */
36440   MemPage *pParent,     /* Parent page */
36441   char *zParentContext  /* Parent context */
36442 ){
36443   MemPage *pPage;
36444   int i, rc, depth, d2, pgno, cnt;
36445   int hdr, cellStart;
36446   int nCell;
36447   u8 *data;
36448   BtShared *pBt;
36449   int usableSize;
36450   char zContext[100];
36451   char *hit;
36452
36453   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
36454
36455   /* Check that the page exists
36456   */
36457   pBt = pCheck->pBt;
36458   usableSize = pBt->usableSize;
36459   if( iPage==0 ) return 0;
36460   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
36461   if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
36462     checkAppendMsg(pCheck, zContext,
36463        "unable to get the page. error code=%d", rc);
36464     return 0;
36465   }
36466   if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
36467     checkAppendMsg(pCheck, zContext, 
36468                    "sqlite3BtreeInitPage() returns error code %d", rc);
36469     releasePage(pPage);
36470     return 0;
36471   }
36472
36473   /* Check out all the cells.
36474   */
36475   depth = 0;
36476   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
36477     u8 *pCell;
36478     int sz;
36479     CellInfo info;
36480
36481     /* Check payload overflow pages
36482     */
36483     sqlite3_snprintf(sizeof(zContext), zContext,
36484              "On tree page %d cell %d: ", iPage, i);
36485     pCell = findCell(pPage,i);
36486     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
36487     sz = info.nData;
36488     if( !pPage->intKey ) sz += info.nKey;
36489     assert( sz==info.nPayload );
36490     if( sz>info.nLocal ){
36491       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
36492       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
36493 #ifndef SQLITE_OMIT_AUTOVACUUM
36494       if( pBt->autoVacuum ){
36495         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
36496       }
36497 #endif
36498       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
36499     }
36500
36501     /* Check sanity of left child page.
36502     */
36503     if( !pPage->leaf ){
36504       pgno = get4byte(pCell);
36505 #ifndef SQLITE_OMIT_AUTOVACUUM
36506       if( pBt->autoVacuum ){
36507         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
36508       }
36509 #endif
36510       d2 = checkTreePage(pCheck,pgno,pPage,zContext);
36511       if( i>0 && d2!=depth ){
36512         checkAppendMsg(pCheck, zContext, "Child page depth differs");
36513       }
36514       depth = d2;
36515     }
36516   }
36517   if( !pPage->leaf ){
36518     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
36519     sqlite3_snprintf(sizeof(zContext), zContext, 
36520                      "On page %d at right child: ", iPage);
36521 #ifndef SQLITE_OMIT_AUTOVACUUM
36522     if( pBt->autoVacuum ){
36523       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
36524     }
36525 #endif
36526     checkTreePage(pCheck, pgno, pPage, zContext);
36527   }
36528  
36529   /* Check for complete coverage of the page
36530   */
36531   data = pPage->aData;
36532   hdr = pPage->hdrOffset;
36533   hit = sqlite3MallocZero( usableSize );
36534   if( hit ){
36535     memset(hit, 1, get2byte(&data[hdr+5]));
36536     nCell = get2byte(&data[hdr+3]);
36537     cellStart = hdr + 12 - 4*pPage->leaf;
36538     for(i=0; i<nCell; i++){
36539       int pc = get2byte(&data[cellStart+i*2]);
36540       u16 size = cellSizePtr(pPage, &data[pc]);
36541       int j;
36542       if( (pc+size-1)>=usableSize || pc<0 ){
36543         checkAppendMsg(pCheck, 0, 
36544             "Corruption detected in cell %d on page %d",i,iPage,0);
36545       }else{
36546         for(j=pc+size-1; j>=pc; j--) hit[j]++;
36547       }
36548     }
36549     for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; 
36550            cnt++){
36551       int size = get2byte(&data[i+2]);
36552       int j;
36553       if( (i+size-1)>=usableSize || i<0 ){
36554         checkAppendMsg(pCheck, 0,  
36555             "Corruption detected in cell %d on page %d",i,iPage,0);
36556       }else{
36557         for(j=i+size-1; j>=i; j--) hit[j]++;
36558       }
36559       i = get2byte(&data[i]);
36560     }
36561     for(i=cnt=0; i<usableSize; i++){
36562       if( hit[i]==0 ){
36563         cnt++;
36564       }else if( hit[i]>1 ){
36565         checkAppendMsg(pCheck, 0,
36566           "Multiple uses for byte %d of page %d", i, iPage);
36567         break;
36568       }
36569     }
36570     if( cnt!=data[hdr+7] ){
36571       checkAppendMsg(pCheck, 0, 
36572           "Fragmented space is %d byte reported as %d on page %d",
36573           cnt, data[hdr+7], iPage);
36574     }
36575   }
36576   sqlite3_free(hit);
36577
36578   releasePage(pPage);
36579   return depth+1;
36580 }
36581 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
36582
36583 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
36584 /*
36585 ** This routine does a complete check of the given BTree file.  aRoot[] is
36586 ** an array of pages numbers were each page number is the root page of
36587 ** a table.  nRoot is the number of entries in aRoot.
36588 **
36589 ** If everything checks out, this routine returns NULL.  If something is
36590 ** amiss, an error message is written into memory obtained from malloc()
36591 ** and a pointer to that error message is returned.  The calling function
36592 ** is responsible for freeing the error message when it is done.
36593 */
36594 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
36595   Btree *p,     /* The btree to be checked */
36596   int *aRoot,   /* An array of root pages numbers for individual trees */
36597   int nRoot,    /* Number of entries in aRoot[] */
36598   int mxErr,    /* Stop reporting errors after this many */
36599   int *pnErr    /* Write number of errors seen to this variable */
36600 ){
36601   int i;
36602   int nRef;
36603   IntegrityCk sCheck;
36604   BtShared *pBt = p->pBt;
36605
36606   sqlite3BtreeEnter(p);
36607   pBt->db = p->db;
36608   nRef = sqlite3PagerRefcount(pBt->pPager);
36609   if( lockBtreeWithRetry(p)!=SQLITE_OK ){
36610     sqlite3BtreeLeave(p);
36611     return sqlite3StrDup("Unable to acquire a read lock on the database");
36612   }
36613   sCheck.pBt = pBt;
36614   sCheck.pPager = pBt->pPager;
36615   sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
36616   sCheck.mxErr = mxErr;
36617   sCheck.nErr = 0;
36618   *pnErr = 0;
36619 #ifndef SQLITE_OMIT_AUTOVACUUM
36620   if( pBt->nTrunc!=0 ){
36621     sCheck.nPage = pBt->nTrunc;
36622   }
36623 #endif
36624   if( sCheck.nPage==0 ){
36625     unlockBtreeIfUnused(pBt);
36626     sqlite3BtreeLeave(p);
36627     return 0;
36628   }
36629   sCheck.anRef = sqlite3_malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
36630   if( !sCheck.anRef ){
36631     unlockBtreeIfUnused(pBt);
36632     *pnErr = 1;
36633     sqlite3BtreeLeave(p);
36634     return sqlite3MPrintf(p->db, "Unable to malloc %d bytes", 
36635         (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
36636   }
36637   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
36638   i = PENDING_BYTE_PAGE(pBt);
36639   if( i<=sCheck.nPage ){
36640     sCheck.anRef[i] = 1;
36641   }
36642   sCheck.zErrMsg = 0;
36643
36644   /* Check the integrity of the freelist
36645   */
36646   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
36647             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
36648
36649   /* Check all the tables.
36650   */
36651   for(i=0; i<nRoot && sCheck.mxErr; i++){
36652     if( aRoot[i]==0 ) continue;
36653 #ifndef SQLITE_OMIT_AUTOVACUUM
36654     if( pBt->autoVacuum && aRoot[i]>1 ){
36655       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
36656     }
36657 #endif
36658     checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
36659   }
36660
36661   /* Make sure every page in the file is referenced
36662   */
36663   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
36664 #ifdef SQLITE_OMIT_AUTOVACUUM
36665     if( sCheck.anRef[i]==0 ){
36666       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
36667     }
36668 #else
36669     /* If the database supports auto-vacuum, make sure no tables contain
36670     ** references to pointer-map pages.
36671     */
36672     if( sCheck.anRef[i]==0 && 
36673        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
36674       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
36675     }
36676     if( sCheck.anRef[i]!=0 && 
36677        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
36678       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
36679     }
36680 #endif
36681   }
36682
36683   /* Make sure this analysis did not leave any unref() pages
36684   */
36685   unlockBtreeIfUnused(pBt);
36686   if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
36687     checkAppendMsg(&sCheck, 0, 
36688       "Outstanding page count goes from %d to %d during this analysis",
36689       nRef, sqlite3PagerRefcount(pBt->pPager)
36690     );
36691   }
36692
36693   /* Clean  up and report errors.
36694   */
36695   sqlite3BtreeLeave(p);
36696   sqlite3_free(sCheck.anRef);
36697   *pnErr = sCheck.nErr;
36698   return sCheck.zErrMsg;
36699 }
36700 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
36701
36702 /*
36703 ** Return the full pathname of the underlying database file.
36704 **
36705 ** The pager filename is invariant as long as the pager is
36706 ** open so it is safe to access without the BtShared mutex.
36707 */
36708 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
36709   assert( p->pBt->pPager!=0 );
36710   return sqlite3PagerFilename(p->pBt->pPager);
36711 }
36712
36713 /*
36714 ** Return the pathname of the directory that contains the database file.
36715 **
36716 ** The pager directory name is invariant as long as the pager is
36717 ** open so it is safe to access without the BtShared mutex.
36718 */
36719 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
36720   assert( p->pBt->pPager!=0 );
36721   return sqlite3PagerDirname(p->pBt->pPager);
36722 }
36723
36724 /*
36725 ** Return the pathname of the journal file for this database. The return
36726 ** value of this routine is the same regardless of whether the journal file
36727 ** has been created or not.
36728 **
36729 ** The pager journal filename is invariant as long as the pager is
36730 ** open so it is safe to access without the BtShared mutex.
36731 */
36732 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
36733   assert( p->pBt->pPager!=0 );
36734   return sqlite3PagerJournalname(p->pBt->pPager);
36735 }
36736
36737 #ifndef SQLITE_OMIT_VACUUM
36738 /*
36739 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
36740 ** must be active for both files.
36741 **
36742 ** The size of file pTo may be reduced by this operation.
36743 ** If anything goes wrong, the transaction on pTo is rolled back. 
36744 **
36745 ** If successful, CommitPhaseOne() may be called on pTo before returning. 
36746 ** The caller should finish committing the transaction on pTo by calling
36747 ** sqlite3BtreeCommit().
36748 */
36749 static int btreeCopyFile(Btree *pTo, Btree *pFrom){
36750   int rc = SQLITE_OK;
36751   Pgno i;
36752
36753   Pgno nFromPage;     /* Number of pages in pFrom */
36754   Pgno nToPage;       /* Number of pages in pTo */
36755   Pgno nNewPage;      /* Number of pages in pTo after the copy */
36756
36757   Pgno iSkip;         /* Pending byte page in pTo */
36758   int nToPageSize;    /* Page size of pTo in bytes */
36759   int nFromPageSize;  /* Page size of pFrom in bytes */
36760
36761   BtShared *pBtTo = pTo->pBt;
36762   BtShared *pBtFrom = pFrom->pBt;
36763   pBtTo->db = pTo->db;
36764   pBtFrom->db = pFrom->db;
36765
36766   nToPageSize = pBtTo->pageSize;
36767   nFromPageSize = pBtFrom->pageSize;
36768
36769   if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
36770     return SQLITE_ERROR;
36771   }
36772   if( pBtTo->pCursor ){
36773     return SQLITE_BUSY;
36774   }
36775
36776   nToPage = sqlite3PagerPagecount(pBtTo->pPager);
36777   nFromPage = sqlite3PagerPagecount(pBtFrom->pPager);
36778   iSkip = PENDING_BYTE_PAGE(pBtTo);
36779
36780   /* Variable nNewPage is the number of pages required to store the
36781   ** contents of pFrom using the current page-size of pTo.
36782   */
36783   nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) / 
36784       (i64)nToPageSize;
36785
36786   for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
36787
36788     /* Journal the original page.
36789     **
36790     ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
36791     ** in database *pTo (before the copy). This page is never written 
36792     ** into the journal file. Unless i==iSkip or the page was not
36793     ** present in pTo before the copy operation, journal page i from pTo.
36794     */
36795     if( i!=iSkip && i<=nToPage ){
36796       DbPage *pDbPage = 0;
36797       rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
36798       if( rc==SQLITE_OK ){
36799         rc = sqlite3PagerWrite(pDbPage);
36800         if( rc==SQLITE_OK && i>nFromPage ){
36801           /* Yeah.  It seems wierd to call DontWrite() right after Write(). But
36802           ** that is because the names of those procedures do not exactly 
36803           ** represent what they do.  Write() really means "put this page in the
36804           ** rollback journal and mark it as dirty so that it will be written
36805           ** to the database file later."  DontWrite() undoes the second part of
36806           ** that and prevents the page from being written to the database. The
36807           ** page is still on the rollback journal, though.  And that is the 
36808           ** whole point of this block: to put pages on the rollback journal. 
36809           */
36810           sqlite3PagerDontWrite(pDbPage);
36811         }
36812         sqlite3PagerUnref(pDbPage);
36813       }
36814     }
36815
36816     /* Overwrite the data in page i of the target database */
36817     if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
36818
36819       DbPage *pToPage = 0;
36820       sqlite3_int64 iOff;
36821
36822       rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
36823       if( rc==SQLITE_OK ){
36824         rc = sqlite3PagerWrite(pToPage);
36825       }
36826
36827       for(
36828         iOff=(i-1)*nToPageSize; 
36829         rc==SQLITE_OK && iOff<i*nToPageSize; 
36830         iOff += nFromPageSize
36831       ){
36832         DbPage *pFromPage = 0;
36833         Pgno iFrom = (iOff/nFromPageSize)+1;
36834
36835         if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
36836           continue;
36837         }
36838
36839         rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
36840         if( rc==SQLITE_OK ){
36841           char *zTo = sqlite3PagerGetData(pToPage);
36842           char *zFrom = sqlite3PagerGetData(pFromPage);
36843           int nCopy;
36844
36845           if( nFromPageSize>=nToPageSize ){
36846             zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
36847             nCopy = nToPageSize;
36848           }else{
36849             zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
36850             nCopy = nFromPageSize;
36851           }
36852
36853           memcpy(zTo, zFrom, nCopy);
36854           sqlite3PagerUnref(pFromPage);
36855         }
36856       }
36857
36858       if( pToPage ) sqlite3PagerUnref(pToPage);
36859     }
36860   }
36861
36862   /* If things have worked so far, the database file may need to be 
36863   ** truncated. The complex part is that it may need to be truncated to
36864   ** a size that is not an integer multiple of nToPageSize - the current
36865   ** page size used by the pager associated with B-Tree pTo.
36866   **
36867   ** For example, say the page-size of pTo is 2048 bytes and the original 
36868   ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024 
36869   ** bytes and 9 pages, then the file needs to be truncated to 9KB.
36870   */
36871   if( rc==SQLITE_OK ){
36872     if( nFromPageSize!=nToPageSize ){
36873       sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
36874       i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
36875       i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize; 
36876       i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
36877   
36878       assert( iSize<=iNow );
36879   
36880       /* Commit phase one syncs the journal file associated with pTo 
36881       ** containing the original data. It does not sync the database file
36882       ** itself. After doing this it is safe to use OsTruncate() and other
36883       ** file APIs on the database file directly.
36884       */
36885       pBtTo->db = pTo->db;
36886       rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
36887       if( iSize<iNow && rc==SQLITE_OK ){
36888         rc = sqlite3OsTruncate(pFile, iSize);
36889       }
36890   
36891       /* The loop that copied data from database pFrom to pTo did not
36892       ** populate the locking page of database pTo. If the page-size of
36893       ** pFrom is smaller than that of pTo, this means some data will
36894       ** not have been copied. 
36895       **
36896       ** This block copies the missing data from database pFrom to pTo 
36897       ** using file APIs. This is safe because at this point we know that
36898       ** all of the original data from pTo has been synced into the 
36899       ** journal file. At this point it would be safe to do anything at
36900       ** all to the database file except truncate it to zero bytes.
36901       */
36902       if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
36903         i64 iOff;
36904         for(
36905           iOff=iPending; 
36906           rc==SQLITE_OK && iOff<(iPending+nToPageSize); 
36907           iOff += nFromPageSize
36908         ){
36909           DbPage *pFromPage = 0;
36910           Pgno iFrom = (iOff/nFromPageSize)+1;
36911   
36912           if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
36913             continue;
36914           }
36915   
36916           rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
36917           if( rc==SQLITE_OK ){
36918             char *zFrom = sqlite3PagerGetData(pFromPage);
36919           rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
36920             sqlite3PagerUnref(pFromPage);
36921           }
36922         }
36923       }
36924   
36925       /* Sync the database file */
36926       if( rc==SQLITE_OK ){
36927         rc = sqlite3PagerSync(pBtTo->pPager);
36928       }
36929     }else{
36930       rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
36931     }
36932     if( rc==SQLITE_OK ){
36933       pBtTo->pageSizeFixed = 0;
36934     }
36935   }
36936
36937   if( rc ){
36938     sqlite3BtreeRollback(pTo);
36939   }
36940
36941   return rc;  
36942 }
36943 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
36944   int rc;
36945   sqlite3BtreeEnter(pTo);
36946   sqlite3BtreeEnter(pFrom);
36947   rc = btreeCopyFile(pTo, pFrom);
36948   sqlite3BtreeLeave(pFrom);
36949   sqlite3BtreeLeave(pTo);
36950   return rc;
36951 }
36952
36953 #endif /* SQLITE_OMIT_VACUUM */
36954
36955 /*
36956 ** Return non-zero if a transaction is active.
36957 */
36958 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
36959   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
36960   return (p && (p->inTrans==TRANS_WRITE));
36961 }
36962
36963 /*
36964 ** Return non-zero if a statement transaction is active.
36965 */
36966 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
36967   assert( sqlite3BtreeHoldsMutex(p) );
36968   return (p->pBt && p->pBt->inStmt);
36969 }
36970
36971 /*
36972 ** Return non-zero if a read (or write) transaction is active.
36973 */
36974 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
36975   assert( sqlite3_mutex_held(p->db->mutex) );
36976   return (p && (p->inTrans!=TRANS_NONE));
36977 }
36978
36979 /*
36980 ** This function returns a pointer to a blob of memory associated with
36981 ** a single shared-btree. The memory is used by client code for its own
36982 ** purposes (for example, to store a high-level schema associated with 
36983 ** the shared-btree). The btree layer manages reference counting issues.
36984 **
36985 ** The first time this is called on a shared-btree, nBytes bytes of memory
36986 ** are allocated, zeroed, and returned to the caller. For each subsequent 
36987 ** call the nBytes parameter is ignored and a pointer to the same blob
36988 ** of memory returned. 
36989 **
36990 ** Just before the shared-btree is closed, the function passed as the 
36991 ** xFree argument when the memory allocation was made is invoked on the 
36992 ** blob of allocated memory. This function should not call sqlite3_free()
36993 ** on the memory, the btree layer does that.
36994 */
36995 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
36996   BtShared *pBt = p->pBt;
36997   sqlite3BtreeEnter(p);
36998   if( !pBt->pSchema ){
36999     pBt->pSchema = sqlite3MallocZero(nBytes);
37000     pBt->xFreeSchema = xFree;
37001   }
37002   sqlite3BtreeLeave(p);
37003   return pBt->pSchema;
37004 }
37005
37006 /*
37007 ** Return true if another user of the same shared btree as the argument
37008 ** handle holds an exclusive lock on the sqlite_master table.
37009 */
37010 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
37011   int rc;
37012   assert( sqlite3_mutex_held(p->db->mutex) );
37013   sqlite3BtreeEnter(p);
37014   rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
37015   sqlite3BtreeLeave(p);
37016   return rc;
37017 }
37018
37019
37020 #ifndef SQLITE_OMIT_SHARED_CACHE
37021 /*
37022 ** Obtain a lock on the table whose root page is iTab.  The
37023 ** lock is a write lock if isWritelock is true or a read lock
37024 ** if it is false.
37025 */
37026 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
37027   int rc = SQLITE_OK;
37028   if( p->sharable ){
37029     u8 lockType = READ_LOCK + isWriteLock;
37030     assert( READ_LOCK+1==WRITE_LOCK );
37031     assert( isWriteLock==0 || isWriteLock==1 );
37032     sqlite3BtreeEnter(p);
37033     rc = queryTableLock(p, iTab, lockType);
37034     if( rc==SQLITE_OK ){
37035       rc = lockTable(p, iTab, lockType);
37036     }
37037     sqlite3BtreeLeave(p);
37038   }
37039   return rc;
37040 }
37041 #endif
37042
37043 #ifndef SQLITE_OMIT_INCRBLOB
37044 /*
37045 ** Argument pCsr must be a cursor opened for writing on an 
37046 ** INTKEY table currently pointing at a valid table entry. 
37047 ** This function modifies the data stored as part of that entry.
37048 ** Only the data content may only be modified, it is not possible
37049 ** to change the length of the data stored.
37050 */
37051 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
37052   assert( cursorHoldsMutex(pCsr) );
37053   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
37054   assert(pCsr->isIncrblobHandle);
37055   if( pCsr->eState>=CURSOR_REQUIRESEEK ){
37056     if( pCsr->eState==CURSOR_FAULT ){
37057       return pCsr->skip;
37058     }else{
37059       return SQLITE_ABORT;
37060     }
37061   }
37062
37063   /* Check some preconditions: 
37064   **   (a) the cursor is open for writing,
37065   **   (b) there is no read-lock on the table being modified and
37066   **   (c) the cursor points at a valid row of an intKey table.
37067   */
37068   if( !pCsr->wrFlag ){
37069     return SQLITE_READONLY;
37070   }
37071   assert( !pCsr->pBt->readOnly 
37072           && pCsr->pBt->inTransaction==TRANS_WRITE );
37073   if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
37074     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
37075   }
37076   if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
37077     return SQLITE_ERROR;
37078   }
37079
37080   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
37081 }
37082
37083 /* 
37084 ** Set a flag on this cursor to cache the locations of pages from the 
37085 ** overflow list for the current row. This is used by cursors opened
37086 ** for incremental blob IO only.
37087 **
37088 ** This function sets a flag only. The actual page location cache
37089 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
37090 ** accessPayload() (the worker function for sqlite3BtreeData() and
37091 ** sqlite3BtreePutData()).
37092 */
37093 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
37094   assert( cursorHoldsMutex(pCur) );
37095   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37096   assert(!pCur->isIncrblobHandle);
37097   assert(!pCur->aOverflow);
37098   pCur->isIncrblobHandle = 1;
37099 }
37100 #endif
37101
37102 /************** End of btree.c ***********************************************/
37103 /************** Begin file vdbefifo.c ****************************************/
37104 /*
37105 ** 2005 June 16
37106 **
37107 ** The author disclaims copyright to this source code.  In place of
37108 ** a legal notice, here is a blessing:
37109 **
37110 **    May you do good and not evil.
37111 **    May you find forgiveness for yourself and forgive others.
37112 **    May you share freely, never taking more than you give.
37113 **
37114 *************************************************************************
37115 ** This file implements a FIFO queue of rowids used for processing
37116 ** UPDATE and DELETE statements.
37117 */
37118
37119 /*
37120 ** Constants FIFOSIZE_FIRST and FIFOSIZE_MAX are the initial
37121 ** number of entries in a fifo page and the maximum number of
37122 ** entries in a fifo page.
37123 */
37124 #define FIFOSIZE_FIRST (((128-sizeof(FifoPage))/8)+1)
37125 #ifdef SQLITE_MALLOC_SOFT_LIMIT
37126 # define FIFOSIZE_MAX   (((SQLITE_MALLOC_SOFT_LIMIT-sizeof(FifoPage))/8)+1)
37127 #else
37128 # define FIFOSIZE_MAX   (((262144-sizeof(FifoPage))/8)+1)
37129 #endif
37130
37131 /*
37132 ** Allocate a new FifoPage and return a pointer to it.  Return NULL if
37133 ** we run out of memory.  Leave space on the page for nEntry entries.
37134 */
37135 static FifoPage *allocateFifoPage(int nEntry){
37136   FifoPage *pPage;
37137   if( nEntry>FIFOSIZE_MAX ){
37138     nEntry = FIFOSIZE_MAX;
37139   }
37140   pPage = sqlite3_malloc( sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
37141   if( pPage ){
37142     pPage->nSlot = nEntry;
37143     pPage->iWrite = 0;
37144     pPage->iRead = 0;
37145     pPage->pNext = 0;
37146   }
37147   return pPage;
37148 }
37149
37150 /*
37151 ** Initialize a Fifo structure.
37152 */
37153 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo *pFifo){
37154   memset(pFifo, 0, sizeof(*pFifo));
37155 }
37156
37157 /*
37158 ** Push a single 64-bit integer value into the Fifo.  Return SQLITE_OK
37159 ** normally.   SQLITE_NOMEM is returned if we are unable to allocate
37160 ** memory.
37161 */
37162 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
37163   FifoPage *pPage;
37164   pPage = pFifo->pLast;
37165   if( pPage==0 ){
37166     pPage = pFifo->pLast = pFifo->pFirst = allocateFifoPage(FIFOSIZE_FIRST);
37167     if( pPage==0 ){
37168       return SQLITE_NOMEM;
37169     }
37170   }else if( pPage->iWrite>=pPage->nSlot ){
37171     pPage->pNext = allocateFifoPage(pFifo->nEntry);
37172     if( pPage->pNext==0 ){
37173       return SQLITE_NOMEM;
37174     }
37175     pPage = pFifo->pLast = pPage->pNext;
37176   }
37177   pPage->aSlot[pPage->iWrite++] = val;
37178   pFifo->nEntry++;
37179   return SQLITE_OK;
37180 }
37181
37182 /*
37183 ** Extract a single 64-bit integer value from the Fifo.  The integer
37184 ** extracted is the one least recently inserted.  If the Fifo is empty
37185 ** return SQLITE_DONE.
37186 */
37187 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
37188   FifoPage *pPage;
37189   if( pFifo->nEntry==0 ){
37190     return SQLITE_DONE;
37191   }
37192   assert( pFifo->nEntry>0 );
37193   pPage = pFifo->pFirst;
37194   assert( pPage!=0 );
37195   assert( pPage->iWrite>pPage->iRead );
37196   assert( pPage->iWrite<=pPage->nSlot );
37197   assert( pPage->iRead<pPage->nSlot );
37198   assert( pPage->iRead>=0 );
37199   *pVal = pPage->aSlot[pPage->iRead++];
37200   pFifo->nEntry--;
37201   if( pPage->iRead>=pPage->iWrite ){
37202     pFifo->pFirst = pPage->pNext;
37203     sqlite3_free(pPage);
37204     if( pFifo->nEntry==0 ){
37205       assert( pFifo->pLast==pPage );
37206       pFifo->pLast = 0;
37207     }else{
37208       assert( pFifo->pFirst!=0 );
37209     }
37210   }else{
37211     assert( pFifo->nEntry>0 );
37212   }
37213   return SQLITE_OK;
37214 }
37215
37216 /*
37217 ** Delete all information from a Fifo object.   Free all memory held
37218 ** by the Fifo.
37219 */
37220 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo *pFifo){
37221   FifoPage *pPage, *pNextPage;
37222   for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
37223     pNextPage = pPage->pNext;
37224     sqlite3_free(pPage);
37225   }
37226   sqlite3VdbeFifoInit(pFifo);
37227 }
37228
37229 /************** End of vdbefifo.c ********************************************/
37230 /************** Begin file vdbemem.c *****************************************/
37231 /*
37232 ** 2004 May 26
37233 **
37234 ** The author disclaims copyright to this source code.  In place of
37235 ** a legal notice, here is a blessing:
37236 **
37237 **    May you do good and not evil.
37238 **    May you find forgiveness for yourself and forgive others.
37239 **    May you share freely, never taking more than you give.
37240 **
37241 *************************************************************************
37242 **
37243 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
37244 ** stores a single value in the VDBE.  Mem is an opaque structure visible
37245 ** only within the VDBE.  Interface routines refer to a Mem using the
37246 ** name sqlite_value
37247 */
37248
37249 /*
37250 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
37251 ** P if required.
37252 */
37253 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
37254
37255 /*
37256 ** If pMem is an object with a valid string representation, this routine
37257 ** ensures the internal encoding for the string representation is
37258 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
37259 **
37260 ** If pMem is not a string object, or the encoding of the string
37261 ** representation is already stored using the requested encoding, then this
37262 ** routine is a no-op.
37263 **
37264 ** SQLITE_OK is returned if the conversion is successful (or not required).
37265 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
37266 ** between formats.
37267 */
37268 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
37269   int rc;
37270   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
37271     return SQLITE_OK;
37272   }
37273   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37274 #ifdef SQLITE_OMIT_UTF16
37275   return SQLITE_ERROR;
37276 #else
37277
37278   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
37279   ** then the encoding of the value may not have changed.
37280   */
37281   rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
37282   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
37283   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
37284   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
37285   return rc;
37286 #endif
37287 }
37288
37289 /*
37290 ** Make sure pMem->z points to a writable allocation of at least 
37291 ** n bytes.
37292 **
37293 ** If the memory cell currently contains string or blob data
37294 ** and the third argument passed to this function is true, the 
37295 ** current content of the cell is preserved. Otherwise, it may
37296 ** be discarded.  
37297 **
37298 ** This function sets the MEM_Dyn flag and clears any xDel callback.
37299 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
37300 ** not set, Mem.n is zeroed.
37301 */
37302 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
37303   assert( 1 >=
37304     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
37305     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
37306     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
37307     ((pMem->flags&MEM_Static) ? 1 : 0)
37308   );
37309
37310   if( !pMem->zMalloc || sqlite3MallocSize(pMem->zMalloc)<n ){
37311     n = (n>32?n:32);
37312     if( preserve && pMem->z==pMem->zMalloc ){
37313       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
37314       if( !pMem->z ){
37315         pMem->flags = MEM_Null;
37316       }
37317       preserve = 0;
37318     }else{
37319       sqlite3_free(pMem->zMalloc);
37320       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
37321     }
37322   }
37323
37324   if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
37325     memcpy(pMem->zMalloc, pMem->z, pMem->n);
37326   }
37327   if( pMem->flags&MEM_Dyn && pMem->xDel ){
37328     pMem->xDel((void *)(pMem->z));
37329   }
37330
37331   pMem->z = pMem->zMalloc;
37332   pMem->flags &= ~(MEM_Ephem|MEM_Static);
37333   pMem->xDel = 0;
37334   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
37335 }
37336
37337 /*
37338 ** Make the given Mem object MEM_Dyn.
37339 **
37340 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
37341 */
37342 SQLITE_PRIVATE int sqlite3VdbeMemDynamicify(Mem *pMem){
37343   int f;
37344   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37345   expandBlob(pMem);
37346   f = pMem->flags;
37347   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
37348     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
37349       return SQLITE_NOMEM;
37350     }
37351     pMem->z[pMem->n] = 0;
37352     pMem->z[pMem->n+1] = 0;
37353     pMem->flags |= MEM_Term;
37354   }
37355
37356   return SQLITE_OK;
37357 }
37358
37359 /*
37360 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
37361 ** blob stored in dynamically allocated space.
37362 */
37363 #ifndef SQLITE_OMIT_INCRBLOB
37364 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
37365   if( pMem->flags & MEM_Zero ){
37366     int nByte;
37367     assert( pMem->flags&MEM_Blob );
37368     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37369
37370     /* Set nByte to the number of bytes required to store the expanded blob. */
37371     nByte = pMem->n + pMem->u.i;
37372     if( nByte<=0 ){
37373       nByte = 1;
37374     }
37375     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
37376       return SQLITE_NOMEM;
37377     }
37378
37379     memset(&pMem->z[pMem->n], 0, pMem->u.i);
37380     pMem->n += pMem->u.i;
37381     pMem->flags &= ~(MEM_Zero|MEM_Term);
37382   }
37383   return SQLITE_OK;
37384 }
37385 #endif
37386
37387
37388 /*
37389 ** Make the given Mem object either MEM_Short or MEM_Dyn so that bytes
37390 ** of the Mem.z[] array can be modified.
37391 **
37392 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
37393 */
37394 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
37395   return sqlite3VdbeMemDynamicify(pMem);
37396 }
37397
37398 /*
37399 ** Make sure the given Mem is \u0000 terminated.
37400 */
37401 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
37402   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37403   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
37404     return SQLITE_OK;   /* Nothing to do */
37405   }
37406   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
37407     return SQLITE_NOMEM;
37408   }
37409   pMem->z[pMem->n] = 0;
37410   pMem->z[pMem->n+1] = 0;
37411   pMem->flags |= MEM_Term;
37412   return SQLITE_OK;
37413 }
37414
37415 /*
37416 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
37417 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
37418 ** is a no-op.
37419 **
37420 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
37421 **
37422 ** A MEM_Null value will never be passed to this function. This function is
37423 ** used for converting values to text for returning to the user (i.e. via
37424 ** sqlite3_value_text()), or for ensuring that values to be used as btree
37425 ** keys are strings. In the former case a NULL pointer is returned the
37426 ** user and the later is an internal programming error.
37427 */
37428 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
37429   int rc = SQLITE_OK;
37430   int fg = pMem->flags;
37431   const int nByte = 32;
37432
37433   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37434   assert( !(fg&MEM_Zero) );
37435   assert( !(fg&(MEM_Str|MEM_Blob)) );
37436   assert( fg&(MEM_Int|MEM_Real) );
37437
37438   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
37439     return SQLITE_NOMEM;
37440   }
37441
37442   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
37443   ** string representation of the value. Then, if the required encoding
37444   ** is UTF-16le or UTF-16be do a translation.
37445   ** 
37446   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
37447   */
37448   if( fg & MEM_Int ){
37449     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
37450   }else{
37451     assert( fg & MEM_Real );
37452     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
37453   }
37454   pMem->n = strlen(pMem->z);
37455   pMem->enc = SQLITE_UTF8;
37456   pMem->flags |= MEM_Str|MEM_Term;
37457   sqlite3VdbeChangeEncoding(pMem, enc);
37458   return rc;
37459 }
37460
37461 /*
37462 ** Memory cell pMem contains the context of an aggregate function.
37463 ** This routine calls the finalize method for that function.  The
37464 ** result of the aggregate is stored back into pMem.
37465 **
37466 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
37467 ** otherwise.
37468 */
37469 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
37470   int rc = SQLITE_OK;
37471   if( pFunc && pFunc->xFinalize ){
37472     sqlite3_context ctx;
37473     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
37474     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37475     ctx.s.flags = MEM_Null;
37476     ctx.s.db = pMem->db;
37477     ctx.s.zMalloc = 0;
37478     ctx.pMem = pMem;
37479     ctx.pFunc = pFunc;
37480     ctx.isError = 0;
37481     pFunc->xFinalize(&ctx);
37482     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
37483     sqlite3_free(pMem->zMalloc);
37484     *pMem = ctx.s;
37485     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
37486   }
37487   return rc;
37488 }
37489
37490 /*
37491 ** If the memory cell contains a string value that must be freed by
37492 ** invoking an external callback, free it now. Calling this function
37493 ** does not free any Mem.zMalloc buffer.
37494 */
37495 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
37496   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
37497   if( p->flags&MEM_Agg ){
37498     sqlite3VdbeMemFinalize(p, p->u.pDef);
37499     assert( (p->flags & MEM_Agg)==0 );
37500     sqlite3VdbeMemRelease(p);
37501   }else if( p->flags&MEM_Dyn && p->xDel ){
37502     p->xDel((void *)p->z);
37503     p->xDel = 0;
37504   }
37505 }
37506
37507 /*
37508 ** Release any memory held by the Mem. This may leave the Mem in an
37509 ** inconsistent state, for example with (Mem.z==0) and
37510 ** (Mem.type==SQLITE_TEXT).
37511 */
37512 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
37513   sqlite3VdbeMemReleaseExternal(p);
37514   sqlite3_free(p->zMalloc);
37515   p->z = 0;
37516   p->zMalloc = 0;
37517   p->xDel = 0;
37518 }
37519
37520 /*
37521 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
37522 ** If the double is too large, return 0x8000000000000000.
37523 **
37524 ** Most systems appear to do this simply by assigning
37525 ** variables and without the extra range tests.  But
37526 ** there are reports that windows throws an expection
37527 ** if the floating point value is out of range. (See ticket #2880.)
37528 ** Because we do not completely understand the problem, we will
37529 ** take the conservative approach and always do range tests
37530 ** before attempting the conversion.
37531 */
37532 static i64 doubleToInt64(double r){
37533   /*
37534   ** Many compilers we encounter do not define constants for the
37535   ** minimum and maximum 64-bit integers, or they define them
37536   ** inconsistently.  And many do not understand the "LL" notation.
37537   ** So we define our own static constants here using nothing
37538   ** larger than a 32-bit integer constant.
37539   */
37540   static const i64 maxInt = LARGEST_INT64;
37541   static const i64 minInt = SMALLEST_INT64;
37542
37543   if( r<(double)minInt ){
37544     return minInt;
37545   }else if( r>(double)maxInt ){
37546     return minInt;
37547   }else{
37548     return (i64)r;
37549   }
37550 }
37551
37552 /*
37553 ** Return some kind of integer value which is the best we can do
37554 ** at representing the value that *pMem describes as an integer.
37555 ** If pMem is an integer, then the value is exact.  If pMem is
37556 ** a floating-point then the value returned is the integer part.
37557 ** If pMem is a string or blob, then we make an attempt to convert
37558 ** it into a integer and return that.  If pMem is NULL, return 0.
37559 **
37560 ** If pMem is a string, its encoding might be changed.
37561 */
37562 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
37563   int flags;
37564   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37565   flags = pMem->flags;
37566   if( flags & MEM_Int ){
37567     return pMem->u.i;
37568   }else if( flags & MEM_Real ){
37569     return doubleToInt64(pMem->r);
37570   }else if( flags & (MEM_Str|MEM_Blob) ){
37571     i64 value;
37572     pMem->flags |= MEM_Str;
37573     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
37574        || sqlite3VdbeMemNulTerminate(pMem) ){
37575       return 0;
37576     }
37577     assert( pMem->z );
37578     sqlite3Atoi64(pMem->z, &value);
37579     return value;
37580   }else{
37581     return 0;
37582   }
37583 }
37584
37585 /*
37586 ** Return the best representation of pMem that we can get into a
37587 ** double.  If pMem is already a double or an integer, return its
37588 ** value.  If it is a string or blob, try to convert it to a double.
37589 ** If it is a NULL, return 0.0.
37590 */
37591 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
37592   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37593   if( pMem->flags & MEM_Real ){
37594     return pMem->r;
37595   }else if( pMem->flags & MEM_Int ){
37596     return (double)pMem->u.i;
37597   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
37598     double val = 0.0;
37599     pMem->flags |= MEM_Str;
37600     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
37601        || sqlite3VdbeMemNulTerminate(pMem) ){
37602       return 0.0;
37603     }
37604     assert( pMem->z );
37605     sqlite3AtoF(pMem->z, &val);
37606     return val;
37607   }else{
37608     return 0.0;
37609   }
37610 }
37611
37612 /*
37613 ** The MEM structure is already a MEM_Real.  Try to also make it a
37614 ** MEM_Int if we can.
37615 */
37616 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
37617   assert( pMem->flags & MEM_Real );
37618   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37619
37620   pMem->u.i = doubleToInt64(pMem->r);
37621   if( pMem->r==(double)pMem->u.i ){
37622     pMem->flags |= MEM_Int;
37623   }
37624 }
37625
37626 static void setTypeFlag(Mem *pMem, int f){
37627   MemSetTypeFlag(pMem, f);
37628 }
37629
37630 /*
37631 ** Convert pMem to type integer.  Invalidate any prior representations.
37632 */
37633 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
37634   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37635   pMem->u.i = sqlite3VdbeIntValue(pMem);
37636   setTypeFlag(pMem, MEM_Int);
37637   return SQLITE_OK;
37638 }
37639
37640 /*
37641 ** Convert pMem so that it is of type MEM_Real.
37642 ** Invalidate any prior representations.
37643 */
37644 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
37645   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37646   pMem->r = sqlite3VdbeRealValue(pMem);
37647   setTypeFlag(pMem, MEM_Real);
37648   return SQLITE_OK;
37649 }
37650
37651 /*
37652 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
37653 ** Invalidate any prior representations.
37654 */
37655 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
37656   double r1, r2;
37657   i64 i;
37658   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
37659   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
37660   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37661   r1 = sqlite3VdbeRealValue(pMem);
37662   i = doubleToInt64(r1);
37663   r2 = (double)i;
37664   if( r1==r2 ){
37665     sqlite3VdbeMemIntegerify(pMem);
37666   }else{
37667     pMem->r = r1;
37668     setTypeFlag(pMem, MEM_Real);
37669   }
37670   return SQLITE_OK;
37671 }
37672
37673 /*
37674 ** Delete any previous value and set the value stored in *pMem to NULL.
37675 */
37676 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
37677   setTypeFlag(pMem, MEM_Null);
37678   pMem->type = SQLITE_NULL;
37679 }
37680
37681 /*
37682 ** Delete any previous value and set the value to be a BLOB of length
37683 ** n containing all zeros.
37684 */
37685 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
37686   sqlite3VdbeMemRelease(pMem);
37687   setTypeFlag(pMem, MEM_Blob);
37688   pMem->flags = MEM_Blob|MEM_Zero;
37689   pMem->type = SQLITE_BLOB;
37690   pMem->n = 0;
37691   if( n<0 ) n = 0;
37692   pMem->u.i = n;
37693   pMem->enc = SQLITE_UTF8;
37694 }
37695
37696 /*
37697 ** Delete any previous value and set the value stored in *pMem to val,
37698 ** manifest type INTEGER.
37699 */
37700 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
37701   sqlite3VdbeMemRelease(pMem);
37702   pMem->u.i = val;
37703   pMem->flags = MEM_Int;
37704   pMem->type = SQLITE_INTEGER;
37705 }
37706
37707 /*
37708 ** Delete any previous value and set the value stored in *pMem to val,
37709 ** manifest type REAL.
37710 */
37711 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
37712   if( sqlite3IsNaN(val) ){
37713     sqlite3VdbeMemSetNull(pMem);
37714   }else{
37715     sqlite3VdbeMemRelease(pMem);
37716     pMem->r = val;
37717     pMem->flags = MEM_Real;
37718     pMem->type = SQLITE_FLOAT;
37719   }
37720 }
37721
37722 /*
37723 ** Return true if the Mem object contains a TEXT or BLOB that is
37724 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
37725 */
37726 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
37727   assert( p->db!=0 );
37728   if( p->flags & (MEM_Str|MEM_Blob) ){
37729     int n = p->n;
37730     if( p->flags & MEM_Zero ){
37731       n += p->u.i;
37732     }
37733     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
37734   }
37735   return 0; 
37736 }
37737
37738 /*
37739 ** Size of struct Mem not including the Mem.zMalloc member.
37740 */
37741 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
37742
37743 /*
37744 ** Make an shallow copy of pFrom into pTo.  Prior contents of
37745 ** pTo are freed.  The pFrom->z field is not duplicated.  If
37746 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
37747 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
37748 */
37749 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
37750   sqlite3VdbeMemReleaseExternal(pTo);
37751   memcpy(pTo, pFrom, MEMCELLSIZE);
37752   pTo->xDel = 0;
37753   if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
37754     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
37755     assert( srcType==MEM_Ephem || srcType==MEM_Static );
37756     pTo->flags |= srcType;
37757   }
37758 }
37759
37760 /*
37761 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
37762 ** freed before the copy is made.
37763 */
37764 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
37765   int rc = SQLITE_OK;
37766
37767   sqlite3VdbeMemReleaseExternal(pTo);
37768   memcpy(pTo, pFrom, MEMCELLSIZE);
37769   pTo->flags &= ~MEM_Dyn;
37770
37771   if( pTo->flags&(MEM_Str|MEM_Blob) ){
37772     if( 0==(pFrom->flags&MEM_Static) ){
37773       pTo->flags |= MEM_Ephem;
37774       rc = sqlite3VdbeMemMakeWriteable(pTo);
37775     }
37776   }
37777
37778   return rc;
37779 }
37780
37781 /*
37782 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
37783 ** freed. If pFrom contains ephemeral data, a copy is made.
37784 **
37785 ** pFrom contains an SQL NULL when this routine returns.
37786 */
37787 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
37788   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
37789   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
37790   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
37791
37792   sqlite3VdbeMemRelease(pTo);
37793   memcpy(pTo, pFrom, sizeof(Mem));
37794   pFrom->flags = MEM_Null;
37795   pFrom->xDel = 0;
37796   pFrom->zMalloc = 0;
37797 }
37798
37799 /*
37800 ** Change the value of a Mem to be a string or a BLOB.
37801 **
37802 ** The memory management strategy depends on the value of the xDel
37803 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
37804 ** string is copied into a (possibly existing) buffer managed by the 
37805 ** Mem structure. Otherwise, any existing buffer is freed and the
37806 ** pointer copied.
37807 */
37808 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
37809   Mem *pMem,          /* Memory cell to set to string value */
37810   const char *z,      /* String pointer */
37811   int n,              /* Bytes in string, or negative */
37812   u8 enc,             /* Encoding of z.  0 for BLOBs */
37813   void (*xDel)(void*) /* Destructor function */
37814 ){
37815   int nByte = n;      /* New value for pMem->n */
37816   int flags = 0;      /* New value for pMem->flags */
37817
37818   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
37819
37820   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
37821   if( !z ){
37822     sqlite3VdbeMemSetNull(pMem);
37823     return SQLITE_OK;
37824   }
37825
37826   flags = (enc==0?MEM_Blob:MEM_Str);
37827   if( nByte<0 ){
37828     assert( enc!=0 );
37829     if( enc==SQLITE_UTF8 ){
37830       for(nByte=0; z[nByte]; nByte++){}
37831     }else{
37832       for(nByte=0; z[nByte] | z[nByte+1]; nByte+=2){}
37833     }
37834     flags |= MEM_Term;
37835   }
37836
37837   /* The following block sets the new values of Mem.z and Mem.xDel. It
37838   ** also sets a flag in local variable "flags" to indicate the memory
37839   ** management (one of MEM_Dyn or MEM_Static).
37840   */
37841   if( xDel==SQLITE_TRANSIENT ){
37842     int nAlloc = nByte;
37843     if( flags&MEM_Term ){
37844       nAlloc += (enc==SQLITE_UTF8?1:2);
37845     }
37846     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
37847       return SQLITE_NOMEM;
37848     }
37849     memcpy(pMem->z, z, nAlloc);
37850   }else{
37851     sqlite3VdbeMemRelease(pMem);
37852     pMem->z = (char *)z;
37853     pMem->xDel = xDel;
37854     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
37855   }
37856
37857   pMem->n = nByte;
37858   pMem->flags = flags;
37859   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
37860   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
37861
37862 #ifndef SQLITE_OMIT_UTF16
37863   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
37864     return SQLITE_NOMEM;
37865   }
37866 #endif
37867
37868   return SQLITE_OK;
37869 }
37870
37871 /*
37872 ** Compare the values contained by the two memory cells, returning
37873 ** negative, zero or positive if pMem1 is less than, equal to, or greater
37874 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
37875 ** and reals) sorted numerically, followed by text ordered by the collating
37876 ** sequence pColl and finally blob's ordered by memcmp().
37877 **
37878 ** Two NULL values are considered equal by this function.
37879 */
37880 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
37881   int rc;
37882   int f1, f2;
37883   int combined_flags;
37884
37885   /* Interchange pMem1 and pMem2 if the collating sequence specifies
37886   ** DESC order.
37887   */
37888   f1 = pMem1->flags;
37889   f2 = pMem2->flags;
37890   combined_flags = f1|f2;
37891  
37892   /* If one value is NULL, it is less than the other. If both values
37893   ** are NULL, return 0.
37894   */
37895   if( combined_flags&MEM_Null ){
37896     return (f2&MEM_Null) - (f1&MEM_Null);
37897   }
37898
37899   /* If one value is a number and the other is not, the number is less.
37900   ** If both are numbers, compare as reals if one is a real, or as integers
37901   ** if both values are integers.
37902   */
37903   if( combined_flags&(MEM_Int|MEM_Real) ){
37904     if( !(f1&(MEM_Int|MEM_Real)) ){
37905       return 1;
37906     }
37907     if( !(f2&(MEM_Int|MEM_Real)) ){
37908       return -1;
37909     }
37910     if( (f1 & f2 & MEM_Int)==0 ){
37911       double r1, r2;
37912       if( (f1&MEM_Real)==0 ){
37913         r1 = pMem1->u.i;
37914       }else{
37915         r1 = pMem1->r;
37916       }
37917       if( (f2&MEM_Real)==0 ){
37918         r2 = pMem2->u.i;
37919       }else{
37920         r2 = pMem2->r;
37921       }
37922       if( r1<r2 ) return -1;
37923       if( r1>r2 ) return 1;
37924       return 0;
37925     }else{
37926       assert( f1&MEM_Int );
37927       assert( f2&MEM_Int );
37928       if( pMem1->u.i < pMem2->u.i ) return -1;
37929       if( pMem1->u.i > pMem2->u.i ) return 1;
37930       return 0;
37931     }
37932   }
37933
37934   /* If one value is a string and the other is a blob, the string is less.
37935   ** If both are strings, compare using the collating functions.
37936   */
37937   if( combined_flags&MEM_Str ){
37938     if( (f1 & MEM_Str)==0 ){
37939       return 1;
37940     }
37941     if( (f2 & MEM_Str)==0 ){
37942       return -1;
37943     }
37944
37945     assert( pMem1->enc==pMem2->enc );
37946     assert( pMem1->enc==SQLITE_UTF8 || 
37947             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
37948
37949     /* The collation sequence must be defined at this point, even if
37950     ** the user deletes the collation sequence after the vdbe program is
37951     ** compiled (this was not always the case).
37952     */
37953     assert( !pColl || pColl->xCmp );
37954
37955     if( pColl ){
37956       if( pMem1->enc==pColl->enc ){
37957         /* The strings are already in the correct encoding.  Call the
37958         ** comparison function directly */
37959         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
37960       }else{
37961         u8 origEnc = pMem1->enc;
37962         const void *v1, *v2;
37963         int n1, n2;
37964         /* Convert the strings into the encoding that the comparison
37965         ** function expects */
37966         v1 = sqlite3ValueText((sqlite3_value*)pMem1, pColl->enc);
37967         n1 = v1==0 ? 0 : pMem1->n;
37968         assert( n1==sqlite3ValueBytes((sqlite3_value*)pMem1, pColl->enc) );
37969         v2 = sqlite3ValueText((sqlite3_value*)pMem2, pColl->enc);
37970         n2 = v2==0 ? 0 : pMem2->n;
37971         assert( n2==sqlite3ValueBytes((sqlite3_value*)pMem2, pColl->enc) );
37972         /* Do the comparison */
37973         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
37974         /* Convert the strings back into the database encoding */
37975         sqlite3ValueText((sqlite3_value*)pMem1, origEnc);
37976         sqlite3ValueText((sqlite3_value*)pMem2, origEnc);
37977         return rc;
37978       }
37979     }
37980     /* If a NULL pointer was passed as the collate function, fall through
37981     ** to the blob case and use memcmp().  */
37982   }
37983  
37984   /* Both values must be blobs.  Compare using memcmp().  */
37985   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
37986   if( rc==0 ){
37987     rc = pMem1->n - pMem2->n;
37988   }
37989   return rc;
37990 }
37991
37992 /*
37993 ** Move data out of a btree key or data field and into a Mem structure.
37994 ** The data or key is taken from the entry that pCur is currently pointing
37995 ** to.  offset and amt determine what portion of the data or key to retrieve.
37996 ** key is true to get the key or false to get data.  The result is written
37997 ** into the pMem element.
37998 **
37999 ** The pMem structure is assumed to be uninitialized.  Any prior content
38000 ** is overwritten without being freed.
38001 **
38002 ** If this routine fails for any reason (malloc returns NULL or unable
38003 ** to read from the disk) then the pMem is left in an inconsistent state.
38004 */
38005 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
38006   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
38007   int offset,       /* Offset from the start of data to return bytes from. */
38008   int amt,          /* Number of bytes to return. */
38009   int key,          /* If true, retrieve from the btree key, not data. */
38010   Mem *pMem         /* OUT: Return data in this Mem structure. */
38011 ){
38012   char *zData;       /* Data from the btree layer */
38013   int available = 0; /* Number of bytes available on the local btree page */
38014   sqlite3 *db;       /* Database connection */
38015   int rc = SQLITE_OK;
38016
38017   db = sqlite3BtreeCursorDb(pCur);
38018   assert( sqlite3_mutex_held(db->mutex) );
38019   if( key ){
38020     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
38021   }else{
38022     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
38023   }
38024   assert( zData!=0 );
38025
38026   if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
38027     sqlite3VdbeMemRelease(pMem);
38028     pMem->z = &zData[offset];
38029     pMem->flags = MEM_Blob|MEM_Ephem;
38030   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
38031     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
38032     pMem->enc = 0;
38033     pMem->type = SQLITE_BLOB;
38034     if( key ){
38035       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
38036     }else{
38037       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
38038     }
38039     pMem->z[amt] = 0;
38040     pMem->z[amt+1] = 0;
38041     if( rc!=SQLITE_OK ){
38042       sqlite3VdbeMemRelease(pMem);
38043     }
38044   }
38045   pMem->n = amt;
38046
38047   return rc;
38048 }
38049
38050 #if 0
38051 /*
38052 ** Perform various checks on the memory cell pMem. An assert() will
38053 ** fail if pMem is internally inconsistent.
38054 */
38055 SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
38056   int flags = pMem->flags;
38057   assert( flags!=0 );  /* Must define some type */
38058   if( flags & (MEM_Str|MEM_Blob) ){
38059     int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
38060     assert( x!=0 );            /* Strings must define a string subtype */
38061     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
38062     assert( pMem->z!=0 );      /* Strings must have a value */
38063     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
38064     assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
38065     assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
38066     /* No destructor unless there is MEM_Dyn */
38067     assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
38068
38069     if( (flags & MEM_Str) ){
38070       assert( pMem->enc==SQLITE_UTF8 || 
38071               pMem->enc==SQLITE_UTF16BE ||
38072               pMem->enc==SQLITE_UTF16LE 
38073       );
38074       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
38075       ** must be the length of the string.  (Later:)  If the database file
38076       ** has been corrupted, '\000' characters might have been inserted
38077       ** into the middle of the string.  In that case, the strlen() might
38078       ** be less.
38079       */
38080       if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){ 
38081         assert( strlen(pMem->z)<=pMem->n );
38082         assert( pMem->z[pMem->n]==0 );
38083       }
38084     }
38085   }else{
38086     /* Cannot define a string subtype for non-string objects */
38087     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
38088     assert( pMem->xDel==0 );
38089   }
38090   /* MEM_Null excludes all other types */
38091   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
38092           || (pMem->flags&MEM_Null)==0 );
38093   /* If the MEM is both real and integer, the values are equal */
38094   assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) 
38095           || pMem->r==pMem->u.i );
38096 }
38097 #endif
38098
38099 /* This function is only available internally, it is not part of the
38100 ** external API. It works in a similar way to sqlite3_value_text(),
38101 ** except the data returned is in the encoding specified by the second
38102 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
38103 ** SQLITE_UTF8.
38104 **
38105 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
38106 ** If that is the case, then the result must be aligned on an even byte
38107 ** boundary.
38108 */
38109 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
38110   if( !pVal ) return 0;
38111
38112   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
38113   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
38114
38115   if( pVal->flags&MEM_Null ){
38116     return 0;
38117   }
38118   assert( (MEM_Blob>>3) == MEM_Str );
38119   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
38120   expandBlob(pVal);
38121   if( pVal->flags&MEM_Str ){
38122     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
38123     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&(int)pVal->z) ){
38124       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
38125       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
38126         return 0;
38127       }
38128     }
38129     sqlite3VdbeMemNulTerminate(pVal);
38130   }else{
38131     assert( (pVal->flags&MEM_Blob)==0 );
38132     sqlite3VdbeMemStringify(pVal, enc);
38133     assert( 0==(1&(int)pVal->z) );
38134   }
38135   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
38136               || pVal->db->mallocFailed );
38137   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
38138     return pVal->z;
38139   }else{
38140     return 0;
38141   }
38142 }
38143
38144 /*
38145 ** Create a new sqlite3_value object.
38146 */
38147 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
38148   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
38149   if( p ){
38150     p->flags = MEM_Null;
38151     p->type = SQLITE_NULL;
38152     p->db = db;
38153   }
38154   return p;
38155 }
38156
38157 /*
38158 ** Create a new sqlite3_value object, containing the value of pExpr.
38159 **
38160 ** This only works for very simple expressions that consist of one constant
38161 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
38162 ** be converted directly into a value, then the value is allocated and
38163 ** a pointer written to *ppVal. The caller is responsible for deallocating
38164 ** the value by passing it to sqlite3ValueFree() later on. If the expression
38165 ** cannot be converted to a value, then *ppVal is set to NULL.
38166 */
38167 SQLITE_PRIVATE int sqlite3ValueFromExpr(
38168   sqlite3 *db,              /* The database connection */
38169   Expr *pExpr,              /* The expression to evaluate */
38170   u8 enc,                   /* Encoding to use */
38171   u8 affinity,              /* Affinity to use */
38172   sqlite3_value **ppVal     /* Write the new value here */
38173 ){
38174   int op;
38175   char *zVal = 0;
38176   sqlite3_value *pVal = 0;
38177
38178   if( !pExpr ){
38179     *ppVal = 0;
38180     return SQLITE_OK;
38181   }
38182   op = pExpr->op;
38183
38184   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
38185     zVal = sqlite3StrNDup((char*)pExpr->token.z, pExpr->token.n);
38186     pVal = sqlite3ValueNew(db);
38187     if( !zVal || !pVal ) goto no_mem;
38188     sqlite3Dequote(zVal);
38189     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, sqlite3_free);
38190     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
38191       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
38192     }else{
38193       sqlite3ValueApplyAffinity(pVal, affinity, enc);
38194     }
38195   }else if( op==TK_UMINUS ) {
38196     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
38197       pVal->u.i = -1 * pVal->u.i;
38198       pVal->r = -1.0 * pVal->r;
38199     }
38200   }
38201 #ifndef SQLITE_OMIT_BLOB_LITERAL
38202   else if( op==TK_BLOB ){
38203     int nVal;
38204     assert( pExpr->token.n>=3 );
38205     assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
38206     assert( pExpr->token.z[1]=='\'' );
38207     assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
38208     pVal = sqlite3ValueNew(db);
38209     nVal = pExpr->token.n - 3;
38210     zVal = (char*)pExpr->token.z + 2;
38211     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
38212                          0, sqlite3_free);
38213   }
38214 #endif
38215
38216   *ppVal = pVal;
38217   return SQLITE_OK;
38218
38219 no_mem:
38220   db->mallocFailed = 1;
38221   sqlite3_free(zVal);
38222   sqlite3ValueFree(pVal);
38223   *ppVal = 0;
38224   return SQLITE_NOMEM;
38225 }
38226
38227 /*
38228 ** Change the string value of an sqlite3_value object
38229 */
38230 SQLITE_PRIVATE void sqlite3ValueSetStr(
38231   sqlite3_value *v,     /* Value to be set */
38232   int n,                /* Length of string z */
38233   const void *z,        /* Text of the new string */
38234   u8 enc,               /* Encoding to use */
38235   void (*xDel)(void*)   /* Destructor for the string */
38236 ){
38237   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
38238 }
38239
38240 /*
38241 ** Free an sqlite3_value object
38242 */
38243 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
38244   if( !v ) return;
38245   sqlite3VdbeMemRelease((Mem *)v);
38246   sqlite3_free(v);
38247 }
38248
38249 /*
38250 ** Return the number of bytes in the sqlite3_value object assuming
38251 ** that it uses the encoding "enc"
38252 */
38253 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
38254   Mem *p = (Mem*)pVal;
38255   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
38256     if( p->flags & MEM_Zero ){
38257       return p->n+p->u.i;
38258     }else{
38259       return p->n;
38260     }
38261   }
38262   return 0;
38263 }
38264
38265 /************** End of vdbemem.c *********************************************/
38266 /************** Begin file vdbeaux.c *****************************************/
38267 /*
38268 ** 2003 September 6
38269 **
38270 ** The author disclaims copyright to this source code.  In place of
38271 ** a legal notice, here is a blessing:
38272 **
38273 **    May you do good and not evil.
38274 **    May you find forgiveness for yourself and forgive others.
38275 **    May you share freely, never taking more than you give.
38276 **
38277 *************************************************************************
38278 ** This file contains code used for creating, destroying, and populating
38279 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
38280 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
38281 ** But that file was getting too big so this subroutines were split out.
38282 **
38283 ** $Id: vdbeaux.c,v 1.383 2008/05/13 13:27:34 drh Exp $
38284 */
38285
38286
38287
38288 /*
38289 ** When debugging the code generator in a symbolic debugger, one can
38290 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
38291 ** as they are added to the instruction stream.
38292 */
38293 #ifdef SQLITE_DEBUG
38294 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
38295 #endif
38296
38297
38298 /*
38299 ** Create a new virtual database engine.
38300 */
38301 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
38302   Vdbe *p;
38303   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
38304   if( p==0 ) return 0;
38305   p->db = db;
38306   if( db->pVdbe ){
38307     db->pVdbe->pPrev = p;
38308   }
38309   p->pNext = db->pVdbe;
38310   p->pPrev = 0;
38311   db->pVdbe = p;
38312   p->magic = VDBE_MAGIC_INIT;
38313   return p;
38314 }
38315
38316 /*
38317 ** Remember the SQL string for a prepared statement.
38318 */
38319 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
38320   if( p==0 ) return;
38321   assert( p->zSql==0 );
38322   p->zSql = sqlite3DbStrNDup(p->db, z, n);
38323 }
38324
38325 /*
38326 ** Return the SQL associated with a prepared statement
38327 */
38328 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
38329   return ((Vdbe *)pStmt)->zSql;
38330 }
38331
38332 /*
38333 ** Swap all content between two VDBE structures.
38334 */
38335 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
38336   Vdbe tmp, *pTmp;
38337   char *zTmp;
38338   int nTmp;
38339   tmp = *pA;
38340   *pA = *pB;
38341   *pB = tmp;
38342   pTmp = pA->pNext;
38343   pA->pNext = pB->pNext;
38344   pB->pNext = pTmp;
38345   pTmp = pA->pPrev;
38346   pA->pPrev = pB->pPrev;
38347   pB->pPrev = pTmp;
38348   zTmp = pA->zSql;
38349   pA->zSql = pB->zSql;
38350   pB->zSql = zTmp;
38351   nTmp = pA->nSql;
38352   pA->nSql = pB->nSql;
38353   pB->nSql = nTmp;
38354 }
38355
38356 #ifdef SQLITE_DEBUG
38357 /*
38358 ** Turn tracing on or off
38359 */
38360 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
38361   p->trace = trace;
38362 }
38363 #endif
38364
38365 /*
38366 ** Resize the Vdbe.aOp array so that it contains at least N
38367 ** elements.
38368 **
38369 ** If an out-of-memory error occurs while resizing the array,
38370 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
38371 ** any opcodes already allocated can be correctly deallocated
38372 ** along with the rest of the Vdbe).
38373 */
38374 static void resizeOpArray(Vdbe *p, int N){
38375   VdbeOp *pNew;
38376   pNew = sqlite3DbRealloc(p->db, p->aOp, N*sizeof(Op));
38377   if( pNew ){
38378     p->nOpAlloc = N;
38379     p->aOp = pNew;
38380   }
38381 }
38382
38383 /*
38384 ** Add a new instruction to the list of instructions current in the
38385 ** VDBE.  Return the address of the new instruction.
38386 **
38387 ** Parameters:
38388 **
38389 **    p               Pointer to the VDBE
38390 **
38391 **    op              The opcode for this instruction
38392 **
38393 **    p1, p2, p3      Operands
38394 **
38395 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
38396 ** the sqlite3VdbeChangeP4() function to change the value of the P4
38397 ** operand.
38398 */
38399 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
38400   int i;
38401   VdbeOp *pOp;
38402
38403   i = p->nOp;
38404   assert( p->magic==VDBE_MAGIC_INIT );
38405   if( p->nOpAlloc<=i ){
38406     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
38407     if( p->db->mallocFailed ){
38408       return 0;
38409     }
38410   }
38411   p->nOp++;
38412   pOp = &p->aOp[i];
38413   pOp->opcode = op;
38414   pOp->p5 = 0;
38415   pOp->p1 = p1;
38416   pOp->p2 = p2;
38417   pOp->p3 = p3;
38418   pOp->p4.p = 0;
38419   pOp->p4type = P4_NOTUSED;
38420   p->expired = 0;
38421 #ifdef SQLITE_DEBUG
38422   pOp->zComment = 0;
38423   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
38424 #endif
38425 #ifdef VDBE_PROFILE
38426   pOp->cycles = 0;
38427   pOp->cnt = 0;
38428 #endif
38429   return i;
38430 }
38431 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
38432   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
38433 }
38434 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
38435   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
38436 }
38437 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
38438   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
38439 }
38440
38441
38442 /*
38443 ** Add an opcode that includes the p4 value as a pointer.
38444 */
38445 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
38446   Vdbe *p,            /* Add the opcode to this VM */
38447   int op,             /* The new opcode */
38448   int p1,             /* The P1 operand */
38449   int p2,             /* The P2 operand */
38450   int p3,             /* The P3 operand */
38451   const char *zP4,    /* The P4 operand */
38452   int p4type          /* P4 operand type */
38453 ){
38454   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
38455   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
38456   return addr;
38457 }
38458
38459 /*
38460 ** Create a new symbolic label for an instruction that has yet to be
38461 ** coded.  The symbolic label is really just a negative number.  The
38462 ** label can be used as the P2 value of an operation.  Later, when
38463 ** the label is resolved to a specific address, the VDBE will scan
38464 ** through its operation list and change all values of P2 which match
38465 ** the label into the resolved address.
38466 **
38467 ** The VDBE knows that a P2 value is a label because labels are
38468 ** always negative and P2 values are suppose to be non-negative.
38469 ** Hence, a negative P2 value is a label that has yet to be resolved.
38470 **
38471 ** Zero is returned if a malloc() fails.
38472 */
38473 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
38474   int i;
38475   i = p->nLabel++;
38476   assert( p->magic==VDBE_MAGIC_INIT );
38477   if( i>=p->nLabelAlloc ){
38478     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
38479     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
38480                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
38481   }
38482   if( p->aLabel ){
38483     p->aLabel[i] = -1;
38484   }
38485   return -1-i;
38486 }
38487
38488 /*
38489 ** Resolve label "x" to be the address of the next instruction to
38490 ** be inserted.  The parameter "x" must have been obtained from
38491 ** a prior call to sqlite3VdbeMakeLabel().
38492 */
38493 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
38494   int j = -1-x;
38495   assert( p->magic==VDBE_MAGIC_INIT );
38496   assert( j>=0 && j<p->nLabel );
38497   if( p->aLabel ){
38498     p->aLabel[j] = p->nOp;
38499   }
38500 }
38501
38502 /*
38503 ** Loop through the program looking for P2 values that are negative
38504 ** on jump instructions.  Each such value is a label.  Resolve the
38505 ** label by setting the P2 value to its correct non-zero value.
38506 **
38507 ** This routine is called once after all opcodes have been inserted.
38508 **
38509 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
38510 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
38511 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
38512 **
38513 ** This routine also does the following optimization:  It scans for
38514 ** instructions that might cause a statement rollback.  Such instructions
38515 ** are:
38516 **
38517 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
38518 **   *  OP_Destroy
38519 **   *  OP_VUpdate
38520 **   *  OP_VRename
38521 **
38522 ** If no such instruction is found, then every Statement instruction 
38523 ** is changed to a Noop.  In this way, we avoid creating the statement 
38524 ** journal file unnecessarily.
38525 */
38526 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
38527   int i;
38528   int nMaxArgs = 0;
38529   Op *pOp;
38530   int *aLabel = p->aLabel;
38531   int doesStatementRollback = 0;
38532   int hasStatementBegin = 0;
38533   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
38534     u8 opcode = pOp->opcode;
38535
38536     if( opcode==OP_Function ){
38537       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
38538     }else if( opcode==OP_AggStep 
38539 #ifndef SQLITE_OMIT_VIRTUALTABLE
38540         || opcode==OP_VUpdate
38541 #endif
38542     ){
38543       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
38544     }
38545     if( opcode==OP_Halt ){
38546       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
38547         doesStatementRollback = 1;
38548       }
38549     }else if( opcode==OP_Statement ){
38550       hasStatementBegin = 1;
38551     }else if( opcode==OP_Destroy ){
38552       doesStatementRollback = 1;
38553 #ifndef SQLITE_OMIT_VIRTUALTABLE
38554     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
38555       doesStatementRollback = 1;
38556     }else if( opcode==OP_VFilter ){
38557       int n;
38558       assert( p->nOp - i >= 3 );
38559       assert( pOp[-1].opcode==OP_Integer );
38560       n = pOp[-1].p1;
38561       if( n>nMaxArgs ) nMaxArgs = n;
38562 #endif
38563     }
38564
38565     if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
38566       assert( -1-pOp->p2<p->nLabel );
38567       pOp->p2 = aLabel[-1-pOp->p2];
38568     }
38569   }
38570   sqlite3_free(p->aLabel);
38571   p->aLabel = 0;
38572
38573   *pMaxFuncArgs = nMaxArgs;
38574
38575   /* If we never rollback a statement transaction, then statement
38576   ** transactions are not needed.  So change every OP_Statement
38577   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
38578   ** which can be expensive on some platforms.
38579   */
38580   if( hasStatementBegin && !doesStatementRollback ){
38581     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
38582       if( pOp->opcode==OP_Statement ){
38583         pOp->opcode = OP_Noop;
38584       }
38585     }
38586   }
38587 }
38588
38589 /*
38590 ** Return the address of the next instruction to be inserted.
38591 */
38592 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
38593   assert( p->magic==VDBE_MAGIC_INIT );
38594   return p->nOp;
38595 }
38596
38597 /*
38598 ** Add a whole list of operations to the operation stack.  Return the
38599 ** address of the first operation added.
38600 */
38601 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
38602   int addr;
38603   assert( p->magic==VDBE_MAGIC_INIT );
38604   if( p->nOp + nOp > p->nOpAlloc ){
38605     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
38606     assert( p->nOp+nOp<=p->nOpAlloc || p->db->mallocFailed );
38607   }
38608   if( p->db->mallocFailed ){
38609     return 0;
38610   }
38611   addr = p->nOp;
38612   if( nOp>0 ){
38613     int i;
38614     VdbeOpList const *pIn = aOp;
38615     for(i=0; i<nOp; i++, pIn++){
38616       int p2 = pIn->p2;
38617       VdbeOp *pOut = &p->aOp[i+addr];
38618       pOut->opcode = pIn->opcode;
38619       pOut->p1 = pIn->p1;
38620       if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
38621         pOut->p2 = addr + ADDR(p2);
38622       }else{
38623         pOut->p2 = p2;
38624       }
38625       pOut->p3 = pIn->p3;
38626       pOut->p4type = P4_NOTUSED;
38627       pOut->p4.p = 0;
38628       pOut->p5 = 0;
38629 #ifdef SQLITE_DEBUG
38630       pOut->zComment = 0;
38631       if( sqlite3VdbeAddopTrace ){
38632         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
38633       }
38634 #endif
38635     }
38636     p->nOp += nOp;
38637   }
38638   return addr;
38639 }
38640
38641 /*
38642 ** Change the value of the P1 operand for a specific instruction.
38643 ** This routine is useful when a large program is loaded from a
38644 ** static array using sqlite3VdbeAddOpList but we want to make a
38645 ** few minor changes to the program.
38646 */
38647 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
38648   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
38649   if( p && addr>=0 && p->nOp>addr && p->aOp ){
38650     p->aOp[addr].p1 = val;
38651   }
38652 }
38653
38654 /*
38655 ** Change the value of the P2 operand for a specific instruction.
38656 ** This routine is useful for setting a jump destination.
38657 */
38658 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
38659   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
38660   if( p && addr>=0 && p->nOp>addr && p->aOp ){
38661     p->aOp[addr].p2 = val;
38662   }
38663 }
38664
38665 /*
38666 ** Change the value of the P3 operand for a specific instruction.
38667 */
38668 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
38669   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
38670   if( p && addr>=0 && p->nOp>addr && p->aOp ){
38671     p->aOp[addr].p3 = val;
38672   }
38673 }
38674
38675 /*
38676 ** Change the value of the P5 operand for the most recently
38677 ** added operation.
38678 */
38679 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
38680   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
38681   if( p && p->aOp ){
38682     assert( p->nOp>0 );
38683     p->aOp[p->nOp-1].p5 = val;
38684   }
38685 }
38686
38687 /*
38688 ** Change the P2 operand of instruction addr so that it points to
38689 ** the address of the next instruction to be coded.
38690 */
38691 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
38692   sqlite3VdbeChangeP2(p, addr, p->nOp);
38693 }
38694
38695
38696 /*
38697 ** If the input FuncDef structure is ephemeral, then free it.  If
38698 ** the FuncDef is not ephermal, then do nothing.
38699 */
38700 static void freeEphemeralFunction(FuncDef *pDef){
38701   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
38702     sqlite3_free(pDef);
38703   }
38704 }
38705
38706 /*
38707 ** Delete a P4 value if necessary.
38708 */
38709 static void freeP4(int p4type, void *p3){
38710   if( p3 ){
38711     switch( p4type ){
38712       case P4_REAL:
38713       case P4_INT64:
38714       case P4_MPRINTF:
38715       case P4_DYNAMIC:
38716       case P4_KEYINFO:
38717       case P4_KEYINFO_HANDOFF: {
38718         sqlite3_free(p3);
38719         break;
38720       }
38721       case P4_VDBEFUNC: {
38722         VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
38723         freeEphemeralFunction(pVdbeFunc->pFunc);
38724         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
38725         sqlite3_free(pVdbeFunc);
38726         break;
38727       }
38728       case P4_FUNCDEF: {
38729         freeEphemeralFunction((FuncDef*)p3);
38730         break;
38731       }
38732       case P4_MEM: {
38733         sqlite3ValueFree((sqlite3_value*)p3);
38734         break;
38735       }
38736     }
38737   }
38738 }
38739
38740
38741 /*
38742 ** Change N opcodes starting at addr to No-ops.
38743 */
38744 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
38745   if( p && p->aOp ){
38746     VdbeOp *pOp = &p->aOp[addr];
38747     while( N-- ){
38748       freeP4(pOp->p4type, pOp->p4.p);
38749       memset(pOp, 0, sizeof(pOp[0]));
38750       pOp->opcode = OP_Noop;
38751       pOp++;
38752     }
38753   }
38754 }
38755
38756 /*
38757 ** Change the value of the P4 operand for a specific instruction.
38758 ** This routine is useful when a large program is loaded from a
38759 ** static array using sqlite3VdbeAddOpList but we want to make a
38760 ** few minor changes to the program.
38761 **
38762 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
38763 ** the string is made into memory obtained from sqlite3_malloc().
38764 ** A value of n==0 means copy bytes of zP4 up to and including the
38765 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
38766 **
38767 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
38768 ** A copy is made of the KeyInfo structure into memory obtained from
38769 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
38770 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
38771 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
38772 ** caller should not free the allocation, it will be freed when the Vdbe is
38773 ** finalized.
38774 ** 
38775 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
38776 ** to a string or structure that is guaranteed to exist for the lifetime of
38777 ** the Vdbe. In these cases we can just copy the pointer.
38778 **
38779 ** If addr<0 then change P4 on the most recently inserted instruction.
38780 */
38781 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
38782   Op *pOp;
38783   assert( p!=0 );
38784   assert( p->magic==VDBE_MAGIC_INIT );
38785   if( p->aOp==0 || p->db->mallocFailed ){
38786     if (n != P4_KEYINFO) {
38787       freeP4(n, (void*)*(char**)&zP4);
38788     }
38789     return;
38790   }
38791   assert( addr<p->nOp );
38792   if( addr<0 ){
38793     addr = p->nOp - 1;
38794     if( addr<0 ) return;
38795   }
38796   pOp = &p->aOp[addr];
38797   freeP4(pOp->p4type, pOp->p4.p);
38798   pOp->p4.p = 0;
38799   if( n==P4_INT32 ){
38800     /* Note: this cast is safe, because the origin data point was an int
38801     ** that was cast to a (const char *). */
38802     pOp->p4.i = (int)zP4;
38803     pOp->p4type = n;
38804   }else if( zP4==0 ){
38805     pOp->p4.p = 0;
38806     pOp->p4type = P4_NOTUSED;
38807   }else if( n==P4_KEYINFO ){
38808     KeyInfo *pKeyInfo;
38809     int nField, nByte;
38810
38811     nField = ((KeyInfo*)zP4)->nField;
38812     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
38813     pKeyInfo = sqlite3_malloc( nByte );
38814     pOp->p4.pKeyInfo = pKeyInfo;
38815     if( pKeyInfo ){
38816       memcpy(pKeyInfo, zP4, nByte);
38817       /* In the current implementation, P4_KEYINFO is only ever used on
38818       ** KeyInfo structures that have no aSortOrder component.  Elements
38819       ** with an aSortOrder always use P4_KEYINFO_HANDOFF.  So we do not
38820       ** need to bother with duplicating the aSortOrder. */
38821       assert( pKeyInfo->aSortOrder==0 );
38822 #if 0
38823       aSortOrder = pKeyInfo->aSortOrder;
38824       if( aSortOrder ){
38825         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
38826         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
38827       }
38828 #endif
38829       pOp->p4type = P4_KEYINFO;
38830     }else{
38831       p->db->mallocFailed = 1;
38832       pOp->p4type = P4_NOTUSED;
38833     }
38834   }else if( n==P4_KEYINFO_HANDOFF ){
38835     pOp->p4.p = (void*)zP4;
38836     pOp->p4type = P4_KEYINFO;
38837   }else if( n<0 ){
38838     pOp->p4.p = (void*)zP4;
38839     pOp->p4type = n;
38840   }else{
38841     if( n==0 ) n = strlen(zP4);
38842     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
38843     pOp->p4type = P4_DYNAMIC;
38844   }
38845 }
38846
38847 #ifndef NDEBUG
38848 /*
38849 ** Change the comment on the the most recently coded instruction.
38850 */
38851 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
38852   va_list ap;
38853   assert( p->nOp>0 || p->aOp==0 );
38854   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
38855   if( p->nOp ){
38856     char **pz = &p->aOp[p->nOp-1].zComment;
38857     va_start(ap, zFormat);
38858     sqlite3_free(*pz);
38859     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
38860     va_end(ap);
38861   }
38862 }
38863 #endif
38864
38865 /*
38866 ** Return the opcode for a given address.
38867 */
38868 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
38869   assert( p->magic==VDBE_MAGIC_INIT );
38870   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
38871   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
38872 }
38873
38874 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
38875      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
38876 /*
38877 ** Compute a string that describes the P4 parameter for an opcode.
38878 ** Use zTemp for any required temporary buffer space.
38879 */
38880 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
38881   char *zP4 = zTemp;
38882   assert( nTemp>=20 );
38883   switch( pOp->p4type ){
38884     case P4_KEYINFO: {
38885       int i, j;
38886       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
38887       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
38888       i = strlen(zTemp);
38889       for(j=0; j<pKeyInfo->nField; j++){
38890         CollSeq *pColl = pKeyInfo->aColl[j];
38891         if( pColl ){
38892           int n = strlen(pColl->zName);
38893           if( i+n>nTemp-6 ){
38894             memcpy(&zTemp[i],",...",4);
38895             break;
38896           }
38897           zTemp[i++] = ',';
38898           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
38899             zTemp[i++] = '-';
38900           }
38901           memcpy(&zTemp[i], pColl->zName,n+1);
38902           i += n;
38903         }else if( i+4<nTemp-6 ){
38904           memcpy(&zTemp[i],",nil",4);
38905           i += 4;
38906         }
38907       }
38908       zTemp[i++] = ')';
38909       zTemp[i] = 0;
38910       assert( i<nTemp );
38911       break;
38912     }
38913     case P4_COLLSEQ: {
38914       CollSeq *pColl = pOp->p4.pColl;
38915       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
38916       break;
38917     }
38918     case P4_FUNCDEF: {
38919       FuncDef *pDef = pOp->p4.pFunc;
38920       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
38921       break;
38922     }
38923     case P4_INT64: {
38924       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
38925       break;
38926     }
38927     case P4_INT32: {
38928       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
38929       break;
38930     }
38931     case P4_REAL: {
38932       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
38933       break;
38934     }
38935     case P4_MEM: {
38936       Mem *pMem = pOp->p4.pMem;
38937       assert( (pMem->flags & MEM_Null)==0 );
38938       if( pMem->flags & MEM_Str ){
38939         zP4 = pMem->z;
38940       }else if( pMem->flags & MEM_Int ){
38941         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
38942       }else if( pMem->flags & MEM_Real ){
38943         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
38944       }
38945       break;
38946     }
38947 #ifndef SQLITE_OMIT_VIRTUALTABLE
38948     case P4_VTAB: {
38949       sqlite3_vtab *pVtab = pOp->p4.pVtab;
38950       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
38951       break;
38952     }
38953 #endif
38954     default: {
38955       zP4 = pOp->p4.z;
38956       if( zP4==0 ){
38957         zP4 = zTemp;
38958         zTemp[0] = 0;
38959       }
38960     }
38961   }
38962   assert( zP4!=0 );
38963   return zP4;
38964 }
38965 #endif
38966
38967 /*
38968 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
38969 **
38970 */
38971 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
38972   int mask;
38973   assert( i>=0 && i<p->db->nDb );
38974   assert( i<sizeof(p->btreeMask)*8 );
38975   mask = 1<<i;
38976   if( (p->btreeMask & mask)==0 ){
38977     p->btreeMask |= mask;
38978     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
38979   }
38980 }
38981
38982
38983 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
38984 /*
38985 ** Print a single opcode.  This routine is used for debugging only.
38986 */
38987 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
38988   char *zP4;
38989   char zPtr[50];
38990   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
38991   if( pOut==0 ) pOut = stdout;
38992   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
38993   fprintf(pOut, zFormat1, pc, 
38994       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
38995 #ifdef SQLITE_DEBUG
38996       pOp->zComment ? pOp->zComment : ""
38997 #else
38998       ""
38999 #endif
39000   );
39001   fflush(pOut);
39002 }
39003 #endif
39004
39005 /*
39006 ** Release an array of N Mem elements
39007 */
39008 static void releaseMemArray(Mem *p, int N, int freebuffers){
39009   if( p && N ){
39010     sqlite3 *db = p->db;
39011     int malloc_failed = db->mallocFailed;
39012     while( N-->0 ){
39013       assert( N<2 || p[0].db==p[1].db );
39014       if( freebuffers ){
39015         sqlite3VdbeMemRelease(p);
39016       }else{
39017         sqlite3VdbeMemReleaseExternal(p);
39018       }
39019       p->flags = MEM_Null;
39020       p++;
39021     }
39022     db->mallocFailed = malloc_failed;
39023   }
39024 }
39025
39026 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
39027 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p){
39028   int ii;
39029   int nFree = 0;
39030   assert( sqlite3_mutex_held(p->db->mutex) );
39031   for(ii=1; ii<=p->nMem; ii++){
39032     Mem *pMem = &p->aMem[ii];
39033     if( pMem->z && pMem->flags&MEM_Dyn ){
39034       assert( !pMem->xDel );
39035       nFree += sqlite3MallocSize(pMem->z);
39036       sqlite3VdbeMemRelease(pMem);
39037     }
39038   }
39039   return nFree;
39040 }
39041 #endif
39042
39043 #ifndef SQLITE_OMIT_EXPLAIN
39044 /*
39045 ** Give a listing of the program in the virtual machine.
39046 **
39047 ** The interface is the same as sqlite3VdbeExec().  But instead of
39048 ** running the code, it invokes the callback once for each instruction.
39049 ** This feature is used to implement "EXPLAIN".
39050 **
39051 ** When p->explain==1, each instruction is listed.  When
39052 ** p->explain==2, only OP_Explain instructions are listed and these
39053 ** are shown in a different format.  p->explain==2 is used to implement
39054 ** EXPLAIN QUERY PLAN.
39055 */
39056 SQLITE_PRIVATE int sqlite3VdbeList(
39057   Vdbe *p                   /* The VDBE */
39058 ){
39059   sqlite3 *db = p->db;
39060   int i;
39061   int rc = SQLITE_OK;
39062   Mem *pMem = p->pResultSet = &p->aMem[1];
39063
39064   assert( p->explain );
39065   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
39066   assert( db->magic==SQLITE_MAGIC_BUSY );
39067   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
39068
39069   /* Even though this opcode does not use dynamic strings for
39070   ** the result, result columns may become dynamic if the user calls
39071   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
39072   */
39073   releaseMemArray(pMem, p->nMem, 1);
39074
39075   do{
39076     i = p->pc++;
39077   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
39078   if( i>=p->nOp ){
39079     p->rc = SQLITE_OK;
39080     rc = SQLITE_DONE;
39081   }else if( db->u1.isInterrupted ){
39082     p->rc = SQLITE_INTERRUPT;
39083     rc = SQLITE_ERROR;
39084     sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
39085   }else{
39086     char *z;
39087     Op *pOp = &p->aOp[i];
39088     if( p->explain==1 ){
39089       pMem->flags = MEM_Int;
39090       pMem->type = SQLITE_INTEGER;
39091       pMem->u.i = i;                                /* Program counter */
39092       pMem++;
39093   
39094       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
39095       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
39096       assert( pMem->z!=0 );
39097       pMem->n = strlen(pMem->z);
39098       pMem->type = SQLITE_TEXT;
39099       pMem->enc = SQLITE_UTF8;
39100       pMem++;
39101     }
39102
39103     pMem->flags = MEM_Int;
39104     pMem->u.i = pOp->p1;                          /* P1 */
39105     pMem->type = SQLITE_INTEGER;
39106     pMem++;
39107
39108     pMem->flags = MEM_Int;
39109     pMem->u.i = pOp->p2;                          /* P2 */
39110     pMem->type = SQLITE_INTEGER;
39111     pMem++;
39112
39113     if( p->explain==1 ){
39114       pMem->flags = MEM_Int;
39115       pMem->u.i = pOp->p3;                          /* P3 */
39116       pMem->type = SQLITE_INTEGER;
39117       pMem++;
39118     }
39119
39120     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
39121       p->db->mallocFailed = 1;
39122       return SQLITE_NOMEM;
39123     }
39124     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
39125     z = displayP4(pOp, pMem->z, 32);
39126     if( z!=pMem->z ){
39127       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
39128     }else{
39129       assert( pMem->z!=0 );
39130       pMem->n = strlen(pMem->z);
39131       pMem->enc = SQLITE_UTF8;
39132     }
39133     pMem->type = SQLITE_TEXT;
39134     pMem++;
39135
39136     if( p->explain==1 ){
39137       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
39138         p->db->mallocFailed = 1;
39139         return SQLITE_NOMEM;
39140       }
39141       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
39142       pMem->n = 2;
39143       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
39144       pMem->type = SQLITE_TEXT;
39145       pMem->enc = SQLITE_UTF8;
39146       pMem++;
39147   
39148 #ifdef SQLITE_DEBUG
39149       if( pOp->zComment ){
39150         pMem->flags = MEM_Str|MEM_Term;
39151         pMem->z = pOp->zComment;
39152         pMem->n = strlen(pMem->z);
39153         pMem->enc = SQLITE_UTF8;
39154       }else
39155 #endif
39156       {
39157         pMem->flags = MEM_Null;                       /* Comment */
39158         pMem->type = SQLITE_NULL;
39159       }
39160     }
39161
39162     p->nResColumn = 8 - 5*(p->explain-1);
39163     p->rc = SQLITE_OK;
39164     rc = SQLITE_ROW;
39165   }
39166   return rc;
39167 }
39168 #endif /* SQLITE_OMIT_EXPLAIN */
39169
39170 #ifdef SQLITE_DEBUG
39171 /*
39172 ** Print the SQL that was used to generate a VDBE program.
39173 */
39174 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
39175   int nOp = p->nOp;
39176   VdbeOp *pOp;
39177   if( nOp<1 ) return;
39178   pOp = &p->aOp[0];
39179   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
39180     const char *z = pOp->p4.z;
39181     while( isspace(*(u8*)z) ) z++;
39182     printf("SQL: [%s]\n", z);
39183   }
39184 }
39185 #endif
39186
39187 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
39188 /*
39189 ** Print an IOTRACE message showing SQL content.
39190 */
39191 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
39192   int nOp = p->nOp;
39193   VdbeOp *pOp;
39194   if( sqlite3IoTrace==0 ) return;
39195   if( nOp<1 ) return;
39196   pOp = &p->aOp[0];
39197   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
39198     int i, j;
39199     char z[1000];
39200     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
39201     for(i=0; isspace((unsigned char)z[i]); i++){}
39202     for(j=0; z[i]; i++){
39203       if( isspace((unsigned char)z[i]) ){
39204         if( z[i-1]!=' ' ){
39205           z[j++] = ' ';
39206         }
39207       }else{
39208         z[j++] = z[i];
39209       }
39210     }
39211     z[j] = 0;
39212     sqlite3IoTrace("SQL %s\n", z);
39213   }
39214 }
39215 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
39216
39217
39218 /*
39219 ** Prepare a virtual machine for execution.  This involves things such
39220 ** as allocating stack space and initializing the program counter.
39221 ** After the VDBE has be prepped, it can be executed by one or more
39222 ** calls to sqlite3VdbeExec().  
39223 **
39224 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
39225 ** VDBE_MAGIC_RUN.
39226 */
39227 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
39228   Vdbe *p,                       /* The VDBE */
39229   int nVar,                      /* Number of '?' see in the SQL statement */
39230   int nMem,                      /* Number of memory cells to allocate */
39231   int nCursor,                   /* Number of cursors to allocate */
39232   int isExplain                  /* True if the EXPLAIN keywords is present */
39233 ){
39234   int n;
39235   sqlite3 *db = p->db;
39236
39237   assert( p!=0 );
39238   assert( p->magic==VDBE_MAGIC_INIT );
39239
39240   /* There should be at least one opcode.
39241   */
39242   assert( p->nOp>0 );
39243
39244   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
39245    * is because the call to resizeOpArray() below may shrink the
39246    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
39247    * state.
39248    */
39249   p->magic = VDBE_MAGIC_RUN;
39250
39251   /* For each cursor required, also allocate a memory cell. Memory
39252   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
39253   ** the vdbe program. Instead they are used to allocate space for
39254   ** Cursor/BtCursor structures. The blob of memory associated with 
39255   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
39256   ** stores the blob of memory associated with cursor 1, etc.
39257   **
39258   ** See also: allocateCursor().
39259   */
39260   nMem += nCursor;
39261
39262   /*
39263   ** Allocation space for registers.
39264   */
39265   if( p->aMem==0 ){
39266     int nArg;       /* Maximum number of args passed to a user function. */
39267     resolveP2Values(p, &nArg);
39268     /*resizeOpArray(p, p->nOp);*/
39269     assert( nVar>=0 );
39270     if( isExplain && nMem<10 ){
39271       p->nMem = nMem = 10;
39272     }
39273     p->aMem = sqlite3DbMallocZero(db,
39274         nMem*sizeof(Mem)               /* aMem */
39275       + nVar*sizeof(Mem)               /* aVar */
39276       + nArg*sizeof(Mem*)              /* apArg */
39277       + nVar*sizeof(char*)             /* azVar */
39278       + nCursor*sizeof(Cursor*) + 1    /* apCsr */
39279     );
39280     if( !db->mallocFailed ){
39281       p->aMem--;             /* aMem[] goes from 1..nMem */
39282       p->nMem = nMem;        /*       not from 0..nMem-1 */
39283       p->aVar = &p->aMem[nMem+1];
39284       p->nVar = nVar;
39285       p->okVar = 0;
39286       p->apArg = (Mem**)&p->aVar[nVar];
39287       p->azVar = (char**)&p->apArg[nArg];
39288       p->apCsr = (Cursor**)&p->azVar[nVar];
39289       p->nCursor = nCursor;
39290       for(n=0; n<nVar; n++){
39291         p->aVar[n].flags = MEM_Null;
39292         p->aVar[n].db = db;
39293       }
39294       for(n=1; n<=nMem; n++){
39295         p->aMem[n].flags = MEM_Null;
39296         p->aMem[n].db = db;
39297       }
39298     }
39299   }
39300 #ifdef SQLITE_DEBUG
39301   for(n=1; n<p->nMem; n++){
39302     assert( p->aMem[n].db==db );
39303   }
39304 #endif
39305
39306   p->pc = -1;
39307   p->rc = SQLITE_OK;
39308   p->uniqueCnt = 0;
39309   p->returnDepth = 0;
39310   p->errorAction = OE_Abort;
39311   p->explain |= isExplain;
39312   p->magic = VDBE_MAGIC_RUN;
39313   p->nChange = 0;
39314   p->cacheCtr = 1;
39315   p->minWriteFileFormat = 255;
39316   p->openedStatement = 0;
39317 #ifdef VDBE_PROFILE
39318   {
39319     int i;
39320     for(i=0; i<p->nOp; i++){
39321       p->aOp[i].cnt = 0;
39322       p->aOp[i].cycles = 0;
39323     }
39324   }
39325 #endif
39326 }
39327
39328 /*
39329 ** Close a VDBE cursor and release all the resources that cursor 
39330 ** happens to hold.
39331 */
39332 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
39333   if( pCx==0 ){
39334     return;
39335   }
39336   if( pCx->pCursor ){
39337     sqlite3BtreeCloseCursor(pCx->pCursor);
39338   }
39339   if( pCx->pBt ){
39340     sqlite3BtreeClose(pCx->pBt);
39341   }
39342 #ifndef SQLITE_OMIT_VIRTUALTABLE
39343   if( pCx->pVtabCursor ){
39344     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
39345     const sqlite3_module *pModule = pCx->pModule;
39346     p->inVtabMethod = 1;
39347     (void)sqlite3SafetyOff(p->db);
39348     pModule->xClose(pVtabCursor);
39349     (void)sqlite3SafetyOn(p->db);
39350     p->inVtabMethod = 0;
39351   }
39352 #endif
39353   if( !pCx->ephemPseudoTable ){
39354     sqlite3_free(pCx->pData);
39355   }
39356   /* memset(pCx, 0, sizeof(Cursor)); */
39357   /* sqlite3_free(pCx->aType); */
39358   /* sqlite3_free(pCx); */
39359 }
39360
39361 /*
39362 ** Close all cursors except for VTab cursors that are currently
39363 ** in use.
39364 */
39365 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
39366   int i;
39367   if( p->apCsr==0 ) return;
39368   for(i=0; i<p->nCursor; i++){
39369     Cursor *pC = p->apCsr[i];
39370     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
39371       sqlite3VdbeFreeCursor(p, pC);
39372       p->apCsr[i] = 0;
39373     }
39374   }
39375 }
39376
39377 /*
39378 ** Clean up the VM after execution.
39379 **
39380 ** This routine will automatically close any cursors, lists, and/or
39381 ** sorters that were left open.  It also deletes the values of
39382 ** variables in the aVar[] array.
39383 */
39384 static void Cleanup(Vdbe *p, int freebuffers){
39385   int i;
39386   closeAllCursorsExceptActiveVtabs(p);
39387   for(i=1; i<=p->nMem; i++){
39388     MemSetTypeFlag(&p->aMem[i], MEM_Null);
39389   }
39390   releaseMemArray(&p->aMem[1], p->nMem, freebuffers);
39391   sqlite3VdbeFifoClear(&p->sFifo);
39392   if( p->contextStack ){
39393     for(i=0; i<p->contextStackTop; i++){
39394       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
39395     }
39396     sqlite3_free(p->contextStack);
39397   }
39398   p->contextStack = 0;
39399   p->contextStackDepth = 0;
39400   p->contextStackTop = 0;
39401   sqlite3_free(p->zErrMsg);
39402   p->zErrMsg = 0;
39403   p->pResultSet = 0;
39404 }
39405
39406 /*
39407 ** Set the number of result columns that will be returned by this SQL
39408 ** statement. This is now set at compile time, rather than during
39409 ** execution of the vdbe program so that sqlite3_column_count() can
39410 ** be called on an SQL statement before sqlite3_step().
39411 */
39412 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
39413   Mem *pColName;
39414   int n;
39415
39416   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N, 1);
39417   sqlite3_free(p->aColName);
39418   n = nResColumn*COLNAME_N;
39419   p->nResColumn = nResColumn;
39420   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(p->db, sizeof(Mem)*n );
39421   if( p->aColName==0 ) return;
39422   while( n-- > 0 ){
39423     pColName->flags = MEM_Null;
39424     pColName->db = p->db;
39425     pColName++;
39426   }
39427 }
39428
39429 /*
39430 ** Set the name of the idx'th column to be returned by the SQL statement.
39431 ** zName must be a pointer to a nul terminated string.
39432 **
39433 ** This call must be made after a call to sqlite3VdbeSetNumCols().
39434 **
39435 ** If N==P4_STATIC  it means that zName is a pointer to a constant static
39436 ** string and we can just copy the pointer. If it is P4_DYNAMIC, then 
39437 ** the string is freed using sqlite3_free() when the vdbe is finished with
39438 ** it. Otherwise, N bytes of zName are copied.
39439 */
39440 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
39441   int rc;
39442   Mem *pColName;
39443   assert( idx<p->nResColumn );
39444   assert( var<COLNAME_N );
39445   if( p->db->mallocFailed ) return SQLITE_NOMEM;
39446   assert( p->aColName!=0 );
39447   pColName = &(p->aColName[idx+var*p->nResColumn]);
39448   if( N==P4_DYNAMIC || N==P4_STATIC ){
39449     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
39450   }else{
39451     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
39452   }
39453   if( rc==SQLITE_OK && N==P4_DYNAMIC ){
39454     pColName->flags &= (~MEM_Static);
39455     pColName->zMalloc = pColName->z;
39456   }
39457   return rc;
39458 }
39459
39460 /*
39461 ** A read or write transaction may or may not be active on database handle
39462 ** db. If a transaction is active, commit it. If there is a
39463 ** write-transaction spanning more than one database file, this routine
39464 ** takes care of the master journal trickery.
39465 */
39466 static int vdbeCommit(sqlite3 *db){
39467   int i;
39468   int nTrans = 0;  /* Number of databases with an active write-transaction */
39469   int rc = SQLITE_OK;
39470   int needXcommit = 0;
39471
39472   /* Before doing anything else, call the xSync() callback for any
39473   ** virtual module tables written in this transaction. This has to
39474   ** be done before determining whether a master journal file is 
39475   ** required, as an xSync() callback may add an attached database
39476   ** to the transaction.
39477   */
39478   rc = sqlite3VtabSync(db, rc);
39479   if( rc!=SQLITE_OK ){
39480     return rc;
39481   }
39482
39483   /* This loop determines (a) if the commit hook should be invoked and
39484   ** (b) how many database files have open write transactions, not 
39485   ** including the temp database. (b) is important because if more than 
39486   ** one database file has an open write transaction, a master journal
39487   ** file is required for an atomic commit.
39488   */ 
39489   for(i=0; i<db->nDb; i++){ 
39490     Btree *pBt = db->aDb[i].pBt;
39491     if( sqlite3BtreeIsInTrans(pBt) ){
39492       needXcommit = 1;
39493       if( i!=1 ) nTrans++;
39494     }
39495   }
39496
39497   /* If there are any write-transactions at all, invoke the commit hook */
39498   if( needXcommit && db->xCommitCallback ){
39499     (void)sqlite3SafetyOff(db);
39500     rc = db->xCommitCallback(db->pCommitArg);
39501     (void)sqlite3SafetyOn(db);
39502     if( rc ){
39503       return SQLITE_CONSTRAINT;
39504     }
39505   }
39506
39507   /* The simple case - no more than one database file (not counting the
39508   ** TEMP database) has a transaction active.   There is no need for the
39509   ** master-journal.
39510   **
39511   ** If the return value of sqlite3BtreeGetFilename() is a zero length
39512   ** string, it means the main database is :memory:.  In that case we do
39513   ** not support atomic multi-file commits, so use the simple case then
39514   ** too.
39515   */
39516   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
39517     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
39518       Btree *pBt = db->aDb[i].pBt;
39519       if( pBt ){
39520         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
39521       }
39522     }
39523
39524     /* Do the commit only if all databases successfully complete phase 1. 
39525     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
39526     ** IO error while deleting or truncating a journal file. It is unlikely,
39527     ** but could happen. In this case abandon processing and return the error.
39528     */
39529     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
39530       Btree *pBt = db->aDb[i].pBt;
39531       if( pBt ){
39532         rc = sqlite3BtreeCommitPhaseTwo(pBt);
39533       }
39534     }
39535     if( rc==SQLITE_OK ){
39536       sqlite3VtabCommit(db);
39537     }
39538   }
39539
39540   /* The complex case - There is a multi-file write-transaction active.
39541   ** This requires a master journal file to ensure the transaction is
39542   ** committed atomicly.
39543   */
39544 #ifndef SQLITE_OMIT_DISKIO
39545   else{
39546     sqlite3_vfs *pVfs = db->pVfs;
39547     int needSync = 0;
39548     char *zMaster = 0;   /* File-name for the master journal */
39549     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
39550     sqlite3_file *pMaster = 0;
39551     i64 offset = 0;
39552
39553     /* Select a master journal file name */
39554     do {
39555       u32 random;
39556       sqlite3_free(zMaster);
39557       sqlite3_randomness(sizeof(random), &random);
39558       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
39559       if( !zMaster ){
39560         return SQLITE_NOMEM;
39561       }
39562       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS);
39563     }while( rc==1 );
39564     if( rc!=0 ){
39565       rc = SQLITE_IOERR_NOMEM;
39566     }else{
39567       /* Open the master journal. */
39568       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
39569           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
39570           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
39571       );
39572     }
39573     if( rc!=SQLITE_OK ){
39574       sqlite3_free(zMaster);
39575       return rc;
39576     }
39577  
39578     /* Write the name of each database file in the transaction into the new
39579     ** master journal file. If an error occurs at this point close
39580     ** and delete the master journal file. All the individual journal files
39581     ** still have 'null' as the master journal pointer, so they will roll
39582     ** back independently if a failure occurs.
39583     */
39584     for(i=0; i<db->nDb; i++){
39585       Btree *pBt = db->aDb[i].pBt;
39586       if( i==1 ) continue;   /* Ignore the TEMP database */
39587       if( sqlite3BtreeIsInTrans(pBt) ){
39588         char const *zFile = sqlite3BtreeGetJournalname(pBt);
39589         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
39590         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
39591           needSync = 1;
39592         }
39593         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
39594         offset += strlen(zFile)+1;
39595         if( rc!=SQLITE_OK ){
39596           sqlite3OsCloseFree(pMaster);
39597           sqlite3OsDelete(pVfs, zMaster, 0);
39598           sqlite3_free(zMaster);
39599           return rc;
39600         }
39601       }
39602     }
39603
39604     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
39605     ** flag is set this is not required.
39606     */
39607     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
39608     if( (needSync 
39609      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
39610      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
39611       sqlite3OsCloseFree(pMaster);
39612       sqlite3OsDelete(pVfs, zMaster, 0);
39613       sqlite3_free(zMaster);
39614       return rc;
39615     }
39616
39617     /* Sync all the db files involved in the transaction. The same call
39618     ** sets the master journal pointer in each individual journal. If
39619     ** an error occurs here, do not delete the master journal file.
39620     **
39621     ** If the error occurs during the first call to
39622     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
39623     ** master journal file will be orphaned. But we cannot delete it,
39624     ** in case the master journal file name was written into the journal
39625     ** file before the failure occured.
39626     */
39627     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
39628       Btree *pBt = db->aDb[i].pBt;
39629       if( pBt ){
39630         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
39631       }
39632     }
39633     sqlite3OsCloseFree(pMaster);
39634     if( rc!=SQLITE_OK ){
39635       sqlite3_free(zMaster);
39636       return rc;
39637     }
39638
39639     /* Delete the master journal file. This commits the transaction. After
39640     ** doing this the directory is synced again before any individual
39641     ** transaction files are deleted.
39642     */
39643     rc = sqlite3OsDelete(pVfs, zMaster, 1);
39644     sqlite3_free(zMaster);
39645     zMaster = 0;
39646     if( rc ){
39647       return rc;
39648     }
39649
39650     /* All files and directories have already been synced, so the following
39651     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
39652     ** deleting or truncating journals. If something goes wrong while
39653     ** this is happening we don't really care. The integrity of the
39654     ** transaction is already guaranteed, but some stray 'cold' journals
39655     ** may be lying around. Returning an error code won't help matters.
39656     */
39657     disable_simulated_io_errors();
39658     sqlite3FaultBeginBenign(SQLITE_FAULTINJECTOR_MALLOC);
39659     for(i=0; i<db->nDb; i++){ 
39660       Btree *pBt = db->aDb[i].pBt;
39661       if( pBt ){
39662         sqlite3BtreeCommitPhaseTwo(pBt);
39663       }
39664     }
39665     sqlite3FaultEndBenign(SQLITE_FAULTINJECTOR_MALLOC);
39666     enable_simulated_io_errors();
39667
39668     sqlite3VtabCommit(db);
39669   }
39670 #endif
39671
39672   return rc;
39673 }
39674
39675 /* 
39676 ** This routine checks that the sqlite3.activeVdbeCnt count variable
39677 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
39678 ** currently active. An assertion fails if the two counts do not match.
39679 ** This is an internal self-check only - it is not an essential processing
39680 ** step.
39681 **
39682 ** This is a no-op if NDEBUG is defined.
39683 */
39684 #ifndef NDEBUG
39685 static void checkActiveVdbeCnt(sqlite3 *db){
39686   Vdbe *p;
39687   int cnt = 0;
39688   p = db->pVdbe;
39689   while( p ){
39690     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
39691       cnt++;
39692     }
39693     p = p->pNext;
39694   }
39695   assert( cnt==db->activeVdbeCnt );
39696 }
39697 #else
39698 #define checkActiveVdbeCnt(x)
39699 #endif
39700
39701 /*
39702 ** For every Btree that in database connection db which 
39703 ** has been modified, "trip" or invalidate each cursor in
39704 ** that Btree might have been modified so that the cursor
39705 ** can never be used again.  This happens when a rollback
39706 *** occurs.  We have to trip all the other cursors, even
39707 ** cursor from other VMs in different database connections,
39708 ** so that none of them try to use the data at which they
39709 ** were pointing and which now may have been changed due
39710 ** to the rollback.
39711 **
39712 ** Remember that a rollback can delete tables complete and
39713 ** reorder rootpages.  So it is not sufficient just to save
39714 ** the state of the cursor.  We have to invalidate the cursor
39715 ** so that it is never used again.
39716 */
39717 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
39718   int i;
39719   for(i=0; i<db->nDb; i++){
39720     Btree *p = db->aDb[i].pBt;
39721     if( p && sqlite3BtreeIsInTrans(p) ){
39722       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
39723     }
39724   }
39725 }
39726
39727 /*
39728 ** This routine is called the when a VDBE tries to halt.  If the VDBE
39729 ** has made changes and is in autocommit mode, then commit those
39730 ** changes.  If a rollback is needed, then do the rollback.
39731 **
39732 ** This routine is the only way to move the state of a VM from
39733 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
39734 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
39735 **
39736 ** Return an error code.  If the commit could not complete because of
39737 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
39738 ** means the close did not happen and needs to be repeated.
39739 */
39740 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
39741   sqlite3 *db = p->db;
39742   int i;
39743   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
39744   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
39745
39746   /* This function contains the logic that determines if a statement or
39747   ** transaction will be committed or rolled back as a result of the
39748   ** execution of this virtual machine. 
39749   **
39750   ** If any of the following errors occur:
39751   **
39752   **     SQLITE_NOMEM
39753   **     SQLITE_IOERR
39754   **     SQLITE_FULL
39755   **     SQLITE_INTERRUPT
39756   **
39757   ** Then the internal cache might have been left in an inconsistent
39758   ** state.  We need to rollback the statement transaction, if there is
39759   ** one, or the complete transaction if there is no statement transaction.
39760   */
39761
39762   if( p->db->mallocFailed ){
39763     p->rc = SQLITE_NOMEM;
39764   }
39765   closeAllCursorsExceptActiveVtabs(p);
39766   if( p->magic!=VDBE_MAGIC_RUN ){
39767     return SQLITE_OK;
39768   }
39769   checkActiveVdbeCnt(db);
39770
39771   /* No commit or rollback needed if the program never started */
39772   if( p->pc>=0 ){
39773     int mrc;   /* Primary error code from p->rc */
39774
39775     /* Lock all btrees used by the statement */
39776     sqlite3BtreeMutexArrayEnter(&p->aMutex);
39777
39778     /* Check for one of the special errors */
39779     mrc = p->rc & 0xff;
39780     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
39781                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
39782     if( isSpecialError ){
39783       /* This loop does static analysis of the query to see which of the
39784       ** following three categories it falls into:
39785       **
39786       **     Read-only
39787       **     Query with statement journal
39788       **     Query without statement journal
39789       **
39790       ** We could do something more elegant than this static analysis (i.e.
39791       ** store the type of query as part of the compliation phase), but 
39792       ** handling malloc() or IO failure is a fairly obscure edge case so 
39793       ** this is probably easier. Todo: Might be an opportunity to reduce 
39794       ** code size a very small amount though...
39795       */
39796       int notReadOnly = 0;
39797       int isStatement = 0;
39798       assert(p->aOp || p->nOp==0);
39799       for(i=0; i<p->nOp; i++){ 
39800         switch( p->aOp[i].opcode ){
39801           case OP_Transaction:
39802             notReadOnly |= p->aOp[i].p2;
39803             break;
39804           case OP_Statement:
39805             isStatement = 1;
39806             break;
39807         }
39808       }
39809
39810    
39811       /* If the query was read-only, we need do no rollback at all. Otherwise,
39812       ** proceed with the special handling.
39813       */
39814       if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
39815         if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
39816           xFunc = sqlite3BtreeRollbackStmt;
39817           p->rc = SQLITE_BUSY;
39818         } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
39819           xFunc = sqlite3BtreeRollbackStmt;
39820         }else{
39821           /* We are forced to roll back the active transaction. Before doing
39822           ** so, abort any other statements this handle currently has active.
39823           */
39824           invalidateCursorsOnModifiedBtrees(db);
39825           sqlite3RollbackAll(db);
39826           db->autoCommit = 1;
39827         }
39828       }
39829     }
39830   
39831     /* If the auto-commit flag is set and this is the only active vdbe, then
39832     ** we do either a commit or rollback of the current transaction. 
39833     **
39834     ** Note: This block also runs if one of the special errors handled 
39835     ** above has occured. 
39836     */
39837     if( db->autoCommit && db->activeVdbeCnt==1 ){
39838       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
39839         /* The auto-commit flag is true, and the vdbe program was 
39840         ** successful or hit an 'OR FAIL' constraint. This means a commit 
39841         ** is required.
39842         */
39843         int rc = vdbeCommit(db);
39844         if( rc==SQLITE_BUSY ){
39845           sqlite3BtreeMutexArrayLeave(&p->aMutex);
39846           return SQLITE_BUSY;
39847         }else if( rc!=SQLITE_OK ){
39848           p->rc = rc;
39849           sqlite3RollbackAll(db);
39850         }else{
39851           sqlite3CommitInternalChanges(db);
39852         }
39853       }else{
39854         sqlite3RollbackAll(db);
39855       }
39856     }else if( !xFunc ){
39857       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
39858         if( p->openedStatement ){
39859           xFunc = sqlite3BtreeCommitStmt;
39860         } 
39861       }else if( p->errorAction==OE_Abort ){
39862         xFunc = sqlite3BtreeRollbackStmt;
39863       }else{
39864         invalidateCursorsOnModifiedBtrees(db);
39865         sqlite3RollbackAll(db);
39866         db->autoCommit = 1;
39867       }
39868     }
39869   
39870     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
39871     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
39872     ** and the return code is still SQLITE_OK, set the return code to the new
39873     ** error value.
39874     */
39875     assert(!xFunc ||
39876       xFunc==sqlite3BtreeCommitStmt ||
39877       xFunc==sqlite3BtreeRollbackStmt
39878     );
39879     for(i=0; xFunc && i<db->nDb; i++){ 
39880       int rc;
39881       Btree *pBt = db->aDb[i].pBt;
39882       if( pBt ){
39883         rc = xFunc(pBt);
39884         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
39885           p->rc = rc;
39886           sqlite3SetString(&p->zErrMsg, 0);
39887         }
39888       }
39889     }
39890   
39891     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
39892     ** set the change counter. 
39893     */
39894     if( p->changeCntOn && p->pc>=0 ){
39895       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
39896         sqlite3VdbeSetChanges(db, p->nChange);
39897       }else{
39898         sqlite3VdbeSetChanges(db, 0);
39899       }
39900       p->nChange = 0;
39901     }
39902   
39903     /* Rollback or commit any schema changes that occurred. */
39904     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
39905       sqlite3ResetInternalSchema(db, 0);
39906       db->flags = (db->flags | SQLITE_InternChanges);
39907     }
39908
39909     /* Release the locks */
39910     sqlite3BtreeMutexArrayLeave(&p->aMutex);
39911   }
39912
39913   /* We have successfully halted and closed the VM.  Record this fact. */
39914   if( p->pc>=0 ){
39915     db->activeVdbeCnt--;
39916   }
39917   p->magic = VDBE_MAGIC_HALT;
39918   checkActiveVdbeCnt(db);
39919   if( p->db->mallocFailed ){
39920     p->rc = SQLITE_NOMEM;
39921   }
39922
39923   return SQLITE_OK;
39924 }
39925
39926
39927 /*
39928 ** Each VDBE holds the result of the most recent sqlite3_step() call
39929 ** in p->rc.  This routine sets that result back to SQLITE_OK.
39930 */
39931 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
39932   p->rc = SQLITE_OK;
39933 }
39934
39935 /*
39936 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
39937 ** Write any error messages into *pzErrMsg.  Return the result code.
39938 **
39939 ** After this routine is run, the VDBE should be ready to be executed
39940 ** again.
39941 **
39942 ** To look at it another way, this routine resets the state of the
39943 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
39944 ** VDBE_MAGIC_INIT.
39945 */
39946 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p, int freebuffers){
39947   sqlite3 *db;
39948   db = p->db;
39949
39950   /* If the VM did not run to completion or if it encountered an
39951   ** error, then it might not have been halted properly.  So halt
39952   ** it now.
39953   */
39954   (void)sqlite3SafetyOn(db);
39955   sqlite3VdbeHalt(p);
39956   (void)sqlite3SafetyOff(db);
39957
39958   /* If the VDBE has be run even partially, then transfer the error code
39959   ** and error message from the VDBE into the main database structure.  But
39960   ** if the VDBE has just been set to run but has not actually executed any
39961   ** instructions yet, leave the main database error information unchanged.
39962   */
39963   if( p->pc>=0 ){
39964     if( p->zErrMsg ){
39965       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,sqlite3_free);
39966       db->errCode = p->rc;
39967       p->zErrMsg = 0;
39968     }else if( p->rc ){
39969       sqlite3Error(db, p->rc, 0);
39970     }else{
39971       sqlite3Error(db, SQLITE_OK, 0);
39972     }
39973   }else if( p->rc && p->expired ){
39974     /* The expired flag was set on the VDBE before the first call
39975     ** to sqlite3_step(). For consistency (since sqlite3_step() was
39976     ** called), set the database error in this case as well.
39977     */
39978     sqlite3Error(db, p->rc, 0);
39979     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3_free);
39980     p->zErrMsg = 0;
39981   }
39982
39983   /* Reclaim all memory used by the VDBE
39984   */
39985   Cleanup(p, freebuffers);
39986
39987   /* Save profiling information from this VDBE run.
39988   */
39989 #ifdef VDBE_PROFILE
39990   {
39991     FILE *out = fopen("vdbe_profile.out", "a");
39992     if( out ){
39993       int i;
39994       fprintf(out, "---- ");
39995       for(i=0; i<p->nOp; i++){
39996         fprintf(out, "%02x", p->aOp[i].opcode);
39997       }
39998       fprintf(out, "\n");
39999       for(i=0; i<p->nOp; i++){
40000         fprintf(out, "%6d %10lld %8lld ",
40001            p->aOp[i].cnt,
40002            p->aOp[i].cycles,
40003            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
40004         );
40005         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
40006       }
40007       fclose(out);
40008     }
40009   }
40010 #endif
40011   p->magic = VDBE_MAGIC_INIT;
40012   p->aborted = 0;
40013   return p->rc & db->errMask;
40014 }
40015  
40016 /*
40017 ** Clean up and delete a VDBE after execution.  Return an integer which is
40018 ** the result code.  Write any error message text into *pzErrMsg.
40019 */
40020 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
40021   int rc = SQLITE_OK;
40022   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
40023     rc = sqlite3VdbeReset(p, 1);
40024     assert( (rc & p->db->errMask)==rc );
40025   }else if( p->magic!=VDBE_MAGIC_INIT ){
40026     return SQLITE_MISUSE;
40027   }
40028   releaseMemArray(&p->aMem[1], p->nMem, 1);
40029   sqlite3VdbeDelete(p);
40030   return rc;
40031 }
40032
40033 /*
40034 ** Call the destructor for each auxdata entry in pVdbeFunc for which
40035 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
40036 ** are always destroyed.  To destroy all auxdata entries, call this
40037 ** routine with mask==0.
40038 */
40039 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
40040   int i;
40041   for(i=0; i<pVdbeFunc->nAux; i++){
40042     struct AuxData *pAux = &pVdbeFunc->apAux[i];
40043     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
40044       if( pAux->xDelete ){
40045         pAux->xDelete(pAux->pAux);
40046       }
40047       pAux->pAux = 0;
40048     }
40049   }
40050 }
40051
40052 /*
40053 ** Delete an entire VDBE.
40054 */
40055 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
40056   int i;
40057   if( p==0 ) return;
40058   Cleanup(p, 1);
40059   if( p->pPrev ){
40060     p->pPrev->pNext = p->pNext;
40061   }else{
40062     assert( p->db->pVdbe==p );
40063     p->db->pVdbe = p->pNext;
40064   }
40065   if( p->pNext ){
40066     p->pNext->pPrev = p->pPrev;
40067   }
40068   if( p->aOp ){
40069     Op *pOp = p->aOp;
40070     for(i=0; i<p->nOp; i++, pOp++){
40071       freeP4(pOp->p4type, pOp->p4.p);
40072 #ifdef SQLITE_DEBUG
40073       sqlite3_free(pOp->zComment);
40074 #endif     
40075     }
40076     sqlite3_free(p->aOp);
40077   }
40078   releaseMemArray(p->aVar, p->nVar, 1);
40079   sqlite3_free(p->aLabel);
40080   if( p->aMem ){
40081     sqlite3_free(&p->aMem[1]);
40082   }
40083   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N, 1);
40084   sqlite3_free(p->aColName);
40085   sqlite3_free(p->zSql);
40086   p->magic = VDBE_MAGIC_DEAD;
40087   sqlite3_free(p);
40088 }
40089
40090 /*
40091 ** If a MoveTo operation is pending on the given cursor, then do that
40092 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
40093 ** routine does nothing and returns SQLITE_OK.
40094 */
40095 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor *p){
40096   if( p->deferredMoveto ){
40097     int res, rc;
40098 #ifdef SQLITE_TEST
40099     extern int sqlite3_search_count;
40100 #endif
40101     assert( p->isTable );
40102     rc = sqlite3BtreeMoveto(p->pCursor, 0, 0, p->movetoTarget, 0, &res);
40103     if( rc ) return rc;
40104     *p->pIncrKey = 0;
40105     p->lastRowid = keyToInt(p->movetoTarget);
40106     p->rowidIsValid = res==0;
40107     if( res<0 ){
40108       rc = sqlite3BtreeNext(p->pCursor, &res);
40109       if( rc ) return rc;
40110     }
40111 #ifdef SQLITE_TEST
40112     sqlite3_search_count++;
40113 #endif
40114     p->deferredMoveto = 0;
40115     p->cacheStatus = CACHE_STALE;
40116   }
40117   return SQLITE_OK;
40118 }
40119
40120 /*
40121 ** The following functions:
40122 **
40123 ** sqlite3VdbeSerialType()
40124 ** sqlite3VdbeSerialTypeLen()
40125 ** sqlite3VdbeSerialRead()
40126 ** sqlite3VdbeSerialLen()
40127 ** sqlite3VdbeSerialWrite()
40128 **
40129 ** encapsulate the code that serializes values for storage in SQLite
40130 ** data and index records. Each serialized value consists of a
40131 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
40132 ** integer, stored as a varint.
40133 **
40134 ** In an SQLite index record, the serial type is stored directly before
40135 ** the blob of data that it corresponds to. In a table record, all serial
40136 ** types are stored at the start of the record, and the blobs of data at
40137 ** the end. Hence these functions allow the caller to handle the
40138 ** serial-type and data blob seperately.
40139 **
40140 ** The following table describes the various storage classes for data:
40141 **
40142 **   serial type        bytes of data      type
40143 **   --------------     ---------------    ---------------
40144 **      0                     0            NULL
40145 **      1                     1            signed integer
40146 **      2                     2            signed integer
40147 **      3                     3            signed integer
40148 **      4                     4            signed integer
40149 **      5                     6            signed integer
40150 **      6                     8            signed integer
40151 **      7                     8            IEEE float
40152 **      8                     0            Integer constant 0
40153 **      9                     0            Integer constant 1
40154 **     10,11                               reserved for expansion
40155 **    N>=12 and even       (N-12)/2        BLOB
40156 **    N>=13 and odd        (N-13)/2        text
40157 **
40158 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
40159 ** of SQLite will not understand those serial types.
40160 */
40161
40162 /*
40163 ** Return the serial-type for the value stored in pMem.
40164 */
40165 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
40166   int flags = pMem->flags;
40167   int n;
40168
40169   if( flags&MEM_Null ){
40170     return 0;
40171   }
40172   if( flags&MEM_Int ){
40173     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
40174 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
40175     i64 i = pMem->u.i;
40176     u64 u;
40177     if( file_format>=4 && (i&1)==i ){
40178       return 8+i;
40179     }
40180     u = i<0 ? -i : i;
40181     if( u<=127 ) return 1;
40182     if( u<=32767 ) return 2;
40183     if( u<=8388607 ) return 3;
40184     if( u<=2147483647 ) return 4;
40185     if( u<=MAX_6BYTE ) return 5;
40186     return 6;
40187   }
40188   if( flags&MEM_Real ){
40189     return 7;
40190   }
40191   assert( flags&(MEM_Str|MEM_Blob) );
40192   n = pMem->n;
40193   if( flags & MEM_Zero ){
40194     n += pMem->u.i;
40195   }
40196   assert( n>=0 );
40197   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
40198 }
40199
40200 /*
40201 ** Return the length of the data corresponding to the supplied serial-type.
40202 */
40203 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
40204   if( serial_type>=12 ){
40205     return (serial_type-12)/2;
40206   }else{
40207     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
40208     return aSize[serial_type];
40209   }
40210 }
40211
40212 /*
40213 ** If we are on an architecture with mixed-endian floating 
40214 ** points (ex: ARM7) then swap the lower 4 bytes with the 
40215 ** upper 4 bytes.  Return the result.
40216 **
40217 ** For most architectures, this is a no-op.
40218 **
40219 ** (later):  It is reported to me that the mixed-endian problem
40220 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
40221 ** that early versions of GCC stored the two words of a 64-bit
40222 ** float in the wrong order.  And that error has been propagated
40223 ** ever since.  The blame is not necessarily with GCC, though.
40224 ** GCC might have just copying the problem from a prior compiler.
40225 ** I am also told that newer versions of GCC that follow a different
40226 ** ABI get the byte order right.
40227 **
40228 ** Developers using SQLite on an ARM7 should compile and run their
40229 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
40230 ** enabled, some asserts below will ensure that the byte order of
40231 ** floating point values is correct.
40232 **
40233 ** (2007-08-30)  Frank van Vugt has studied this problem closely
40234 ** and has send his findings to the SQLite developers.  Frank
40235 ** writes that some Linux kernels offer floating point hardware
40236 ** emulation that uses only 32-bit mantissas instead of a full 
40237 ** 48-bits as required by the IEEE standard.  (This is the
40238 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
40239 ** byte swapping becomes very complicated.  To avoid problems,
40240 ** the necessary byte swapping is carried out using a 64-bit integer
40241 ** rather than a 64-bit float.  Frank assures us that the code here
40242 ** works for him.  We, the developers, have no way to independently
40243 ** verify this, but Frank seems to know what he is talking about
40244 ** so we trust him.
40245 */
40246 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
40247 static u64 floatSwap(u64 in){
40248   union {
40249     u64 r;
40250     u32 i[2];
40251   } u;
40252   u32 t;
40253
40254   u.r = in;
40255   t = u.i[0];
40256   u.i[0] = u.i[1];
40257   u.i[1] = t;
40258   return u.r;
40259 }
40260 # define swapMixedEndianFloat(X)  X = floatSwap(X)
40261 #else
40262 # define swapMixedEndianFloat(X)
40263 #endif
40264
40265 /*
40266 ** Write the serialized data blob for the value stored in pMem into 
40267 ** buf. It is assumed that the caller has allocated sufficient space.
40268 ** Return the number of bytes written.
40269 **
40270 ** nBuf is the amount of space left in buf[].  nBuf must always be
40271 ** large enough to hold the entire field.  Except, if the field is
40272 ** a blob with a zero-filled tail, then buf[] might be just the right
40273 ** size to hold everything except for the zero-filled tail.  If buf[]
40274 ** is only big enough to hold the non-zero prefix, then only write that
40275 ** prefix into buf[].  But if buf[] is large enough to hold both the
40276 ** prefix and the tail then write the prefix and set the tail to all
40277 ** zeros.
40278 **
40279 ** Return the number of bytes actually written into buf[].  The number
40280 ** of bytes in the zero-filled tail is included in the return value only
40281 ** if those bytes were zeroed in buf[].
40282 */ 
40283 SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
40284   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
40285   int len;
40286
40287   /* Integer and Real */
40288   if( serial_type<=7 && serial_type>0 ){
40289     u64 v;
40290     int i;
40291     if( serial_type==7 ){
40292       assert( sizeof(v)==sizeof(pMem->r) );
40293       memcpy(&v, &pMem->r, sizeof(v));
40294       swapMixedEndianFloat(v);
40295     }else{
40296       v = pMem->u.i;
40297     }
40298     len = i = sqlite3VdbeSerialTypeLen(serial_type);
40299     assert( len<=nBuf );
40300     while( i-- ){
40301       buf[i] = (v&0xFF);
40302       v >>= 8;
40303     }
40304     return len;
40305   }
40306
40307   /* String or blob */
40308   if( serial_type>=12 ){
40309     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
40310              == sqlite3VdbeSerialTypeLen(serial_type) );
40311     assert( pMem->n<=nBuf );
40312     len = pMem->n;
40313     memcpy(buf, pMem->z, len);
40314     if( pMem->flags & MEM_Zero ){
40315       len += pMem->u.i;
40316       if( len>nBuf ){
40317         len = nBuf;
40318       }
40319       memset(&buf[pMem->n], 0, len-pMem->n);
40320     }
40321     return len;
40322   }
40323
40324   /* NULL or constants 0 or 1 */
40325   return 0;
40326 }
40327
40328 /*
40329 ** Deserialize the data blob pointed to by buf as serial type serial_type
40330 ** and store the result in pMem.  Return the number of bytes read.
40331 */ 
40332 SQLITE_PRIVATE int sqlite3VdbeSerialGet(
40333   const unsigned char *buf,     /* Buffer to deserialize from */
40334   u32 serial_type,              /* Serial type to deserialize */
40335   Mem *pMem                     /* Memory cell to write value into */
40336 ){
40337   switch( serial_type ){
40338     case 10:   /* Reserved for future use */
40339     case 11:   /* Reserved for future use */
40340     case 0: {  /* NULL */
40341       pMem->flags = MEM_Null;
40342       break;
40343     }
40344     case 1: { /* 1-byte signed integer */
40345       pMem->u.i = (signed char)buf[0];
40346       pMem->flags = MEM_Int;
40347       return 1;
40348     }
40349     case 2: { /* 2-byte signed integer */
40350       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
40351       pMem->flags = MEM_Int;
40352       return 2;
40353     }
40354     case 3: { /* 3-byte signed integer */
40355       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
40356       pMem->flags = MEM_Int;
40357       return 3;
40358     }
40359     case 4: { /* 4-byte signed integer */
40360       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
40361       pMem->flags = MEM_Int;
40362       return 4;
40363     }
40364     case 5: { /* 6-byte signed integer */
40365       u64 x = (((signed char)buf[0])<<8) | buf[1];
40366       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
40367       x = (x<<32) | y;
40368       pMem->u.i = *(i64*)&x;
40369       pMem->flags = MEM_Int;
40370       return 6;
40371     }
40372     case 6:   /* 8-byte signed integer */
40373     case 7: { /* IEEE floating point */
40374       u64 x;
40375       u32 y;
40376 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
40377       /* Verify that integers and floating point values use the same
40378       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
40379       ** defined that 64-bit floating point values really are mixed
40380       ** endian.
40381       */
40382       static const u64 t1 = ((u64)0x3ff00000)<<32;
40383       static const double r1 = 1.0;
40384       u64 t2 = t1;
40385       swapMixedEndianFloat(t2);
40386       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
40387 #endif
40388
40389       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
40390       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
40391       x = (x<<32) | y;
40392       if( serial_type==6 ){
40393         pMem->u.i = *(i64*)&x;
40394         pMem->flags = MEM_Int;
40395       }else{
40396         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
40397         swapMixedEndianFloat(x);
40398         memcpy(&pMem->r, &x, sizeof(x));
40399         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
40400       }
40401       return 8;
40402     }
40403     case 8:    /* Integer 0 */
40404     case 9: {  /* Integer 1 */
40405       pMem->u.i = serial_type-8;
40406       pMem->flags = MEM_Int;
40407       return 0;
40408     }
40409     default: {
40410       int len = (serial_type-12)/2;
40411       pMem->z = (char *)buf;
40412       pMem->n = len;
40413       pMem->xDel = 0;
40414       if( serial_type&0x01 ){
40415         pMem->flags = MEM_Str | MEM_Ephem;
40416       }else{
40417         pMem->flags = MEM_Blob | MEM_Ephem;
40418       }
40419       return len;
40420     }
40421   }
40422   return 0;
40423 }
40424
40425
40426 /*
40427 ** Given the nKey-byte encoding of a record in pKey[], parse the
40428 ** record into a UnpackedRecord structure.  Return a pointer to
40429 ** that structure.
40430 **
40431 ** The calling function might provide szSpace bytes of memory
40432 ** space at pSpace.  This space can be used to hold the returned
40433 ** VDbeParsedRecord structure if it is large enough.  If it is
40434 ** not big enough, space is obtained from sqlite3_malloc().
40435 **
40436 ** The returned structure should be closed by a call to
40437 ** sqlite3VdbeDeleteUnpackedRecord().
40438 */ 
40439 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
40440   KeyInfo *pKeyInfo,     /* Information about the record format */
40441   int nKey,              /* Size of the binary record */
40442   const void *pKey,      /* The binary record */
40443   void *pSpace,          /* Space available to hold resulting object */
40444   int szSpace            /* Size of pSpace[] in bytes */
40445 ){
40446   const unsigned char *aKey = (const unsigned char *)pKey;
40447   UnpackedRecord *p;
40448   int nByte;
40449   int i, idx, d;
40450   u32 szHdr;
40451   Mem *pMem;
40452   
40453   assert( sizeof(Mem)>sizeof(*p) );
40454   nByte = sizeof(Mem)*(pKeyInfo->nField+2);
40455   if( nByte>szSpace ){
40456     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
40457     if( p==0 ) return 0;
40458     p->needFree = 1;
40459   }else{
40460     p = pSpace;
40461     p->needFree = 0;
40462   }
40463   p->pKeyInfo = pKeyInfo;
40464   p->nField = pKeyInfo->nField + 1;
40465   p->needDestroy = 1;
40466   p->aMem = pMem = &((Mem*)p)[1];
40467   idx = getVarint32(aKey, szHdr);
40468   d = szHdr;
40469   i = 0;
40470   while( idx<szHdr && i<p->nField ){
40471     u32 serial_type;
40472
40473     idx += getVarint32( aKey+idx, serial_type);
40474     if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
40475     pMem->enc = pKeyInfo->enc;
40476     pMem->db = pKeyInfo->db;
40477     pMem->flags = 0;
40478     pMem->zMalloc = 0;
40479     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
40480     pMem++;
40481     i++;
40482   }
40483   p->nField = i;
40484   return (void*)p;
40485 }
40486
40487 /*
40488 ** This routine destroys a UnpackedRecord object
40489 */
40490 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
40491   if( p ){
40492     if( p->needDestroy ){
40493       int i;
40494       Mem *pMem;
40495       for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
40496         if( pMem->zMalloc ){
40497           sqlite3VdbeMemRelease(pMem);
40498         }
40499       }
40500     }
40501     if( p->needFree ){
40502       sqlite3_free(p);
40503     }
40504   }
40505 }
40506
40507 /*
40508 ** This function compares the two table rows or index records
40509 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
40510 ** or positive integer if {nKey1, pKey1} is less than, equal to or 
40511 ** greater than pPKey2.  The {nKey1, pKey1} key must be a blob
40512 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
40513 ** key must be a parsed key such as obtained from
40514 ** sqlite3VdbeParseRecord.
40515 **
40516 ** Key1 and Key2 do not have to contain the same number of fields.
40517 ** But if the lengths differ, Key2 must be the shorter of the two.
40518 **
40519 ** Historical note: In earlier versions of this routine both Key1
40520 ** and Key2 were blobs obtained from OP_MakeRecord.  But we found
40521 ** that in typical use the same Key2 would be submitted multiple times
40522 ** in a row.  So an optimization was added to parse the Key2 key
40523 ** separately and submit the parsed version.  In this way, we avoid
40524 ** parsing the same Key2 multiple times in a row.
40525 */
40526 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
40527   int nKey1, const void *pKey1, 
40528   UnpackedRecord *pPKey2
40529 ){
40530   u32 d1;            /* Offset into aKey[] of next data element */
40531   u32 idx1;          /* Offset into aKey[] of next header element */
40532   u32 szHdr1;        /* Number of bytes in header */
40533   int i = 0;
40534   int nField;
40535   int rc = 0;
40536   const unsigned char *aKey1 = (const unsigned char *)pKey1;
40537   KeyInfo *pKeyInfo;
40538   Mem mem1;
40539
40540   pKeyInfo = pPKey2->pKeyInfo;
40541   mem1.enc = pKeyInfo->enc;
40542   mem1.db = pKeyInfo->db;
40543   mem1.flags = 0;
40544   mem1.zMalloc = 0;
40545   
40546   idx1 = getVarint32(aKey1, szHdr1);
40547   d1 = szHdr1;
40548   nField = pKeyInfo->nField;
40549   while( idx1<szHdr1 && i<pPKey2->nField ){
40550     u32 serial_type1;
40551
40552     /* Read the serial types for the next element in each key. */
40553     idx1 += getVarint32( aKey1+idx1, serial_type1 );
40554     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
40555
40556     /* Extract the values to be compared.
40557     */
40558     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
40559
40560     /* Do the comparison
40561     */
40562     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
40563                            i<nField ? pKeyInfo->aColl[i] : 0);
40564     if( rc!=0 ){
40565       break;
40566     }
40567     i++;
40568   }
40569   if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
40570
40571   /* One of the keys ran out of fields, but all the fields up to that point
40572   ** were equal. If the incrKey flag is true, then the second key is
40573   ** treated as larger.
40574   */
40575   if( rc==0 ){
40576     if( pKeyInfo->incrKey ){
40577       rc = -1;
40578     }else if( !pKeyInfo->prefixIsEqual ){
40579       if( d1<nKey1 ){
40580         rc = 1;
40581       }
40582     }
40583   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
40584                && pKeyInfo->aSortOrder[i] ){
40585     rc = -rc;
40586   }
40587
40588   return rc;
40589 }
40590
40591 /*
40592 ** The argument is an index entry composed using the OP_MakeRecord opcode.
40593 ** The last entry in this record should be an integer (specifically
40594 ** an integer rowid).  This routine returns the number of bytes in
40595 ** that integer.
40596 */
40597 SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8 *aKey){
40598   u32 szHdr;        /* Size of the header */
40599   u32 typeRowid;    /* Serial type of the rowid */
40600
40601   (void)getVarint32(aKey, szHdr);
40602   (void)getVarint32(&aKey[szHdr-1], typeRowid);
40603   return sqlite3VdbeSerialTypeLen(typeRowid);
40604 }
40605   
40606
40607 /*
40608 ** pCur points at an index entry created using the OP_MakeRecord opcode.
40609 ** Read the rowid (the last field in the record) and store it in *rowid.
40610 ** Return SQLITE_OK if everything works, or an error code otherwise.
40611 */
40612 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
40613   i64 nCellKey = 0;
40614   int rc;
40615   u32 szHdr;        /* Size of the header */
40616   u32 typeRowid;    /* Serial type of the rowid */
40617   u32 lenRowid;     /* Size of the rowid */
40618   Mem m, v;
40619
40620   sqlite3BtreeKeySize(pCur, &nCellKey);
40621   if( nCellKey<=0 ){
40622     return SQLITE_CORRUPT_BKPT;
40623   }
40624   m.flags = 0;
40625   m.db = 0;
40626   m.zMalloc = 0;
40627   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
40628   if( rc ){
40629     return rc;
40630   }
40631   (void)getVarint32((u8*)m.z, szHdr);
40632   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
40633   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
40634   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
40635   *rowid = v.u.i;
40636   sqlite3VdbeMemRelease(&m);
40637   return SQLITE_OK;
40638 }
40639
40640 /*
40641 ** Compare the key of the index entry that cursor pC is point to against
40642 ** the key string in pKey (of length nKey).  Write into *pRes a number
40643 ** that is negative, zero, or positive if pC is less than, equal to,
40644 ** or greater than pKey.  Return SQLITE_OK on success.
40645 **
40646 ** pKey is either created without a rowid or is truncated so that it
40647 ** omits the rowid at the end.  The rowid at the end of the index entry
40648 ** is ignored as well.
40649 */
40650 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
40651   Cursor *pC,                 /* The cursor to compare against */
40652   UnpackedRecord *pUnpacked,
40653   int nKey, const u8 *pKey,   /* The key to compare */
40654   int *res                    /* Write the comparison result here */
40655 ){
40656   i64 nCellKey = 0;
40657   int rc;
40658   BtCursor *pCur = pC->pCursor;
40659   int lenRowid;
40660   Mem m;
40661   UnpackedRecord *pRec;
40662   char zSpace[200];
40663
40664   sqlite3BtreeKeySize(pCur, &nCellKey);
40665   if( nCellKey<=0 ){
40666     *res = 0;
40667     return SQLITE_OK;
40668   }
40669   m.db = 0;
40670   m.flags = 0;
40671   m.zMalloc = 0;
40672   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
40673   if( rc ){
40674     return rc;
40675   }
40676   lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
40677   if( !pUnpacked ){
40678     pRec = sqlite3VdbeRecordUnpack(pC->pKeyInfo, nKey, pKey,
40679                                 zSpace, sizeof(zSpace));
40680   }else{
40681     pRec = pUnpacked;
40682   }
40683   if( pRec==0 ){
40684     return SQLITE_NOMEM;
40685   }
40686   *res = sqlite3VdbeRecordCompare(m.n-lenRowid, m.z, pRec);
40687   if( !pUnpacked ){
40688     sqlite3VdbeDeleteUnpackedRecord(pRec);
40689   }
40690   sqlite3VdbeMemRelease(&m);
40691   return SQLITE_OK;
40692 }
40693
40694 /*
40695 ** This routine sets the value to be returned by subsequent calls to
40696 ** sqlite3_changes() on the database handle 'db'. 
40697 */
40698 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
40699   assert( sqlite3_mutex_held(db->mutex) );
40700   db->nChange = nChange;
40701   db->nTotalChange += nChange;
40702 }
40703
40704 /*
40705 ** Set a flag in the vdbe to update the change counter when it is finalised
40706 ** or reset.
40707 */
40708 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
40709   v->changeCntOn = 1;
40710 }
40711
40712 /*
40713 ** Mark every prepared statement associated with a database connection
40714 ** as expired.
40715 **
40716 ** An expired statement means that recompilation of the statement is
40717 ** recommend.  Statements expire when things happen that make their
40718 ** programs obsolete.  Removing user-defined functions or collating
40719 ** sequences, or changing an authorization function are the types of
40720 ** things that make prepared statements obsolete.
40721 */
40722 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
40723   Vdbe *p;
40724   for(p = db->pVdbe; p; p=p->pNext){
40725     p->expired = 1;
40726   }
40727 }
40728
40729 /*
40730 ** Return the database associated with the Vdbe.
40731 */
40732 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
40733   return v->db;
40734 }
40735
40736 /************** End of vdbeaux.c *********************************************/
40737 /************** Begin file vdbeapi.c *****************************************/
40738 /*
40739 ** 2004 May 26
40740 **
40741 ** The author disclaims copyright to this source code.  In place of
40742 ** a legal notice, here is a blessing:
40743 **
40744 **    May you do good and not evil.
40745 **    May you find forgiveness for yourself and forgive others.
40746 **    May you share freely, never taking more than you give.
40747 **
40748 *************************************************************************
40749 **
40750 ** This file contains code use to implement APIs that are part of the
40751 ** VDBE.
40752 */
40753
40754 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
40755 /*
40756 ** The following structure contains pointers to the end points of a
40757 ** doubly-linked list of all compiled SQL statements that may be holding
40758 ** buffers eligible for release when the sqlite3_release_memory() interface is
40759 ** invoked. Access to this list is protected by the SQLITE_MUTEX_STATIC_LRU2
40760 ** mutex.
40761 **
40762 ** Statements are added to the end of this list when sqlite3_reset() is
40763 ** called. They are removed either when sqlite3_step() or sqlite3_finalize()
40764 ** is called. When statements are added to this list, the associated 
40765 ** register array (p->aMem[1..p->nMem]) may contain dynamic buffers that
40766 ** can be freed using sqlite3VdbeReleaseMemory().
40767 **
40768 ** When statements are added or removed from this list, the mutex
40769 ** associated with the Vdbe being added or removed (Vdbe.db->mutex) is
40770 ** already held. The LRU2 mutex is then obtained, blocking if necessary,
40771 ** the linked-list pointers manipulated and the LRU2 mutex relinquished.
40772 */
40773 struct StatementLruList {
40774   Vdbe *pFirst;
40775   Vdbe *pLast;
40776 };
40777 static struct StatementLruList sqlite3LruStatements;
40778
40779 /*
40780 ** Check that the list looks to be internally consistent. This is used
40781 ** as part of an assert() statement as follows:
40782 **
40783 **   assert( stmtLruCheck() );
40784 */
40785 #ifndef NDEBUG
40786 static int stmtLruCheck(){
40787   Vdbe *p;
40788   for(p=sqlite3LruStatements.pFirst; p; p=p->pLruNext){
40789     assert(p->pLruNext || p==sqlite3LruStatements.pLast);
40790     assert(!p->pLruNext || p->pLruNext->pLruPrev==p);
40791     assert(p->pLruPrev || p==sqlite3LruStatements.pFirst);
40792     assert(!p->pLruPrev || p->pLruPrev->pLruNext==p);
40793   }
40794   return 1;
40795 }
40796 #endif
40797
40798 /*
40799 ** Add vdbe p to the end of the statement lru list. It is assumed that
40800 ** p is not already part of the list when this is called. The lru list
40801 ** is protected by the SQLITE_MUTEX_STATIC_LRU mutex.
40802 */
40803 static void stmtLruAdd(Vdbe *p){
40804   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU2));
40805
40806   if( p->pLruPrev || p->pLruNext || sqlite3LruStatements.pFirst==p ){
40807     sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU2));
40808     return;
40809   }
40810
40811   assert( stmtLruCheck() );
40812
40813   if( !sqlite3LruStatements.pFirst ){
40814     assert( !sqlite3LruStatements.pLast );
40815     sqlite3LruStatements.pFirst = p;
40816     sqlite3LruStatements.pLast = p;
40817   }else{
40818     assert( !sqlite3LruStatements.pLast->pLruNext );
40819     p->pLruPrev = sqlite3LruStatements.pLast;
40820     sqlite3LruStatements.pLast->pLruNext = p;
40821     sqlite3LruStatements.pLast = p;
40822   }
40823
40824   assert( stmtLruCheck() );
40825
40826   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU2));
40827 }
40828
40829 /*
40830 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is already held, remove
40831 ** statement p from the least-recently-used statement list. If the 
40832 ** statement is not currently part of the list, this call is a no-op.
40833 */
40834 static void stmtLruRemoveNomutex(Vdbe *p){
40835   if( p->pLruPrev || p->pLruNext || p==sqlite3LruStatements.pFirst ){
40836     assert( stmtLruCheck() );
40837     if( p->pLruNext ){
40838       p->pLruNext->pLruPrev = p->pLruPrev;
40839     }else{
40840       sqlite3LruStatements.pLast = p->pLruPrev;
40841     }
40842     if( p->pLruPrev ){
40843       p->pLruPrev->pLruNext = p->pLruNext;
40844     }else{
40845       sqlite3LruStatements.pFirst = p->pLruNext;
40846     }
40847     p->pLruNext = 0;
40848     p->pLruPrev = 0;
40849     assert( stmtLruCheck() );
40850   }
40851 }
40852
40853 /*
40854 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is not held, remove
40855 ** statement p from the least-recently-used statement list. If the 
40856 ** statement is not currently part of the list, this call is a no-op.
40857 */
40858 static void stmtLruRemove(Vdbe *p){
40859   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU2));
40860   stmtLruRemoveNomutex(p);
40861   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU2));
40862 }
40863
40864 /*
40865 ** Try to release n bytes of memory by freeing buffers associated 
40866 ** with the memory registers of currently unused vdbes.
40867 */
40868 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int n){
40869   Vdbe *p;
40870   Vdbe *pNext;
40871   int nFree = 0;
40872
40873   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU2));
40874   for(p=sqlite3LruStatements.pFirst; p && nFree<n; p=pNext){
40875     pNext = p->pLruNext;
40876
40877     /* For each statement handle in the lru list, attempt to obtain the
40878     ** associated database mutex. If it cannot be obtained, continue
40879     ** to the next statement handle. It is not possible to block on
40880     ** the database mutex - that could cause deadlock.
40881     */
40882     if( SQLITE_OK==sqlite3_mutex_try(p->db->mutex) ){
40883       nFree += sqlite3VdbeReleaseBuffers(p);
40884       stmtLruRemoveNomutex(p);
40885       sqlite3_mutex_leave(p->db->mutex);
40886     }
40887   }
40888   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU2));
40889
40890   return nFree;
40891 }
40892
40893 /*
40894 ** Call sqlite3Reprepare() on the statement. Remove it from the
40895 ** lru list before doing so, as Reprepare() will free all the
40896 ** memory register buffers anyway.
40897 */
40898 int vdbeReprepare(Vdbe *p){
40899   stmtLruRemove(p);
40900   return sqlite3Reprepare(p);
40901 }
40902
40903 #else       /* !SQLITE_ENABLE_MEMORY_MANAGEMENT */
40904   #define stmtLruRemove(x)
40905   #define stmtLruAdd(x)
40906   #define vdbeReprepare(x) sqlite3Reprepare(x)
40907 #endif
40908
40909
40910 /*
40911 ** Return TRUE (non-zero) of the statement supplied as an argument needs
40912 ** to be recompiled.  A statement needs to be recompiled whenever the
40913 ** execution environment changes in a way that would alter the program
40914 ** that sqlite3_prepare() generates.  For example, if new functions or
40915 ** collating sequences are registered or if an authorizer function is
40916 ** added or changed.
40917 */
40918 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
40919   Vdbe *p = (Vdbe*)pStmt;
40920   return p==0 || p->expired;
40921 }
40922
40923 /*
40924 ** The following routine destroys a virtual machine that is created by
40925 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
40926 ** success/failure code that describes the result of executing the virtual
40927 ** machine.
40928 **
40929 ** This routine sets the error code and string returned by
40930 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
40931 */
40932 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
40933   int rc;
40934   if( pStmt==0 ){
40935     rc = SQLITE_OK;
40936   }else{
40937     Vdbe *v = (Vdbe*)pStmt;
40938 #ifndef SQLITE_MUTEX_NOOP
40939     sqlite3_mutex *mutex = v->db->mutex;
40940 #endif
40941     sqlite3_mutex_enter(mutex);
40942     stmtLruRemove(v);
40943     rc = sqlite3VdbeFinalize(v);
40944     sqlite3_mutex_leave(mutex);
40945   }
40946   return rc;
40947 }
40948
40949 /*
40950 ** Terminate the current execution of an SQL statement and reset it
40951 ** back to its starting state so that it can be reused. A success code from
40952 ** the prior execution is returned.
40953 **
40954 ** This routine sets the error code and string returned by
40955 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
40956 */
40957 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
40958   int rc;
40959   if( pStmt==0 ){
40960     rc = SQLITE_OK;
40961   }else{
40962     Vdbe *v = (Vdbe*)pStmt;
40963     sqlite3_mutex_enter(v->db->mutex);
40964     rc = sqlite3VdbeReset(v, 1);
40965     stmtLruAdd(v);
40966     sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
40967     assert( (rc & (v->db->errMask))==rc );
40968     sqlite3_mutex_leave(v->db->mutex);
40969   }
40970   return rc;
40971 }
40972
40973 /*
40974 ** Set all the parameters in the compiled SQL statement to NULL.
40975 */
40976 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
40977   int i;
40978   int rc = SQLITE_OK;
40979   Vdbe *p = (Vdbe*)pStmt;
40980 #ifndef SQLITE_MUTEX_NOOP
40981   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
40982 #endif
40983   sqlite3_mutex_enter(mutex);
40984   for(i=0; i<p->nVar; i++){
40985     sqlite3VdbeMemRelease(&p->aVar[i]);
40986     p->aVar[i].flags = MEM_Null;
40987   }
40988   sqlite3_mutex_leave(mutex);
40989   return rc;
40990 }
40991
40992
40993 /**************************** sqlite3_value_  *******************************
40994 ** The following routines extract information from a Mem or sqlite3_value
40995 ** structure.
40996 */
40997 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
40998   Mem *p = (Mem*)pVal;
40999   if( p->flags & (MEM_Blob|MEM_Str) ){
41000     sqlite3VdbeMemExpandBlob(p);
41001     p->flags &= ~MEM_Str;
41002     p->flags |= MEM_Blob;
41003     return p->z;
41004   }else{
41005     return sqlite3_value_text(pVal);
41006   }
41007 }
41008 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
41009   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
41010 }
41011 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
41012   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
41013 }
41014 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
41015   return sqlite3VdbeRealValue((Mem*)pVal);
41016 }
41017 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
41018   return sqlite3VdbeIntValue((Mem*)pVal);
41019 }
41020 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
41021   return sqlite3VdbeIntValue((Mem*)pVal);
41022 }
41023 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
41024   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
41025 }
41026 #ifndef SQLITE_OMIT_UTF16
41027 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
41028   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
41029 }
41030 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
41031   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
41032 }
41033 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
41034   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
41035 }
41036 #endif /* SQLITE_OMIT_UTF16 */
41037 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
41038   return pVal->type;
41039 }
41040
41041 /**************************** sqlite3_result_  *******************************
41042 ** The following routines are used by user-defined functions to specify
41043 ** the function result.
41044 */
41045 SQLITE_API void sqlite3_result_blob(
41046   sqlite3_context *pCtx, 
41047   const void *z, 
41048   int n, 
41049   void (*xDel)(void *)
41050 ){
41051   assert( n>=0 );
41052   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41053   sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
41054 }
41055 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
41056   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41057   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
41058 }
41059 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
41060   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41061   pCtx->isError = SQLITE_ERROR;
41062   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
41063 }
41064 #ifndef SQLITE_OMIT_UTF16
41065 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
41066   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41067   pCtx->isError = SQLITE_ERROR;
41068   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
41069 }
41070 #endif
41071 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
41072   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41073   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
41074 }
41075 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
41076   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41077   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
41078 }
41079 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
41080   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41081   sqlite3VdbeMemSetNull(&pCtx->s);
41082 }
41083 SQLITE_API void sqlite3_result_text(
41084   sqlite3_context *pCtx, 
41085   const char *z, 
41086   int n,
41087   void (*xDel)(void *)
41088 ){
41089   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41090   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
41091 }
41092 #ifndef SQLITE_OMIT_UTF16
41093 SQLITE_API void sqlite3_result_text16(
41094   sqlite3_context *pCtx, 
41095   const void *z, 
41096   int n, 
41097   void (*xDel)(void *)
41098 ){
41099   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41100   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
41101 }
41102 SQLITE_API void sqlite3_result_text16be(
41103   sqlite3_context *pCtx, 
41104   const void *z, 
41105   int n, 
41106   void (*xDel)(void *)
41107 ){
41108   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41109   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
41110 }
41111 SQLITE_API void sqlite3_result_text16le(
41112   sqlite3_context *pCtx, 
41113   const void *z, 
41114   int n, 
41115   void (*xDel)(void *)
41116 ){
41117   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41118   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
41119 }
41120 #endif /* SQLITE_OMIT_UTF16 */
41121 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
41122   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41123   sqlite3VdbeMemCopy(&pCtx->s, pValue);
41124 }
41125 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
41126   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41127   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
41128 }
41129 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
41130   pCtx->isError = errCode;
41131 }
41132
41133 /* Force an SQLITE_TOOBIG error. */
41134 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
41135   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41136   pCtx->isError = SQLITE_TOOBIG;
41137   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
41138                        SQLITE_UTF8, SQLITE_STATIC);
41139 }
41140
41141 /* An SQLITE_NOMEM error. */
41142 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
41143   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41144   sqlite3VdbeMemSetNull(&pCtx->s);
41145   pCtx->isError = SQLITE_NOMEM;
41146   pCtx->s.db->mallocFailed = 1;
41147 }
41148
41149 /*
41150 ** Execute the statement pStmt, either until a row of data is ready, the
41151 ** statement is completely executed or an error occurs.
41152 **
41153 ** This routine implements the bulk of the logic behind the sqlite_step()
41154 ** API.  The only thing omitted is the automatic recompile if a 
41155 ** schema change has occurred.  That detail is handled by the
41156 ** outer sqlite3_step() wrapper procedure.
41157 */
41158 static int sqlite3Step(Vdbe *p){
41159   sqlite3 *db;
41160   int rc;
41161
41162   assert(p);
41163   if( p->magic!=VDBE_MAGIC_RUN ){
41164     return SQLITE_MISUSE;
41165   }
41166
41167   /* Assert that malloc() has not failed */
41168   db = p->db;
41169   assert( !db->mallocFailed );
41170
41171   if( p->aborted ){
41172     return SQLITE_ABORT;
41173   }
41174   if( p->pc<=0 && p->expired ){
41175     if( p->rc==SQLITE_OK ){
41176       p->rc = SQLITE_SCHEMA;
41177     }
41178     rc = SQLITE_ERROR;
41179     goto end_of_step;
41180   }
41181   if( sqlite3SafetyOn(db) ){
41182     p->rc = SQLITE_MISUSE;
41183     return SQLITE_MISUSE;
41184   }
41185   if( p->pc<0 ){
41186     /* If there are no other statements currently running, then
41187     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
41188     ** from interrupting a statement that has not yet started.
41189     */
41190     if( db->activeVdbeCnt==0 ){
41191       db->u1.isInterrupted = 0;
41192     }
41193
41194 #ifndef SQLITE_OMIT_TRACE
41195     if( db->xProfile && !db->init.busy ){
41196       double rNow;
41197       sqlite3OsCurrentTime(db->pVfs, &rNow);
41198       p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
41199     }
41200 #endif
41201
41202     db->activeVdbeCnt++;
41203     p->pc = 0;
41204     stmtLruRemove(p);
41205   }
41206 #ifndef SQLITE_OMIT_EXPLAIN
41207   if( p->explain ){
41208     rc = sqlite3VdbeList(p);
41209   }else
41210 #endif /* SQLITE_OMIT_EXPLAIN */
41211   {
41212     rc = sqlite3VdbeExec(p);
41213   }
41214
41215   if( sqlite3SafetyOff(db) ){
41216     rc = SQLITE_MISUSE;
41217   }
41218
41219 #ifndef SQLITE_OMIT_TRACE
41220   /* Invoke the profile callback if there is one
41221   */
41222   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0
41223            && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){
41224     double rNow;
41225     u64 elapseTime;
41226
41227     sqlite3OsCurrentTime(db->pVfs, &rNow);
41228     elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
41229     db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime);
41230   }
41231 #endif
41232
41233   sqlite3Error(p->db, rc, 0);
41234   p->rc = sqlite3ApiExit(p->db, p->rc);
41235 end_of_step:
41236   assert( (rc&0xff)==rc );
41237   if( p->zSql && (rc&0xff)<SQLITE_ROW ){
41238     /* This behavior occurs if sqlite3_prepare_v2() was used to build
41239     ** the prepared statement.  Return error codes directly */
41240     sqlite3Error(p->db, p->rc, 0);
41241     return p->rc;
41242   }else{
41243     /* This is for legacy sqlite3_prepare() builds and when the code
41244     ** is SQLITE_ROW or SQLITE_DONE */
41245     return rc;
41246   }
41247 }
41248
41249 /*
41250 ** This is the top-level implementation of sqlite3_step().  Call
41251 ** sqlite3Step() to do most of the work.  If a schema error occurs,
41252 ** call sqlite3Reprepare() and try again.
41253 */
41254 #ifdef SQLITE_OMIT_PARSER
41255 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
41256   int rc = SQLITE_MISUSE;
41257   if( pStmt ){
41258     Vdbe *v;
41259     v = (Vdbe*)pStmt;
41260     sqlite3_mutex_enter(v->db->mutex);
41261     rc = sqlite3Step(v);
41262     sqlite3_mutex_leave(v->db->mutex);
41263   }
41264   return rc;
41265 }
41266 #else
41267 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
41268   int rc = SQLITE_MISUSE;
41269   if( pStmt ){
41270     int cnt = 0;
41271     Vdbe *v = (Vdbe*)pStmt;
41272     sqlite3 *db = v->db;
41273     sqlite3_mutex_enter(db->mutex);
41274     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
41275            && cnt++ < 5
41276            && vdbeReprepare(v) ){
41277       sqlite3_reset(pStmt);
41278       v->expired = 0;
41279     }
41280     if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
41281       /* This case occurs after failing to recompile an sql statement. 
41282       ** The error message from the SQL compiler has already been loaded 
41283       ** into the database handle. This block copies the error message 
41284       ** from the database handle into the statement and sets the statement
41285       ** program counter to 0 to ensure that when the statement is 
41286       ** finalized or reset the parser error message is available via
41287       ** sqlite3_errmsg() and sqlite3_errcode().
41288       */
41289       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
41290       sqlite3_free(v->zErrMsg);
41291       if( !db->mallocFailed ){
41292         v->zErrMsg = sqlite3DbStrDup(db, zErr);
41293       } else {
41294         v->zErrMsg = 0;
41295         v->rc = SQLITE_NOMEM;
41296       }
41297     }
41298     rc = sqlite3ApiExit(db, rc);
41299     sqlite3_mutex_leave(db->mutex);
41300   }
41301   return rc;
41302 }
41303 #endif
41304
41305 /*
41306 ** Extract the user data from a sqlite3_context structure and return a
41307 ** pointer to it.
41308 */
41309 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
41310   assert( p && p->pFunc );
41311   return p->pFunc->pUserData;
41312 }
41313
41314 /*
41315 ** Extract the user data from a sqlite3_context structure and return a
41316 ** pointer to it.
41317 */
41318 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
41319   assert( p && p->pFunc );
41320   return p->s.db;
41321 }
41322
41323 /*
41324 ** The following is the implementation of an SQL function that always
41325 ** fails with an error message stating that the function is used in the
41326 ** wrong context.  The sqlite3_overload_function() API might construct
41327 ** SQL function that use this routine so that the functions will exist
41328 ** for name resolution but are actually overloaded by the xFindFunction
41329 ** method of virtual tables.
41330 */
41331 SQLITE_PRIVATE void sqlite3InvalidFunction(
41332   sqlite3_context *context,  /* The function calling context */
41333   int argc,                  /* Number of arguments to the function */
41334   sqlite3_value **argv       /* Value of each argument */
41335 ){
41336   const char *zName = context->pFunc->zName;
41337   char *zErr;
41338   zErr = sqlite3MPrintf(0,
41339       "unable to use function %s in the requested context", zName);
41340   sqlite3_result_error(context, zErr, -1);
41341   sqlite3_free(zErr);
41342 }
41343
41344 /*
41345 ** Allocate or return the aggregate context for a user function.  A new
41346 ** context is allocated on the first call.  Subsequent calls return the
41347 ** same context that was returned on prior calls.
41348 */
41349 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
41350   Mem *pMem;
41351   assert( p && p->pFunc && p->pFunc->xStep );
41352   assert( sqlite3_mutex_held(p->s.db->mutex) );
41353   pMem = p->pMem;
41354   if( (pMem->flags & MEM_Agg)==0 ){
41355     if( nByte==0 ){
41356       sqlite3VdbeMemReleaseExternal(pMem);
41357       pMem->flags = MEM_Null;
41358       pMem->z = 0;
41359     }else{
41360       sqlite3VdbeMemGrow(pMem, nByte, 0);
41361       pMem->flags = MEM_Agg;
41362       pMem->u.pDef = p->pFunc;
41363       if( pMem->z ){
41364         memset(pMem->z, 0, nByte);
41365       }
41366     }
41367   }
41368   return (void*)pMem->z;
41369 }
41370
41371 /*
41372 ** Return the auxilary data pointer, if any, for the iArg'th argument to
41373 ** the user-function defined by pCtx.
41374 */
41375 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
41376   VdbeFunc *pVdbeFunc;
41377
41378   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41379   pVdbeFunc = pCtx->pVdbeFunc;
41380   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
41381     return 0;
41382   }
41383   return pVdbeFunc->apAux[iArg].pAux;
41384 }
41385
41386 /*
41387 ** Set the auxilary data pointer and delete function, for the iArg'th
41388 ** argument to the user-function defined by pCtx. Any previous value is
41389 ** deleted by calling the delete function specified when it was set.
41390 */
41391 SQLITE_API void sqlite3_set_auxdata(
41392   sqlite3_context *pCtx, 
41393   int iArg, 
41394   void *pAux, 
41395   void (*xDelete)(void*)
41396 ){
41397   struct AuxData *pAuxData;
41398   VdbeFunc *pVdbeFunc;
41399   if( iArg<0 ) goto failed;
41400
41401   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
41402   pVdbeFunc = pCtx->pVdbeFunc;
41403   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
41404     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
41405     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
41406     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
41407     if( !pVdbeFunc ){
41408       goto failed;
41409     }
41410     pCtx->pVdbeFunc = pVdbeFunc;
41411     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
41412     pVdbeFunc->nAux = iArg+1;
41413     pVdbeFunc->pFunc = pCtx->pFunc;
41414   }
41415
41416   pAuxData = &pVdbeFunc->apAux[iArg];
41417   if( pAuxData->pAux && pAuxData->xDelete ){
41418     pAuxData->xDelete(pAuxData->pAux);
41419   }
41420   pAuxData->pAux = pAux;
41421   pAuxData->xDelete = xDelete;
41422   return;
41423
41424 failed:
41425   if( xDelete ){
41426     xDelete(pAux);
41427   }
41428 }
41429
41430 /*
41431 ** Return the number of times the Step function of a aggregate has been 
41432 ** called.
41433 **
41434 ** This function is deprecated.  Do not use it for new code.  It is
41435 ** provide only to avoid breaking legacy code.  New aggregate function
41436 ** implementations should keep their own counts within their aggregate
41437 ** context.
41438 */
41439 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
41440   assert( p && p->pFunc && p->pFunc->xStep );
41441   return p->pMem->n;
41442 }
41443
41444 /*
41445 ** Return the number of columns in the result set for the statement pStmt.
41446 */
41447 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
41448   Vdbe *pVm = (Vdbe *)pStmt;
41449   return pVm ? pVm->nResColumn : 0;
41450 }
41451
41452 /*
41453 ** Return the number of values available from the current row of the
41454 ** currently executing statement pStmt.
41455 */
41456 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
41457   Vdbe *pVm = (Vdbe *)pStmt;
41458   if( pVm==0 || pVm->pResultSet==0 ) return 0;
41459   return pVm->nResColumn;
41460 }
41461
41462
41463 /*
41464 ** Check to see if column iCol of the given statement is valid.  If
41465 ** it is, return a pointer to the Mem for the value of that column.
41466 ** If iCol is not valid, return a pointer to a Mem which has a value
41467 ** of NULL.
41468 */
41469 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
41470   Vdbe *pVm;
41471   int vals;
41472   Mem *pOut;
41473
41474   pVm = (Vdbe *)pStmt;
41475   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
41476     sqlite3_mutex_enter(pVm->db->mutex);
41477     vals = sqlite3_data_count(pStmt);
41478     pOut = &pVm->pResultSet[i];
41479   }else{
41480     static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
41481     if( pVm->db ){
41482       sqlite3_mutex_enter(pVm->db->mutex);
41483       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
41484     }
41485     pOut = (Mem*)&nullMem;
41486   }
41487   return pOut;
41488 }
41489
41490 /*
41491 ** This function is called after invoking an sqlite3_value_XXX function on a 
41492 ** column value (i.e. a value returned by evaluating an SQL expression in the
41493 ** select list of a SELECT statement) that may cause a malloc() failure. If 
41494 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
41495 ** code of statement pStmt set to SQLITE_NOMEM.
41496 **
41497 ** Specifically, this is called from within:
41498 **
41499 **     sqlite3_column_int()
41500 **     sqlite3_column_int64()
41501 **     sqlite3_column_text()
41502 **     sqlite3_column_text16()
41503 **     sqlite3_column_real()
41504 **     sqlite3_column_bytes()
41505 **     sqlite3_column_bytes16()
41506 **
41507 ** But not for sqlite3_column_blob(), which never calls malloc().
41508 */
41509 static void columnMallocFailure(sqlite3_stmt *pStmt)
41510 {
41511   /* If malloc() failed during an encoding conversion within an
41512   ** sqlite3_column_XXX API, then set the return code of the statement to
41513   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
41514   ** and _finalize() will return NOMEM.
41515   */
41516   Vdbe *p = (Vdbe *)pStmt;
41517   if( p ){
41518     p->rc = sqlite3ApiExit(p->db, p->rc);
41519     sqlite3_mutex_leave(p->db->mutex);
41520   }
41521 }
41522
41523 /**************************** sqlite3_column_  *******************************
41524 ** The following routines are used to access elements of the current row
41525 ** in the result set.
41526 */
41527 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
41528   const void *val;
41529   val = sqlite3_value_blob( columnMem(pStmt,i) );
41530   /* Even though there is no encoding conversion, value_blob() might
41531   ** need to call malloc() to expand the result of a zeroblob() 
41532   ** expression. 
41533   */
41534   columnMallocFailure(pStmt);
41535   return val;
41536 }
41537 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
41538   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
41539   columnMallocFailure(pStmt);
41540   return val;
41541 }
41542 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
41543   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
41544   columnMallocFailure(pStmt);
41545   return val;
41546 }
41547 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
41548   double val = sqlite3_value_double( columnMem(pStmt,i) );
41549   columnMallocFailure(pStmt);
41550   return val;
41551 }
41552 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
41553   int val = sqlite3_value_int( columnMem(pStmt,i) );
41554   columnMallocFailure(pStmt);
41555   return val;
41556 }
41557 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
41558   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
41559   columnMallocFailure(pStmt);
41560   return val;
41561 }
41562 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
41563   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
41564   columnMallocFailure(pStmt);
41565   return val;
41566 }
41567 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
41568   sqlite3_value *pOut = columnMem(pStmt, i);
41569   columnMallocFailure(pStmt);
41570   return pOut;
41571 }
41572 #ifndef SQLITE_OMIT_UTF16
41573 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
41574   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
41575   columnMallocFailure(pStmt);
41576   return val;
41577 }
41578 #endif /* SQLITE_OMIT_UTF16 */
41579 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
41580   int iType = sqlite3_value_type( columnMem(pStmt,i) );
41581   columnMallocFailure(pStmt);
41582   return iType;
41583 }
41584
41585 /* The following function is experimental and subject to change or
41586 ** removal */
41587 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
41588 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
41589 **}
41590 */
41591
41592 /*
41593 ** Convert the N-th element of pStmt->pColName[] into a string using
41594 ** xFunc() then return that string.  If N is out of range, return 0.
41595 **
41596 ** There are up to 5 names for each column.  useType determines which
41597 ** name is returned.  Here are the names:
41598 **
41599 **    0      The column name as it should be displayed for output
41600 **    1      The datatype name for the column
41601 **    2      The name of the database that the column derives from
41602 **    3      The name of the table that the column derives from
41603 **    4      The name of the table column that the result column derives from
41604 **
41605 ** If the result is not a simple column reference (if it is an expression
41606 ** or a constant) then useTypes 2, 3, and 4 return NULL.
41607 */
41608 static const void *columnName(
41609   sqlite3_stmt *pStmt,
41610   int N,
41611   const void *(*xFunc)(Mem*),
41612   int useType
41613 ){
41614   const void *ret = 0;
41615   Vdbe *p = (Vdbe *)pStmt;
41616   int n;
41617   
41618
41619   if( p!=0 ){
41620     n = sqlite3_column_count(pStmt);
41621     if( N<n && N>=0 ){
41622       N += useType*n;
41623       sqlite3_mutex_enter(p->db->mutex);
41624       ret = xFunc(&p->aColName[N]);
41625
41626       /* A malloc may have failed inside of the xFunc() call. If this
41627       ** is the case, clear the mallocFailed flag and return NULL.
41628       */
41629       if( p->db && p->db->mallocFailed ){
41630         p->db->mallocFailed = 0;
41631         ret = 0;
41632       }
41633       sqlite3_mutex_leave(p->db->mutex);
41634     }
41635   }
41636   return ret;
41637 }
41638
41639 /*
41640 ** Return the name of the Nth column of the result set returned by SQL
41641 ** statement pStmt.
41642 */
41643 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
41644   return columnName(
41645       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
41646 }
41647 #ifndef SQLITE_OMIT_UTF16
41648 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
41649   return columnName(
41650       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
41651 }
41652 #endif
41653
41654 /*
41655 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
41656 ** not define OMIT_DECLTYPE.
41657 */
41658 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
41659 # error "Must not define both SQLITE_OMIT_DECLTYPE \
41660          and SQLITE_ENABLE_COLUMN_METADATA"
41661 #endif
41662
41663 #ifndef SQLITE_OMIT_DECLTYPE
41664 /*
41665 ** Return the column declaration type (if applicable) of the 'i'th column
41666 ** of the result set of SQL statement pStmt.
41667 */
41668 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
41669   return columnName(
41670       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
41671 }
41672 #ifndef SQLITE_OMIT_UTF16
41673 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
41674   return columnName(
41675       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
41676 }
41677 #endif /* SQLITE_OMIT_UTF16 */
41678 #endif /* SQLITE_OMIT_DECLTYPE */
41679
41680 #ifdef SQLITE_ENABLE_COLUMN_METADATA
41681 /*
41682 ** Return the name of the database from which a result column derives.
41683 ** NULL is returned if the result column is an expression or constant or
41684 ** anything else which is not an unabiguous reference to a database column.
41685 */
41686 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
41687   return columnName(
41688       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
41689 }
41690 #ifndef SQLITE_OMIT_UTF16
41691 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
41692   return columnName(
41693       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
41694 }
41695 #endif /* SQLITE_OMIT_UTF16 */
41696
41697 /*
41698 ** Return the name of the table from which a result column derives.
41699 ** NULL is returned if the result column is an expression or constant or
41700 ** anything else which is not an unabiguous reference to a database column.
41701 */
41702 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
41703   return columnName(
41704       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
41705 }
41706 #ifndef SQLITE_OMIT_UTF16
41707 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
41708   return columnName(
41709       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
41710 }
41711 #endif /* SQLITE_OMIT_UTF16 */
41712
41713 /*
41714 ** Return the name of the table column from which a result column derives.
41715 ** NULL is returned if the result column is an expression or constant or
41716 ** anything else which is not an unabiguous reference to a database column.
41717 */
41718 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
41719   return columnName(
41720       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
41721 }
41722 #ifndef SQLITE_OMIT_UTF16
41723 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
41724   return columnName(
41725       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
41726 }
41727 #endif /* SQLITE_OMIT_UTF16 */
41728 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
41729
41730
41731 /******************************* sqlite3_bind_  ***************************
41732 ** 
41733 ** Routines used to attach values to wildcards in a compiled SQL statement.
41734 */
41735 /*
41736 ** Unbind the value bound to variable i in virtual machine p. This is the 
41737 ** the same as binding a NULL value to the column. If the "i" parameter is
41738 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
41739 **
41740 ** The error code stored in database p->db is overwritten with the return
41741 ** value in any case.
41742 */
41743 static int vdbeUnbind(Vdbe *p, int i){
41744   Mem *pVar;
41745   if( p==0 || p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
41746     if( p ) sqlite3Error(p->db, SQLITE_MISUSE, 0);
41747     return SQLITE_MISUSE;
41748   }
41749   if( i<1 || i>p->nVar ){
41750     sqlite3Error(p->db, SQLITE_RANGE, 0);
41751     return SQLITE_RANGE;
41752   }
41753   i--;
41754   pVar = &p->aVar[i];
41755   sqlite3VdbeMemRelease(pVar);
41756   pVar->flags = MEM_Null;
41757   sqlite3Error(p->db, SQLITE_OK, 0);
41758   return SQLITE_OK;
41759 }
41760
41761 /*
41762 ** Bind a text or BLOB value.
41763 */
41764 static int bindText(
41765   sqlite3_stmt *pStmt,   /* The statement to bind against */
41766   int i,                 /* Index of the parameter to bind */
41767   const void *zData,     /* Pointer to the data to be bound */
41768   int nData,             /* Number of bytes of data to be bound */
41769   void (*xDel)(void*),   /* Destructor for the data */
41770   int encoding           /* Encoding for the data */
41771 ){
41772   Vdbe *p = (Vdbe *)pStmt;
41773   Mem *pVar;
41774   int rc;
41775
41776   if( p==0 ){
41777     return SQLITE_MISUSE;
41778   }
41779   sqlite3_mutex_enter(p->db->mutex);
41780   rc = vdbeUnbind(p, i);
41781   if( rc==SQLITE_OK && zData!=0 ){
41782     pVar = &p->aVar[i-1];
41783     rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
41784     if( rc==SQLITE_OK && encoding!=0 ){
41785       rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
41786     }
41787     sqlite3Error(p->db, rc, 0);
41788     rc = sqlite3ApiExit(p->db, rc);
41789   }
41790   sqlite3_mutex_leave(p->db->mutex);
41791   return rc;
41792 }
41793
41794
41795 /*
41796 ** Bind a blob value to an SQL statement variable.
41797 */
41798 SQLITE_API int sqlite3_bind_blob(
41799   sqlite3_stmt *pStmt, 
41800   int i, 
41801   const void *zData, 
41802   int nData, 
41803   void (*xDel)(void*)
41804 ){
41805   return bindText(pStmt, i, zData, nData, xDel, 0);
41806 }
41807 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
41808   int rc;
41809   Vdbe *p = (Vdbe *)pStmt;
41810   sqlite3_mutex_enter(p->db->mutex);
41811   rc = vdbeUnbind(p, i);
41812   if( rc==SQLITE_OK ){
41813     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
41814   }
41815   sqlite3_mutex_leave(p->db->mutex);
41816   return rc;
41817 }
41818 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
41819   return sqlite3_bind_int64(p, i, (i64)iValue);
41820 }
41821 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
41822   int rc;
41823   Vdbe *p = (Vdbe *)pStmt;
41824   sqlite3_mutex_enter(p->db->mutex);
41825   rc = vdbeUnbind(p, i);
41826   if( rc==SQLITE_OK ){
41827     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
41828   }
41829   sqlite3_mutex_leave(p->db->mutex);
41830   return rc;
41831 }
41832 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
41833   int rc;
41834   Vdbe *p = (Vdbe*)pStmt;
41835   sqlite3_mutex_enter(p->db->mutex);
41836   rc = vdbeUnbind(p, i);
41837   sqlite3_mutex_leave(p->db->mutex);
41838   return rc;
41839 }
41840 SQLITE_API int sqlite3_bind_text( 
41841   sqlite3_stmt *pStmt, 
41842   int i, 
41843   const char *zData, 
41844   int nData, 
41845   void (*xDel)(void*)
41846 ){
41847   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
41848 }
41849 #ifndef SQLITE_OMIT_UTF16
41850 SQLITE_API int sqlite3_bind_text16(
41851   sqlite3_stmt *pStmt, 
41852   int i, 
41853   const void *zData, 
41854   int nData, 
41855   void (*xDel)(void*)
41856 ){
41857   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
41858 }
41859 #endif /* SQLITE_OMIT_UTF16 */
41860 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
41861   int rc;
41862   Vdbe *p = (Vdbe *)pStmt;
41863   sqlite3_mutex_enter(p->db->mutex);
41864   rc = vdbeUnbind(p, i);
41865   if( rc==SQLITE_OK ){
41866     rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
41867   }
41868   rc = sqlite3ApiExit(p->db, rc);
41869   sqlite3_mutex_leave(p->db->mutex);
41870   return rc;
41871 }
41872 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
41873   int rc;
41874   Vdbe *p = (Vdbe *)pStmt;
41875   sqlite3_mutex_enter(p->db->mutex);
41876   rc = vdbeUnbind(p, i);
41877   if( rc==SQLITE_OK ){
41878     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
41879   }
41880   sqlite3_mutex_leave(p->db->mutex);
41881   return rc;
41882 }
41883
41884 /*
41885 ** Return the number of wildcards that can be potentially bound to.
41886 ** This routine is added to support DBD::SQLite.  
41887 */
41888 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
41889   Vdbe *p = (Vdbe*)pStmt;
41890   return p ? p->nVar : 0;
41891 }
41892
41893 /*
41894 ** Create a mapping from variable numbers to variable names
41895 ** in the Vdbe.azVar[] array, if such a mapping does not already
41896 ** exist.
41897 */
41898 static void createVarMap(Vdbe *p){
41899   if( !p->okVar ){
41900     sqlite3_mutex_enter(p->db->mutex);
41901     if( !p->okVar ){
41902       int j;
41903       Op *pOp;
41904       for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
41905         if( pOp->opcode==OP_Variable ){
41906           assert( pOp->p1>0 && pOp->p1<=p->nVar );
41907           p->azVar[pOp->p1-1] = pOp->p4.z;
41908         }
41909       }
41910       p->okVar = 1;
41911     }
41912     sqlite3_mutex_leave(p->db->mutex);
41913   }
41914 }
41915
41916 /*
41917 ** Return the name of a wildcard parameter.  Return NULL if the index
41918 ** is out of range or if the wildcard is unnamed.
41919 **
41920 ** The result is always UTF-8.
41921 */
41922 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
41923   Vdbe *p = (Vdbe*)pStmt;
41924   if( p==0 || i<1 || i>p->nVar ){
41925     return 0;
41926   }
41927   createVarMap(p);
41928   return p->azVar[i-1];
41929 }
41930
41931 /*
41932 ** Given a wildcard parameter name, return the index of the variable
41933 ** with that name.  If there is no variable with the given name,
41934 ** return 0.
41935 */
41936 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
41937   Vdbe *p = (Vdbe*)pStmt;
41938   int i;
41939   if( p==0 ){
41940     return 0;
41941   }
41942   createVarMap(p); 
41943   if( zName ){
41944     for(i=0; i<p->nVar; i++){
41945       const char *z = p->azVar[i];
41946       if( z && strcmp(z,zName)==0 ){
41947         return i+1;
41948       }
41949     }
41950   }
41951   return 0;
41952 }
41953
41954 /*
41955 ** Transfer all bindings from the first statement over to the second.
41956 ** If the two statements contain a different number of bindings, then
41957 ** an SQLITE_ERROR is returned.
41958 */
41959 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
41960   Vdbe *pFrom = (Vdbe*)pFromStmt;
41961   Vdbe *pTo = (Vdbe*)pToStmt;
41962   int i, rc = SQLITE_OK;
41963   if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
41964     || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
41965     || pTo->db!=pFrom->db ){
41966     return SQLITE_MISUSE;
41967   }
41968   if( pFrom->nVar!=pTo->nVar ){
41969     return SQLITE_ERROR;
41970   }
41971   sqlite3_mutex_enter(pTo->db->mutex);
41972   for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
41973     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
41974   }
41975   sqlite3_mutex_leave(pTo->db->mutex);
41976   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41977   return rc;
41978 }
41979
41980 /*
41981 ** Return the sqlite3* database handle to which the prepared statement given
41982 ** in the argument belongs.  This is the same database handle that was
41983 ** the first argument to the sqlite3_prepare() that was used to create
41984 ** the statement in the first place.
41985 */
41986 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
41987   return pStmt ? ((Vdbe*)pStmt)->db : 0;
41988 }
41989
41990 /************** End of vdbeapi.c *********************************************/
41991 /************** Begin file vdbe.c ********************************************/
41992 /*
41993 ** 2001 September 15
41994 **
41995 ** The author disclaims copyright to this source code.  In place of
41996 ** a legal notice, here is a blessing:
41997 **
41998 **    May you do good and not evil.
41999 **    May you find forgiveness for yourself and forgive others.
42000 **    May you share freely, never taking more than you give.
42001 **
42002 *************************************************************************
42003 ** The code in this file implements execution method of the 
42004 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
42005 ** handles housekeeping details such as creating and deleting
42006 ** VDBE instances.  This file is solely interested in executing
42007 ** the VDBE program.
42008 **
42009 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
42010 ** to a VDBE.
42011 **
42012 ** The SQL parser generates a program which is then executed by
42013 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
42014 ** similar in form to assembly language.  The program consists of
42015 ** a linear sequence of operations.  Each operation has an opcode 
42016 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
42017 ** is a null-terminated string.  Operand P5 is an unsigned character.
42018 ** Few opcodes use all 5 operands.
42019 **
42020 ** Computation results are stored on a set of registers numbered beginning
42021 ** with 1 and going up to Vdbe.nMem.  Each register can store
42022 ** either an integer, a null-terminated string, a floating point
42023 ** number, or the SQL "NULL" value.  An inplicit conversion from one
42024 ** type to the other occurs as necessary.
42025 ** 
42026 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
42027 ** function which does the work of interpreting a VDBE program.
42028 ** But other routines are also provided to help in building up
42029 ** a program instruction by instruction.
42030 **
42031 ** Various scripts scan this source file in order to generate HTML
42032 ** documentation, headers files, or other derived files.  The formatting
42033 ** of the code in this file is, therefore, important.  See other comments
42034 ** in this file for details.  If in doubt, do not deviate from existing
42035 ** commenting and indentation practices when changing or adding code.
42036 **
42037 ** $Id: vdbe.c,v 1.740 2008/05/13 13:27:34 drh Exp $
42038 */
42039
42040 /*
42041 ** The following global variable is incremented every time a cursor
42042 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
42043 ** procedures use this information to make sure that indices are
42044 ** working correctly.  This variable has no function other than to
42045 ** help verify the correct operation of the library.
42046 */
42047 #ifdef SQLITE_TEST
42048 SQLITE_API int sqlite3_search_count = 0;
42049 #endif
42050
42051 /*
42052 ** When this global variable is positive, it gets decremented once before
42053 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
42054 ** field of the sqlite3 structure is set in order to simulate and interrupt.
42055 **
42056 ** This facility is used for testing purposes only.  It does not function
42057 ** in an ordinary build.
42058 */
42059 #ifdef SQLITE_TEST
42060 SQLITE_API int sqlite3_interrupt_count = 0;
42061 #endif
42062
42063 /*
42064 ** The next global variable is incremented each type the OP_Sort opcode
42065 ** is executed.  The test procedures use this information to make sure that
42066 ** sorting is occurring or not occuring at appropriate times.   This variable
42067 ** has no function other than to help verify the correct operation of the
42068 ** library.
42069 */
42070 #ifdef SQLITE_TEST
42071 SQLITE_API int sqlite3_sort_count = 0;
42072 #endif
42073
42074 /*
42075 ** The next global variable records the size of the largest MEM_Blob
42076 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
42077 ** use this information to make sure that the zero-blob functionality
42078 ** is working correctly.   This variable has no function other than to
42079 ** help verify the correct operation of the library.
42080 */
42081 #ifdef SQLITE_TEST
42082 SQLITE_API int sqlite3_max_blobsize = 0;
42083 static void updateMaxBlobsize(Mem *p){
42084   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
42085     sqlite3_max_blobsize = p->n;
42086   }
42087 }
42088 #endif
42089
42090 /*
42091 ** Test a register to see if it exceeds the current maximum blob size.
42092 ** If it does, record the new maximum blob size.
42093 */
42094 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
42095 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
42096 #else
42097 # define UPDATE_MAX_BLOBSIZE(P)
42098 #endif
42099
42100 /*
42101 ** Release the memory associated with a register.  This
42102 ** leaves the Mem.flags field in an inconsistent state.
42103 */
42104 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
42105
42106 /*
42107 ** Convert the given register into a string if it isn't one
42108 ** already. Return non-zero if a malloc() fails.
42109 */
42110 #define Stringify(P, enc) \
42111    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
42112      { goto no_mem; }
42113
42114 /*
42115 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
42116 ** a pointer to a dynamically allocated string where some other entity
42117 ** is responsible for deallocating that string.  Because the register
42118 ** does not control the string, it might be deleted without the register
42119 ** knowing it.
42120 **
42121 ** This routine converts an ephemeral string into a dynamically allocated
42122 ** string that the register itself controls.  In other words, it
42123 ** converts an MEM_Ephem string into an MEM_Dyn string.
42124 */
42125 #define Deephemeralize(P) \
42126    if( ((P)->flags&MEM_Ephem)!=0 \
42127        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
42128
42129 /*
42130 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
42131 ** P if required.
42132 */
42133 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
42134
42135 /*
42136 ** Argument pMem points at a regiser that will be passed to a
42137 ** user-defined function or returned to the user as the result of a query.
42138 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
42139 ** register variables.  This routine sets the pMem->enc and pMem->type
42140 ** variables used by the sqlite3_value_*() routines.
42141 */
42142 #define storeTypeInfo(A,B) _storeTypeInfo(A)
42143 static void _storeTypeInfo(Mem *pMem){
42144   int flags = pMem->flags;
42145   if( flags & MEM_Null ){
42146     pMem->type = SQLITE_NULL;
42147   }
42148   else if( flags & MEM_Int ){
42149     pMem->type = SQLITE_INTEGER;
42150   }
42151   else if( flags & MEM_Real ){
42152     pMem->type = SQLITE_FLOAT;
42153   }
42154   else if( flags & MEM_Str ){
42155     pMem->type = SQLITE_TEXT;
42156   }else{
42157     pMem->type = SQLITE_BLOB;
42158   }
42159 }
42160
42161 /*
42162 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
42163 ** created by mkopcodeh.awk during compilation.  Data is obtained
42164 ** from the comments following the "case OP_xxxx:" statements in
42165 ** this file.  
42166 */
42167 static unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
42168
42169 /*
42170 ** Return true if an opcode has any of the OPFLG_xxx properties
42171 ** specified by mask.
42172 */
42173 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
42174   assert( opcode>0 && opcode<sizeof(opcodeProperty) );
42175   return (opcodeProperty[opcode]&mask)!=0;
42176 }
42177
42178 /*
42179 ** Allocate cursor number iCur.  Return a pointer to it.  Return NULL
42180 ** if we run out of memory.
42181 */
42182 static Cursor *allocateCursor(
42183   Vdbe *p, 
42184   int iCur, 
42185   Op *pOp,
42186   int iDb, 
42187   int isBtreeCursor
42188 ){
42189   /* Find the memory cell that will be used to store the blob of memory
42190   ** required for this Cursor structure. It is convenient to use a 
42191   ** vdbe memory cell to manage the memory allocation required for a
42192   ** Cursor structure for the following reasons:
42193   **
42194   **   * Sometimes cursor numbers are used for a couple of different
42195   **     purposes in a vdbe program. The different uses might require
42196   **     different sized allocations. Memory cells provide growable
42197   **     allocations.
42198   **
42199   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
42200   **     be freed lazily via the sqlite3_release_memory() API. This
42201   **     minimizes the number of malloc calls made by the system.
42202   **
42203   ** Memory cells for cursors are allocated at the top of the address
42204   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
42205   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
42206   */
42207   Mem *pMem = &p->aMem[p->nMem-iCur];
42208
42209   int nByte;
42210   Cursor *pCx = 0;
42211   /* If the opcode of pOp is OP_SetNumColumns, then pOp->p2 contains
42212   ** the number of fields in the records contained in the table or
42213   ** index being opened. Use this to reserve space for the 
42214   ** Cursor.aType[] array.
42215   */
42216   int nField = 0;
42217   if( pOp->opcode==OP_SetNumColumns || pOp->opcode==OP_OpenEphemeral ){
42218     nField = pOp->p2;
42219   }
42220   nByte = 
42221       sizeof(Cursor) + 
42222       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
42223       2*nField*sizeof(u32);
42224
42225   assert( iCur<p->nCursor );
42226   if( p->apCsr[iCur] ){
42227     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
42228     p->apCsr[iCur] = 0;
42229   }
42230   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
42231     p->apCsr[iCur] = pCx = (Cursor *)pMem->z;
42232     memset(pMem->z, 0, nByte);
42233     pCx->iDb = iDb;
42234     pCx->nField = nField;
42235     if( nField ){
42236       pCx->aType = (u32 *)&pMem->z[sizeof(Cursor)];
42237     }
42238     if( isBtreeCursor ){
42239       pCx->pCursor = (BtCursor *)&pMem->z[sizeof(Cursor)+2*nField*sizeof(u32)];
42240     }
42241   }
42242   return pCx;
42243 }
42244
42245 /*
42246 ** Try to convert a value into a numeric representation if we can
42247 ** do so without loss of information.  In other words, if the string
42248 ** looks like a number, convert it into a number.  If it does not
42249 ** look like a number, leave it alone.
42250 */
42251 static void applyNumericAffinity(Mem *pRec){
42252   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
42253     int realnum;
42254     sqlite3VdbeMemNulTerminate(pRec);
42255     if( (pRec->flags&MEM_Str)
42256          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
42257       i64 value;
42258       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
42259       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
42260         pRec->u.i = value;
42261         MemSetTypeFlag(pRec, MEM_Int);
42262       }else{
42263         sqlite3VdbeMemRealify(pRec);
42264       }
42265     }
42266   }
42267 }
42268
42269 /*
42270 ** Processing is determine by the affinity parameter:
42271 **
42272 ** SQLITE_AFF_INTEGER:
42273 ** SQLITE_AFF_REAL:
42274 ** SQLITE_AFF_NUMERIC:
42275 **    Try to convert pRec to an integer representation or a 
42276 **    floating-point representation if an integer representation
42277 **    is not possible.  Note that the integer representation is
42278 **    always preferred, even if the affinity is REAL, because
42279 **    an integer representation is more space efficient on disk.
42280 **
42281 ** SQLITE_AFF_TEXT:
42282 **    Convert pRec to a text representation.
42283 **
42284 ** SQLITE_AFF_NONE:
42285 **    No-op.  pRec is unchanged.
42286 */
42287 static void applyAffinity(
42288   Mem *pRec,          /* The value to apply affinity to */
42289   char affinity,      /* The affinity to be applied */
42290   u8 enc              /* Use this text encoding */
42291 ){
42292   if( affinity==SQLITE_AFF_TEXT ){
42293     /* Only attempt the conversion to TEXT if there is an integer or real
42294     ** representation (blob and NULL do not get converted) but no string
42295     ** representation.
42296     */
42297     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
42298       sqlite3VdbeMemStringify(pRec, enc);
42299     }
42300     pRec->flags &= ~(MEM_Real|MEM_Int);
42301   }else if( affinity!=SQLITE_AFF_NONE ){
42302     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
42303              || affinity==SQLITE_AFF_NUMERIC );
42304     applyNumericAffinity(pRec);
42305     if( pRec->flags & MEM_Real ){
42306       sqlite3VdbeIntegerAffinity(pRec);
42307     }
42308   }
42309 }
42310
42311 /*
42312 ** Try to convert the type of a function argument or a result column
42313 ** into a numeric representation.  Use either INTEGER or REAL whichever
42314 ** is appropriate.  But only do the conversion if it is possible without
42315 ** loss of information and return the revised type of the argument.
42316 **
42317 ** This is an EXPERIMENTAL api and is subject to change or removal.
42318 */
42319 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
42320   Mem *pMem = (Mem*)pVal;
42321   applyNumericAffinity(pMem);
42322   storeTypeInfo(pMem, 0);
42323   return pMem->type;
42324 }
42325
42326 /*
42327 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
42328 ** not the internal Mem* type.
42329 */
42330 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
42331   sqlite3_value *pVal, 
42332   u8 affinity, 
42333   u8 enc
42334 ){
42335   applyAffinity((Mem *)pVal, affinity, enc);
42336 }
42337
42338 #ifdef SQLITE_DEBUG
42339 /*
42340 ** Write a nice string representation of the contents of cell pMem
42341 ** into buffer zBuf, length nBuf.
42342 */
42343 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
42344   char *zCsr = zBuf;
42345   int f = pMem->flags;
42346
42347   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
42348
42349   if( f&MEM_Blob ){
42350     int i;
42351     char c;
42352     if( f & MEM_Dyn ){
42353       c = 'z';
42354       assert( (f & (MEM_Static|MEM_Ephem))==0 );
42355     }else if( f & MEM_Static ){
42356       c = 't';
42357       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
42358     }else if( f & MEM_Ephem ){
42359       c = 'e';
42360       assert( (f & (MEM_Static|MEM_Dyn))==0 );
42361     }else{
42362       c = 's';
42363     }
42364
42365     sqlite3_snprintf(100, zCsr, "%c", c);
42366     zCsr += strlen(zCsr);
42367     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
42368     zCsr += strlen(zCsr);
42369     for(i=0; i<16 && i<pMem->n; i++){
42370       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
42371       zCsr += strlen(zCsr);
42372     }
42373     for(i=0; i<16 && i<pMem->n; i++){
42374       char z = pMem->z[i];
42375       if( z<32 || z>126 ) *zCsr++ = '.';
42376       else *zCsr++ = z;
42377     }
42378
42379     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
42380     zCsr += strlen(zCsr);
42381     if( f & MEM_Zero ){
42382       sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
42383       zCsr += strlen(zCsr);
42384     }
42385     *zCsr = '\0';
42386   }else if( f & MEM_Str ){
42387     int j, k;
42388     zBuf[0] = ' ';
42389     if( f & MEM_Dyn ){
42390       zBuf[1] = 'z';
42391       assert( (f & (MEM_Static|MEM_Ephem))==0 );
42392     }else if( f & MEM_Static ){
42393       zBuf[1] = 't';
42394       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
42395     }else if( f & MEM_Ephem ){
42396       zBuf[1] = 'e';
42397       assert( (f & (MEM_Static|MEM_Dyn))==0 );
42398     }else{
42399       zBuf[1] = 's';
42400     }
42401     k = 2;
42402     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
42403     k += strlen(&zBuf[k]);
42404     zBuf[k++] = '[';
42405     for(j=0; j<15 && j<pMem->n; j++){
42406       u8 c = pMem->z[j];
42407       if( c>=0x20 && c<0x7f ){
42408         zBuf[k++] = c;
42409       }else{
42410         zBuf[k++] = '.';
42411       }
42412     }
42413     zBuf[k++] = ']';
42414     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
42415     k += strlen(&zBuf[k]);
42416     zBuf[k++] = 0;
42417   }
42418 }
42419 #endif
42420
42421 #ifdef SQLITE_DEBUG
42422 /*
42423 ** Print the value of a register for tracing purposes:
42424 */
42425 static void memTracePrint(FILE *out, Mem *p){
42426   if( p->flags & MEM_Null ){
42427     fprintf(out, " NULL");
42428   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
42429     fprintf(out, " si:%lld", p->u.i);
42430   }else if( p->flags & MEM_Int ){
42431     fprintf(out, " i:%lld", p->u.i);
42432   }else if( p->flags & MEM_Real ){
42433     fprintf(out, " r:%g", p->r);
42434   }else{
42435     char zBuf[200];
42436     sqlite3VdbeMemPrettyPrint(p, zBuf);
42437     fprintf(out, " ");
42438     fprintf(out, "%s", zBuf);
42439   }
42440 }
42441 static void registerTrace(FILE *out, int iReg, Mem *p){
42442   fprintf(out, "REG[%d] = ", iReg);
42443   memTracePrint(out, p);
42444   fprintf(out, "\n");
42445 }
42446 #endif
42447
42448 #ifdef SQLITE_DEBUG
42449 #  define REGISTER_TRACE(R,M) if(p->trace&&R>0)registerTrace(p->trace,R,M)
42450 #else
42451 #  define REGISTER_TRACE(R,M)
42452 #endif
42453
42454
42455 #ifdef VDBE_PROFILE
42456 /*
42457 ** The following routine only works on pentium-class processors.
42458 ** It uses the RDTSC opcode to read the cycle count value out of the
42459 ** processor and returns that value.  This can be used for high-res
42460 ** profiling.
42461 */
42462 __inline__ unsigned long long int hwtime(void){
42463    unsigned int lo, hi;
42464    /* We cannot use "=A", since this would use %rax on x86_64 */
42465    __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
42466    return (unsigned long long int)hi << 32 | lo;
42467 }
42468 #endif
42469
42470 /*
42471 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
42472 ** sqlite3_interrupt() routine has been called.  If it has been, then
42473 ** processing of the VDBE program is interrupted.
42474 **
42475 ** This macro added to every instruction that does a jump in order to
42476 ** implement a loop.  This test used to be on every single instruction,
42477 ** but that meant we more testing that we needed.  By only testing the
42478 ** flag on jump instructions, we get a (small) speed improvement.
42479 */
42480 #define CHECK_FOR_INTERRUPT \
42481    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
42482
42483
42484 /*
42485 ** Execute as much of a VDBE program as we can then return.
42486 **
42487 ** sqlite3VdbeMakeReady() must be called before this routine in order to
42488 ** close the program with a final OP_Halt and to set up the callbacks
42489 ** and the error message pointer.
42490 **
42491 ** Whenever a row or result data is available, this routine will either
42492 ** invoke the result callback (if there is one) or return with
42493 ** SQLITE_ROW.
42494 **
42495 ** If an attempt is made to open a locked database, then this routine
42496 ** will either invoke the busy callback (if there is one) or it will
42497 ** return SQLITE_BUSY.
42498 **
42499 ** If an error occurs, an error message is written to memory obtained
42500 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
42501 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
42502 **
42503 ** If the callback ever returns non-zero, then the program exits
42504 ** immediately.  There will be no error message but the p->rc field is
42505 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
42506 **
42507 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
42508 ** routine to return SQLITE_ERROR.
42509 **
42510 ** Other fatal errors return SQLITE_ERROR.
42511 **
42512 ** After this routine has finished, sqlite3VdbeFinalize() should be
42513 ** used to clean up the mess that was left behind.
42514 */
42515 SQLITE_PRIVATE int sqlite3VdbeExec(
42516   Vdbe *p                    /* The VDBE */
42517 ){
42518   int pc;                    /* The program counter */
42519   Op *pOp;                   /* Current operation */
42520   int rc = SQLITE_OK;        /* Value to return */
42521   sqlite3 *db = p->db;       /* The database */
42522   u8 encoding = ENC(db);     /* The database encoding */
42523   Mem *pIn1, *pIn2, *pIn3;   /* Input operands */
42524   Mem *pOut;                 /* Output operand */
42525   u8 opProperty;
42526 #ifdef VDBE_PROFILE
42527   unsigned long long start;  /* CPU clock count at start of opcode */
42528   int origPc;                /* Program counter at start of opcode */
42529 #endif
42530 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
42531   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
42532 #endif
42533
42534   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
42535   assert( db->magic==SQLITE_MAGIC_BUSY );
42536   sqlite3BtreeMutexArrayEnter(&p->aMutex);
42537   if( p->rc==SQLITE_NOMEM ){
42538     /* This happens if a malloc() inside a call to sqlite3_column_text() or
42539     ** sqlite3_column_text16() failed.  */
42540     goto no_mem;
42541   }
42542   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
42543   p->rc = SQLITE_OK;
42544   assert( p->explain==0 );
42545   p->pResultSet = 0;
42546   db->busyHandler.nBusy = 0;
42547   CHECK_FOR_INTERRUPT;
42548   sqlite3VdbeIOTraceSql(p);
42549 #ifdef SQLITE_DEBUG
42550   sqlite3FaultBeginBenign(-1);
42551   if( p->pc==0 && ((p->db->flags & SQLITE_VdbeListing)!=0
42552     || sqlite3OsAccess(db->pVfs, "vdbe_explain", SQLITE_ACCESS_EXISTS)==1 )
42553   ){
42554     int i;
42555     printf("VDBE Program Listing:\n");
42556     sqlite3VdbePrintSql(p);
42557     for(i=0; i<p->nOp; i++){
42558       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
42559     }
42560   }
42561   if( sqlite3OsAccess(db->pVfs, "vdbe_trace", SQLITE_ACCESS_EXISTS)==1 ){
42562     p->trace = stdout;
42563   }
42564   sqlite3FaultEndBenign(-1);
42565 #endif
42566   for(pc=p->pc; rc==SQLITE_OK; pc++){
42567     assert( pc>=0 && pc<p->nOp );
42568     if( db->mallocFailed ) goto no_mem;
42569 #ifdef VDBE_PROFILE
42570     origPc = pc;
42571     start = hwtime();
42572 #endif
42573     pOp = &p->aOp[pc];
42574
42575     /* Only allow tracing if SQLITE_DEBUG is defined.
42576     */
42577 #ifdef SQLITE_DEBUG
42578     if( p->trace ){
42579       if( pc==0 ){
42580         printf("VDBE Execution Trace:\n");
42581         sqlite3VdbePrintSql(p);
42582       }
42583       sqlite3VdbePrintOp(p->trace, pc, pOp);
42584     }
42585     if( p->trace==0 && pc==0 ){
42586       sqlite3FaultBeginBenign(-1);
42587       if( sqlite3OsAccess(db->pVfs, "vdbe_sqltrace", SQLITE_ACCESS_EXISTS)==1 ){
42588         sqlite3VdbePrintSql(p);
42589       }
42590       sqlite3FaultEndBenign(-1);
42591     }
42592 #endif
42593       
42594
42595     /* Check to see if we need to simulate an interrupt.  This only happens
42596     ** if we have a special test build.
42597     */
42598 #ifdef SQLITE_TEST
42599     if( sqlite3_interrupt_count>0 ){
42600       sqlite3_interrupt_count--;
42601       if( sqlite3_interrupt_count==0 ){
42602         sqlite3_interrupt(db);
42603       }
42604     }
42605 #endif
42606
42607 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
42608     /* Call the progress callback if it is configured and the required number
42609     ** of VDBE ops have been executed (either since this invocation of
42610     ** sqlite3VdbeExec() or since last time the progress callback was called).
42611     ** If the progress callback returns non-zero, exit the virtual machine with
42612     ** a return code SQLITE_ABORT.
42613     */
42614     if( db->xProgress ){
42615       if( db->nProgressOps==nProgressOps ){
42616         int prc;
42617         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
42618         prc =db->xProgress(db->pProgressArg);
42619         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
42620         if( prc!=0 ){
42621           rc = SQLITE_INTERRUPT;
42622           goto vdbe_error_halt;
42623         }
42624         nProgressOps = 0;
42625       }
42626       nProgressOps++;
42627     }
42628 #endif
42629
42630     /* Do common setup processing for any opcode that is marked
42631     ** with the "out2-prerelease" tag.  Such opcodes have a single
42632     ** output which is specified by the P2 parameter.  The P2 register
42633     ** is initialized to a NULL.
42634     */
42635     opProperty = opcodeProperty[pOp->opcode];
42636     if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
42637       assert( pOp->p2>0 );
42638       assert( pOp->p2<=p->nMem );
42639       pOut = &p->aMem[pOp->p2];
42640       sqlite3VdbeMemReleaseExternal(pOut);
42641       pOut->flags = MEM_Null;
42642     }else
42643  
42644     /* Do common setup for opcodes marked with one of the following
42645     ** combinations of properties.
42646     **
42647     **           in1
42648     **           in1 in2
42649     **           in1 in2 out3
42650     **           in1 in3
42651     **
42652     ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
42653     ** registers for inputs.  Variable pOut points to the output register.
42654     */
42655     if( (opProperty & OPFLG_IN1)!=0 ){
42656       assert( pOp->p1>0 );
42657       assert( pOp->p1<=p->nMem );
42658       pIn1 = &p->aMem[pOp->p1];
42659       REGISTER_TRACE(pOp->p1, pIn1);
42660       if( (opProperty & OPFLG_IN2)!=0 ){
42661         assert( pOp->p2>0 );
42662         assert( pOp->p2<=p->nMem );
42663         pIn2 = &p->aMem[pOp->p2];
42664         REGISTER_TRACE(pOp->p2, pIn2);
42665         if( (opProperty & OPFLG_OUT3)!=0 ){
42666           assert( pOp->p3>0 );
42667           assert( pOp->p3<=p->nMem );
42668           pOut = &p->aMem[pOp->p3];
42669         }
42670       }else if( (opProperty & OPFLG_IN3)!=0 ){
42671         assert( pOp->p3>0 );
42672         assert( pOp->p3<=p->nMem );
42673         pIn3 = &p->aMem[pOp->p3];
42674         REGISTER_TRACE(pOp->p3, pIn3);
42675       }
42676     }else if( (opProperty & OPFLG_IN2)!=0 ){
42677       assert( pOp->p2>0 );
42678       assert( pOp->p2<=p->nMem );
42679       pIn2 = &p->aMem[pOp->p2];
42680       REGISTER_TRACE(pOp->p2, pIn2);
42681     }else if( (opProperty & OPFLG_IN3)!=0 ){
42682       assert( pOp->p3>0 );
42683       assert( pOp->p3<=p->nMem );
42684       pIn3 = &p->aMem[pOp->p3];
42685       REGISTER_TRACE(pOp->p3, pIn3);
42686     }
42687
42688     switch( pOp->opcode ){
42689
42690 /*****************************************************************************
42691 ** What follows is a massive switch statement where each case implements a
42692 ** separate instruction in the virtual machine.  If we follow the usual
42693 ** indentation conventions, each case should be indented by 6 spaces.  But
42694 ** that is a lot of wasted space on the left margin.  So the code within
42695 ** the switch statement will break with convention and be flush-left. Another
42696 ** big comment (similar to this one) will mark the point in the code where
42697 ** we transition back to normal indentation.
42698 **
42699 ** The formatting of each case is important.  The makefile for SQLite
42700 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
42701 ** file looking for lines that begin with "case OP_".  The opcodes.h files
42702 ** will be filled with #defines that give unique integer values to each
42703 ** opcode and the opcodes.c file is filled with an array of strings where
42704 ** each string is the symbolic name for the corresponding opcode.  If the
42705 ** case statement is followed by a comment of the form "/# same as ... #/"
42706 ** that comment is used to determine the particular value of the opcode.
42707 **
42708 ** Other keywords in the comment that follows each case are used to
42709 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
42710 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
42711 ** the mkopcodeh.awk script for additional information.
42712 **
42713 ** Documentation about VDBE opcodes is generated by scanning this file
42714 ** for lines of that contain "Opcode:".  That line and all subsequent
42715 ** comment lines are used in the generation of the opcode.html documentation
42716 ** file.
42717 **
42718 ** SUMMARY:
42719 **
42720 **     Formatting is important to scripts that scan this file.
42721 **     Do not deviate from the formatting style currently in use.
42722 **
42723 *****************************************************************************/
42724
42725 /* Opcode:  Goto * P2 * * *
42726 **
42727 ** An unconditional jump to address P2.
42728 ** The next instruction executed will be 
42729 ** the one at index P2 from the beginning of
42730 ** the program.
42731 */
42732 case OP_Goto: {             /* jump */
42733   CHECK_FOR_INTERRUPT;
42734   pc = pOp->p2 - 1;
42735   break;
42736 }
42737
42738 /* Opcode:  Gosub * P2 * * *
42739 **
42740 ** Push the current address plus 1 onto the return address stack
42741 ** and then jump to address P2.
42742 **
42743 ** The return address stack is of limited depth.  If too many
42744 ** OP_Gosub operations occur without intervening OP_Returns, then
42745 ** the return address stack will fill up and processing will abort
42746 ** with a fatal error.
42747 */
42748 case OP_Gosub: {            /* jump */
42749   assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
42750   p->returnStack[p->returnDepth++] = pc+1;
42751   pc = pOp->p2 - 1;
42752   break;
42753 }
42754
42755 /* Opcode:  Return * * * * *
42756 **
42757 ** Jump immediately to the next instruction after the last unreturned
42758 ** OP_Gosub.  If an OP_Return has occurred for all OP_Gosubs, then
42759 ** processing aborts with a fatal error.
42760 */
42761 case OP_Return: {
42762   assert( p->returnDepth>0 );
42763   p->returnDepth--;
42764   pc = p->returnStack[p->returnDepth] - 1;
42765   break;
42766 }
42767
42768 /* Opcode:  Halt P1 P2 * P4 *
42769 **
42770 ** Exit immediately.  All open cursors, Fifos, etc are closed
42771 ** automatically.
42772 **
42773 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
42774 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
42775 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
42776 ** whether or not to rollback the current transaction.  Do not rollback
42777 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
42778 ** then back out all changes that have occurred during this execution of the
42779 ** VDBE, but do not rollback the transaction. 
42780 **
42781 ** If P4 is not null then it is an error message string.
42782 **
42783 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
42784 ** every program.  So a jump past the last instruction of the program
42785 ** is the same as executing Halt.
42786 */
42787 case OP_Halt: {
42788   p->rc = pOp->p1;
42789   p->pc = pc;
42790   p->errorAction = pOp->p2;
42791   if( pOp->p4.z ){
42792     sqlite3SetString(&p->zErrMsg, pOp->p4.z, (char*)0);
42793   }
42794   rc = sqlite3VdbeHalt(p);
42795   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
42796   if( rc==SQLITE_BUSY ){
42797     p->rc = rc = SQLITE_BUSY;
42798   }else{
42799     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
42800   }
42801   goto vdbe_return;
42802 }
42803
42804 /* Opcode: Integer P1 P2 * * *
42805 **
42806 ** The 32-bit integer value P1 is written into register P2.
42807 */
42808 case OP_Integer: {         /* out2-prerelease */
42809   pOut->flags = MEM_Int;
42810   pOut->u.i = pOp->p1;
42811   break;
42812 }
42813
42814 /* Opcode: Int64 * P2 * P4 *
42815 **
42816 ** P4 is a pointer to a 64-bit integer value.
42817 ** Write that value into register P2.
42818 */
42819 case OP_Int64: {           /* out2-prerelease */
42820   assert( pOp->p4.pI64!=0 );
42821   pOut->flags = MEM_Int;
42822   pOut->u.i = *pOp->p4.pI64;
42823   break;
42824 }
42825
42826 /* Opcode: Real * P2 * P4 *
42827 **
42828 ** P4 is a pointer to a 64-bit floating point value.
42829 ** Write that value into register P2.
42830 */
42831 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
42832   pOut->flags = MEM_Real;
42833   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
42834   pOut->r = *pOp->p4.pReal;
42835   break;
42836 }
42837
42838 /* Opcode: String8 * P2 * P4 *
42839 **
42840 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
42841 ** into an OP_String before it is executed for the first time.
42842 */
42843 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
42844   assert( pOp->p4.z!=0 );
42845   pOp->opcode = OP_String;
42846   pOp->p1 = strlen(pOp->p4.z);
42847
42848 #ifndef SQLITE_OMIT_UTF16
42849   if( encoding!=SQLITE_UTF8 ){
42850     sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
42851     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
42852     if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pOut) ) goto no_mem;
42853     pOut->zMalloc = 0;
42854     pOut->flags |= MEM_Static;
42855     pOut->flags &= ~MEM_Dyn;
42856     if( pOp->p4type==P4_DYNAMIC ){
42857       sqlite3_free(pOp->p4.z);
42858     }
42859     pOp->p4type = P4_DYNAMIC;
42860     pOp->p4.z = pOut->z;
42861     pOp->p1 = pOut->n;
42862     if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
42863       goto too_big;
42864     }
42865     UPDATE_MAX_BLOBSIZE(pOut);
42866     break;
42867   }
42868 #endif
42869   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
42870     goto too_big;
42871   }
42872   /* Fall through to the next case, OP_String */
42873 }
42874   
42875 /* Opcode: String P1 P2 * P4 *
42876 **
42877 ** The string value P4 of length P1 (bytes) is stored in register P2.
42878 */
42879 case OP_String: {          /* out2-prerelease */
42880   assert( pOp->p4.z!=0 );
42881   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
42882   pOut->z = pOp->p4.z;
42883   pOut->n = pOp->p1;
42884   pOut->enc = encoding;
42885   UPDATE_MAX_BLOBSIZE(pOut);
42886   break;
42887 }
42888
42889 /* Opcode: Null * P2 * * *
42890 **
42891 ** Write a NULL into register P2.
42892 */
42893 case OP_Null: {           /* out2-prerelease */
42894   break;
42895 }
42896
42897
42898 #ifndef SQLITE_OMIT_BLOB_LITERAL
42899 /* Opcode: Blob P1 P2 * P4
42900 **
42901 ** P4 points to a blob of data P1 bytes long.  Store this
42902 ** blob in register P2. This instruction is not coded directly
42903 ** by the compiler. Instead, the compiler layer specifies
42904 ** an OP_HexBlob opcode, with the hex string representation of
42905 ** the blob as P4. This opcode is transformed to an OP_Blob
42906 ** the first time it is executed.
42907 */
42908 case OP_Blob: {                /* out2-prerelease */
42909   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
42910   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
42911   pOut->enc = encoding;
42912   UPDATE_MAX_BLOBSIZE(pOut);
42913   break;
42914 }
42915 #endif /* SQLITE_OMIT_BLOB_LITERAL */
42916
42917 /* Opcode: Variable P1 P2 * * *
42918 **
42919 ** The value of variable P1 is written into register P2. A variable is
42920 ** an unknown in the original SQL string as handed to sqlite3_compile().
42921 ** Any occurance of the '?' character in the original SQL is considered
42922 ** a variable.  Variables in the SQL string are number from left to
42923 ** right beginning with 1.  The values of variables are set using the
42924 ** sqlite3_bind() API.
42925 */
42926 case OP_Variable: {           /* out2-prerelease */
42927   int j = pOp->p1 - 1;
42928   Mem *pVar;
42929   assert( j>=0 && j<p->nVar );
42930
42931   pVar = &p->aVar[j];
42932   if( sqlite3VdbeMemTooBig(pVar) ){
42933     goto too_big;
42934   }
42935   sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
42936   UPDATE_MAX_BLOBSIZE(pOut);
42937   break;
42938 }
42939
42940 /* Opcode: Move P1 P2 * * *
42941 **
42942 ** Move the value in register P1 over into register P2.  Register P1
42943 ** is left holding a NULL.  It is an error for P1 and P2 to be the
42944 ** same register.
42945 */
42946 case OP_Move: {
42947   char *zMalloc;
42948   assert( pOp->p1>0 );
42949   assert( pOp->p1<=p->nMem );
42950   pIn1 = &p->aMem[pOp->p1];
42951   REGISTER_TRACE(pOp->p1, pIn1);
42952   assert( pOp->p2>0 );
42953   assert( pOp->p2<=p->nMem );
42954   pOut = &p->aMem[pOp->p2];
42955   assert( pOut!=pIn1 );
42956   zMalloc = pOut->zMalloc;
42957   pOut->zMalloc = 0;
42958   sqlite3VdbeMemMove(pOut, pIn1);
42959   pIn1->zMalloc = zMalloc;
42960   REGISTER_TRACE(pOp->p2, pOut);
42961   break;
42962 }
42963
42964 /* Opcode: Copy P1 P2 * * *
42965 **
42966 ** Make a copy of register P1 into register P2.
42967 **
42968 ** This instruction makes a deep copy of the value.  A duplicate
42969 ** is made of any string or blob constant.  See also OP_SCopy.
42970 */
42971 case OP_Copy: {
42972   assert( pOp->p1>0 );
42973   assert( pOp->p1<=p->nMem );
42974   pIn1 = &p->aMem[pOp->p1];
42975   REGISTER_TRACE(pOp->p1, pIn1);
42976   assert( pOp->p2>0 );
42977   assert( pOp->p2<=p->nMem );
42978   pOut = &p->aMem[pOp->p2];
42979   assert( pOut!=pIn1 );
42980   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
42981   Deephemeralize(pOut);
42982   REGISTER_TRACE(pOp->p2, pOut);
42983   break;
42984 }
42985
42986 /* Opcode: SCopy P1 P2 * * *
42987 **
42988 ** Make a shallow copy of register P1 into register P2.
42989 **
42990 ** This instruction makes a shallow copy of the value.  If the value
42991 ** is a string or blob, then the copy is only a pointer to the
42992 ** original and hence if the original changes so will the copy.
42993 ** Worse, if the original is deallocated, the copy becomes invalid.
42994 ** Thus the program must guarantee that the original will not change
42995 ** during the lifetime of the copy.  Use OP_Copy to make a complete
42996 ** copy.
42997 */
42998 case OP_SCopy: {
42999   assert( pOp->p1>0 );
43000   assert( pOp->p1<=p->nMem );
43001   pIn1 = &p->aMem[pOp->p1];
43002   REGISTER_TRACE(pOp->p1, pIn1);
43003   assert( pOp->p2>0 );
43004   assert( pOp->p2<=p->nMem );
43005   pOut = &p->aMem[pOp->p2];
43006   assert( pOut!=pIn1 );
43007   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
43008   REGISTER_TRACE(pOp->p2, pOut);
43009   break;
43010 }
43011
43012 /* Opcode: ResultRow P1 P2 * * *
43013 **
43014 ** The registers P1 throught P1+P2-1 contain a single row of
43015 ** results. This opcode causes the sqlite3_step() call to terminate
43016 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
43017 ** structure to provide access to the top P1 values as the result
43018 ** row.
43019 */
43020 case OP_ResultRow: {
43021   Mem *pMem;
43022   int i;
43023   assert( p->nResColumn==pOp->p2 );
43024   assert( pOp->p1>0 );
43025   assert( pOp->p1+pOp->p2<=p->nMem );
43026
43027   /* Invalidate all ephemeral cursor row caches */
43028   p->cacheCtr = (p->cacheCtr + 2)|1;
43029
43030   /* Make sure the results of the current row are \000 terminated
43031   ** and have an assigned type.  The results are deephemeralized as
43032   ** as side effect.
43033   */
43034   pMem = p->pResultSet = &p->aMem[pOp->p1];
43035   for(i=0; i<pOp->p2; i++){
43036     sqlite3VdbeMemNulTerminate(&pMem[i]);
43037     storeTypeInfo(&pMem[i], encoding);
43038   }
43039   if( db->mallocFailed ) goto no_mem;
43040
43041   /* Return SQLITE_ROW
43042   */
43043   p->nCallback++;
43044   p->pc = pc + 1;
43045   rc = SQLITE_ROW;
43046   goto vdbe_return;
43047 }
43048
43049 /* Opcode: Concat P1 P2 P3 * *
43050 **
43051 ** Add the text in register P1 onto the end of the text in
43052 ** register P2 and store the result in register P3.
43053 ** If either the P1 or P2 text are NULL then store NULL in P3.
43054 **
43055 **   P3 = P2 || P1
43056 **
43057 ** It is illegal for P1 and P3 to be the same register. Sometimes,
43058 ** if P3 is the same register as P2, the implementation is able
43059 ** to avoid a memcpy().
43060 */
43061 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
43062   i64 nByte;
43063
43064   assert( pIn1!=pOut );
43065   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
43066     sqlite3VdbeMemSetNull(pOut);
43067     break;
43068   }
43069   ExpandBlob(pIn1);
43070   Stringify(pIn1, encoding);
43071   ExpandBlob(pIn2);
43072   Stringify(pIn2, encoding);
43073   nByte = pIn1->n + pIn2->n;
43074   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
43075     goto too_big;
43076   }
43077   MemSetTypeFlag(pOut, MEM_Str);
43078   if( sqlite3VdbeMemGrow(pOut, nByte+2, pOut==pIn2) ){
43079     goto no_mem;
43080   }
43081   if( pOut!=pIn2 ){
43082     memcpy(pOut->z, pIn2->z, pIn2->n);
43083   }
43084   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
43085   pOut->z[nByte] = 0;
43086   pOut->z[nByte+1] = 0;
43087   pOut->flags |= MEM_Term;
43088   pOut->n = nByte;
43089   pOut->enc = encoding;
43090   UPDATE_MAX_BLOBSIZE(pOut);
43091   break;
43092 }
43093
43094 /* Opcode: Add P1 P2 P3 * *
43095 **
43096 ** Add the value in register P1 to the value in register P2
43097 ** and store the result in regiser P3.
43098 ** If either input is NULL, the result is NULL.
43099 */
43100 /* Opcode: Multiply P1 P2 P3 * *
43101 **
43102 **
43103 ** Multiply the value in regiser P1 by the value in regiser P2
43104 ** and store the result in register P3.
43105 ** If either input is NULL, the result is NULL.
43106 */
43107 /* Opcode: Subtract P1 P2 P3 * *
43108 **
43109 ** Subtract the value in register P1 from the value in register P2
43110 ** and store the result in register P3.
43111 ** If either input is NULL, the result is NULL.
43112 */
43113 /* Opcode: Divide P1 P2 P3 * *
43114 **
43115 ** Divide the value in register P1 by the value in register P2
43116 ** and store the result in register P3.  If the value in register P2
43117 ** is zero, then the result is NULL.
43118 ** If either input is NULL, the result is NULL.
43119 */
43120 /* Opcode: Remainder P1 P2 P3 * *
43121 **
43122 ** Compute the remainder after integer division of the value in
43123 ** register P1 by the value in register P2 and store the result in P3. 
43124 ** If the value in register P2 is zero the result is NULL.
43125 ** If either operand is NULL, the result is NULL.
43126 */
43127 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
43128 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
43129 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
43130 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
43131 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
43132   int flags;
43133   flags = pIn1->flags | pIn2->flags;
43134   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
43135   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
43136     i64 a, b;
43137     a = pIn1->u.i;
43138     b = pIn2->u.i;
43139     switch( pOp->opcode ){
43140       case OP_Add:         b += a;       break;
43141       case OP_Subtract:    b -= a;       break;
43142       case OP_Multiply:    b *= a;       break;
43143       case OP_Divide: {
43144         if( a==0 ) goto arithmetic_result_is_null;
43145         /* Dividing the largest possible negative 64-bit integer (1<<63) by 
43146         ** -1 returns an integer too large to store in a 64-bit data-type. On
43147         ** some architectures, the value overflows to (1<<63). On others,
43148         ** a SIGFPE is issued. The following statement normalizes this
43149         ** behaviour so that all architectures behave as if integer 
43150         ** overflow occured.
43151         */
43152         if( a==-1 && b==SMALLEST_INT64 ) a = 1;
43153         b /= a;
43154         break;
43155       }
43156       default: {
43157         if( a==0 ) goto arithmetic_result_is_null;
43158         if( a==-1 ) a = 1;
43159         b %= a;
43160         break;
43161       }
43162     }
43163     pOut->u.i = b;
43164     MemSetTypeFlag(pOut, MEM_Int);
43165   }else{
43166     double a, b;
43167     a = sqlite3VdbeRealValue(pIn1);
43168     b = sqlite3VdbeRealValue(pIn2);
43169     switch( pOp->opcode ){
43170       case OP_Add:         b += a;       break;
43171       case OP_Subtract:    b -= a;       break;
43172       case OP_Multiply:    b *= a;       break;
43173       case OP_Divide: {
43174         if( a==0.0 ) goto arithmetic_result_is_null;
43175         b /= a;
43176         break;
43177       }
43178       default: {
43179         i64 ia = (i64)a;
43180         i64 ib = (i64)b;
43181         if( ia==0 ) goto arithmetic_result_is_null;
43182         if( ia==-1 ) ia = 1;
43183         b = ib % ia;
43184         break;
43185       }
43186     }
43187     if( sqlite3IsNaN(b) ){
43188       goto arithmetic_result_is_null;
43189     }
43190     pOut->r = b;
43191     MemSetTypeFlag(pOut, MEM_Real);
43192     if( (flags & MEM_Real)==0 ){
43193       sqlite3VdbeIntegerAffinity(pOut);
43194     }
43195   }
43196   break;
43197
43198 arithmetic_result_is_null:
43199   sqlite3VdbeMemSetNull(pOut);
43200   break;
43201 }
43202
43203 /* Opcode: CollSeq * * P4
43204 **
43205 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
43206 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
43207 ** be returned. This is used by the built-in min(), max() and nullif()
43208 ** functions.
43209 **
43210 ** The interface used by the implementation of the aforementioned functions
43211 ** to retrieve the collation sequence set by this opcode is not available
43212 ** publicly, only to user functions defined in func.c.
43213 */
43214 case OP_CollSeq: {
43215   assert( pOp->p4type==P4_COLLSEQ );
43216   break;
43217 }
43218
43219 /* Opcode: Function P1 P2 P3 P4 P5
43220 **
43221 ** Invoke a user function (P4 is a pointer to a Function structure that
43222 ** defines the function) with P5 arguments taken from register P2 and
43223 ** successors.  The result of the function is stored in register P3.
43224 ** Register P3 must not be one of the function inputs.
43225 **
43226 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
43227 ** function was determined to be constant at compile time. If the first
43228 ** argument was constant then bit 0 of P1 is set. This is used to determine
43229 ** whether meta data associated with a user function argument using the
43230 ** sqlite3_set_auxdata() API may be safely retained until the next
43231 ** invocation of this opcode.
43232 **
43233 ** See also: AggStep and AggFinal
43234 */
43235 case OP_Function: {
43236   int i;
43237   Mem *pArg;
43238   sqlite3_context ctx;
43239   sqlite3_value **apVal;
43240   int n = pOp->p5;
43241
43242   apVal = p->apArg;
43243   assert( apVal || n==0 );
43244
43245   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
43246   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
43247   pArg = &p->aMem[pOp->p2];
43248   for(i=0; i<n; i++, pArg++){
43249     apVal[i] = pArg;
43250     storeTypeInfo(pArg, encoding);
43251     REGISTER_TRACE(pOp->p2, pArg);
43252   }
43253
43254   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
43255   if( pOp->p4type==P4_FUNCDEF ){
43256     ctx.pFunc = pOp->p4.pFunc;
43257     ctx.pVdbeFunc = 0;
43258   }else{
43259     ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
43260     ctx.pFunc = ctx.pVdbeFunc->pFunc;
43261   }
43262
43263   assert( pOp->p3>0 && pOp->p3<=p->nMem );
43264   pOut = &p->aMem[pOp->p3];
43265   ctx.s.flags = MEM_Null;
43266   ctx.s.db = db;
43267   ctx.s.xDel = 0;
43268   ctx.s.zMalloc = 0;
43269
43270   /* The output cell may already have a buffer allocated. Move
43271   ** the pointer to ctx.s so in case the user-function can use
43272   ** the already allocated buffer instead of allocating a new one.
43273   */
43274   sqlite3VdbeMemMove(&ctx.s, pOut);
43275   MemSetTypeFlag(&ctx.s, MEM_Null);
43276
43277   ctx.isError = 0;
43278   if( ctx.pFunc->needCollSeq ){
43279     assert( pOp>p->aOp );
43280     assert( pOp[-1].p4type==P4_COLLSEQ );
43281     assert( pOp[-1].opcode==OP_CollSeq );
43282     ctx.pColl = pOp[-1].p4.pColl;
43283   }
43284   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
43285   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
43286   if( sqlite3SafetyOn(db) ){
43287     sqlite3VdbeMemRelease(&ctx.s);
43288     goto abort_due_to_misuse;
43289   }
43290   if( db->mallocFailed ){
43291     /* Even though a malloc() has failed, the implementation of the
43292     ** user function may have called an sqlite3_result_XXX() function
43293     ** to return a value. The following call releases any resources
43294     ** associated with such a value.
43295     **
43296     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
43297     ** fails also (the if(...) statement above). But if people are
43298     ** misusing sqlite, they have bigger problems than a leaked value.
43299     */
43300     sqlite3VdbeMemRelease(&ctx.s);
43301     goto no_mem;
43302   }
43303
43304   /* If any auxilary data functions have been called by this user function,
43305   ** immediately call the destructor for any non-static values.
43306   */
43307   if( ctx.pVdbeFunc ){
43308     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
43309     pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
43310     pOp->p4type = P4_VDBEFUNC;
43311   }
43312
43313   /* If the function returned an error, throw an exception */
43314   if( ctx.isError ){
43315     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
43316     rc = ctx.isError;
43317   }
43318
43319   /* Copy the result of the function into register P3 */
43320   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
43321   sqlite3VdbeMemMove(pOut, &ctx.s);
43322   if( sqlite3VdbeMemTooBig(pOut) ){
43323     goto too_big;
43324   }
43325   REGISTER_TRACE(pOp->p3, pOut);
43326   UPDATE_MAX_BLOBSIZE(pOut);
43327   break;
43328 }
43329
43330 /* Opcode: BitAnd P1 P2 P3 * *
43331 **
43332 ** Take the bit-wise AND of the values in register P1 and P2 and
43333 ** store the result in register P3.
43334 ** If either input is NULL, the result is NULL.
43335 */
43336 /* Opcode: BitOr P1 P2 P3 * *
43337 **
43338 ** Take the bit-wise OR of the values in register P1 and P2 and
43339 ** store the result in register P3.
43340 ** If either input is NULL, the result is NULL.
43341 */
43342 /* Opcode: ShiftLeft P1 P2 P3 * *
43343 **
43344 ** Shift the integer value in register P2 to the left by the
43345 ** number of bits specified by the integer in regiser P1.
43346 ** Store the result in register P3.
43347 ** If either input is NULL, the result is NULL.
43348 */
43349 /* Opcode: ShiftRight P1 P2 P3 * *
43350 **
43351 ** Shift the integer value in register P2 to the right by the
43352 ** number of bits specified by the integer in register P1.
43353 ** Store the result in register P3.
43354 ** If either input is NULL, the result is NULL.
43355 */
43356 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
43357 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
43358 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
43359 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
43360   i64 a, b;
43361
43362   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
43363     sqlite3VdbeMemSetNull(pOut);
43364     break;
43365   }
43366   a = sqlite3VdbeIntValue(pIn2);
43367   b = sqlite3VdbeIntValue(pIn1);
43368   switch( pOp->opcode ){
43369     case OP_BitAnd:      a &= b;     break;
43370     case OP_BitOr:       a |= b;     break;
43371     case OP_ShiftLeft:   a <<= b;    break;
43372     default:  assert( pOp->opcode==OP_ShiftRight );
43373                          a >>= b;    break;
43374   }
43375   pOut->u.i = a;
43376   MemSetTypeFlag(pOut, MEM_Int);
43377   break;
43378 }
43379
43380 /* Opcode: AddImm  P1 P2 * * *
43381 ** 
43382 ** Add the constant P2 the value in register P1.
43383 ** The result is always an integer.
43384 **
43385 ** To force any register to be an integer, just add 0.
43386 */
43387 case OP_AddImm: {            /* in1 */
43388   sqlite3VdbeMemIntegerify(pIn1);
43389   pIn1->u.i += pOp->p2;
43390   break;
43391 }
43392
43393 /* Opcode: ForceInt P1 P2 P3 * *
43394 **
43395 ** Convert value in register P1 into an integer.  If the value 
43396 ** in P1 is not numeric (meaning that is is a NULL or a string that
43397 ** does not look like an integer or floating point number) then
43398 ** jump to P2.  If the value in P1 is numeric then
43399 ** convert it into the least integer that is greater than or equal to its
43400 ** current value if P3==0, or to the least integer that is strictly
43401 ** greater than its current value if P3==1.
43402 */
43403 case OP_ForceInt: {            /* jump, in1 */
43404   i64 v;
43405   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
43406   if( (pIn1->flags & (MEM_Int|MEM_Real))==0 ){
43407     pc = pOp->p2 - 1;
43408     break;
43409   }
43410   if( pIn1->flags & MEM_Int ){
43411     v = pIn1->u.i + (pOp->p3!=0);
43412   }else{
43413     assert( pIn1->flags & MEM_Real );
43414     v = (sqlite3_int64)pIn1->r;
43415     if( pIn1->r>(double)v ) v++;
43416     if( pOp->p3 && pIn1->r==(double)v ) v++;
43417   }
43418   pIn1->u.i = v;
43419   MemSetTypeFlag(pIn1, MEM_Int);
43420   break;
43421 }
43422
43423 /* Opcode: MustBeInt P1 P2 * * *
43424 ** 
43425 ** Force the value in register P1 to be an integer.  If the value
43426 ** in P1 is not an integer and cannot be converted into an integer
43427 ** without data loss, then jump immediately to P2, or if P2==0
43428 ** raise an SQLITE_MISMATCH exception.
43429 */
43430 case OP_MustBeInt: {            /* jump, in1 */
43431   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
43432   if( (pIn1->flags & MEM_Int)==0 ){
43433     if( pOp->p2==0 ){
43434       rc = SQLITE_MISMATCH;
43435       goto abort_due_to_error;
43436     }else{
43437       pc = pOp->p2 - 1;
43438     }
43439   }else{
43440     MemSetTypeFlag(pIn1, MEM_Int);
43441   }
43442   break;
43443 }
43444
43445 /* Opcode: RealAffinity P1 * * * *
43446 **
43447 ** If register P1 holds an integer convert it to a real value.
43448 **
43449 ** This opcode is used when extracting information from a column that
43450 ** has REAL affinity.  Such column values may still be stored as
43451 ** integers, for space efficiency, but after extraction we want them
43452 ** to have only a real value.
43453 */
43454 case OP_RealAffinity: {                  /* in1 */
43455   if( pIn1->flags & MEM_Int ){
43456     sqlite3VdbeMemRealify(pIn1);
43457   }
43458   break;
43459 }
43460
43461 #ifndef SQLITE_OMIT_CAST
43462 /* Opcode: ToText P1 * * * *
43463 **
43464 ** Force the value in register P1 to be text.
43465 ** If the value is numeric, convert it to a string using the
43466 ** equivalent of printf().  Blob values are unchanged and
43467 ** are afterwards simply interpreted as text.
43468 **
43469 ** A NULL value is not changed by this routine.  It remains NULL.
43470 */
43471 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
43472   if( pIn1->flags & MEM_Null ) break;
43473   assert( MEM_Str==(MEM_Blob>>3) );
43474   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
43475   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
43476   rc = ExpandBlob(pIn1);
43477   assert( pIn1->flags & MEM_Str || db->mallocFailed );
43478   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
43479   UPDATE_MAX_BLOBSIZE(pIn1);
43480   break;
43481 }
43482
43483 /* Opcode: ToBlob P1 * * * *
43484 **
43485 ** Force the value in register P1 to be a BLOB.
43486 ** If the value is numeric, convert it to a string first.
43487 ** Strings are simply reinterpreted as blobs with no change
43488 ** to the underlying data.
43489 **
43490 ** A NULL value is not changed by this routine.  It remains NULL.
43491 */
43492 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
43493   if( pIn1->flags & MEM_Null ) break;
43494   if( (pIn1->flags & MEM_Blob)==0 ){
43495     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
43496     assert( pIn1->flags & MEM_Str || db->mallocFailed );
43497   }
43498   MemSetTypeFlag(pIn1, MEM_Blob);
43499   UPDATE_MAX_BLOBSIZE(pIn1);
43500   break;
43501 }
43502
43503 /* Opcode: ToNumeric P1 * * * *
43504 **
43505 ** Force the value in register P1 to be numeric (either an
43506 ** integer or a floating-point number.)
43507 ** If the value is text or blob, try to convert it to an using the
43508 ** equivalent of atoi() or atof() and store 0 if no such conversion 
43509 ** is possible.
43510 **
43511 ** A NULL value is not changed by this routine.  It remains NULL.
43512 */
43513 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
43514   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
43515     sqlite3VdbeMemNumerify(pIn1);
43516   }
43517   break;
43518 }
43519 #endif /* SQLITE_OMIT_CAST */
43520
43521 /* Opcode: ToInt P1 * * * *
43522 **
43523 ** Force the value in register P1 be an integer.  If
43524 ** The value is currently a real number, drop its fractional part.
43525 ** If the value is text or blob, try to convert it to an integer using the
43526 ** equivalent of atoi() and store 0 if no such conversion is possible.
43527 **
43528 ** A NULL value is not changed by this routine.  It remains NULL.
43529 */
43530 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
43531   if( (pIn1->flags & MEM_Null)==0 ){
43532     sqlite3VdbeMemIntegerify(pIn1);
43533   }
43534   break;
43535 }
43536
43537 #ifndef SQLITE_OMIT_CAST
43538 /* Opcode: ToReal P1 * * * *
43539 **
43540 ** Force the value in register P1 to be a floating point number.
43541 ** If The value is currently an integer, convert it.
43542 ** If the value is text or blob, try to convert it to an integer using the
43543 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
43544 **
43545 ** A NULL value is not changed by this routine.  It remains NULL.
43546 */
43547 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
43548   if( (pIn1->flags & MEM_Null)==0 ){
43549     sqlite3VdbeMemRealify(pIn1);
43550   }
43551   break;
43552 }
43553 #endif /* SQLITE_OMIT_CAST */
43554
43555 /* Opcode: Lt P1 P2 P3 P4 P5
43556 **
43557 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
43558 ** jump to address P2.  
43559 **
43560 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
43561 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
43562 ** bit is clear then fall thru if either operand is NULL.
43563 **
43564 ** If the SQLITE_NULLEQUAL bit of P5 is set then treat NULL operands
43565 ** as being equal to one another.  Normally NULLs are not equal to 
43566 ** anything including other NULLs.
43567 **
43568 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
43569 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
43570 ** to coerce both inputs according to this affinity before the
43571 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
43572 ** affinity is used. Note that the affinity conversions are stored
43573 ** back into the input registers P1 and P3.  So this opcode can cause
43574 ** persistent changes to registers P1 and P3.
43575 **
43576 ** Once any conversions have taken place, and neither value is NULL, 
43577 ** the values are compared. If both values are blobs then memcmp() is
43578 ** used to determine the results of the comparison.  If both values
43579 ** are text, then the appropriate collating function specified in
43580 ** P4 is  used to do the comparison.  If P4 is not specified then
43581 ** memcmp() is used to compare text string.  If both values are
43582 ** numeric, then a numeric comparison is used. If the two values
43583 ** are of different types, then numbers are considered less than
43584 ** strings and strings are considered less than blobs.
43585 **
43586 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
43587 ** store a boolean result (either 0, or 1, or NULL) in register P2.
43588 */
43589 /* Opcode: Ne P1 P2 P3 P4 P5
43590 **
43591 ** This works just like the Lt opcode except that the jump is taken if
43592 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
43593 ** additional information.
43594 */
43595 /* Opcode: Eq P1 P2 P3 P4 P5
43596 **
43597 ** This works just like the Lt opcode except that the jump is taken if
43598 ** the operands in registers P1 and P3 are equal.
43599 ** See the Lt opcode for additional information.
43600 */
43601 /* Opcode: Le P1 P2 P3 P4 P5
43602 **
43603 ** This works just like the Lt opcode except that the jump is taken if
43604 ** the content of register P3 is less than or equal to the content of
43605 ** register P1.  See the Lt opcode for additional information.
43606 */
43607 /* Opcode: Gt P1 P2 P3 P4 P5
43608 **
43609 ** This works just like the Lt opcode except that the jump is taken if
43610 ** the content of register P3 is greater than the content of
43611 ** register P1.  See the Lt opcode for additional information.
43612 */
43613 /* Opcode: Ge P1 P2 P3 P4 P5
43614 **
43615 ** This works just like the Lt opcode except that the jump is taken if
43616 ** the content of register P3 is greater than or equal to the content of
43617 ** register P1.  See the Lt opcode for additional information.
43618 */
43619 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
43620 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
43621 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
43622 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
43623 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
43624 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
43625   int flags;
43626   int res;
43627   char affinity;
43628   Mem x1, x3;
43629
43630   flags = pIn1->flags|pIn3->flags;
43631
43632   if( flags&MEM_Null ){
43633     if( (pOp->p5 & SQLITE_NULLEQUAL)!=0 ){
43634       /*
43635       ** When SQLITE_NULLEQUAL set and either operand is NULL
43636       ** then both operands are converted to integers prior to being 
43637       ** passed down into the normal comparison logic below.  
43638       ** NULL operands are converted to zero and non-NULL operands
43639       ** are converted to 1.  Thus, for example, with SQLITE_NULLEQUAL
43640       ** set,  NULL==NULL is true whereas it would normally NULL.
43641       ** Similarly,  NULL!=123 is true.
43642       */
43643       x1.flags = MEM_Int;
43644       x1.u.i = (pIn1->flags & MEM_Null)==0;
43645       pIn1 = &x1;
43646       x3.flags = MEM_Int;
43647       x3.u.i = (pIn3->flags & MEM_Null)==0;
43648       pIn3 = &x3;
43649     }else{
43650       /* If the SQLITE_NULLEQUAL bit is clear and either operand is NULL then
43651       ** the result is always NULL.  The jump is taken if the 
43652       ** SQLITE_JUMPIFNULL bit is set.
43653       */
43654       if( pOp->p5 & SQLITE_STOREP2 ){
43655         pOut = &p->aMem[pOp->p2];
43656         MemSetTypeFlag(pOut, MEM_Null);
43657         REGISTER_TRACE(pOp->p2, pOut);
43658       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
43659         pc = pOp->p2-1;
43660       }
43661       break;
43662     }
43663   }
43664
43665   affinity = pOp->p5 & SQLITE_AFF_MASK;
43666   if( affinity ){
43667     applyAffinity(pIn1, affinity, encoding);
43668     applyAffinity(pIn3, affinity, encoding);
43669   }
43670
43671   assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
43672   ExpandBlob(pIn1);
43673   ExpandBlob(pIn3);
43674   res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
43675   switch( pOp->opcode ){
43676     case OP_Eq:    res = res==0;     break;
43677     case OP_Ne:    res = res!=0;     break;
43678     case OP_Lt:    res = res<0;      break;
43679     case OP_Le:    res = res<=0;     break;
43680     case OP_Gt:    res = res>0;      break;
43681     default:       res = res>=0;     break;
43682   }
43683
43684   if( pOp->p5 & SQLITE_STOREP2 ){
43685     pOut = &p->aMem[pOp->p2];
43686     MemSetTypeFlag(pOut, MEM_Int);
43687     pOut->u.i = res;
43688     REGISTER_TRACE(pOp->p2, pOut);
43689   }else if( res ){
43690     pc = pOp->p2-1;
43691   }
43692   break;
43693 }
43694
43695 /* Opcode: And P1 P2 P3 * *
43696 **
43697 ** Take the logical AND of the values in registers P1 and P2 and
43698 ** write the result into register P3.
43699 **
43700 ** If either P1 or P2 is 0 (false) then the result is 0 even if
43701 ** the other input is NULL.  A NULL and true or two NULLs give
43702 ** a NULL output.
43703 */
43704 /* Opcode: Or P1 P2 P3 * *
43705 **
43706 ** Take the logical OR of the values in register P1 and P2 and
43707 ** store the answer in register P3.
43708 **
43709 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
43710 ** even if the other input is NULL.  A NULL and false or two NULLs
43711 ** give a NULL output.
43712 */
43713 case OP_And:              /* same as TK_AND, in1, in2, out3 */
43714 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
43715   int v1, v2;    /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
43716
43717   if( pIn1->flags & MEM_Null ){
43718     v1 = 2;
43719   }else{
43720     v1 = sqlite3VdbeIntValue(pIn1)!=0;
43721   }
43722   if( pIn2->flags & MEM_Null ){
43723     v2 = 2;
43724   }else{
43725     v2 = sqlite3VdbeIntValue(pIn2)!=0;
43726   }
43727   if( pOp->opcode==OP_And ){
43728     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
43729     v1 = and_logic[v1*3+v2];
43730   }else{
43731     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
43732     v1 = or_logic[v1*3+v2];
43733   }
43734   if( v1==2 ){
43735     MemSetTypeFlag(pOut, MEM_Null);
43736   }else{
43737     pOut->u.i = v1;
43738     MemSetTypeFlag(pOut, MEM_Int);
43739   }
43740   break;
43741 }
43742
43743 /* Opcode: Not P1 * * * *
43744 **
43745 ** Interpret the value in register P1 as a boolean value.  Replace it
43746 ** with its complement.  If the value in register P1 is NULL its value
43747 ** is unchanged.
43748 */
43749 case OP_Not: {                /* same as TK_NOT, in1 */
43750   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
43751   sqlite3VdbeMemIntegerify(pIn1);
43752   pIn1->u.i = !pIn1->u.i;
43753   assert( pIn1->flags&MEM_Int );
43754   break;
43755 }
43756
43757 /* Opcode: BitNot P1 * * * *
43758 **
43759 ** Interpret the content of register P1 as an integer.  Replace it
43760 ** with its ones-complement.  If the value is originally NULL, leave
43761 ** it unchanged.
43762 */
43763 case OP_BitNot: {             /* same as TK_BITNOT, in1 */
43764   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
43765   sqlite3VdbeMemIntegerify(pIn1);
43766   pIn1->u.i = ~pIn1->u.i;
43767   assert( pIn1->flags&MEM_Int );
43768   break;
43769 }
43770
43771 /* Opcode: If P1 P2 P3 * *
43772 **
43773 ** Jump to P2 if the value in register P1 is true.  The value is
43774 ** is considered true if it is numeric and non-zero.  If the value
43775 ** in P1 is NULL then take the jump if P3 is true.
43776 */
43777 /* Opcode: IfNot P1 P2 P3 * *
43778 **
43779 ** Jump to P2 if the value in register P1 is False.  The value is
43780 ** is considered true if it has a numeric value of zero.  If the value
43781 ** in P1 is NULL then take the jump if P3 is true.
43782 */
43783 case OP_If:                 /* jump, in1 */
43784 case OP_IfNot: {            /* jump, in1 */
43785   int c;
43786   if( pIn1->flags & MEM_Null ){
43787     c = pOp->p3;
43788   }else{
43789 #ifdef SQLITE_OMIT_FLOATING_POINT
43790     c = sqlite3VdbeIntValue(pIn1);
43791 #else
43792     c = sqlite3VdbeRealValue(pIn1)!=0.0;
43793 #endif
43794     if( pOp->opcode==OP_IfNot ) c = !c;
43795   }
43796   if( c ){
43797     pc = pOp->p2-1;
43798   }
43799   break;
43800 }
43801
43802 /* Opcode: IsNull P1 P2 P3 * *
43803 **
43804 ** Jump to P2 if the value in register P1 is NULL.  If P3 is greater
43805 ** than zero, then check all values reg(P1), reg(P1+1), 
43806 ** reg(P1+2), ..., reg(P1+P3-1).
43807 */
43808 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
43809   int n = pOp->p3;
43810   assert( pOp->p3==0 || pOp->p1>0 );
43811   do{
43812     if( (pIn1->flags & MEM_Null)!=0 ){
43813       pc = pOp->p2 - 1;
43814       break;
43815     }
43816     pIn1++;
43817   }while( --n > 0 );
43818   break;
43819 }
43820
43821 /* Opcode: NotNull P1 P2 * * *
43822 **
43823 ** Jump to P2 if the value in register P1 is not NULL.  
43824 */
43825 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
43826   if( (pIn1->flags & MEM_Null)==0 ){
43827     pc = pOp->p2 - 1;
43828   }
43829   break;
43830 }
43831
43832 /* Opcode: SetNumColumns * P2 * * *
43833 **
43834 ** This opcode sets the number of columns for the cursor opened by the
43835 ** following instruction to P2.
43836 **
43837 ** An OP_SetNumColumns is only useful if it occurs immediately before 
43838 ** one of the following opcodes:
43839 **
43840 **     OpenRead
43841 **     OpenWrite
43842 **     OpenPseudo
43843 **
43844 ** If the OP_Column opcode is to be executed on a cursor, then
43845 ** this opcode must be present immediately before the opcode that
43846 ** opens the cursor.
43847 */
43848 case OP_SetNumColumns: {
43849   break;
43850 }
43851
43852 /* Opcode: Column P1 P2 P3 P4 *
43853 **
43854 ** Interpret the data that cursor P1 points to as a structure built using
43855 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
43856 ** information about the format of the data.)  Extract the P2-th column
43857 ** from this record.  If there are less that (P2+1) 
43858 ** values in the record, extract a NULL.
43859 **
43860 ** The value extracted is stored in register P3.
43861 **
43862 ** If the KeyAsData opcode has previously executed on this cursor, then the
43863 ** field might be extracted from the key rather than the data.
43864 **
43865 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
43866 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
43867 ** the result.
43868 */
43869 case OP_Column: {
43870   u32 payloadSize;   /* Number of bytes in the record */
43871   int p1 = pOp->p1;  /* P1 value of the opcode */
43872   int p2 = pOp->p2;  /* column number to retrieve */
43873   Cursor *pC = 0;    /* The VDBE cursor */
43874   char *zRec;        /* Pointer to complete record-data */
43875   BtCursor *pCrsr;   /* The BTree cursor */
43876   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
43877   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
43878   u32 nField;        /* number of fields in the record */
43879   int len;           /* The length of the serialized data for the column */
43880   int i;             /* Loop counter */
43881   char *zData;       /* Part of the record being decoded */
43882   Mem *pDest;        /* Where to write the extracted value */
43883   Mem sMem;          /* For storing the record being decoded */
43884
43885   sMem.flags = 0;
43886   sMem.db = 0;
43887   sMem.zMalloc = 0;
43888   assert( p1<p->nCursor );
43889   assert( pOp->p3>0 && pOp->p3<=p->nMem );
43890   pDest = &p->aMem[pOp->p3];
43891   MemSetTypeFlag(pDest, MEM_Null);
43892
43893   /* This block sets the variable payloadSize to be the total number of
43894   ** bytes in the record.
43895   **
43896   ** zRec is set to be the complete text of the record if it is available.
43897   ** The complete record text is always available for pseudo-tables
43898   ** If the record is stored in a cursor, the complete record text
43899   ** might be available in the  pC->aRow cache.  Or it might not be.
43900   ** If the data is unavailable,  zRec is set to NULL.
43901   **
43902   ** We also compute the number of columns in the record.  For cursors,
43903   ** the number of columns is stored in the Cursor.nField element.
43904   */
43905   pC = p->apCsr[p1];
43906   assert( pC!=0 );
43907 #ifndef SQLITE_OMIT_VIRTUALTABLE
43908   assert( pC->pVtabCursor==0 );
43909 #endif
43910   if( pC->pCursor!=0 ){
43911     /* The record is stored in a B-Tree */
43912     rc = sqlite3VdbeCursorMoveto(pC);
43913     if( rc ) goto abort_due_to_error;
43914     zRec = 0;
43915     pCrsr = pC->pCursor;
43916     if( pC->nullRow ){
43917       payloadSize = 0;
43918     }else if( pC->cacheStatus==p->cacheCtr ){
43919       payloadSize = pC->payloadSize;
43920       zRec = (char*)pC->aRow;
43921     }else if( pC->isIndex ){
43922       i64 payloadSize64;
43923       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
43924       payloadSize = payloadSize64;
43925     }else{
43926       sqlite3BtreeDataSize(pCrsr, &payloadSize);
43927     }
43928     nField = pC->nField;
43929   }else{
43930     assert( pC->pseudoTable );
43931     /* The record is the sole entry of a pseudo-table */
43932     payloadSize = pC->nData;
43933     zRec = pC->pData;
43934     pC->cacheStatus = CACHE_STALE;
43935     assert( payloadSize==0 || zRec!=0 );
43936     nField = pC->nField;
43937     pCrsr = 0;
43938   }
43939
43940   /* If payloadSize is 0, then just store a NULL */
43941   if( payloadSize==0 ){
43942     assert( pDest->flags&MEM_Null );
43943     goto op_column_out;
43944   }
43945   if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
43946     goto too_big;
43947   }
43948
43949   assert( p2<nField );
43950
43951   /* Read and parse the table header.  Store the results of the parse
43952   ** into the record header cache fields of the cursor.
43953   */
43954   aType = pC->aType;
43955   if( pC->cacheStatus==p->cacheCtr ){
43956     aOffset = pC->aOffset;
43957   }else{
43958     u8 *zIdx;        /* Index into header */
43959     u8 *zEndHdr;     /* Pointer to first byte after the header */
43960     u32 offset;      /* Offset into the data */
43961     int szHdrSz;     /* Size of the header size field at start of record */
43962     int avail;       /* Number of bytes of available data */
43963
43964     assert(aType);
43965     pC->aOffset = aOffset = &aType[nField];
43966     pC->payloadSize = payloadSize;
43967     pC->cacheStatus = p->cacheCtr;
43968
43969     /* Figure out how many bytes are in the header */
43970     if( zRec ){
43971       zData = zRec;
43972     }else{
43973       if( pC->isIndex ){
43974         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
43975       }else{
43976         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
43977       }
43978       /* If KeyFetch()/DataFetch() managed to get the entire payload,
43979       ** save the payload in the pC->aRow cache.  That will save us from
43980       ** having to make additional calls to fetch the content portion of
43981       ** the record.
43982       */
43983       if( avail>=payloadSize ){
43984         zRec = zData;
43985         pC->aRow = (u8*)zData;
43986       }else{
43987         pC->aRow = 0;
43988       }
43989     }
43990     /* The following assert is true in all cases accept when
43991     ** the database file has been corrupted externally.
43992     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
43993     szHdrSz = getVarint32((u8*)zData, offset);
43994
43995     /* The KeyFetch() or DataFetch() above are fast and will get the entire
43996     ** record header in most cases.  But they will fail to get the complete
43997     ** record header if the record header does not fit on a single page
43998     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
43999     ** acquire the complete header text.
44000     */
44001     if( !zRec && avail<offset ){
44002       sMem.flags = 0;
44003       sMem.db = 0;
44004       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
44005       if( rc!=SQLITE_OK ){
44006         goto op_column_out;
44007       }
44008       zData = sMem.z;
44009     }
44010     zEndHdr = (u8 *)&zData[offset];
44011     zIdx = (u8 *)&zData[szHdrSz];
44012
44013     /* Scan the header and use it to fill in the aType[] and aOffset[]
44014     ** arrays.  aType[i] will contain the type integer for the i-th
44015     ** column and aOffset[i] will contain the offset from the beginning
44016     ** of the record to the start of the data for the i-th column
44017     */
44018     for(i=0; i<nField; i++){
44019       if( zIdx<zEndHdr ){
44020         aOffset[i] = offset;
44021         zIdx += getVarint32(zIdx, aType[i]);
44022         offset += sqlite3VdbeSerialTypeLen(aType[i]);
44023       }else{
44024         /* If i is less that nField, then there are less fields in this
44025         ** record than SetNumColumns indicated there are columns in the
44026         ** table. Set the offset for any extra columns not present in
44027         ** the record to 0. This tells code below to store a NULL
44028         ** instead of deserializing a value from the record.
44029         */
44030         aOffset[i] = 0;
44031       }
44032     }
44033     sqlite3VdbeMemRelease(&sMem);
44034     sMem.flags = MEM_Null;
44035
44036     /* If we have read more header data than was contained in the header,
44037     ** or if the end of the last field appears to be past the end of the
44038     ** record, or if the end of the last field appears to be before the end
44039     ** of the record (when all fields present), then we must be dealing 
44040     ** with a corrupt database.
44041     */
44042     if( zIdx>zEndHdr || offset>payloadSize || (zIdx==zEndHdr && offset!=payloadSize) ){
44043       rc = SQLITE_CORRUPT_BKPT;
44044       goto op_column_out;
44045     }
44046   }
44047
44048   /* Get the column information. If aOffset[p2] is non-zero, then 
44049   ** deserialize the value from the record. If aOffset[p2] is zero,
44050   ** then there are not enough fields in the record to satisfy the
44051   ** request.  In this case, set the value NULL or to P4 if P4 is
44052   ** a pointer to a Mem object.
44053   */
44054   if( aOffset[p2] ){
44055     assert( rc==SQLITE_OK );
44056     if( zRec ){
44057       if( pDest->flags&MEM_Dyn ){
44058         sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], &sMem);
44059         sMem.db = db; 
44060         rc = sqlite3VdbeMemCopy(pDest, &sMem);
44061         assert( !(sMem.flags&MEM_Dyn) );
44062         if( rc!=SQLITE_OK ){
44063           goto op_column_out;
44064         }
44065       }else{
44066         sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
44067       }
44068     }else{
44069       len = sqlite3VdbeSerialTypeLen(aType[p2]);
44070       sqlite3VdbeMemMove(&sMem, pDest);
44071       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
44072       if( rc!=SQLITE_OK ){
44073         goto op_column_out;
44074       }
44075       zData = sMem.z;
44076       sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
44077     }
44078     pDest->enc = encoding;
44079   }else{
44080     if( pOp->p4type==P4_MEM ){
44081       sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
44082     }else{
44083       assert( pDest->flags&MEM_Null );
44084     }
44085   }
44086
44087   /* If we dynamically allocated space to hold the data (in the
44088   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
44089   ** dynamically allocated space over to the pDest structure.
44090   ** This prevents a memory copy.
44091   */
44092   if( sMem.zMalloc ){
44093     assert( sMem.z==sMem.zMalloc );
44094     assert( !(pDest->flags & MEM_Dyn) );
44095     assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
44096     pDest->flags &= ~(MEM_Ephem|MEM_Static);
44097     pDest->flags |= MEM_Term;
44098     pDest->z = sMem.z;
44099     pDest->zMalloc = sMem.zMalloc;
44100   }
44101
44102   rc = sqlite3VdbeMemMakeWriteable(pDest);
44103
44104 op_column_out:
44105   UPDATE_MAX_BLOBSIZE(pDest);
44106   REGISTER_TRACE(pOp->p3, pDest);
44107   break;
44108 }
44109
44110 /* Opcode: Affinity P1 P2 * P4 *
44111 **
44112 ** Apply affinities to a range of P2 registers starting with P1.
44113 **
44114 ** P4 is a string that is P2 characters long. The nth character of the
44115 ** string indicates the column affinity that should be used for the nth
44116 ** memory cell in the range.
44117 */
44118 case OP_Affinity: {
44119   char *zAffinity = pOp->p4.z;
44120   Mem *pData0 = &p->aMem[pOp->p1];
44121   Mem *pLast = &pData0[pOp->p2-1];
44122   Mem *pRec;
44123
44124   for(pRec=pData0; pRec<=pLast; pRec++){
44125     ExpandBlob(pRec);
44126     applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
44127   }
44128   break;
44129 }
44130
44131 /* Opcode: MakeRecord P1 P2 P3 P4 *
44132 **
44133 ** Convert P2 registers beginning with P1 into a single entry
44134 ** suitable for use as a data record in a database table or as a key
44135 ** in an index.  The details of the format are irrelavant as long as
44136 ** the OP_Column opcode can decode the record later.
44137 ** Refer to source code comments for the details of the record
44138 ** format.
44139 **
44140 ** P4 may be a string that is P2 characters long.  The nth character of the
44141 ** string indicates the column affinity that should be used for the nth
44142 ** field of the index key.
44143 **
44144 ** The mapping from character to affinity is given by the SQLITE_AFF_
44145 ** macros defined in sqliteInt.h.
44146 **
44147 ** If P4 is NULL then all index fields have the affinity NONE.
44148 */
44149 case OP_MakeRecord: {
44150   /* Assuming the record contains N fields, the record format looks
44151   ** like this:
44152   **
44153   ** ------------------------------------------------------------------------
44154   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
44155   ** ------------------------------------------------------------------------
44156   **
44157   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
44158   ** and so froth.
44159   **
44160   ** Each type field is a varint representing the serial type of the 
44161   ** corresponding data element (see sqlite3VdbeSerialType()). The
44162   ** hdr-size field is also a varint which is the offset from the beginning
44163   ** of the record to data0.
44164   */
44165   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
44166   Mem *pRec;             /* The new record */
44167   u64 nData = 0;         /* Number of bytes of data space */
44168   int nHdr = 0;          /* Number of bytes of header space */
44169   u64 nByte = 0;         /* Data space required for this record */
44170   int nZero = 0;         /* Number of zero bytes at the end of the record */
44171   int nVarint;           /* Number of bytes in a varint */
44172   u32 serial_type;       /* Type field */
44173   Mem *pData0;           /* First field to be combined into the record */
44174   Mem *pLast;            /* Last field of the record */
44175   int nField;            /* Number of fields in the record */
44176   char *zAffinity;       /* The affinity string for the record */
44177   int file_format;       /* File format to use for encoding */
44178   int i;                 /* Space used in zNewRecord[] */
44179
44180   nField = pOp->p1;
44181   zAffinity = pOp->p4.z;
44182   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
44183   pData0 = &p->aMem[nField];
44184   nField = pOp->p2;
44185   pLast = &pData0[nField-1];
44186   file_format = p->minWriteFileFormat;
44187
44188   /* Loop through the elements that will make up the record to figure
44189   ** out how much space is required for the new record.
44190   */
44191   for(pRec=pData0; pRec<=pLast; pRec++){
44192     int len;
44193     if( zAffinity ){
44194       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
44195     }
44196     if( pRec->flags&MEM_Zero && pRec->n>0 ){
44197       sqlite3VdbeMemExpandBlob(pRec);
44198     }
44199     serial_type = sqlite3VdbeSerialType(pRec, file_format);
44200     len = sqlite3VdbeSerialTypeLen(serial_type);
44201     nData += len;
44202     nHdr += sqlite3VarintLen(serial_type);
44203     if( pRec->flags & MEM_Zero ){
44204       /* Only pure zero-filled BLOBs can be input to this Opcode.
44205       ** We do not allow blobs with a prefix and a zero-filled tail. */
44206       nZero += pRec->u.i;
44207     }else if( len ){
44208       nZero = 0;
44209     }
44210   }
44211
44212   /* Add the initial header varint and total the size */
44213   nHdr += nVarint = sqlite3VarintLen(nHdr);
44214   if( nVarint<sqlite3VarintLen(nHdr) ){
44215     nHdr++;
44216   }
44217   nByte = nHdr+nData-nZero;
44218   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
44219     goto too_big;
44220   }
44221
44222   /* Make sure the output register has a buffer large enough to store 
44223   ** the new record. The output register (pOp->p3) is not allowed to
44224   ** be one of the input registers (because the following call to
44225   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
44226   */
44227   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
44228   pOut = &p->aMem[pOp->p3];
44229   if( sqlite3VdbeMemGrow(pOut, nByte, 0) ){
44230     goto no_mem;
44231   }
44232   zNewRecord = (u8 *)pOut->z;
44233
44234   /* Write the record */
44235   i = putVarint32(zNewRecord, nHdr);
44236   for(pRec=pData0; pRec<=pLast; pRec++){
44237     serial_type = sqlite3VdbeSerialType(pRec, file_format);
44238     i += putVarint32(&zNewRecord[i], serial_type);      /* serial type */
44239   }
44240   for(pRec=pData0; pRec<=pLast; pRec++){  /* serial data */
44241     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
44242   }
44243   assert( i==nByte );
44244
44245   assert( pOp->p3>0 && pOp->p3<=p->nMem );
44246   pOut->n = nByte;
44247   pOut->flags = MEM_Blob | MEM_Dyn;
44248   pOut->xDel = 0;
44249   if( nZero ){
44250     pOut->u.i = nZero;
44251     pOut->flags |= MEM_Zero;
44252   }
44253   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
44254   REGISTER_TRACE(pOp->p3, pOut);
44255   UPDATE_MAX_BLOBSIZE(pOut);
44256   break;
44257 }
44258
44259 /* Opcode: Statement P1 * * * *
44260 **
44261 ** Begin an individual statement transaction which is part of a larger
44262 ** transaction.  This is needed so that the statement
44263 ** can be rolled back after an error without having to roll back the
44264 ** entire transaction.  The statement transaction will automatically
44265 ** commit when the VDBE halts.
44266 **
44267 ** If the database connection is currently in autocommit mode (that 
44268 ** is to say, if it is in between BEGIN and COMMIT)
44269 ** and if there are no other active statements on the same database
44270 ** connection, then this operation is a no-op.  No statement transaction
44271 ** is needed since any error can use the normal ROLLBACK process to
44272 ** undo changes.
44273 **
44274 ** If a statement transaction is started, then a statement journal file
44275 ** will be allocated and initialized.
44276 **
44277 ** The statement is begun on the database file with index P1.  The main
44278 ** database file has an index of 0 and the file used for temporary tables
44279 ** has an index of 1.
44280 */
44281 case OP_Statement: {
44282   if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
44283     int i = pOp->p1;
44284     Btree *pBt;
44285     assert( i>=0 && i<db->nDb );
44286     assert( db->aDb[i].pBt!=0 );
44287     pBt = db->aDb[i].pBt;
44288     assert( sqlite3BtreeIsInTrans(pBt) );
44289     assert( (p->btreeMask & (1<<i))!=0 );
44290     if( !sqlite3BtreeIsInStmt(pBt) ){
44291       rc = sqlite3BtreeBeginStmt(pBt);
44292       p->openedStatement = 1;
44293     }
44294   }
44295   break;
44296 }
44297
44298 /* Opcode: AutoCommit P1 P2 * * *
44299 **
44300 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
44301 ** back any currently active btree transactions. If there are any active
44302 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
44303 **
44304 ** This instruction causes the VM to halt.
44305 */
44306 case OP_AutoCommit: {
44307   u8 i = pOp->p1;
44308   u8 rollback = pOp->p2;
44309
44310   assert( i==1 || i==0 );
44311   assert( i==1 || rollback==0 );
44312
44313   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
44314
44315   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
44316     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
44317     ** still running, and a transaction is active, return an error indicating
44318     ** that the other VMs must complete first. 
44319     */
44320     sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit", 
44321         " transaction - SQL statements in progress", (char*)0);
44322     rc = SQLITE_ERROR;
44323   }else if( i!=db->autoCommit ){
44324     if( pOp->p2 ){
44325       assert( i==1 );
44326       sqlite3RollbackAll(db);
44327       db->autoCommit = 1;
44328     }else{
44329       db->autoCommit = i;
44330       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
44331         p->pc = pc;
44332         db->autoCommit = 1-i;
44333         p->rc = rc = SQLITE_BUSY;
44334         goto vdbe_return;
44335       }
44336     }
44337     if( p->rc==SQLITE_OK ){
44338       rc = SQLITE_DONE;
44339     }else{
44340       rc = SQLITE_ERROR;
44341     }
44342     goto vdbe_return;
44343   }else{
44344     sqlite3SetString(&p->zErrMsg,
44345         (!i)?"cannot start a transaction within a transaction":(
44346         (rollback)?"cannot rollback - no transaction is active":
44347                    "cannot commit - no transaction is active"), (char*)0);
44348          
44349     rc = SQLITE_ERROR;
44350   }
44351   break;
44352 }
44353
44354 /* Opcode: Transaction P1 P2 * * *
44355 **
44356 ** Begin a transaction.  The transaction ends when a Commit or Rollback
44357 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
44358 ** transaction might also be rolled back if an error is encountered.
44359 **
44360 ** P1 is the index of the database file on which the transaction is
44361 ** started.  Index 0 is the main database file and index 1 is the
44362 ** file used for temporary tables.  Indices of 2 or more are used for
44363 ** attached databases.
44364 **
44365 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
44366 ** obtained on the database file when a write-transaction is started.  No
44367 ** other process can start another write transaction while this transaction is
44368 ** underway.  Starting a write transaction also creates a rollback journal. A
44369 ** write transaction must be started before any changes can be made to the
44370 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
44371 ** on the file.
44372 **
44373 ** If P2 is zero, then a read-lock is obtained on the database file.
44374 */
44375 case OP_Transaction: {
44376   int i = pOp->p1;
44377   Btree *pBt;
44378
44379   assert( i>=0 && i<db->nDb );
44380   assert( (p->btreeMask & (1<<i))!=0 );
44381   pBt = db->aDb[i].pBt;
44382
44383   if( pBt ){
44384     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
44385     if( rc==SQLITE_BUSY ){
44386       p->pc = pc;
44387       p->rc = rc = SQLITE_BUSY;
44388       goto vdbe_return;
44389     }
44390     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
44391       goto abort_due_to_error;
44392     }
44393   }
44394   break;
44395 }
44396
44397 /* Opcode: ReadCookie P1 P2 P3 * *
44398 **
44399 ** Read cookie number P3 from database P1 and write it into register P2.
44400 ** P3==0 is the schema version.  P3==1 is the database format.
44401 ** P3==2 is the recommended pager cache size, and so forth.  P1==0 is
44402 ** the main database file and P1==1 is the database file used to store
44403 ** temporary tables.
44404 **
44405 ** If P1 is negative, then this is a request to read the size of a
44406 ** databases free-list. P3 must be set to 1 in this case. The actual
44407 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
44408 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
44409 **
44410 ** There must be a read-lock on the database (either a transaction
44411 ** must be started or there must be an open cursor) before
44412 ** executing this instruction.
44413 */
44414 case OP_ReadCookie: {               /* out2-prerelease */
44415   int iMeta;
44416   int iDb = pOp->p1;
44417   int iCookie = pOp->p3;
44418
44419   assert( pOp->p3<SQLITE_N_BTREE_META );
44420   if( iDb<0 ){
44421     iDb = (-1*(iDb+1));
44422     iCookie *= -1;
44423   }
44424   assert( iDb>=0 && iDb<db->nDb );
44425   assert( db->aDb[iDb].pBt!=0 );
44426   assert( (p->btreeMask & (1<<iDb))!=0 );
44427   /* The indexing of meta values at the schema layer is off by one from
44428   ** the indexing in the btree layer.  The btree considers meta[0] to
44429   ** be the number of free pages in the database (a read-only value)
44430   ** and meta[1] to be the schema cookie.  The schema layer considers
44431   ** meta[1] to be the schema cookie.  So we have to shift the index
44432   ** by one in the following statement.
44433   */
44434   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
44435   pOut->u.i = iMeta;
44436   MemSetTypeFlag(pOut, MEM_Int);
44437   break;
44438 }
44439
44440 /* Opcode: SetCookie P1 P2 P3 * *
44441 **
44442 ** Write the content of register P3 (interpreted as an integer)
44443 ** into cookie number P2 of database P1.
44444 ** P2==0 is the schema version.  P2==1 is the database format.
44445 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
44446 ** the main database file and P1==1 is the database file used to store
44447 ** temporary tables.
44448 **
44449 ** A transaction must be started before executing this opcode.
44450 */
44451 case OP_SetCookie: {       /* in3 */
44452   Db *pDb;
44453   assert( pOp->p2<SQLITE_N_BTREE_META );
44454   assert( pOp->p1>=0 && pOp->p1<db->nDb );
44455   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
44456   pDb = &db->aDb[pOp->p1];
44457   assert( pDb->pBt!=0 );
44458   sqlite3VdbeMemIntegerify(pIn3);
44459   /* See note about index shifting on OP_ReadCookie */
44460   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
44461   if( pOp->p2==0 ){
44462     /* When the schema cookie changes, record the new cookie internally */
44463     pDb->pSchema->schema_cookie = pIn3->u.i;
44464     db->flags |= SQLITE_InternChanges;
44465   }else if( pOp->p2==1 ){
44466     /* Record changes in the file format */
44467     pDb->pSchema->file_format = pIn3->u.i;
44468   }
44469   if( pOp->p1==1 ){
44470     /* Invalidate all prepared statements whenever the TEMP database
44471     ** schema is changed.  Ticket #1644 */
44472     sqlite3ExpirePreparedStatements(db);
44473   }
44474   break;
44475 }
44476
44477 /* Opcode: VerifyCookie P1 P2 *
44478 **
44479 ** Check the value of global database parameter number 0 (the
44480 ** schema version) and make sure it is equal to P2.  
44481 ** P1 is the database number which is 0 for the main database file
44482 ** and 1 for the file holding temporary tables and some higher number
44483 ** for auxiliary databases.
44484 **
44485 ** The cookie changes its value whenever the database schema changes.
44486 ** This operation is used to detect when that the cookie has changed
44487 ** and that the current process needs to reread the schema.
44488 **
44489 ** Either a transaction needs to have been started or an OP_Open needs
44490 ** to be executed (to establish a read lock) before this opcode is
44491 ** invoked.
44492 */
44493 case OP_VerifyCookie: {
44494   int iMeta;
44495   Btree *pBt;
44496   assert( pOp->p1>=0 && pOp->p1<db->nDb );
44497   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
44498   pBt = db->aDb[pOp->p1].pBt;
44499   if( pBt ){
44500     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
44501   }else{
44502     rc = SQLITE_OK;
44503     iMeta = 0;
44504   }
44505   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
44506     sqlite3_free(p->zErrMsg);
44507     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
44508     /* If the schema-cookie from the database file matches the cookie 
44509     ** stored with the in-memory representation of the schema, do
44510     ** not reload the schema from the database file.
44511     **
44512     ** If virtual-tables are in use, this is not just an optimisation.
44513     ** Often, v-tables store their data in other SQLite tables, which
44514     ** are queried from within xNext() and other v-table methods using
44515     ** prepared queries. If such a query is out-of-date, we do not want to
44516     ** discard the database schema, as the user code implementing the
44517     ** v-table would have to be ready for the sqlite3_vtab structure itself
44518     ** to be invalidated whenever sqlite3_step() is called from within 
44519     ** a v-table method.
44520     */
44521     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
44522       sqlite3ResetInternalSchema(db, pOp->p1);
44523     }
44524
44525     sqlite3ExpirePreparedStatements(db);
44526     rc = SQLITE_SCHEMA;
44527   }
44528   break;
44529 }
44530
44531 /* Opcode: OpenRead P1 P2 P3 P4 P5
44532 **
44533 ** Open a read-only cursor for the database table whose root page is
44534 ** P2 in a database file.  The database file is determined by P3. 
44535 ** P3==0 means the main database, P3==1 means the database used for 
44536 ** temporary tables, and P3>1 means used the corresponding attached
44537 ** database.  Give the new cursor an identifier of P1.  The P1
44538 ** values need not be contiguous but all P1 values should be small integers.
44539 ** It is an error for P1 to be negative.
44540 **
44541 ** If P5!=0 then use the content of register P2 as the root page, not
44542 ** the value of P2 itself.
44543 **
44544 ** There will be a read lock on the database whenever there is an
44545 ** open cursor.  If the database was unlocked prior to this instruction
44546 ** then a read lock is acquired as part of this instruction.  A read
44547 ** lock allows other processes to read the database but prohibits
44548 ** any other process from modifying the database.  The read lock is
44549 ** released when all cursors are closed.  If this instruction attempts
44550 ** to get a read lock but fails, the script terminates with an
44551 ** SQLITE_BUSY error code.
44552 **
44553 ** The P4 value is a pointer to a KeyInfo structure that defines the
44554 ** content and collating sequence of indices.  P4 is NULL for cursors
44555 ** that are not pointing to indices.
44556 **
44557 ** See also OpenWrite.
44558 */
44559 /* Opcode: OpenWrite P1 P2 P3 P4 P5
44560 **
44561 ** Open a read/write cursor named P1 on the table or index whose root
44562 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
44563 ** root page.
44564 **
44565 ** The P4 value is a pointer to a KeyInfo structure that defines the
44566 ** content and collating sequence of indices.  P4 is NULL for cursors
44567 ** that are not pointing to indices.
44568 **
44569 ** This instruction works just like OpenRead except that it opens the cursor
44570 ** in read/write mode.  For a given table, there can be one or more read-only
44571 ** cursors or a single read/write cursor but not both.
44572 **
44573 ** See also OpenRead.
44574 */
44575 case OP_OpenRead:
44576 case OP_OpenWrite: {
44577   int i = pOp->p1;
44578   int p2 = pOp->p2;
44579   int iDb = pOp->p3;
44580   int wrFlag;
44581   Btree *pX;
44582   Cursor *pCur;
44583   Db *pDb;
44584   
44585   assert( iDb>=0 && iDb<db->nDb );
44586   assert( (p->btreeMask & (1<<iDb))!=0 );
44587   pDb = &db->aDb[iDb];
44588   pX = pDb->pBt;
44589   assert( pX!=0 );
44590   if( pOp->opcode==OP_OpenWrite ){
44591     wrFlag = 1;
44592     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
44593       p->minWriteFileFormat = pDb->pSchema->file_format;
44594     }
44595   }else{
44596     wrFlag = 0;
44597   }
44598   if( pOp->p5 ){
44599     assert( p2>0 );
44600     assert( p2<=p->nMem );
44601     pIn2 = &p->aMem[p2];
44602     sqlite3VdbeMemIntegerify(pIn2);
44603     p2 = pIn2->u.i;
44604     assert( p2>=2 );
44605   }
44606   assert( i>=0 );
44607   pCur = allocateCursor(p, i, &pOp[-1], iDb, 1);
44608   if( pCur==0 ) goto no_mem;
44609   pCur->nullRow = 1;
44610   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pOp->p4.p, pCur->pCursor);
44611   if( pOp->p4type==P4_KEYINFO ){
44612     pCur->pKeyInfo = pOp->p4.pKeyInfo;
44613     pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
44614     pCur->pKeyInfo->enc = ENC(p->db);
44615   }else{
44616     pCur->pKeyInfo = 0;
44617     pCur->pIncrKey = &pCur->bogusIncrKey;
44618   }
44619   switch( rc ){
44620     case SQLITE_BUSY: {
44621       p->pc = pc;
44622       p->rc = rc = SQLITE_BUSY;
44623       goto vdbe_return;
44624     }
44625     case SQLITE_OK: {
44626       int flags = sqlite3BtreeFlags(pCur->pCursor);
44627       /* Sanity checking.  Only the lower four bits of the flags byte should
44628       ** be used.  Bit 3 (mask 0x08) is unpreditable.  The lower 3 bits
44629       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
44630       ** 2 (zerodata for indices).  If these conditions are not met it can
44631       ** only mean that we are dealing with a corrupt database file
44632       */
44633       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
44634         rc = SQLITE_CORRUPT_BKPT;
44635         goto abort_due_to_error;
44636       }
44637       pCur->isTable = (flags & BTREE_INTKEY)!=0;
44638       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
44639       /* If P4==0 it means we are expected to open a table.  If P4!=0 then
44640       ** we expect to be opening an index.  If this is not what happened,
44641       ** then the database is corrupt
44642       */
44643       if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
44644        || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
44645         rc = SQLITE_CORRUPT_BKPT;
44646         goto abort_due_to_error;
44647       }
44648       break;
44649     }
44650     case SQLITE_EMPTY: {
44651       pCur->isTable = pOp->p4type!=P4_KEYINFO;
44652       pCur->isIndex = !pCur->isTable;
44653       pCur->pCursor = 0;
44654       rc = SQLITE_OK;
44655       break;
44656     }
44657     default: {
44658       goto abort_due_to_error;
44659     }
44660   }
44661   break;
44662 }
44663
44664 /* Opcode: OpenEphemeral P1 P2 * P4 *
44665 **
44666 ** Open a new cursor P1 to a transient table.
44667 ** The cursor is always opened read/write even if 
44668 ** the main database is read-only.  The transient or virtual
44669 ** table is deleted automatically when the cursor is closed.
44670 **
44671 ** P2 is the number of columns in the virtual table.
44672 ** The cursor points to a BTree table if P4==0 and to a BTree index
44673 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
44674 ** that defines the format of keys in the index.
44675 **
44676 ** This opcode was once called OpenTemp.  But that created
44677 ** confusion because the term "temp table", might refer either
44678 ** to a TEMP table at the SQL level, or to a table opened by
44679 ** this opcode.  Then this opcode was call OpenVirtual.  But
44680 ** that created confusion with the whole virtual-table idea.
44681 */
44682 case OP_OpenEphemeral: {
44683   int i = pOp->p1;
44684   Cursor *pCx;
44685   static const int openFlags = 
44686       SQLITE_OPEN_READWRITE |
44687       SQLITE_OPEN_CREATE |
44688       SQLITE_OPEN_EXCLUSIVE |
44689       SQLITE_OPEN_DELETEONCLOSE |
44690       SQLITE_OPEN_TRANSIENT_DB;
44691
44692   assert( i>=0 );
44693   pCx = allocateCursor(p, i, pOp, -1, 1);
44694   if( pCx==0 ) goto no_mem;
44695   pCx->nullRow = 1;
44696   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
44697                            &pCx->pBt);
44698   if( rc==SQLITE_OK ){
44699     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
44700   }
44701   if( rc==SQLITE_OK ){
44702     /* If a transient index is required, create it by calling
44703     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
44704     ** opening it. If a transient table is required, just use the
44705     ** automatically created table with root-page 1 (an INTKEY table).
44706     */
44707     if( pOp->p4.pKeyInfo ){
44708       int pgno;
44709       assert( pOp->p4type==P4_KEYINFO );
44710       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
44711       if( rc==SQLITE_OK ){
44712         assert( pgno==MASTER_ROOT+1 );
44713         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, 
44714                                 (KeyInfo*)pOp->p4.z, pCx->pCursor);
44715         pCx->pKeyInfo = pOp->p4.pKeyInfo;
44716         pCx->pKeyInfo->enc = ENC(p->db);
44717         pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
44718       }
44719       pCx->isTable = 0;
44720     }else{
44721       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
44722       pCx->isTable = 1;
44723       pCx->pIncrKey = &pCx->bogusIncrKey;
44724     }
44725   }
44726   pCx->isIndex = !pCx->isTable;
44727   break;
44728 }
44729
44730 /* Opcode: OpenPseudo P1 P2 * * *
44731 **
44732 ** Open a new cursor that points to a fake table that contains a single
44733 ** row of data.  Any attempt to write a second row of data causes the
44734 ** first row to be deleted.  All data is deleted when the cursor is
44735 ** closed.
44736 **
44737 ** A pseudo-table created by this opcode is useful for holding the
44738 ** NEW or OLD tables in a trigger.  Also used to hold the a single
44739 ** row output from the sorter so that the row can be decomposed into
44740 ** individual columns using the OP_Column opcode.
44741 **
44742 ** When OP_Insert is executed to insert a row in to the pseudo table,
44743 ** the pseudo-table cursor may or may not make it's own copy of the
44744 ** original row data. If P2 is 0, then the pseudo-table will copy the
44745 ** original row data. Otherwise, a pointer to the original memory cell
44746 ** is stored. In this case, the vdbe program must ensure that the 
44747 ** memory cell containing the row data is not overwritten until the
44748 ** pseudo table is closed (or a new row is inserted into it).
44749 */
44750 case OP_OpenPseudo: {
44751   int i = pOp->p1;
44752   Cursor *pCx;
44753   assert( i>=0 );
44754   pCx = allocateCursor(p, i, &pOp[-1], -1, 0);
44755   if( pCx==0 ) goto no_mem;
44756   pCx->nullRow = 1;
44757   pCx->pseudoTable = 1;
44758   pCx->ephemPseudoTable = pOp->p2;
44759   pCx->pIncrKey = &pCx->bogusIncrKey;
44760   pCx->isTable = 1;
44761   pCx->isIndex = 0;
44762   break;
44763 }
44764
44765 /* Opcode: Close P1 * * * *
44766 **
44767 ** Close a cursor previously opened as P1.  If P1 is not
44768 ** currently open, this instruction is a no-op.
44769 */
44770 case OP_Close: {
44771   int i = pOp->p1;
44772   assert( i>=0 && i<p->nCursor );
44773   sqlite3VdbeFreeCursor(p, p->apCsr[i]);
44774   p->apCsr[i] = 0;
44775   break;
44776 }
44777
44778 /* Opcode: MoveGe P1 P2 P3 P4 *
44779 **
44780 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
44781 ** use the integer value in register P3 as a key. If cursor P1 refers 
44782 ** to an SQL index, then P3 is the first in an array of P4 registers 
44783 ** that are used as an unpacked index key. 
44784 **
44785 ** Reposition cursor P1 so that  it points to the smallest entry that 
44786 ** is greater than or equal to the key value. If there are no records 
44787 ** greater than or equal to the key and P2 is not zero, then jump to P2.
44788 **
44789 ** A special feature of this opcode (and different from the
44790 ** related OP_MoveGt, OP_MoveLt, and OP_MoveLe) is that if P2 is
44791 ** zero and P1 is an SQL table (a b-tree with integer keys) then
44792 ** the seek is deferred until it is actually needed.  It might be
44793 ** the case that the cursor is never accessed.  By deferring the
44794 ** seek, we avoid unnecessary seeks.
44795 **
44796 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
44797 */
44798 /* Opcode: MoveGt P1 P2 P3 P4 *
44799 **
44800 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
44801 ** use the integer value in register P3 as a key. If cursor P1 refers 
44802 ** to an SQL index, then P3 is the first in an array of P4 registers 
44803 ** that are used as an unpacked index key. 
44804 **
44805 ** Reposition cursor P1 so that  it points to the smallest entry that 
44806 ** is greater than the key value. If there are no records greater than 
44807 ** the key and P2 is not zero, then jump to P2.
44808 **
44809 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
44810 */
44811 /* Opcode: MoveLt P1 P2 P3 P4 * 
44812 **
44813 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
44814 ** use the integer value in register P3 as a key. If cursor P1 refers 
44815 ** to an SQL index, then P3 is the first in an array of P4 registers 
44816 ** that are used as an unpacked index key. 
44817 **
44818 ** Reposition cursor P1 so that  it points to the largest entry that 
44819 ** is less than the key value. If there are no records less than 
44820 ** the key and P2 is not zero, then jump to P2.
44821 **
44822 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
44823 */
44824 /* Opcode: MoveLe P1 P2 P3 P4 *
44825 **
44826 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
44827 ** use the integer value in register P3 as a key. If cursor P1 refers 
44828 ** to an SQL index, then P3 is the first in an array of P4 registers 
44829 ** that are used as an unpacked index key. 
44830 **
44831 ** Reposition cursor P1 so that it points to the largest entry that 
44832 ** is less than or equal to the key value. If there are no records 
44833 ** less than or equal to the key and P2 is not zero, then jump to P2.
44834 **
44835 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
44836 */
44837 case OP_MoveLt:         /* jump, in3 */
44838 case OP_MoveLe:         /* jump, in3 */
44839 case OP_MoveGe:         /* jump, in3 */
44840 case OP_MoveGt: {       /* jump, in3 */
44841   int i = pOp->p1;
44842   Cursor *pC;
44843
44844   assert( i>=0 && i<p->nCursor );
44845   pC = p->apCsr[i];
44846   assert( pC!=0 );
44847   if( pC->pCursor!=0 ){
44848     int res, oc;
44849     oc = pOp->opcode;
44850     pC->nullRow = 0;
44851     *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
44852     if( pC->isTable ){
44853       i64 iKey = sqlite3VdbeIntValue(pIn3);
44854       if( pOp->p2==0 ){
44855         assert( pOp->opcode==OP_MoveGe );
44856         pC->movetoTarget = iKey;
44857         pC->rowidIsValid = 0;
44858         pC->deferredMoveto = 1;
44859         break;
44860       }
44861       rc = sqlite3BtreeMoveto(pC->pCursor, 0, 0, (u64)iKey, 0, &res);
44862       if( rc!=SQLITE_OK ){
44863         goto abort_due_to_error;
44864       }
44865       pC->lastRowid = iKey;
44866       pC->rowidIsValid = res==0;
44867     }else{
44868       UnpackedRecord r;
44869       int nField = pOp->p4.i;
44870       assert( pOp->p4type==P4_INT32 );
44871       assert( nField>0 );
44872       r.pKeyInfo = pC->pKeyInfo;
44873       r.nField = nField;
44874       r.needFree = 0;
44875       r.needDestroy = 0;
44876       r.aMem = &p->aMem[pOp->p3];
44877       rc = sqlite3BtreeMoveto(pC->pCursor, 0, &r, 0, 0, &res);
44878       if( rc!=SQLITE_OK ){
44879         goto abort_due_to_error;
44880       }
44881       pC->rowidIsValid = 0;
44882     }
44883     pC->deferredMoveto = 0;
44884     pC->cacheStatus = CACHE_STALE;
44885     *pC->pIncrKey = 0;
44886 #ifdef SQLITE_TEST
44887     sqlite3_search_count++;
44888 #endif
44889     if( oc==OP_MoveGe || oc==OP_MoveGt ){
44890       if( res<0 ){
44891         rc = sqlite3BtreeNext(pC->pCursor, &res);
44892         if( rc!=SQLITE_OK ) goto abort_due_to_error;
44893         pC->rowidIsValid = 0;
44894       }else{
44895         res = 0;
44896       }
44897     }else{
44898       assert( oc==OP_MoveLt || oc==OP_MoveLe );
44899       if( res>=0 ){
44900         rc = sqlite3BtreePrevious(pC->pCursor, &res);
44901         if( rc!=SQLITE_OK ) goto abort_due_to_error;
44902         pC->rowidIsValid = 0;
44903       }else{
44904         /* res might be negative because the table is empty.  Check to
44905         ** see if this is the case.
44906         */
44907         res = sqlite3BtreeEof(pC->pCursor);
44908       }
44909     }
44910     assert( pOp->p2>0 );
44911     if( res ){
44912       pc = pOp->p2 - 1;
44913     }
44914   }
44915   break;
44916 }
44917
44918 /* Opcode: Found P1 P2 P3 * *
44919 **
44920 ** Register P3 holds a blob constructed by MakeRecord.  P1 is an index.
44921 ** If an entry that matches the value in register p3 exists in P1 then
44922 ** jump to P2.  If the P3 value does not match any entry in P1
44923 ** then fall thru.  The P1 cursor is left pointing at the matching entry
44924 ** if it exists.
44925 **
44926 ** This instruction is used to implement the IN operator where the
44927 ** left-hand side is a SELECT statement.  P1 may be a true index, or it
44928 ** may be a temporary index that holds the results of the SELECT
44929 ** statement.   This instruction is also used to implement the
44930 ** DISTINCT keyword in SELECT statements.
44931 **
44932 ** This instruction checks if index P1 contains a record for which 
44933 ** the first N serialised values exactly match the N serialised values
44934 ** in the record in register P3, where N is the total number of values in
44935 ** the P3 record (the P3 record is a prefix of the P1 record). 
44936 **
44937 ** See also: NotFound, MoveTo, IsUnique, NotExists
44938 */
44939 /* Opcode: NotFound P1 P2 P3 * *
44940 **
44941 ** Register P3 holds a blob constructed by MakeRecord.  P1 is
44942 ** an index.  If no entry exists in P1 that matches the blob then jump
44943 ** to P2.  If an entry does existing, fall through.  The cursor is left
44944 ** pointing to the entry that matches.
44945 **
44946 ** See also: Found, MoveTo, NotExists, IsUnique
44947 */
44948 case OP_NotFound:       /* jump, in3 */
44949 case OP_Found: {        /* jump, in3 */
44950   int i = pOp->p1;
44951   int alreadyExists = 0;
44952   Cursor *pC;
44953   assert( i>=0 && i<p->nCursor );
44954   assert( p->apCsr[i]!=0 );
44955   if( (pC = p->apCsr[i])->pCursor!=0 ){
44956     int res;
44957     assert( pC->isTable==0 );
44958     assert( pIn3->flags & MEM_Blob );
44959     if( pOp->opcode==OP_Found ){
44960       pC->pKeyInfo->prefixIsEqual = 1;
44961     }
44962     rc = sqlite3BtreeMoveto(pC->pCursor, pIn3->z, 0, pIn3->n, 0, &res);
44963     pC->pKeyInfo->prefixIsEqual = 0;
44964     if( rc!=SQLITE_OK ){
44965       break;
44966     }
44967     alreadyExists = (res==0);
44968     pC->deferredMoveto = 0;
44969     pC->cacheStatus = CACHE_STALE;
44970   }
44971   if( pOp->opcode==OP_Found ){
44972     if( alreadyExists ) pc = pOp->p2 - 1;
44973   }else{
44974     if( !alreadyExists ) pc = pOp->p2 - 1;
44975   }
44976   break;
44977 }
44978
44979 /* Opcode: IsUnique P1 P2 P3 P4 *
44980 **
44981 ** The P3 register contains an integer record number.  Call this
44982 ** record number R.  The P4 register contains an index key created
44983 ** using MakeIdxRec.  Call it K.
44984 **
44985 ** P1 is an index.  So it has no data and its key consists of a
44986 ** record generated by OP_MakeRecord where the last field is the 
44987 ** rowid of the entry that the index refers to.
44988 ** 
44989 ** This instruction asks if there is an entry in P1 where the
44990 ** fields matches K but the rowid is different from R.
44991 ** If there is no such entry, then there is an immediate
44992 ** jump to P2.  If any entry does exist where the index string
44993 ** matches K but the record number is not R, then the record
44994 ** number for that entry is written into P3 and control
44995 ** falls through to the next instruction.
44996 **
44997 ** See also: NotFound, NotExists, Found
44998 */
44999 case OP_IsUnique: {        /* jump, in3 */
45000   int i = pOp->p1;
45001   Cursor *pCx;
45002   BtCursor *pCrsr;
45003   Mem *pK;
45004   i64 R;
45005
45006   /* Pop the value R off the top of the stack
45007   */
45008   assert( pOp->p4type==P4_INT32 );
45009   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
45010   pK = &p->aMem[pOp->p4.i];
45011   sqlite3VdbeMemIntegerify(pIn3);
45012   R = pIn3->u.i;
45013   assert( i>=0 && i<p->nCursor );
45014   pCx = p->apCsr[i];
45015   assert( pCx!=0 );
45016   pCrsr = pCx->pCursor;
45017   if( pCrsr!=0 ){
45018     int res;
45019     i64 v;         /* The record number on the P1 entry that matches K */
45020     char *zKey;    /* The value of K */
45021     int nKey;      /* Number of bytes in K */
45022     int len;       /* Number of bytes in K without the rowid at the end */
45023     int szRowid;   /* Size of the rowid column at the end of zKey */
45024
45025     /* Make sure K is a string and make zKey point to K
45026     */
45027     assert( pK->flags & MEM_Blob );
45028     zKey = pK->z;
45029     nKey = pK->n;
45030
45031     szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
45032     len = nKey-szRowid;
45033
45034     /* Search for an entry in P1 where all but the last four bytes match K.
45035     ** If there is no such entry, jump immediately to P2.
45036     */
45037     assert( pCx->deferredMoveto==0 );
45038     pCx->cacheStatus = CACHE_STALE;
45039     rc = sqlite3BtreeMoveto(pCrsr, zKey, 0, len, 0, &res);
45040     if( rc!=SQLITE_OK ){
45041       goto abort_due_to_error;
45042     }
45043     if( res<0 ){
45044       rc = sqlite3BtreeNext(pCrsr, &res);
45045       if( res ){
45046         pc = pOp->p2 - 1;
45047         break;
45048       }
45049     }
45050     rc = sqlite3VdbeIdxKeyCompare(pCx, 0, len, (u8*)zKey, &res); 
45051     if( rc!=SQLITE_OK ) goto abort_due_to_error;
45052     if( res>0 ){
45053       pc = pOp->p2 - 1;
45054       break;
45055     }
45056
45057     /* At this point, pCrsr is pointing to an entry in P1 where all but
45058     ** the final entry (the rowid) matches K.  Check to see if the
45059     ** final rowid column is different from R.  If it equals R then jump
45060     ** immediately to P2.
45061     */
45062     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
45063     if( rc!=SQLITE_OK ){
45064       goto abort_due_to_error;
45065     }
45066     if( v==R ){
45067       pc = pOp->p2 - 1;
45068       break;
45069     }
45070
45071     /* The final varint of the key is different from R.  Store it back
45072     ** into register R3.  (The record number of an entry that violates
45073     ** a UNIQUE constraint.)
45074     */
45075     pIn3->u.i = v;
45076     assert( pIn3->flags&MEM_Int );
45077   }
45078   break;
45079 }
45080
45081 /* Opcode: NotExists P1 P2 P3 * *
45082 **
45083 ** Use the content of register P3 as a integer key.  If a record 
45084 ** with that key does not exist in table of P1, then jump to P2. 
45085 ** If the record does exist, then fall thru.  The cursor is left 
45086 ** pointing to the record if it exists.
45087 **
45088 ** The difference between this operation and NotFound is that this
45089 ** operation assumes the key is an integer and that P1 is a table whereas
45090 ** NotFound assumes key is a blob constructed from MakeRecord and
45091 ** P1 is an index.
45092 **
45093 ** See also: Found, MoveTo, NotFound, IsUnique
45094 */
45095 case OP_NotExists: {        /* jump, in3 */
45096   int i = pOp->p1;
45097   Cursor *pC;
45098   BtCursor *pCrsr;
45099   assert( i>=0 && i<p->nCursor );
45100   assert( p->apCsr[i]!=0 );
45101   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
45102     int res;
45103     u64 iKey;
45104     assert( pIn3->flags & MEM_Int );
45105     assert( p->apCsr[i]->isTable );
45106     iKey = intToKey(pIn3->u.i);
45107     rc = sqlite3BtreeMoveto(pCrsr, 0, 0, iKey, 0,&res);
45108     pC->lastRowid = pIn3->u.i;
45109     pC->rowidIsValid = res==0;
45110     pC->nullRow = 0;
45111     pC->cacheStatus = CACHE_STALE;
45112     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
45113     ** processing is about to abort so we really do not care whether or not
45114     ** the following jump is taken.  (In other words, do not stress over
45115     ** the error that valgrind sometimes shows on the next statement when
45116     ** running ioerr.test and similar failure-recovery test scripts.) */
45117     if( res!=0 ){
45118       pc = pOp->p2 - 1;
45119       assert( pC->rowidIsValid==0 );
45120     }
45121   }
45122   break;
45123 }
45124
45125 /* Opcode: Sequence P1 P2 * * *
45126 **
45127 ** Find the next available sequence number for cursor P1.
45128 ** Write the sequence number into register P2.
45129 ** The sequence number on the cursor is incremented after this
45130 ** instruction.  
45131 */
45132 case OP_Sequence: {           /* out2-prerelease */
45133   int i = pOp->p1;
45134   assert( i>=0 && i<p->nCursor );
45135   assert( p->apCsr[i]!=0 );
45136   pOut->u.i = p->apCsr[i]->seqCount++;
45137   MemSetTypeFlag(pOut, MEM_Int);
45138   break;
45139 }
45140
45141
45142 /* Opcode: NewRowid P1 P2 P3 * *
45143 **
45144 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
45145 ** The record number is not previously used as a key in the database
45146 ** table that cursor P1 points to.  The new record number is written
45147 ** written to register P2.
45148 **
45149 ** If P3>0 then P3 is a register that holds the largest previously
45150 ** generated record number.  No new record numbers are allowed to be less
45151 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
45152 ** error is generated.  The P3 register is updated with the generated
45153 ** record number.  This P3 mechanism is used to help implement the
45154 ** AUTOINCREMENT feature.
45155 */
45156 case OP_NewRowid: {           /* out2-prerelease */
45157   int i = pOp->p1;
45158   i64 v = 0;
45159   Cursor *pC;
45160   assert( i>=0 && i<p->nCursor );
45161   assert( p->apCsr[i]!=0 );
45162   if( (pC = p->apCsr[i])->pCursor==0 ){
45163     /* The zero initialization above is all that is needed */
45164   }else{
45165     /* The next rowid or record number (different terms for the same
45166     ** thing) is obtained in a two-step algorithm.
45167     **
45168     ** First we attempt to find the largest existing rowid and add one
45169     ** to that.  But if the largest existing rowid is already the maximum
45170     ** positive integer, we have to fall through to the second
45171     ** probabilistic algorithm
45172     **
45173     ** The second algorithm is to select a rowid at random and see if
45174     ** it already exists in the table.  If it does not exist, we have
45175     ** succeeded.  If the random rowid does exist, we select a new one
45176     ** and try again, up to 1000 times.
45177     **
45178     ** For a table with less than 2 billion entries, the probability
45179     ** of not finding a unused rowid is about 1.0e-300.  This is a 
45180     ** non-zero probability, but it is still vanishingly small and should
45181     ** never cause a problem.  You are much, much more likely to have a
45182     ** hardware failure than for this algorithm to fail.
45183     **
45184     ** The analysis in the previous paragraph assumes that you have a good
45185     ** source of random numbers.  Is a library function like lrand48()
45186     ** good enough?  Maybe. Maybe not. It's hard to know whether there
45187     ** might be subtle bugs is some implementations of lrand48() that
45188     ** could cause problems. To avoid uncertainty, SQLite uses its own 
45189     ** random number generator based on the RC4 algorithm.
45190     **
45191     ** To promote locality of reference for repetitive inserts, the
45192     ** first few attempts at chosing a random rowid pick values just a little
45193     ** larger than the previous rowid.  This has been shown experimentally
45194     ** to double the speed of the COPY operation.
45195     */
45196     int res, rx=SQLITE_OK, cnt;
45197     i64 x;
45198     cnt = 0;
45199     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
45200           BTREE_INTKEY ){
45201       rc = SQLITE_CORRUPT_BKPT;
45202       goto abort_due_to_error;
45203     }
45204     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
45205     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
45206
45207 #ifdef SQLITE_32BIT_ROWID
45208 #   define MAX_ROWID 0x7fffffff
45209 #else
45210     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
45211     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
45212     ** to provide the constant while making all compilers happy.
45213     */
45214 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
45215 #endif
45216
45217     if( !pC->useRandomRowid ){
45218       if( pC->nextRowidValid ){
45219         v = pC->nextRowid;
45220       }else{
45221         rc = sqlite3BtreeLast(pC->pCursor, &res);
45222         if( rc!=SQLITE_OK ){
45223           goto abort_due_to_error;
45224         }
45225         if( res ){
45226           v = 1;
45227         }else{
45228           sqlite3BtreeKeySize(pC->pCursor, &v);
45229           v = keyToInt(v);
45230           if( v==MAX_ROWID ){
45231             pC->useRandomRowid = 1;
45232           }else{
45233             v++;
45234           }
45235         }
45236       }
45237
45238 #ifndef SQLITE_OMIT_AUTOINCREMENT
45239       if( pOp->p3 ){
45240         Mem *pMem;
45241         assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
45242         pMem = &p->aMem[pOp->p3];
45243         REGISTER_TRACE(pOp->p3, pMem);
45244         sqlite3VdbeMemIntegerify(pMem);
45245         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
45246         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
45247           rc = SQLITE_FULL;
45248           goto abort_due_to_error;
45249         }
45250         if( v<pMem->u.i+1 ){
45251           v = pMem->u.i + 1;
45252         }
45253         pMem->u.i = v;
45254       }
45255 #endif
45256
45257       if( v<MAX_ROWID ){
45258         pC->nextRowidValid = 1;
45259         pC->nextRowid = v+1;
45260       }else{
45261         pC->nextRowidValid = 0;
45262       }
45263     }
45264     if( pC->useRandomRowid ){
45265       assert( pOp->p3==0 );  /* SQLITE_FULL must have occurred prior to this */
45266       v = db->priorNewRowid;
45267       cnt = 0;
45268       do{
45269         if( cnt==0 && (v&0xffffff)==v ){
45270           v++;
45271         }else{
45272           sqlite3_randomness(sizeof(v), &v);
45273           if( cnt<5 ) v &= 0xffffff;
45274         }
45275         if( v==0 ) continue;
45276         x = intToKey(v);
45277         rx = sqlite3BtreeMoveto(pC->pCursor, 0, 0, (u64)x, 0, &res);
45278         cnt++;
45279       }while( cnt<100 && rx==SQLITE_OK && res==0 );
45280       db->priorNewRowid = v;
45281       if( rx==SQLITE_OK && res==0 ){
45282         rc = SQLITE_FULL;
45283         goto abort_due_to_error;
45284       }
45285     }
45286     pC->rowidIsValid = 0;
45287     pC->deferredMoveto = 0;
45288     pC->cacheStatus = CACHE_STALE;
45289   }
45290   MemSetTypeFlag(pOut, MEM_Int);
45291   pOut->u.i = v;
45292   break;
45293 }
45294
45295 /* Opcode: Insert P1 P2 P3 P4 P5
45296 **
45297 ** Write an entry into the table of cursor P1.  A new entry is
45298 ** created if it doesn't already exist or the data for an existing
45299 ** entry is overwritten.  The data is the value stored register
45300 ** number P2. The key is stored in register P3. The key must
45301 ** be an integer.
45302 **
45303 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
45304 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
45305 ** then rowid is stored for subsequent return by the
45306 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
45307 **
45308 ** Parameter P4 may point to a string containing the table-name, or
45309 ** may be NULL. If it is not NULL, then the update-hook 
45310 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
45311 **
45312 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
45313 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
45314 ** and register P2 becomes ephemeral.  If the cursor is changed, the
45315 ** value of register P2 will then change.  Make sure this does not
45316 ** cause any problems.)
45317 **
45318 ** This instruction only works on tables.  The equivalent instruction
45319 ** for indices is OP_IdxInsert.
45320 */
45321 case OP_Insert: {
45322   Mem *pData = &p->aMem[pOp->p2];
45323   Mem *pKey = &p->aMem[pOp->p3];
45324
45325   i64 iKey;   /* The integer ROWID or key for the record to be inserted */
45326   int i = pOp->p1;
45327   Cursor *pC;
45328   assert( i>=0 && i<p->nCursor );
45329   pC = p->apCsr[i];
45330   assert( pC!=0 );
45331   assert( pC->pCursor!=0 || pC->pseudoTable );
45332   assert( pKey->flags & MEM_Int );
45333   assert( pC->isTable );
45334   REGISTER_TRACE(pOp->p2, pData);
45335   REGISTER_TRACE(pOp->p3, pKey);
45336
45337   iKey = intToKey(pKey->u.i);
45338   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
45339   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
45340   if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
45341     pC->nextRowidValid = 0;
45342   }
45343   if( pData->flags & MEM_Null ){
45344     pData->z = 0;
45345     pData->n = 0;
45346   }else{
45347     assert( pData->flags & (MEM_Blob|MEM_Str) );
45348   }
45349   if( pC->pseudoTable ){
45350     if( !pC->ephemPseudoTable ){
45351       sqlite3_free(pC->pData);
45352     }
45353     pC->iKey = iKey;
45354     pC->nData = pData->n;
45355     if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
45356       pC->pData = pData->z;
45357       if( !pC->ephemPseudoTable ){
45358         pData->flags &= ~MEM_Dyn;
45359         pData->flags |= MEM_Ephem;
45360         pData->zMalloc = 0;
45361       }
45362     }else{
45363       pC->pData = sqlite3_malloc( pC->nData+2 );
45364       if( !pC->pData ) goto no_mem;
45365       memcpy(pC->pData, pData->z, pC->nData);
45366       pC->pData[pC->nData] = 0;
45367       pC->pData[pC->nData+1] = 0;
45368     }
45369     pC->nullRow = 0;
45370   }else{
45371     int nZero;
45372     if( pData->flags & MEM_Zero ){
45373       nZero = pData->u.i;
45374     }else{
45375       nZero = 0;
45376     }
45377     rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
45378                             pData->z, pData->n, nZero,
45379                             pOp->p5 & OPFLAG_APPEND);
45380   }
45381   
45382   pC->rowidIsValid = 0;
45383   pC->deferredMoveto = 0;
45384   pC->cacheStatus = CACHE_STALE;
45385
45386   /* Invoke the update-hook if required. */
45387   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
45388     const char *zDb = db->aDb[pC->iDb].zName;
45389     const char *zTbl = pOp->p4.z;
45390     int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
45391     assert( pC->isTable );
45392     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
45393     assert( pC->iDb>=0 );
45394   }
45395   break;
45396 }
45397
45398 /* Opcode: Delete P1 P2 * P4 *
45399 **
45400 ** Delete the record at which the P1 cursor is currently pointing.
45401 **
45402 ** The cursor will be left pointing at either the next or the previous
45403 ** record in the table. If it is left pointing at the next record, then
45404 ** the next Next instruction will be a no-op.  Hence it is OK to delete
45405 ** a record from within an Next loop.
45406 **
45407 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
45408 ** incremented (otherwise not).
45409 **
45410 ** P1 must not be pseudo-table.  It has to be a real table with
45411 ** multiple rows.
45412 **
45413 ** If P4 is not NULL, then it is the name of the table that P1 is
45414 ** pointing to.  The update hook will be invoked, if it exists.
45415 ** If P4 is not NULL then the P1 cursor must have been positioned
45416 ** using OP_NotFound prior to invoking this opcode.
45417 */
45418 case OP_Delete: {
45419   int i = pOp->p1;
45420   i64 iKey;
45421   Cursor *pC;
45422
45423   assert( i>=0 && i<p->nCursor );
45424   pC = p->apCsr[i];
45425   assert( pC!=0 );
45426   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
45427
45428   /* If the update-hook will be invoked, set iKey to the rowid of the
45429   ** row being deleted.
45430   */
45431   if( db->xUpdateCallback && pOp->p4.z ){
45432     assert( pC->isTable );
45433     assert( pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
45434     iKey = pC->lastRowid;
45435   }
45436
45437   rc = sqlite3VdbeCursorMoveto(pC);
45438   if( rc ) goto abort_due_to_error;
45439   rc = sqlite3BtreeDelete(pC->pCursor);
45440   pC->nextRowidValid = 0;
45441   pC->cacheStatus = CACHE_STALE;
45442
45443   /* Invoke the update-hook if required. */
45444   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
45445     const char *zDb = db->aDb[pC->iDb].zName;
45446     const char *zTbl = pOp->p4.z;
45447     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
45448     assert( pC->iDb>=0 );
45449   }
45450   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
45451   break;
45452 }
45453
45454 /* Opcode: ResetCount P1 * *
45455 **
45456 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
45457 ** then the value of the change counter is copied to the database handle
45458 ** change counter (returned by subsequent calls to sqlite3_changes())
45459 ** before it is reset. This is used by trigger programs.
45460 */
45461 case OP_ResetCount: {
45462   if( pOp->p1 ){
45463     sqlite3VdbeSetChanges(db, p->nChange);
45464   }
45465   p->nChange = 0;
45466   break;
45467 }
45468
45469 /* Opcode: RowData P1 P2 * * *
45470 **
45471 ** Write into register P2 the complete row data for cursor P1.
45472 ** There is no interpretation of the data.  
45473 ** It is just copied onto the P2 register exactly as 
45474 ** it is found in the database file.
45475 **
45476 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
45477 ** of a real table, not a pseudo-table.
45478 */
45479 /* Opcode: RowKey P1 P2 * * *
45480 **
45481 ** Write into register P2 the complete row key for cursor P1.
45482 ** There is no interpretation of the data.  
45483 ** The key is copied onto the P3 register exactly as 
45484 ** it is found in the database file.
45485 **
45486 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
45487 ** of a real table, not a pseudo-table.
45488 */
45489 case OP_RowKey:
45490 case OP_RowData: {
45491   int i = pOp->p1;
45492   Cursor *pC;
45493   BtCursor *pCrsr;
45494   u32 n;
45495
45496   pOut = &p->aMem[pOp->p2];
45497
45498   /* Note that RowKey and RowData are really exactly the same instruction */
45499   assert( i>=0 && i<p->nCursor );
45500   pC = p->apCsr[i];
45501   assert( pC->isTable || pOp->opcode==OP_RowKey );
45502   assert( pC->isIndex || pOp->opcode==OP_RowData );
45503   assert( pC!=0 );
45504   assert( pC->nullRow==0 );
45505   assert( pC->pseudoTable==0 );
45506   assert( pC->pCursor!=0 );
45507   pCrsr = pC->pCursor;
45508   rc = sqlite3VdbeCursorMoveto(pC);
45509   if( rc ) goto abort_due_to_error;
45510   if( pC->isIndex ){
45511     i64 n64;
45512     assert( !pC->isTable );
45513     sqlite3BtreeKeySize(pCrsr, &n64);
45514     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
45515       goto too_big;
45516     }
45517     n = n64;
45518   }else{
45519     sqlite3BtreeDataSize(pCrsr, &n);
45520     if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
45521       goto too_big;
45522     }
45523   }
45524   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
45525     goto no_mem;
45526   }
45527   pOut->n = n;
45528   MemSetTypeFlag(pOut, MEM_Blob);
45529   if( pC->isIndex ){
45530     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
45531   }else{
45532     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
45533   }
45534   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
45535   UPDATE_MAX_BLOBSIZE(pOut);
45536   break;
45537 }
45538
45539 /* Opcode: Rowid P1 P2 * * *
45540 **
45541 ** Store in register P2 an integer which is the key of the table entry that
45542 ** P1 is currently point to.  If p2==0 then push the integer.
45543 */
45544 case OP_Rowid: {                 /* out2-prerelease */
45545   int i = pOp->p1;
45546   Cursor *pC;
45547   i64 v;
45548
45549   assert( i>=0 && i<p->nCursor );
45550   pC = p->apCsr[i];
45551   assert( pC!=0 );
45552   rc = sqlite3VdbeCursorMoveto(pC);
45553   if( rc ) goto abort_due_to_error;
45554   if( pC->rowidIsValid ){
45555     v = pC->lastRowid;
45556   }else if( pC->pseudoTable ){
45557     v = keyToInt(pC->iKey);
45558   }else if( pC->nullRow ){
45559     /* Leave the rowid set to a NULL */
45560     break;
45561   }else{
45562     assert( pC->pCursor!=0 );
45563     sqlite3BtreeKeySize(pC->pCursor, &v);
45564     v = keyToInt(v);
45565   }
45566   pOut->u.i = v;
45567   MemSetTypeFlag(pOut, MEM_Int);
45568   break;
45569 }
45570
45571 /* Opcode: NullRow P1 * * * *
45572 **
45573 ** Move the cursor P1 to a null row.  Any OP_Column operations
45574 ** that occur while the cursor is on the null row will always
45575 ** write a NULL.
45576 */
45577 case OP_NullRow: {
45578   int i = pOp->p1;
45579   Cursor *pC;
45580
45581   assert( i>=0 && i<p->nCursor );
45582   pC = p->apCsr[i];
45583   assert( pC!=0 );
45584   pC->nullRow = 1;
45585   pC->rowidIsValid = 0;
45586   break;
45587 }
45588
45589 /* Opcode: Last P1 P2 * * *
45590 **
45591 ** The next use of the Rowid or Column or Next instruction for P1 
45592 ** will refer to the last entry in the database table or index.
45593 ** If the table or index is empty and P2>0, then jump immediately to P2.
45594 ** If P2 is 0 or if the table or index is not empty, fall through
45595 ** to the following instruction.
45596 */
45597 case OP_Last: {        /* jump */
45598   int i = pOp->p1;
45599   Cursor *pC;
45600   BtCursor *pCrsr;
45601   int res;
45602
45603   assert( i>=0 && i<p->nCursor );
45604   pC = p->apCsr[i];
45605   assert( pC!=0 );
45606   pCrsr = pC->pCursor;
45607   assert( pCrsr!=0 );
45608   rc = sqlite3BtreeLast(pCrsr, &res);
45609   pC->nullRow = res;
45610   pC->deferredMoveto = 0;
45611   pC->cacheStatus = CACHE_STALE;
45612   if( res && pOp->p2>0 ){
45613     pc = pOp->p2 - 1;
45614   }
45615   break;
45616 }
45617
45618
45619 /* Opcode: Sort P1 P2 * * *
45620 **
45621 ** This opcode does exactly the same thing as OP_Rewind except that
45622 ** it increments an undocumented global variable used for testing.
45623 **
45624 ** Sorting is accomplished by writing records into a sorting index,
45625 ** then rewinding that index and playing it back from beginning to
45626 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
45627 ** rewinding so that the global variable will be incremented and
45628 ** regression tests can determine whether or not the optimizer is
45629 ** correctly optimizing out sorts.
45630 */
45631 case OP_Sort: {        /* jump */
45632 #ifdef SQLITE_TEST
45633   sqlite3_sort_count++;
45634   sqlite3_search_count--;
45635 #endif
45636   /* Fall through into OP_Rewind */
45637 }
45638 /* Opcode: Rewind P1 P2 * * *
45639 **
45640 ** The next use of the Rowid or Column or Next instruction for P1 
45641 ** will refer to the first entry in the database table or index.
45642 ** If the table or index is empty and P2>0, then jump immediately to P2.
45643 ** If P2 is 0 or if the table or index is not empty, fall through
45644 ** to the following instruction.
45645 */
45646 case OP_Rewind: {        /* jump */
45647   int i = pOp->p1;
45648   Cursor *pC;
45649   BtCursor *pCrsr;
45650   int res;
45651
45652   assert( i>=0 && i<p->nCursor );
45653   pC = p->apCsr[i];
45654   assert( pC!=0 );
45655   if( (pCrsr = pC->pCursor)!=0 ){
45656     rc = sqlite3BtreeFirst(pCrsr, &res);
45657     pC->atFirst = res==0;
45658     pC->deferredMoveto = 0;
45659     pC->cacheStatus = CACHE_STALE;
45660   }else{
45661     res = 1;
45662   }
45663   pC->nullRow = res;
45664   assert( pOp->p2>0 && pOp->p2<p->nOp );
45665   if( res ){
45666     pc = pOp->p2 - 1;
45667   }
45668   break;
45669 }
45670
45671 /* Opcode: Next P1 P2 * * *
45672 **
45673 ** Advance cursor P1 so that it points to the next key/data pair in its
45674 ** table or index.  If there are no more key/value pairs then fall through
45675 ** to the following instruction.  But if the cursor advance was successful,
45676 ** jump immediately to P2.
45677 **
45678 ** The P1 cursor must be for a real table, not a pseudo-table.
45679 **
45680 ** See also: Prev
45681 */
45682 /* Opcode: Prev P1 P2 * * *
45683 **
45684 ** Back up cursor P1 so that it points to the previous key/data pair in its
45685 ** table or index.  If there is no previous key/value pairs then fall through
45686 ** to the following instruction.  But if the cursor backup was successful,
45687 ** jump immediately to P2.
45688 **
45689 ** The P1 cursor must be for a real table, not a pseudo-table.
45690 */
45691 case OP_Prev:          /* jump */
45692 case OP_Next: {        /* jump */
45693   Cursor *pC;
45694   BtCursor *pCrsr;
45695
45696   CHECK_FOR_INTERRUPT;
45697   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
45698   pC = p->apCsr[pOp->p1];
45699   if( pC==0 ){
45700     break;  /* See ticket #2273 */
45701   }
45702   pCrsr = pC->pCursor;
45703   assert( pCrsr );
45704   if( pC->nullRow==0 ){
45705     int res = 1;
45706     assert( pC->deferredMoveto==0 );
45707     rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
45708                                 sqlite3BtreePrevious(pCrsr, &res);
45709     pC->nullRow = res;
45710     pC->cacheStatus = CACHE_STALE;
45711     if( res==0 ){
45712       pc = pOp->p2 - 1;
45713 #ifdef SQLITE_TEST
45714       sqlite3_search_count++;
45715 #endif
45716     }
45717   }
45718   pC->rowidIsValid = 0;
45719   break;
45720 }
45721
45722 /* Opcode: IdxInsert P1 P2 P3 * *
45723 **
45724 ** Register P2 holds a SQL index key made using the
45725 ** MakeIdxRec instructions.  This opcode writes that key
45726 ** into the index P1.  Data for the entry is nil.
45727 **
45728 ** P3 is a flag that provides a hint to the b-tree layer that this
45729 ** insert is likely to be an append.
45730 **
45731 ** This instruction only works for indices.  The equivalent instruction
45732 ** for tables is OP_Insert.
45733 */
45734 case OP_IdxInsert: {        /* in2 */
45735   int i = pOp->p1;
45736   Cursor *pC;
45737   BtCursor *pCrsr;
45738   assert( i>=0 && i<p->nCursor );
45739   assert( p->apCsr[i]!=0 );
45740   assert( pIn2->flags & MEM_Blob );
45741   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
45742     assert( pC->isTable==0 );
45743     rc = ExpandBlob(pIn2);
45744     if( rc==SQLITE_OK ){
45745       int nKey = pIn2->n;
45746       const char *zKey = pIn2->z;
45747       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
45748       assert( pC->deferredMoveto==0 );
45749       pC->cacheStatus = CACHE_STALE;
45750     }
45751   }
45752   break;
45753 }
45754
45755 /* Opcode: IdxDeleteM P1 P2 P3 * *
45756 **
45757 ** The content of P3 registers starting at register P2 form
45758 ** an unpacked index key. This opcode removes that entry from the 
45759 ** index opened by cursor P1.
45760 */
45761 case OP_IdxDelete: {
45762   int i = pOp->p1;
45763   Cursor *pC;
45764   BtCursor *pCrsr;
45765   assert( pOp->p3>0 );
45766   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem );
45767   assert( i>=0 && i<p->nCursor );
45768   assert( p->apCsr[i]!=0 );
45769   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
45770     int res;
45771     UnpackedRecord r;
45772     r.pKeyInfo = pC->pKeyInfo;
45773     r.nField = pOp->p3;
45774     r.needFree = 0;
45775     r.needDestroy = 0;
45776     r.aMem = &p->aMem[pOp->p2];
45777     rc = sqlite3BtreeMoveto(pCrsr, 0, &r, 0, 0, &res);
45778     if( rc==SQLITE_OK && res==0 ){
45779       rc = sqlite3BtreeDelete(pCrsr);
45780     }
45781     assert( pC->deferredMoveto==0 );
45782     pC->cacheStatus = CACHE_STALE;
45783   }
45784   break;
45785 }
45786
45787 /* Opcode: IdxRowid P1 P2 * * *
45788 **
45789 ** Write into register P2 an integer which is the last entry in the record at
45790 ** the end of the index key pointed to by cursor P1.  This integer should be
45791 ** the rowid of the table entry to which this index entry points.
45792 **
45793 ** See also: Rowid, MakeIdxRec.
45794 */
45795 case OP_IdxRowid: {              /* out2-prerelease */
45796   int i = pOp->p1;
45797   BtCursor *pCrsr;
45798   Cursor *pC;
45799
45800   assert( i>=0 && i<p->nCursor );
45801   assert( p->apCsr[i]!=0 );
45802   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
45803     i64 rowid;
45804
45805     assert( pC->deferredMoveto==0 );
45806     assert( pC->isTable==0 );
45807     if( !pC->nullRow ){
45808       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
45809       if( rc!=SQLITE_OK ){
45810         goto abort_due_to_error;
45811       }
45812       MemSetTypeFlag(pOut, MEM_Int);
45813       pOut->u.i = rowid;
45814     }
45815   }
45816   break;
45817 }
45818
45819 /* Opcode: IdxGE P1 P2 P3 P4 P5
45820 **
45821 ** The P4 register values beginning with P3 form an unpacked index 
45822 ** key that omits the ROWID.  Compare this key value against the index 
45823 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
45824 **
45825 ** If the P1 index entry is greater than or equal to the key value
45826 ** then jump to P2.  Otherwise fall through to the next instruction.
45827 **
45828 ** If P5 is non-zero then the key value is increased by an epsilon 
45829 ** prior to the comparison.  This make the opcode work like IdxGT except
45830 ** that if the key from register P3 is a prefix of the key in the cursor,
45831 ** the result is false whereas it would be true with IdxGT.
45832 */
45833 /* Opcode: IdxLT P1 P2 P3 * P5
45834 **
45835 ** The P4 register values beginning with P3 form an unpacked index 
45836 ** key that omits the ROWID.  Compare this key value against the index 
45837 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
45838 **
45839 ** If the P1 index entry is less than the key value then jump to P2.
45840 ** Otherwise fall through to the next instruction.
45841 **
45842 ** If P5 is non-zero then the key value is increased by an epsilon prior 
45843 ** to the comparison.  This makes the opcode work like IdxLE.
45844 */
45845 case OP_IdxLT:          /* jump, in3 */
45846 case OP_IdxGE: {        /* jump, in3 */
45847   int i= pOp->p1;
45848   Cursor *pC;
45849
45850   assert( i>=0 && i<p->nCursor );
45851   assert( p->apCsr[i]!=0 );
45852   if( (pC = p->apCsr[i])->pCursor!=0 ){
45853     int res;
45854     UnpackedRecord r;
45855     assert( pC->deferredMoveto==0 );
45856     assert( pOp->p5==0 || pOp->p5==1 );
45857     assert( pOp->p4type==P4_INT32 );
45858     r.pKeyInfo = pC->pKeyInfo;
45859     r.nField = pOp->p4.i;
45860     r.needFree = 0;
45861     r.needDestroy = 0;
45862     r.aMem = &p->aMem[pOp->p3];
45863     *pC->pIncrKey = pOp->p5;
45864     rc = sqlite3VdbeIdxKeyCompare(pC, &r, 0, 0, &res);
45865     *pC->pIncrKey = 0;
45866     if( pOp->opcode==OP_IdxLT ){
45867       res = -res;
45868     }else{
45869       assert( pOp->opcode==OP_IdxGE );
45870       res++;
45871     }
45872     if( res>0 ){
45873       pc = pOp->p2 - 1 ;
45874     }
45875   }
45876   break;
45877 }
45878
45879 /* Opcode: Destroy P1 P2 P3 * *
45880 **
45881 ** Delete an entire database table or index whose root page in the database
45882 ** file is given by P1.
45883 **
45884 ** The table being destroyed is in the main database file if P3==0.  If
45885 ** P3==1 then the table to be clear is in the auxiliary database file
45886 ** that is used to store tables create using CREATE TEMPORARY TABLE.
45887 **
45888 ** If AUTOVACUUM is enabled then it is possible that another root page
45889 ** might be moved into the newly deleted root page in order to keep all
45890 ** root pages contiguous at the beginning of the database.  The former
45891 ** value of the root page that moved - its value before the move occurred -
45892 ** is stored in register P2.  If no page 
45893 ** movement was required (because the table being dropped was already 
45894 ** the last one in the database) then a zero is stored in register P2.
45895 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
45896 **
45897 ** See also: Clear
45898 */
45899 case OP_Destroy: {     /* out2-prerelease */
45900   int iMoved;
45901   int iCnt;
45902 #ifndef SQLITE_OMIT_VIRTUALTABLE
45903   Vdbe *pVdbe;
45904   iCnt = 0;
45905   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
45906     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
45907       iCnt++;
45908     }
45909   }
45910 #else
45911   iCnt = db->activeVdbeCnt;
45912 #endif
45913   if( iCnt>1 ){
45914     rc = SQLITE_LOCKED;
45915     p->errorAction = OE_Abort;
45916   }else{
45917     int iDb = pOp->p3;
45918     assert( iCnt==1 );
45919     assert( (p->btreeMask & (1<<iDb))!=0 );
45920     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
45921     MemSetTypeFlag(pOut, MEM_Int);
45922     pOut->u.i = iMoved;
45923 #ifndef SQLITE_OMIT_AUTOVACUUM
45924     if( rc==SQLITE_OK && iMoved!=0 ){
45925       sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
45926     }
45927 #endif
45928   }
45929   break;
45930 }
45931
45932 /* Opcode: Clear P1 P2 *
45933 **
45934 ** Delete all contents of the database table or index whose root page
45935 ** in the database file is given by P1.  But, unlike Destroy, do not
45936 ** remove the table or index from the database file.
45937 **
45938 ** The table being clear is in the main database file if P2==0.  If
45939 ** P2==1 then the table to be clear is in the auxiliary database file
45940 ** that is used to store tables create using CREATE TEMPORARY TABLE.
45941 **
45942 ** See also: Destroy
45943 */
45944 case OP_Clear: {
45945   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
45946   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
45947   break;
45948 }
45949
45950 /* Opcode: CreateTable P1 P2 * * *
45951 **
45952 ** Allocate a new table in the main database file if P1==0 or in the
45953 ** auxiliary database file if P1==1 or in an attached database if
45954 ** P1>1.  Write the root page number of the new table into
45955 ** register P2
45956 **
45957 ** The difference between a table and an index is this:  A table must
45958 ** have a 4-byte integer key and can have arbitrary data.  An index
45959 ** has an arbitrary key but no data.
45960 **
45961 ** See also: CreateIndex
45962 */
45963 /* Opcode: CreateIndex P1 P2 * * *
45964 **
45965 ** Allocate a new index in the main database file if P1==0 or in the
45966 ** auxiliary database file if P1==1 or in an attached database if
45967 ** P1>1.  Write the root page number of the new table into
45968 ** register P2.
45969 **
45970 ** See documentation on OP_CreateTable for additional information.
45971 */
45972 case OP_CreateIndex:            /* out2-prerelease */
45973 case OP_CreateTable: {          /* out2-prerelease */
45974   int pgno;
45975   int flags;
45976   Db *pDb;
45977   assert( pOp->p1>=0 && pOp->p1<db->nDb );
45978   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
45979   pDb = &db->aDb[pOp->p1];
45980   assert( pDb->pBt!=0 );
45981   if( pOp->opcode==OP_CreateTable ){
45982     /* flags = BTREE_INTKEY; */
45983     flags = BTREE_LEAFDATA|BTREE_INTKEY;
45984   }else{
45985     flags = BTREE_ZERODATA;
45986   }
45987   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
45988   if( rc==SQLITE_OK ){
45989     pOut->u.i = pgno;
45990     MemSetTypeFlag(pOut, MEM_Int);
45991   }
45992   break;
45993 }
45994
45995 /* Opcode: ParseSchema P1 P2 * P4 *
45996 **
45997 ** Read and parse all entries from the SQLITE_MASTER table of database P1
45998 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
45999 ** the parsing if P2 is true.  If P2 is false, then this routine is a
46000 ** no-op if the schema is not currently loaded.  In other words, if P2
46001 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
46002 ** schema is already loaded into the symbol table.
46003 **
46004 ** This opcode invokes the parser to create a new virtual machine,
46005 ** then runs the new virtual machine.  It is thus a reentrant opcode.
46006 */
46007 case OP_ParseSchema: {
46008   char *zSql;
46009   int iDb = pOp->p1;
46010   const char *zMaster;
46011   InitData initData;
46012
46013   assert( iDb>=0 && iDb<db->nDb );
46014   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
46015     break;
46016   }
46017   zMaster = SCHEMA_TABLE(iDb);
46018   initData.db = db;
46019   initData.iDb = pOp->p1;
46020   initData.pzErrMsg = &p->zErrMsg;
46021   zSql = sqlite3MPrintf(db,
46022      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
46023      db->aDb[iDb].zName, zMaster, pOp->p4.z);
46024   if( zSql==0 ) goto no_mem;
46025   (void)sqlite3SafetyOff(db);
46026   assert( db->init.busy==0 );
46027   db->init.busy = 1;
46028   assert( !db->mallocFailed );
46029   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
46030   if( rc==SQLITE_ABORT ) rc = initData.rc;
46031   sqlite3_free(zSql);
46032   db->init.busy = 0;
46033   (void)sqlite3SafetyOn(db);
46034   if( rc==SQLITE_NOMEM ){
46035     goto no_mem;
46036   }
46037   break;  
46038 }
46039
46040 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
46041 /* Opcode: LoadAnalysis P1 * * * *
46042 **
46043 ** Read the sqlite_stat1 table for database P1 and load the content
46044 ** of that table into the internal index hash table.  This will cause
46045 ** the analysis to be used when preparing all subsequent queries.
46046 */
46047 case OP_LoadAnalysis: {
46048   int iDb = pOp->p1;
46049   assert( iDb>=0 && iDb<db->nDb );
46050   rc = sqlite3AnalysisLoad(db, iDb);
46051   break;  
46052 }
46053 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
46054
46055 /* Opcode: DropTable P1 * * P4 *
46056 **
46057 ** Remove the internal (in-memory) data structures that describe
46058 ** the table named P4 in database P1.  This is called after a table
46059 ** is dropped in order to keep the internal representation of the
46060 ** schema consistent with what is on disk.
46061 */
46062 case OP_DropTable: {
46063   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
46064   break;
46065 }
46066
46067 /* Opcode: DropIndex P1 * * P4 *
46068 **
46069 ** Remove the internal (in-memory) data structures that describe
46070 ** the index named P4 in database P1.  This is called after an index
46071 ** is dropped in order to keep the internal representation of the
46072 ** schema consistent with what is on disk.
46073 */
46074 case OP_DropIndex: {
46075   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
46076   break;
46077 }
46078
46079 /* Opcode: DropTrigger P1 * * P4 *
46080 **
46081 ** Remove the internal (in-memory) data structures that describe
46082 ** the trigger named P4 in database P1.  This is called after a trigger
46083 ** is dropped in order to keep the internal representation of the
46084 ** schema consistent with what is on disk.
46085 */
46086 case OP_DropTrigger: {
46087   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
46088   break;
46089 }
46090
46091
46092 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
46093 /* Opcode: IntegrityCk P1 P2 P3 * P5
46094 **
46095 ** Do an analysis of the currently open database.  Store in
46096 ** register P1 the text of an error message describing any problems.
46097 ** If no problems are found, store a NULL in register P1.
46098 **
46099 ** The register P3 contains the maximum number of allowed errors.
46100 ** At most reg(P3) errors will be reported.
46101 ** In other words, the analysis stops as soon as reg(P1) errors are 
46102 ** seen.  Reg(P1) is updated with the number of errors remaining.
46103 **
46104 ** The root page numbers of all tables in the database are integer
46105 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
46106 ** total.
46107 **
46108 ** If P5 is not zero, the check is done on the auxiliary database
46109 ** file, not the main database file.
46110 **
46111 ** This opcode is used to implement the integrity_check pragma.
46112 */
46113 case OP_IntegrityCk: {
46114   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
46115   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
46116   int j;          /* Loop counter */
46117   int nErr;       /* Number of errors reported */
46118   char *z;        /* Text of the error report */
46119   Mem *pnErr;     /* Register keeping track of errors remaining */
46120   
46121   nRoot = pOp->p2;
46122   assert( nRoot>0 );
46123   aRoot = sqlite3_malloc( sizeof(int)*(nRoot+1) );
46124   if( aRoot==0 ) goto no_mem;
46125   assert( pOp->p3>0 && pOp->p3<=p->nMem );
46126   pnErr = &p->aMem[pOp->p3];
46127   assert( (pnErr->flags & MEM_Int)!=0 );
46128   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
46129   pIn1 = &p->aMem[pOp->p1];
46130   for(j=0; j<nRoot; j++){
46131     aRoot[j] = sqlite3VdbeIntValue(&pIn1[j]);
46132   }
46133   aRoot[j] = 0;
46134   assert( pOp->p5<db->nDb );
46135   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
46136   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
46137                                  pnErr->u.i, &nErr);
46138   pnErr->u.i -= nErr;
46139   sqlite3VdbeMemSetNull(pIn1);
46140   if( nErr==0 ){
46141     assert( z==0 );
46142   }else{
46143     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
46144   }
46145   UPDATE_MAX_BLOBSIZE(pIn1);
46146   sqlite3VdbeChangeEncoding(pIn1, encoding);
46147   sqlite3_free(aRoot);
46148   break;
46149 }
46150 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
46151
46152 /* Opcode: FifoWrite P1 * * * *
46153 **
46154 ** Write the integer from register P1 into the Fifo.
46155 */
46156 case OP_FifoWrite: {        /* in1 */
46157   if( sqlite3VdbeFifoPush(&p->sFifo, sqlite3VdbeIntValue(pIn1))==SQLITE_NOMEM ){
46158     goto no_mem;
46159   }
46160   break;
46161 }
46162
46163 /* Opcode: FifoRead P1 P2 * * *
46164 **
46165 ** Attempt to read a single integer from the Fifo.  Store that
46166 ** integer in register P1.
46167 ** 
46168 ** If the Fifo is empty jump to P2.
46169 */
46170 case OP_FifoRead: {         /* jump */
46171   CHECK_FOR_INTERRUPT;
46172   assert( pOp->p1>0 && pOp->p1<=p->nMem );
46173   pOut = &p->aMem[pOp->p1];
46174   MemSetTypeFlag(pOut, MEM_Int);
46175   if( sqlite3VdbeFifoPop(&p->sFifo, &pOut->u.i)==SQLITE_DONE ){
46176     pc = pOp->p2 - 1;
46177   }
46178   break;
46179 }
46180
46181 #ifndef SQLITE_OMIT_TRIGGER
46182 /* Opcode: ContextPush * * * 
46183 **
46184 ** Save the current Vdbe context such that it can be restored by a ContextPop
46185 ** opcode. The context stores the last insert row id, the last statement change
46186 ** count, and the current statement change count.
46187 */
46188 case OP_ContextPush: {
46189   int i = p->contextStackTop++;
46190   Context *pContext;
46191
46192   assert( i>=0 );
46193   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
46194   if( i>=p->contextStackDepth ){
46195     p->contextStackDepth = i+1;
46196     p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
46197                                           sizeof(Context)*(i+1));
46198     if( p->contextStack==0 ) goto no_mem;
46199   }
46200   pContext = &p->contextStack[i];
46201   pContext->lastRowid = db->lastRowid;
46202   pContext->nChange = p->nChange;
46203   pContext->sFifo = p->sFifo;
46204   sqlite3VdbeFifoInit(&p->sFifo);
46205   break;
46206 }
46207
46208 /* Opcode: ContextPop * * * 
46209 **
46210 ** Restore the Vdbe context to the state it was in when contextPush was last
46211 ** executed. The context stores the last insert row id, the last statement
46212 ** change count, and the current statement change count.
46213 */
46214 case OP_ContextPop: {
46215   Context *pContext = &p->contextStack[--p->contextStackTop];
46216   assert( p->contextStackTop>=0 );
46217   db->lastRowid = pContext->lastRowid;
46218   p->nChange = pContext->nChange;
46219   sqlite3VdbeFifoClear(&p->sFifo);
46220   p->sFifo = pContext->sFifo;
46221   break;
46222 }
46223 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
46224
46225 #ifndef SQLITE_OMIT_AUTOINCREMENT
46226 /* Opcode: MemMax P1 P2 * * *
46227 **
46228 ** Set the value of register P1 to the maximum of its current value
46229 ** and the value in register P2.
46230 **
46231 ** This instruction throws an error if the memory cell is not initially
46232 ** an integer.
46233 */
46234 case OP_MemMax: {        /* in1, in2 */
46235   sqlite3VdbeMemIntegerify(pIn1);
46236   sqlite3VdbeMemIntegerify(pIn2);
46237   if( pIn1->u.i<pIn2->u.i){
46238     pIn1->u.i = pIn2->u.i;
46239   }
46240   break;
46241 }
46242 #endif /* SQLITE_OMIT_AUTOINCREMENT */
46243
46244 /* Opcode: IfPos P1 P2 * * *
46245 **
46246 ** If the value of register P1 is 1 or greater, jump to P2.
46247 **
46248 ** It is illegal to use this instruction on a register that does
46249 ** not contain an integer.  An assertion fault will result if you try.
46250 */
46251 case OP_IfPos: {        /* jump, in1 */
46252   assert( pIn1->flags&MEM_Int );
46253   if( pIn1->u.i>0 ){
46254      pc = pOp->p2 - 1;
46255   }
46256   break;
46257 }
46258
46259 /* Opcode: IfNeg P1 P2 * * *
46260 **
46261 ** If the value of register P1 is less than zero, jump to P2. 
46262 **
46263 ** It is illegal to use this instruction on a register that does
46264 ** not contain an integer.  An assertion fault will result if you try.
46265 */
46266 case OP_IfNeg: {        /* jump, in1 */
46267   assert( pIn1->flags&MEM_Int );
46268   if( pIn1->u.i<0 ){
46269      pc = pOp->p2 - 1;
46270   }
46271   break;
46272 }
46273
46274 /* Opcode: IfZero P1 P2 * * *
46275 **
46276 ** If the value of register P1 is exactly 0, jump to P2. 
46277 **
46278 ** It is illegal to use this instruction on a register that does
46279 ** not contain an integer.  An assertion fault will result if you try.
46280 */
46281 case OP_IfZero: {        /* jump, in1 */
46282   assert( pIn1->flags&MEM_Int );
46283   if( pIn1->u.i==0 ){
46284      pc = pOp->p2 - 1;
46285   }
46286   break;
46287 }
46288
46289 /* Opcode: AggStep * P2 P3 P4 P5
46290 **
46291 ** Execute the step function for an aggregate.  The
46292 ** function has P5 arguments.   P4 is a pointer to the FuncDef
46293 ** structure that specifies the function.  Use register
46294 ** P3 as the accumulator.
46295 **
46296 ** The P5 arguments are taken from register P2 and its
46297 ** successors.
46298 */
46299 case OP_AggStep: {
46300   int n = pOp->p5;
46301   int i;
46302   Mem *pMem, *pRec;
46303   sqlite3_context ctx;
46304   sqlite3_value **apVal;
46305
46306   assert( n>=0 );
46307   pRec = &p->aMem[pOp->p2];
46308   apVal = p->apArg;
46309   assert( apVal || n==0 );
46310   for(i=0; i<n; i++, pRec++){
46311     apVal[i] = pRec;
46312     storeTypeInfo(pRec, encoding);
46313   }
46314   ctx.pFunc = pOp->p4.pFunc;
46315   assert( pOp->p3>0 && pOp->p3<=p->nMem );
46316   ctx.pMem = pMem = &p->aMem[pOp->p3];
46317   pMem->n++;
46318   ctx.s.flags = MEM_Null;
46319   ctx.s.z = 0;
46320   ctx.s.zMalloc = 0;
46321   ctx.s.xDel = 0;
46322   ctx.s.db = db;
46323   ctx.isError = 0;
46324   ctx.pColl = 0;
46325   if( ctx.pFunc->needCollSeq ){
46326     assert( pOp>p->aOp );
46327     assert( pOp[-1].p4type==P4_COLLSEQ );
46328     assert( pOp[-1].opcode==OP_CollSeq );
46329     ctx.pColl = pOp[-1].p4.pColl;
46330   }
46331   (ctx.pFunc->xStep)(&ctx, n, apVal);
46332   if( ctx.isError ){
46333     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
46334     rc = ctx.isError;
46335   }
46336   sqlite3VdbeMemRelease(&ctx.s);
46337   break;
46338 }
46339
46340 /* Opcode: AggFinal P1 P2 * P4 *
46341 **
46342 ** Execute the finalizer function for an aggregate.  P1 is
46343 ** the memory location that is the accumulator for the aggregate.
46344 **
46345 ** P2 is the number of arguments that the step function takes and
46346 ** P4 is a pointer to the FuncDef for this function.  The P2
46347 ** argument is not used by this opcode.  It is only there to disambiguate
46348 ** functions that can take varying numbers of arguments.  The
46349 ** P4 argument is only needed for the degenerate case where
46350 ** the step function was not previously called.
46351 */
46352 case OP_AggFinal: {
46353   Mem *pMem;
46354   assert( pOp->p1>0 && pOp->p1<=p->nMem );
46355   pMem = &p->aMem[pOp->p1];
46356   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
46357   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
46358   if( rc==SQLITE_ERROR ){
46359     sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
46360   }
46361   sqlite3VdbeChangeEncoding(pMem, encoding);
46362   UPDATE_MAX_BLOBSIZE(pMem);
46363   if( sqlite3VdbeMemTooBig(pMem) ){
46364     goto too_big;
46365   }
46366   break;
46367 }
46368
46369
46370 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
46371 /* Opcode: Vacuum * * * * *
46372 **
46373 ** Vacuum the entire database.  This opcode will cause other virtual
46374 ** machines to be created and run.  It may not be called from within
46375 ** a transaction.
46376 */
46377 case OP_Vacuum: {
46378   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
46379   rc = sqlite3RunVacuum(&p->zErrMsg, db);
46380   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46381   break;
46382 }
46383 #endif
46384
46385 #if !defined(SQLITE_OMIT_AUTOVACUUM)
46386 /* Opcode: IncrVacuum P1 P2 * * *
46387 **
46388 ** Perform a single step of the incremental vacuum procedure on
46389 ** the P1 database. If the vacuum has finished, jump to instruction
46390 ** P2. Otherwise, fall through to the next instruction.
46391 */
46392 case OP_IncrVacuum: {        /* jump */
46393   Btree *pBt;
46394
46395   assert( pOp->p1>=0 && pOp->p1<db->nDb );
46396   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
46397   pBt = db->aDb[pOp->p1].pBt;
46398   rc = sqlite3BtreeIncrVacuum(pBt);
46399   if( rc==SQLITE_DONE ){
46400     pc = pOp->p2 - 1;
46401     rc = SQLITE_OK;
46402   }
46403   break;
46404 }
46405 #endif
46406
46407 /* Opcode: Expire P1 * * * *
46408 **
46409 ** Cause precompiled statements to become expired. An expired statement
46410 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
46411 ** (via sqlite3_step()).
46412 ** 
46413 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
46414 ** then only the currently executing statement is affected. 
46415 */
46416 case OP_Expire: {
46417   if( !pOp->p1 ){
46418     sqlite3ExpirePreparedStatements(db);
46419   }else{
46420     p->expired = 1;
46421   }
46422   break;
46423 }
46424
46425 #ifndef SQLITE_OMIT_SHARED_CACHE
46426 /* Opcode: TableLock P1 P2 P3 P4 *
46427 **
46428 ** Obtain a lock on a particular table. This instruction is only used when
46429 ** the shared-cache feature is enabled. 
46430 **
46431 ** If P1 is  the index of the database in sqlite3.aDb[] of the database
46432 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
46433 ** a write lock if P3==1.
46434 **
46435 ** P2 contains the root-page of the table to lock.
46436 **
46437 ** P4 contains a pointer to the name of the table being locked. This is only
46438 ** used to generate an error message if the lock cannot be obtained.
46439 */
46440 case OP_TableLock: {
46441   int p1 = pOp->p1; 
46442   u8 isWriteLock = pOp->p3;
46443   assert( p1>=0 && p1<db->nDb );
46444   assert( (p->btreeMask & (1<<p1))!=0 );
46445   assert( isWriteLock==0 || isWriteLock==1 );
46446   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
46447   if( rc==SQLITE_LOCKED ){
46448     const char *z = pOp->p4.z;
46449     sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
46450   }
46451   break;
46452 }
46453 #endif /* SQLITE_OMIT_SHARED_CACHE */
46454
46455 #ifndef SQLITE_OMIT_VIRTUALTABLE
46456 /* Opcode: VBegin * * * P4 *
46457 **
46458 ** P4 a pointer to an sqlite3_vtab structure. Call the xBegin method 
46459 ** for that table.
46460 */
46461 case OP_VBegin: {
46462   rc = sqlite3VtabBegin(db, pOp->p4.pVtab);
46463   break;
46464 }
46465 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46466
46467 #ifndef SQLITE_OMIT_VIRTUALTABLE
46468 /* Opcode: VCreate P1 * * P4 *
46469 **
46470 ** P4 is the name of a virtual table in database P1. Call the xCreate method
46471 ** for that table.
46472 */
46473 case OP_VCreate: {
46474   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
46475   break;
46476 }
46477 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46478
46479 #ifndef SQLITE_OMIT_VIRTUALTABLE
46480 /* Opcode: VDestroy P1 * * P4 *
46481 **
46482 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
46483 ** of that table.
46484 */
46485 case OP_VDestroy: {
46486   p->inVtabMethod = 2;
46487   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
46488   p->inVtabMethod = 0;
46489   break;
46490 }
46491 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46492
46493 #ifndef SQLITE_OMIT_VIRTUALTABLE
46494 /* Opcode: VOpen P1 * * P4 *
46495 **
46496 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
46497 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
46498 ** table and stores that cursor in P1.
46499 */
46500 case OP_VOpen: {
46501   Cursor *pCur = 0;
46502   sqlite3_vtab_cursor *pVtabCursor = 0;
46503
46504   sqlite3_vtab *pVtab = pOp->p4.pVtab;
46505   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
46506
46507   assert(pVtab && pModule);
46508   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46509   rc = pModule->xOpen(pVtab, &pVtabCursor);
46510   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46511   if( SQLITE_OK==rc ){
46512     /* Initialise sqlite3_vtab_cursor base class */
46513     pVtabCursor->pVtab = pVtab;
46514
46515     /* Initialise vdbe cursor object */
46516     pCur = allocateCursor(p, pOp->p1, &pOp[-1], -1, 0);
46517     if( pCur ){
46518       pCur->pVtabCursor = pVtabCursor;
46519       pCur->pModule = pVtabCursor->pVtab->pModule;
46520     }else{
46521       db->mallocFailed = 1;
46522       pModule->xClose(pVtabCursor);
46523     }
46524   }
46525   break;
46526 }
46527 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46528
46529 #ifndef SQLITE_OMIT_VIRTUALTABLE
46530 /* Opcode: VFilter P1 P2 P3 P4 *
46531 **
46532 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
46533 ** the filtered result set is empty.
46534 **
46535 ** P4 is either NULL or a string that was generated by the xBestIndex
46536 ** method of the module.  The interpretation of the P4 string is left
46537 ** to the module implementation.
46538 **
46539 ** This opcode invokes the xFilter method on the virtual table specified
46540 ** by P1.  The integer query plan parameter to xFilter is stored in register
46541 ** P3. Register P3+1 stores the argc parameter to be passed to the
46542 ** xFilter method. Registers P3+2..P3+1+argc are the argc additional
46543 ** parametersneath additional parameters which are passed to
46544 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
46545 **
46546 ** A jump is made to P2 if the result set after filtering would be empty.
46547 */
46548 case OP_VFilter: {   /* jump */
46549   int nArg;
46550   int iQuery;
46551   const sqlite3_module *pModule;
46552   Mem *pQuery = &p->aMem[pOp->p3];
46553   Mem *pArgc = &pQuery[1];
46554
46555   Cursor *pCur = p->apCsr[pOp->p1];
46556
46557   REGISTER_TRACE(pOp->p3, pQuery);
46558   assert( pCur->pVtabCursor );
46559   pModule = pCur->pVtabCursor->pVtab->pModule;
46560
46561   /* Grab the index number and argc parameters */
46562   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
46563   nArg = pArgc->u.i;
46564   iQuery = pQuery->u.i;
46565
46566   /* Invoke the xFilter method */
46567   {
46568     int res = 0;
46569     int i;
46570     Mem **apArg = p->apArg;
46571     for(i = 0; i<nArg; i++){
46572       apArg[i] = &pArgc[i+1];
46573       storeTypeInfo(apArg[i], 0);
46574     }
46575
46576     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46577     p->inVtabMethod = 1;
46578     rc = pModule->xFilter(pCur->pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
46579     p->inVtabMethod = 0;
46580     if( rc==SQLITE_OK ){
46581       res = pModule->xEof(pCur->pVtabCursor);
46582     }
46583     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46584
46585     if( res ){
46586       pc = pOp->p2 - 1;
46587     }
46588   }
46589   pCur->nullRow = 0;
46590
46591   break;
46592 }
46593 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46594
46595 #ifndef SQLITE_OMIT_VIRTUALTABLE
46596 /* Opcode: VRowid P1 P2 * * *
46597 **
46598 ** Store into register P2  the rowid of
46599 ** the virtual-table that the P1 cursor is pointing to.
46600 */
46601 case OP_VRowid: {             /* out2-prerelease */
46602   const sqlite3_module *pModule;
46603   sqlite_int64 iRow;
46604   Cursor *pCur = p->apCsr[pOp->p1];
46605
46606   assert( pCur->pVtabCursor );
46607   if( pCur->nullRow ){
46608     break;
46609   }
46610   pModule = pCur->pVtabCursor->pVtab->pModule;
46611   assert( pModule->xRowid );
46612   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46613   rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
46614   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46615   MemSetTypeFlag(pOut, MEM_Int);
46616   pOut->u.i = iRow;
46617   break;
46618 }
46619 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46620
46621 #ifndef SQLITE_OMIT_VIRTUALTABLE
46622 /* Opcode: VColumn P1 P2 P3 * *
46623 **
46624 ** Store the value of the P2-th column of
46625 ** the row of the virtual-table that the 
46626 ** P1 cursor is pointing to into register P3.
46627 */
46628 case OP_VColumn: {
46629   const sqlite3_module *pModule;
46630   Mem *pDest;
46631   sqlite3_context sContext;
46632
46633   Cursor *pCur = p->apCsr[pOp->p1];
46634   assert( pCur->pVtabCursor );
46635   assert( pOp->p3>0 && pOp->p3<=p->nMem );
46636   pDest = &p->aMem[pOp->p3];
46637   if( pCur->nullRow ){
46638     sqlite3VdbeMemSetNull(pDest);
46639     break;
46640   }
46641   pModule = pCur->pVtabCursor->pVtab->pModule;
46642   assert( pModule->xColumn );
46643   memset(&sContext, 0, sizeof(sContext));
46644
46645   /* The output cell may already have a buffer allocated. Move
46646   ** the current contents to sContext.s so in case the user-function 
46647   ** can use the already allocated buffer instead of allocating a 
46648   ** new one.
46649   */
46650   sqlite3VdbeMemMove(&sContext.s, pDest);
46651   MemSetTypeFlag(&sContext.s, MEM_Null);
46652
46653   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46654   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
46655
46656   /* Copy the result of the function to the P3 register. We
46657   ** do this regardless of whether or not an error occured to ensure any
46658   ** dynamic allocation in sContext.s (a Mem struct) is  released.
46659   */
46660   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
46661   REGISTER_TRACE(pOp->p3, pDest);
46662   sqlite3VdbeMemMove(pDest, &sContext.s);
46663   UPDATE_MAX_BLOBSIZE(pDest);
46664
46665   if( sqlite3SafetyOn(db) ){
46666     goto abort_due_to_misuse;
46667   }
46668   if( sqlite3VdbeMemTooBig(pDest) ){
46669     goto too_big;
46670   }
46671   break;
46672 }
46673 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46674
46675 #ifndef SQLITE_OMIT_VIRTUALTABLE
46676 /* Opcode: VNext P1 P2 * * *
46677 **
46678 ** Advance virtual table P1 to the next row in its result set and
46679 ** jump to instruction P2.  Or, if the virtual table has reached
46680 ** the end of its result set, then fall through to the next instruction.
46681 */
46682 case OP_VNext: {   /* jump */
46683   const sqlite3_module *pModule;
46684   int res = 0;
46685
46686   Cursor *pCur = p->apCsr[pOp->p1];
46687   assert( pCur->pVtabCursor );
46688   if( pCur->nullRow ){
46689     break;
46690   }
46691   pModule = pCur->pVtabCursor->pVtab->pModule;
46692   assert( pModule->xNext );
46693
46694   /* Invoke the xNext() method of the module. There is no way for the
46695   ** underlying implementation to return an error if one occurs during
46696   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
46697   ** data is available) and the error code returned when xColumn or
46698   ** some other method is next invoked on the save virtual table cursor.
46699   */
46700   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46701   p->inVtabMethod = 1;
46702   rc = pModule->xNext(pCur->pVtabCursor);
46703   p->inVtabMethod = 0;
46704   if( rc==SQLITE_OK ){
46705     res = pModule->xEof(pCur->pVtabCursor);
46706   }
46707   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46708
46709   if( !res ){
46710     /* If there is data, jump to P2 */
46711     pc = pOp->p2 - 1;
46712   }
46713   break;
46714 }
46715 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46716
46717 #ifndef SQLITE_OMIT_VIRTUALTABLE
46718 /* Opcode: VRename P1 * * P4 *
46719 **
46720 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
46721 ** This opcode invokes the corresponding xRename method. The value
46722 ** in register P1 is passed as the zName argument to the xRename method.
46723 */
46724 case OP_VRename: {
46725   sqlite3_vtab *pVtab = pOp->p4.pVtab;
46726   Mem *pName = &p->aMem[pOp->p1];
46727   assert( pVtab->pModule->xRename );
46728   REGISTER_TRACE(pOp->p1, pName);
46729
46730   Stringify(pName, encoding);
46731
46732   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46733   sqlite3VtabLock(pVtab);
46734   rc = pVtab->pModule->xRename(pVtab, pName->z);
46735   sqlite3VtabUnlock(db, pVtab);
46736   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46737
46738   break;
46739 }
46740 #endif
46741
46742 #ifndef SQLITE_OMIT_VIRTUALTABLE
46743 /* Opcode: VUpdate P1 P2 P3 P4 *
46744 **
46745 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
46746 ** This opcode invokes the corresponding xUpdate method. P2 values
46747 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
46748 ** invocation. The value in register (P3+P2-1) corresponds to the 
46749 ** p2th element of the argv array passed to xUpdate.
46750 **
46751 ** The xUpdate method will do a DELETE or an INSERT or both.
46752 ** The argv[0] element (which corresponds to memory cell P3)
46753 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
46754 ** deletion occurs.  The argv[1] element is the rowid of the new 
46755 ** row.  This can be NULL to have the virtual table select the new 
46756 ** rowid for itself.  The subsequent elements in the array are 
46757 ** the values of columns in the new row.
46758 **
46759 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
46760 ** a row to delete.
46761 **
46762 ** P1 is a boolean flag. If it is set to true and the xUpdate call
46763 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
46764 ** is set to the value of the rowid for the row just inserted.
46765 */
46766 case OP_VUpdate: {
46767   sqlite3_vtab *pVtab = pOp->p4.pVtab;
46768   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
46769   int nArg = pOp->p2;
46770   assert( pOp->p4type==P4_VTAB );
46771   if( pModule->xUpdate==0 ){
46772     sqlite3SetString(&p->zErrMsg, "read-only table", 0);
46773     rc = SQLITE_ERROR;
46774   }else{
46775     int i;
46776     sqlite_int64 rowid;
46777     Mem **apArg = p->apArg;
46778     Mem *pX = &p->aMem[pOp->p3];
46779     for(i=0; i<nArg; i++){
46780       storeTypeInfo(pX, 0);
46781       apArg[i] = pX;
46782       pX++;
46783     }
46784     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46785     sqlite3VtabLock(pVtab);
46786     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
46787     sqlite3VtabUnlock(db, pVtab);
46788     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46789     if( pOp->p1 && rc==SQLITE_OK ){
46790       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
46791       db->lastRowid = rowid;
46792     }
46793     p->nChange++;
46794   }
46795   break;
46796 }
46797 #endif /* SQLITE_OMIT_VIRTUALTABLE */
46798
46799 #ifndef SQLITE_OMIT_TRACE
46800 /* Opcode: Trace * * * P4 *
46801 **
46802 ** If tracing is enabled (by the sqlite3_trace()) interface, then
46803 ** the UTF-8 string contained in P4 is emitted on the trace callback.
46804 */
46805 case OP_Trace: {
46806   if( pOp->p4.z ){
46807     if( db->xTrace ){
46808       db->xTrace(db->pTraceArg, pOp->p4.z);
46809     }
46810 #ifdef SQLITE_DEBUG
46811     if( (db->flags & SQLITE_SqlTrace)!=0 ){
46812       sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
46813     }
46814 #endif /* SQLITE_DEBUG */
46815   }
46816   break;
46817 }
46818 #endif
46819
46820
46821 /* Opcode: Noop * * * * *
46822 **
46823 ** Do nothing.  This instruction is often useful as a jump
46824 ** destination.
46825 */
46826 /*
46827 ** The magic Explain opcode are only inserted when explain==2 (which
46828 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
46829 ** This opcode records information from the optimizer.  It is the
46830 ** the same as a no-op.  This opcodesnever appears in a real VM program.
46831 */
46832 default: {          /* This is really OP_Noop and OP_Explain */
46833   break;
46834 }
46835
46836 /*****************************************************************************
46837 ** The cases of the switch statement above this line should all be indented
46838 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
46839 ** readability.  From this point on down, the normal indentation rules are
46840 ** restored.
46841 *****************************************************************************/
46842     }
46843
46844 #ifdef VDBE_PROFILE
46845     {
46846       long long elapse = hwtime() - start;
46847       pOp->cycles += elapse;
46848       pOp->cnt++;
46849 #if 0
46850         fprintf(stdout, "%10lld ", elapse);
46851         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
46852 #endif
46853     }
46854 #endif
46855
46856     /* The following code adds nothing to the actual functionality
46857     ** of the program.  It is only here for testing and debugging.
46858     ** On the other hand, it does burn CPU cycles every time through
46859     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
46860     */
46861 #ifndef NDEBUG
46862     assert( pc>=-1 && pc<p->nOp );
46863
46864 #ifdef SQLITE_DEBUG
46865     if( p->trace ){
46866       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
46867       if( opProperty & OPFLG_OUT2_PRERELEASE ){
46868         registerTrace(p->trace, pOp->p2, pOut);
46869       }
46870       if( opProperty & OPFLG_OUT3 ){
46871         registerTrace(p->trace, pOp->p3, pOut);
46872       }
46873     }
46874 #endif  /* SQLITE_DEBUG */
46875 #endif  /* NDEBUG */
46876   }  /* The end of the for(;;) loop the loops through opcodes */
46877
46878   /* If we reach this point, it means that execution is finished with
46879   ** an error of some kind.
46880   */
46881 vdbe_error_halt:
46882   assert( rc );
46883   p->rc = rc;
46884   rc = SQLITE_ERROR;
46885   sqlite3VdbeHalt(p);
46886
46887   /* This is the only way out of this procedure.  We have to
46888   ** release the mutexes on btrees that were acquired at the
46889   ** top. */
46890 vdbe_return:
46891   sqlite3BtreeMutexArrayLeave(&p->aMutex);
46892   return rc;
46893
46894   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
46895   ** is encountered.
46896   */
46897 too_big:
46898   sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
46899   rc = SQLITE_TOOBIG;
46900   goto vdbe_error_halt;
46901
46902   /* Jump to here if a malloc() fails.
46903   */
46904 no_mem:
46905   db->mallocFailed = 1;
46906   sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
46907   rc = SQLITE_NOMEM;
46908   goto vdbe_error_halt;
46909
46910   /* Jump to here for an SQLITE_MISUSE error.
46911   */
46912 abort_due_to_misuse:
46913   rc = SQLITE_MISUSE;
46914   /* Fall thru into abort_due_to_error */
46915
46916   /* Jump to here for any other kind of fatal error.  The "rc" variable
46917   ** should hold the error number.
46918   */
46919 abort_due_to_error:
46920   assert( p->zErrMsg==0 );
46921   if( db->mallocFailed ) rc = SQLITE_NOMEM;
46922   sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
46923   goto vdbe_error_halt;
46924
46925   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
46926   ** flag.
46927   */
46928 abort_due_to_interrupt:
46929   assert( db->u1.isInterrupted );
46930   rc = SQLITE_INTERRUPT;
46931   p->rc = rc;
46932   sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
46933   goto vdbe_error_halt;
46934 }
46935
46936 /************** End of vdbe.c ************************************************/
46937 /************** Begin file vdbeblob.c ****************************************/
46938 /*
46939 ** 2007 May 1
46940 **
46941 ** The author disclaims copyright to this source code.  In place of
46942 ** a legal notice, here is a blessing:
46943 **
46944 **    May you do good and not evil.
46945 **    May you find forgiveness for yourself and forgive others.
46946 **    May you share freely, never taking more than you give.
46947 **
46948 *************************************************************************
46949 **
46950 ** This file contains code used to implement incremental BLOB I/O.
46951 **
46952 ** $Id: vdbeblob.c,v 1.22 2008/04/24 09:49:55 danielk1977 Exp $
46953 */
46954
46955
46956 #ifndef SQLITE_OMIT_INCRBLOB
46957
46958 /*
46959 ** Valid sqlite3_blob* handles point to Incrblob structures.
46960 */
46961 typedef struct Incrblob Incrblob;
46962 struct Incrblob {
46963   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
46964   int nByte;              /* Size of open blob, in bytes */
46965   int iOffset;            /* Byte offset of blob in cursor data */
46966   BtCursor *pCsr;         /* Cursor pointing at blob row */
46967   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
46968   sqlite3 *db;            /* The associated database */
46969 };
46970
46971 /*
46972 ** Open a blob handle.
46973 */
46974 SQLITE_API int sqlite3_blob_open(
46975   sqlite3* db,            /* The database connection */
46976   const char *zDb,        /* The attached database containing the blob */
46977   const char *zTable,     /* The table containing the blob */
46978   const char *zColumn,    /* The column containing the blob */
46979   sqlite_int64 iRow,      /* The row containing the glob */
46980   int flags,              /* True -> read/write access, false -> read-only */
46981   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
46982 ){
46983   int nAttempt = 0;
46984   int iCol;               /* Index of zColumn in row-record */
46985
46986   /* This VDBE program seeks a btree cursor to the identified 
46987   ** db/table/row entry. The reason for using a vdbe program instead
46988   ** of writing code to use the b-tree layer directly is that the
46989   ** vdbe program will take advantage of the various transaction,
46990   ** locking and error handling infrastructure built into the vdbe.
46991   **
46992   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
46993   ** Code external to the Vdbe then "borrows" the b-tree cursor and
46994   ** uses it to implement the blob_read(), blob_write() and 
46995   ** blob_bytes() functions.
46996   **
46997   ** The sqlite3_blob_close() function finalizes the vdbe program,
46998   ** which closes the b-tree cursor and (possibly) commits the 
46999   ** transaction.
47000   */
47001   static const VdbeOpList openBlob[] = {
47002     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
47003     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
47004
47005     /* One of the following two instructions is replaced by an
47006     ** OP_Noop before exection.
47007     */
47008     {OP_SetNumColumns, 0, 0, 0},   /* 2: Num cols for cursor */
47009     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
47010     {OP_SetNumColumns, 0, 0, 0},   /* 4: Num cols for cursor */
47011     {OP_OpenWrite, 0, 0, 0},       /* 5: Open cursor 0 for read/write */
47012
47013     {OP_Variable, 1, 1, 0},        /* 6: Push the rowid to the stack */
47014     {OP_NotExists, 0, 10, 1},      /* 7: Seek the cursor */
47015     {OP_Column, 0, 0, 1},          /* 8  */
47016     {OP_ResultRow, 1, 0, 0},       /* 9  */
47017     {OP_Close, 0, 0, 0},           /* 10  */
47018     {OP_Halt, 0, 0, 0},            /* 11 */
47019   };
47020
47021   Vdbe *v = 0;
47022   int rc = SQLITE_OK;
47023   char zErr[128];
47024
47025   zErr[0] = 0;
47026   sqlite3_mutex_enter(db->mutex);
47027   do {
47028     Parse sParse;
47029     Table *pTab;
47030
47031     memset(&sParse, 0, sizeof(Parse));
47032     sParse.db = db;
47033
47034     rc = sqlite3SafetyOn(db);
47035     if( rc!=SQLITE_OK ){
47036       sqlite3_mutex_leave(db->mutex);
47037       return rc;
47038     }
47039
47040     sqlite3BtreeEnterAll(db);
47041     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
47042     if( pTab && IsVirtual(pTab) ){
47043       pTab = 0;
47044       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
47045     }
47046 #ifndef SQLITE_OMIT_VIEW
47047     if( pTab && pTab->pSelect ){
47048       pTab = 0;
47049       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
47050     }
47051 #endif
47052     if( !pTab ){
47053       if( sParse.zErrMsg ){
47054         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
47055       }
47056       sqlite3_free(sParse.zErrMsg);
47057       rc = SQLITE_ERROR;
47058       (void)sqlite3SafetyOff(db);
47059       sqlite3BtreeLeaveAll(db);
47060       goto blob_open_out;
47061     }
47062
47063     /* Now search pTab for the exact column. */
47064     for(iCol=0; iCol < pTab->nCol; iCol++) {
47065       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
47066         break;
47067       }
47068     }
47069     if( iCol==pTab->nCol ){
47070       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
47071       rc = SQLITE_ERROR;
47072       (void)sqlite3SafetyOff(db);
47073       sqlite3BtreeLeaveAll(db);
47074       goto blob_open_out;
47075     }
47076
47077     /* If the value is being opened for writing, check that the
47078     ** column is not indexed. It is against the rules to open an
47079     ** indexed column for writing.
47080     */
47081     if( flags ){
47082       Index *pIdx;
47083       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
47084         int j;
47085         for(j=0; j<pIdx->nColumn; j++){
47086           if( pIdx->aiColumn[j]==iCol ){
47087             sqlite3_snprintf(sizeof(zErr), zErr,
47088                              "cannot open indexed column for writing");
47089             rc = SQLITE_ERROR;
47090             (void)sqlite3SafetyOff(db);
47091             sqlite3BtreeLeaveAll(db);
47092             goto blob_open_out;
47093           }
47094         }
47095       }
47096     }
47097
47098     v = sqlite3VdbeCreate(db);
47099     if( v ){
47100       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
47101       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
47102
47103       /* Configure the OP_Transaction */
47104       sqlite3VdbeChangeP1(v, 0, iDb);
47105       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
47106
47107       /* Configure the OP_VerifyCookie */
47108       sqlite3VdbeChangeP1(v, 1, iDb);
47109       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
47110
47111       /* Make sure a mutex is held on the table to be accessed */
47112       sqlite3VdbeUsesBtree(v, iDb); 
47113
47114       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
47115       ** parameter of the other to pTab->tnum. 
47116       */
47117       sqlite3VdbeChangeToNoop(v, (flags ? 3 : 5), 1);
47118       sqlite3VdbeChangeP2(v, (flags ? 5 : 3), pTab->tnum);
47119       sqlite3VdbeChangeP3(v, (flags ? 5 : 3), iDb);
47120
47121       /* Configure the OP_SetNumColumns. Configure the cursor to
47122       ** think that the table has one more column than it really
47123       ** does. An OP_Column to retrieve this imaginary column will
47124       ** always return an SQL NULL. This is useful because it means
47125       ** we can invoke OP_Column to fill in the vdbe cursors type 
47126       ** and offset cache without causing any IO.
47127       */
47128       sqlite3VdbeChangeP2(v, flags ? 4 : 2, pTab->nCol+1);
47129       if( !db->mallocFailed ){
47130         sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
47131       }
47132     }
47133    
47134     sqlite3BtreeLeaveAll(db);
47135     rc = sqlite3SafetyOff(db);
47136     if( rc!=SQLITE_OK || db->mallocFailed ){
47137       goto blob_open_out;
47138     }
47139
47140     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
47141     rc = sqlite3_step((sqlite3_stmt *)v);
47142     if( rc!=SQLITE_ROW ){
47143       nAttempt++;
47144       rc = sqlite3_finalize((sqlite3_stmt *)v);
47145       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
47146       v = 0;
47147     }
47148   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
47149
47150   if( rc==SQLITE_ROW ){
47151     /* The row-record has been opened successfully. Check that the
47152     ** column in question contains text or a blob. If it contains
47153     ** text, it is up to the caller to get the encoding right.
47154     */
47155     Incrblob *pBlob;
47156     u32 type = v->apCsr[0]->aType[iCol];
47157
47158     if( type<12 ){
47159       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
47160           type==0?"null": type==7?"real": "integer"
47161       );
47162       rc = SQLITE_ERROR;
47163       goto blob_open_out;
47164     }
47165     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
47166     if( db->mallocFailed ){
47167       sqlite3_free(pBlob);
47168       goto blob_open_out;
47169     }
47170     pBlob->flags = flags;
47171     pBlob->pCsr =  v->apCsr[0]->pCursor;
47172     sqlite3BtreeEnterCursor(pBlob->pCsr);
47173     sqlite3BtreeCacheOverflow(pBlob->pCsr);
47174     sqlite3BtreeLeaveCursor(pBlob->pCsr);
47175     pBlob->pStmt = (sqlite3_stmt *)v;
47176     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
47177     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
47178     pBlob->db = db;
47179     *ppBlob = (sqlite3_blob *)pBlob;
47180     rc = SQLITE_OK;
47181   }else if( rc==SQLITE_OK ){
47182     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
47183     rc = SQLITE_ERROR;
47184   }
47185
47186 blob_open_out:
47187   zErr[sizeof(zErr)-1] = '\0';
47188   if( rc!=SQLITE_OK || db->mallocFailed ){
47189     sqlite3_finalize((sqlite3_stmt *)v);
47190   }
47191   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
47192   rc = sqlite3ApiExit(db, rc);
47193   sqlite3_mutex_leave(db->mutex);
47194   return rc;
47195 }
47196
47197 /*
47198 ** Close a blob handle that was previously created using
47199 ** sqlite3_blob_open().
47200 */
47201 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
47202   Incrblob *p = (Incrblob *)pBlob;
47203   int rc;
47204
47205   rc = sqlite3_finalize(p->pStmt);
47206   sqlite3_free(p);
47207   return rc;
47208 }
47209
47210 /*
47211 ** Perform a read or write operation on a blob
47212 */
47213 static int blobReadWrite(
47214   sqlite3_blob *pBlob, 
47215   void *z, 
47216   int n, 
47217   int iOffset, 
47218   int (*xCall)(BtCursor*, u32, u32, void*)
47219 ){
47220   int rc;
47221   Incrblob *p = (Incrblob *)pBlob;
47222   Vdbe *v;
47223   sqlite3 *db = p->db;  
47224
47225   /* Request is out of range. Return a transient error. */
47226   if( (iOffset+n)>p->nByte ){
47227     return SQLITE_ERROR;
47228   }
47229   sqlite3_mutex_enter(db->mutex);
47230
47231   /* If there is no statement handle, then the blob-handle has
47232   ** already been invalidated. Return SQLITE_ABORT in this case.
47233   */
47234   v = (Vdbe*)p->pStmt;
47235   if( v==0 ){
47236     rc = SQLITE_ABORT;
47237   }else{
47238     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
47239     ** returned, clean-up the statement handle.
47240     */
47241     assert( db == v->db );
47242     sqlite3BtreeEnterCursor(p->pCsr);
47243     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
47244     sqlite3BtreeLeaveCursor(p->pCsr);
47245     if( rc==SQLITE_ABORT ){
47246       sqlite3VdbeFinalize(v);
47247       p->pStmt = 0;
47248     }else{
47249       db->errCode = rc;
47250       v->rc = rc;
47251     }
47252   }
47253   rc = sqlite3ApiExit(db, rc);
47254   sqlite3_mutex_leave(db->mutex);
47255   return rc;
47256 }
47257
47258 /*
47259 ** Read data from a blob handle.
47260 */
47261 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
47262   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
47263 }
47264
47265 /*
47266 ** Write data to a blob handle.
47267 */
47268 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
47269   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
47270 }
47271
47272 /*
47273 ** Query a blob handle for the size of the data.
47274 **
47275 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
47276 ** so no mutex is required for access.
47277 */
47278 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
47279   Incrblob *p = (Incrblob *)pBlob;
47280   return p->nByte;
47281 }
47282
47283 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
47284
47285 /************** End of vdbeblob.c ********************************************/
47286 /************** Begin file journal.c *****************************************/
47287 /*
47288 ** 2007 August 22
47289 **
47290 ** The author disclaims copyright to this source code.  In place of
47291 ** a legal notice, here is a blessing:
47292 **
47293 **    May you do good and not evil.
47294 **    May you find forgiveness for yourself and forgive others.
47295 **    May you share freely, never taking more than you give.
47296 **
47297 *************************************************************************
47298 **
47299 ** @(#) $Id: journal.c,v 1.8 2008/05/01 18:01:47 drh Exp $
47300 */
47301
47302 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47303
47304 /*
47305 ** This file implements a special kind of sqlite3_file object used
47306 ** by SQLite to create journal files if the atomic-write optimization
47307 ** is enabled.
47308 **
47309 ** The distinctive characteristic of this sqlite3_file is that the
47310 ** actual on disk file is created lazily. When the file is created,
47311 ** the caller specifies a buffer size for an in-memory buffer to
47312 ** be used to service read() and write() requests. The actual file
47313 ** on disk is not created or populated until either:
47314 **
47315 **   1) The in-memory representation grows too large for the allocated 
47316 **      buffer, or
47317 **   2) The xSync() method is called.
47318 */
47319
47320
47321
47322 /*
47323 ** A JournalFile object is a subclass of sqlite3_file used by
47324 ** as an open file handle for journal files.
47325 */
47326 struct JournalFile {
47327   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
47328   int nBuf;                       /* Size of zBuf[] in bytes */
47329   char *zBuf;                     /* Space to buffer journal writes */
47330   int iSize;                      /* Amount of zBuf[] currently used */
47331   int flags;                      /* xOpen flags */
47332   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
47333   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
47334   const char *zJournal;           /* Name of the journal file */
47335 };
47336 typedef struct JournalFile JournalFile;
47337
47338 /*
47339 ** If it does not already exists, create and populate the on-disk file 
47340 ** for JournalFile p.
47341 */
47342 static int createFile(JournalFile *p){
47343   int rc = SQLITE_OK;
47344   if( !p->pReal ){
47345     sqlite3_file *pReal = (sqlite3_file *)&p[1];
47346     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
47347     if( rc==SQLITE_OK ){
47348       p->pReal = pReal;
47349       if( p->iSize>0 ){
47350         assert(p->iSize<=p->nBuf);
47351         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
47352       }
47353     }
47354   }
47355   return rc;
47356 }
47357
47358 /*
47359 ** Close the file.
47360 */
47361 static int jrnlClose(sqlite3_file *pJfd){
47362   JournalFile *p = (JournalFile *)pJfd;
47363   if( p->pReal ){
47364     sqlite3OsClose(p->pReal);
47365   }
47366   sqlite3_free(p->zBuf);
47367   return SQLITE_OK;
47368 }
47369
47370 /*
47371 ** Read data from the file.
47372 */
47373 static int jrnlRead(
47374   sqlite3_file *pJfd,    /* The journal file from which to read */
47375   void *zBuf,            /* Put the results here */
47376   int iAmt,              /* Number of bytes to read */
47377   sqlite_int64 iOfst     /* Begin reading at this offset */
47378 ){
47379   int rc = SQLITE_OK;
47380   JournalFile *p = (JournalFile *)pJfd;
47381   if( p->pReal ){
47382     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
47383   }else{
47384     assert( iAmt+iOfst<=p->iSize );
47385     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
47386   }
47387   return rc;
47388 }
47389
47390 /*
47391 ** Write data to the file.
47392 */
47393 static int jrnlWrite(
47394   sqlite3_file *pJfd,    /* The journal file into which to write */
47395   const void *zBuf,      /* Take data to be written from here */
47396   int iAmt,              /* Number of bytes to write */
47397   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
47398 ){
47399   int rc = SQLITE_OK;
47400   JournalFile *p = (JournalFile *)pJfd;
47401   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
47402     rc = createFile(p);
47403   }
47404   if( rc==SQLITE_OK ){
47405     if( p->pReal ){
47406       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
47407     }else{
47408       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
47409       if( p->iSize<(iOfst+iAmt) ){
47410         p->iSize = (iOfst+iAmt);
47411       }
47412     }
47413   }
47414   return rc;
47415 }
47416
47417 /*
47418 ** Truncate the file.
47419 */
47420 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
47421   int rc = SQLITE_OK;
47422   JournalFile *p = (JournalFile *)pJfd;
47423   if( p->pReal ){
47424     rc = sqlite3OsTruncate(p->pReal, size);
47425   }else if( size<p->iSize ){
47426     p->iSize = size;
47427   }
47428   return rc;
47429 }
47430
47431 /*
47432 ** Sync the file.
47433 */
47434 static int jrnlSync(sqlite3_file *pJfd, int flags){
47435   int rc;
47436   JournalFile *p = (JournalFile *)pJfd;
47437   if( p->pReal ){
47438     rc = sqlite3OsSync(p->pReal, flags);
47439   }else{
47440     rc = SQLITE_OK;
47441   }
47442   return rc;
47443 }
47444
47445 /*
47446 ** Query the size of the file in bytes.
47447 */
47448 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
47449   int rc = SQLITE_OK;
47450   JournalFile *p = (JournalFile *)pJfd;
47451   if( p->pReal ){
47452     rc = sqlite3OsFileSize(p->pReal, pSize);
47453   }else{
47454     *pSize = (sqlite_int64) p->iSize;
47455   }
47456   return rc;
47457 }
47458
47459 /*
47460 ** Table of methods for JournalFile sqlite3_file object.
47461 */
47462 static struct sqlite3_io_methods JournalFileMethods = {
47463   1,             /* iVersion */
47464   jrnlClose,     /* xClose */
47465   jrnlRead,      /* xRead */
47466   jrnlWrite,     /* xWrite */
47467   jrnlTruncate,  /* xTruncate */
47468   jrnlSync,      /* xSync */
47469   jrnlFileSize,  /* xFileSize */
47470   0,             /* xLock */
47471   0,             /* xUnlock */
47472   0,             /* xCheckReservedLock */
47473   0,             /* xFileControl */
47474   0,             /* xSectorSize */
47475   0              /* xDeviceCharacteristics */
47476 };
47477
47478 /* 
47479 ** Open a journal file.
47480 */
47481 SQLITE_PRIVATE int sqlite3JournalOpen(
47482   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
47483   const char *zName,         /* Name of the journal file */
47484   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
47485   int flags,                 /* Opening flags */
47486   int nBuf                   /* Bytes buffered before opening the file */
47487 ){
47488   JournalFile *p = (JournalFile *)pJfd;
47489   memset(p, 0, sqlite3JournalSize(pVfs));
47490   if( nBuf>0 ){
47491     p->zBuf = sqlite3MallocZero(nBuf);
47492     if( !p->zBuf ){
47493       return SQLITE_NOMEM;
47494     }
47495   }else{
47496     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
47497   }
47498   p->pMethod = &JournalFileMethods;
47499   p->nBuf = nBuf;
47500   p->flags = flags;
47501   p->zJournal = zName;
47502   p->pVfs = pVfs;
47503   return SQLITE_OK;
47504 }
47505
47506 /*
47507 ** If the argument p points to a JournalFile structure, and the underlying
47508 ** file has not yet been created, create it now.
47509 */
47510 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
47511   if( p->pMethods!=&JournalFileMethods ){
47512     return SQLITE_OK;
47513   }
47514   return createFile((JournalFile *)p);
47515 }
47516
47517 /* 
47518 ** Return the number of bytes required to store a JournalFile that uses vfs
47519 ** pVfs to create the underlying on-disk files.
47520 */
47521 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
47522   return (pVfs->szOsFile+sizeof(JournalFile));
47523 }
47524 #endif
47525
47526 /************** End of journal.c *********************************************/
47527 /************** Begin file expr.c ********************************************/
47528 /*
47529 ** 2001 September 15
47530 **
47531 ** The author disclaims copyright to this source code.  In place of
47532 ** a legal notice, here is a blessing:
47533 **
47534 **    May you do good and not evil.
47535 **    May you find forgiveness for yourself and forgive others.
47536 **    May you share freely, never taking more than you give.
47537 **
47538 *************************************************************************
47539 ** This file contains routines used for analyzing expressions and
47540 ** for generating VDBE code that evaluates expressions in SQLite.
47541 **
47542 ** $Id: expr.c,v 1.371 2008/05/01 17:16:53 drh Exp $
47543 */
47544
47545 /*
47546 ** Return the 'affinity' of the expression pExpr if any.
47547 **
47548 ** If pExpr is a column, a reference to a column via an 'AS' alias,
47549 ** or a sub-select with a column as the return value, then the 
47550 ** affinity of that column is returned. Otherwise, 0x00 is returned,
47551 ** indicating no affinity for the expression.
47552 **
47553 ** i.e. the WHERE clause expresssions in the following statements all
47554 ** have an affinity:
47555 **
47556 ** CREATE TABLE t1(a);
47557 ** SELECT * FROM t1 WHERE a;
47558 ** SELECT a AS b FROM t1 WHERE b;
47559 ** SELECT * FROM t1 WHERE (select a from t1);
47560 */
47561 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
47562   int op = pExpr->op;
47563   if( op==TK_SELECT ){
47564     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
47565   }
47566 #ifndef SQLITE_OMIT_CAST
47567   if( op==TK_CAST ){
47568     return sqlite3AffinityType(&pExpr->token);
47569   }
47570 #endif
47571   return pExpr->affinity;
47572 }
47573
47574 /*
47575 ** Set the collating sequence for expression pExpr to be the collating
47576 ** sequence named by pToken.   Return a pointer to the revised expression.
47577 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
47578 ** flag.  An explicit collating sequence will override implicit
47579 ** collating sequences.
47580 */
47581 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
47582   char *zColl = 0;            /* Dequoted name of collation sequence */
47583   CollSeq *pColl;
47584   zColl = sqlite3NameFromToken(pParse->db, pName);
47585   if( pExpr && zColl ){
47586     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
47587     if( pColl ){
47588       pExpr->pColl = pColl;
47589       pExpr->flags |= EP_ExpCollate;
47590     }
47591   }
47592   sqlite3_free(zColl);
47593   return pExpr;
47594 }
47595
47596 /*
47597 ** Return the default collation sequence for the expression pExpr. If
47598 ** there is no default collation type, return 0.
47599 */
47600 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
47601   CollSeq *pColl = 0;
47602   if( pExpr ){
47603     int op;
47604     pColl = pExpr->pColl;
47605     op = pExpr->op;
47606     if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
47607       return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
47608     }
47609   }
47610   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
47611     pColl = 0;
47612   }
47613   return pColl;
47614 }
47615
47616 /*
47617 ** pExpr is an operand of a comparison operator.  aff2 is the
47618 ** type affinity of the other operand.  This routine returns the
47619 ** type affinity that should be used for the comparison operator.
47620 */
47621 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
47622   char aff1 = sqlite3ExprAffinity(pExpr);
47623   if( aff1 && aff2 ){
47624     /* Both sides of the comparison are columns. If one has numeric
47625     ** affinity, use that. Otherwise use no affinity.
47626     */
47627     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
47628       return SQLITE_AFF_NUMERIC;
47629     }else{
47630       return SQLITE_AFF_NONE;
47631     }
47632   }else if( !aff1 && !aff2 ){
47633     /* Neither side of the comparison is a column.  Compare the
47634     ** results directly.
47635     */
47636     return SQLITE_AFF_NONE;
47637   }else{
47638     /* One side is a column, the other is not. Use the columns affinity. */
47639     assert( aff1==0 || aff2==0 );
47640     return (aff1 + aff2);
47641   }
47642 }
47643
47644 /*
47645 ** pExpr is a comparison operator.  Return the type affinity that should
47646 ** be applied to both operands prior to doing the comparison.
47647 */
47648 static char comparisonAffinity(Expr *pExpr){
47649   char aff;
47650   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
47651           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
47652           pExpr->op==TK_NE );
47653   assert( pExpr->pLeft );
47654   aff = sqlite3ExprAffinity(pExpr->pLeft);
47655   if( pExpr->pRight ){
47656     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
47657   }
47658   else if( pExpr->pSelect ){
47659     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
47660   }
47661   else if( !aff ){
47662     aff = SQLITE_AFF_NONE;
47663   }
47664   return aff;
47665 }
47666
47667 /*
47668 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
47669 ** idx_affinity is the affinity of an indexed column. Return true
47670 ** if the index with affinity idx_affinity may be used to implement
47671 ** the comparison in pExpr.
47672 */
47673 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
47674   char aff = comparisonAffinity(pExpr);
47675   switch( aff ){
47676     case SQLITE_AFF_NONE:
47677       return 1;
47678     case SQLITE_AFF_TEXT:
47679       return idx_affinity==SQLITE_AFF_TEXT;
47680     default:
47681       return sqlite3IsNumericAffinity(idx_affinity);
47682   }
47683 }
47684
47685 /*
47686 ** Return the P5 value that should be used for a binary comparison
47687 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
47688 */
47689 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
47690   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
47691   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
47692   return aff;
47693 }
47694
47695 /*
47696 ** Return a pointer to the collation sequence that should be used by
47697 ** a binary comparison operator comparing pLeft and pRight.
47698 **
47699 ** If the left hand expression has a collating sequence type, then it is
47700 ** used. Otherwise the collation sequence for the right hand expression
47701 ** is used, or the default (BINARY) if neither expression has a collating
47702 ** type.
47703 **
47704 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
47705 ** it is not considered.
47706 */
47707 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
47708   Parse *pParse, 
47709   Expr *pLeft, 
47710   Expr *pRight
47711 ){
47712   CollSeq *pColl;
47713   assert( pLeft );
47714   if( pLeft->flags & EP_ExpCollate ){
47715     assert( pLeft->pColl );
47716     pColl = pLeft->pColl;
47717   }else if( pRight && pRight->flags & EP_ExpCollate ){
47718     assert( pRight->pColl );
47719     pColl = pRight->pColl;
47720   }else{
47721     pColl = sqlite3ExprCollSeq(pParse, pLeft);
47722     if( !pColl ){
47723       pColl = sqlite3ExprCollSeq(pParse, pRight);
47724     }
47725   }
47726   return pColl;
47727 }
47728
47729 /*
47730 ** Generate the operands for a comparison operation.  Before
47731 ** generating the code for each operand, set the EP_AnyAff
47732 ** flag on the expression so that it will be able to used a
47733 ** cached column value that has previously undergone an
47734 ** affinity change.
47735 */
47736 static void codeCompareOperands(
47737   Parse *pParse,    /* Parsing and code generating context */
47738   Expr *pLeft,      /* The left operand */
47739   int *pRegLeft,    /* Register where left operand is stored */
47740   int *pFreeLeft,   /* Free this register when done */
47741   Expr *pRight,     /* The right operand */
47742   int *pRegRight,   /* Register where right operand is stored */
47743   int *pFreeRight   /* Write temp register for right operand there */
47744 ){
47745   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
47746   pLeft->flags |= EP_AnyAff;
47747   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
47748   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
47749   pRight->flags |= EP_AnyAff;
47750   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
47751 }
47752
47753 /*
47754 ** Generate code for a comparison operator.
47755 */
47756 static int codeCompare(
47757   Parse *pParse,    /* The parsing (and code generating) context */
47758   Expr *pLeft,      /* The left operand */
47759   Expr *pRight,     /* The right operand */
47760   int opcode,       /* The comparison opcode */
47761   int in1, int in2, /* Register holding operands */
47762   int dest,         /* Jump here if true.  */
47763   int jumpIfNull    /* If true, jump if either operand is NULL */
47764 ){
47765   int p5;
47766   int addr;
47767   CollSeq *p4;
47768
47769   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
47770   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
47771   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
47772                            (void*)p4, P4_COLLSEQ);
47773   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
47774   if( p5 & SQLITE_AFF_MASK ){
47775     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
47776     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
47777   }
47778   return addr;
47779 }
47780
47781 /*
47782 ** Construct a new expression node and return a pointer to it.  Memory
47783 ** for this node is obtained from sqlite3_malloc().  The calling function
47784 ** is responsible for making sure the node eventually gets freed.
47785 */
47786 SQLITE_PRIVATE Expr *sqlite3Expr(
47787   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
47788   int op,                 /* Expression opcode */
47789   Expr *pLeft,            /* Left operand */
47790   Expr *pRight,           /* Right operand */
47791   const Token *pToken     /* Argument token */
47792 ){
47793   Expr *pNew;
47794   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
47795   if( pNew==0 ){
47796     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
47797     ** this function must always be allocated with sqlite3Expr() for this 
47798     ** reason. 
47799     */
47800     sqlite3ExprDelete(pLeft);
47801     sqlite3ExprDelete(pRight);
47802     return 0;
47803   }
47804   pNew->op = op;
47805   pNew->pLeft = pLeft;
47806   pNew->pRight = pRight;
47807   pNew->iAgg = -1;
47808   if( pToken ){
47809     assert( pToken->dyn==0 );
47810     pNew->span = pNew->token = *pToken;
47811   }else if( pLeft ){
47812     if( pRight ){
47813       sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
47814       if( pRight->flags & EP_ExpCollate ){
47815         pNew->flags |= EP_ExpCollate;
47816         pNew->pColl = pRight->pColl;
47817       }
47818     }
47819     if( pLeft->flags & EP_ExpCollate ){
47820       pNew->flags |= EP_ExpCollate;
47821       pNew->pColl = pLeft->pColl;
47822     }
47823   }
47824
47825   sqlite3ExprSetHeight(pNew);
47826   return pNew;
47827 }
47828
47829 /*
47830 ** Works like sqlite3Expr() except that it takes an extra Parse*
47831 ** argument and notifies the associated connection object if malloc fails.
47832 */
47833 SQLITE_PRIVATE Expr *sqlite3PExpr(
47834   Parse *pParse,          /* Parsing context */
47835   int op,                 /* Expression opcode */
47836   Expr *pLeft,            /* Left operand */
47837   Expr *pRight,           /* Right operand */
47838   const Token *pToken     /* Argument token */
47839 ){
47840   return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
47841 }
47842
47843 /*
47844 ** When doing a nested parse, you can include terms in an expression
47845 ** that look like this:   #1 #2 ...  These terms refer to registers
47846 ** in the virtual machine.  #N is the N-th register.
47847 **
47848 ** This routine is called by the parser to deal with on of those terms.
47849 ** It immediately generates code to store the value in a memory location.
47850 ** The returns an expression that will code to extract the value from
47851 ** that memory location as needed.
47852 */
47853 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
47854   Vdbe *v = pParse->pVdbe;
47855   Expr *p;
47856   if( pParse->nested==0 ){
47857     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
47858     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
47859   }
47860   if( v==0 ) return 0;
47861   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
47862   if( p==0 ){
47863     return 0;  /* Malloc failed */
47864   }
47865   p->iTable = atoi((char*)&pToken->z[1]);
47866   return p;
47867 }
47868
47869 /*
47870 ** Join two expressions using an AND operator.  If either expression is
47871 ** NULL, then just return the other expression.
47872 */
47873 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
47874   if( pLeft==0 ){
47875     return pRight;
47876   }else if( pRight==0 ){
47877     return pLeft;
47878   }else{
47879     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
47880   }
47881 }
47882
47883 /*
47884 ** Set the Expr.span field of the given expression to span all
47885 ** text between the two given tokens.
47886 */
47887 SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
47888   assert( pRight!=0 );
47889   assert( pLeft!=0 );
47890   if( pExpr && pRight->z && pLeft->z ){
47891     assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
47892     if( pLeft->dyn==0 && pRight->dyn==0 ){
47893       pExpr->span.z = pLeft->z;
47894       pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
47895     }else{
47896       pExpr->span.z = 0;
47897     }
47898   }
47899 }
47900
47901 /*
47902 ** Construct a new expression node for a function with multiple
47903 ** arguments.
47904 */
47905 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
47906   Expr *pNew;
47907   assert( pToken );
47908   pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) );
47909   if( pNew==0 ){
47910     sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
47911     return 0;
47912   }
47913   pNew->op = TK_FUNCTION;
47914   pNew->pList = pList;
47915   assert( pToken->dyn==0 );
47916   pNew->token = *pToken;
47917   pNew->span = pNew->token;
47918
47919   sqlite3ExprSetHeight(pNew);
47920   return pNew;
47921 }
47922
47923 /*
47924 ** Assign a variable number to an expression that encodes a wildcard
47925 ** in the original SQL statement.  
47926 **
47927 ** Wildcards consisting of a single "?" are assigned the next sequential
47928 ** variable number.
47929 **
47930 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
47931 ** sure "nnn" is not too be to avoid a denial of service attack when
47932 ** the SQL statement comes from an external source.
47933 **
47934 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
47935 ** as the previous instance of the same wildcard.  Or if this is the first
47936 ** instance of the wildcard, the next sequenial variable number is
47937 ** assigned.
47938 */
47939 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
47940   Token *pToken;
47941   sqlite3 *db = pParse->db;
47942
47943   if( pExpr==0 ) return;
47944   pToken = &pExpr->token;
47945   assert( pToken->n>=1 );
47946   assert( pToken->z!=0 );
47947   assert( pToken->z[0]!=0 );
47948   if( pToken->n==1 ){
47949     /* Wildcard of the form "?".  Assign the next variable number */
47950     pExpr->iTable = ++pParse->nVar;
47951   }else if( pToken->z[0]=='?' ){
47952     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
47953     ** use it as the variable number */
47954     int i;
47955     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
47956     testcase( i==0 );
47957     testcase( i==1 );
47958     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
47959     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
47960     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
47961       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
47962           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
47963     }
47964     if( i>pParse->nVar ){
47965       pParse->nVar = i;
47966     }
47967   }else{
47968     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
47969     ** number as the prior appearance of the same name, or if the name
47970     ** has never appeared before, reuse the same variable number
47971     */
47972     int i, n;
47973     n = pToken->n;
47974     for(i=0; i<pParse->nVarExpr; i++){
47975       Expr *pE;
47976       if( (pE = pParse->apVarExpr[i])!=0
47977           && pE->token.n==n
47978           && memcmp(pE->token.z, pToken->z, n)==0 ){
47979         pExpr->iTable = pE->iTable;
47980         break;
47981       }
47982     }
47983     if( i>=pParse->nVarExpr ){
47984       pExpr->iTable = ++pParse->nVar;
47985       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
47986         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
47987         pParse->apVarExpr =
47988             sqlite3DbReallocOrFree(
47989               db,
47990               pParse->apVarExpr,
47991               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
47992             );
47993       }
47994       if( !db->mallocFailed ){
47995         assert( pParse->apVarExpr!=0 );
47996         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
47997       }
47998     }
47999   } 
48000   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
48001     sqlite3ErrorMsg(pParse, "too many SQL variables");
48002   }
48003 }
48004
48005 /*
48006 ** Recursively delete an expression tree.
48007 */
48008 SQLITE_PRIVATE void sqlite3ExprDelete(Expr *p){
48009   if( p==0 ) return;
48010   if( p->span.dyn ) sqlite3_free((char*)p->span.z);
48011   if( p->token.dyn ) sqlite3_free((char*)p->token.z);
48012   sqlite3ExprDelete(p->pLeft);
48013   sqlite3ExprDelete(p->pRight);
48014   sqlite3ExprListDelete(p->pList);
48015   sqlite3SelectDelete(p->pSelect);
48016   sqlite3_free(p);
48017 }
48018
48019 /*
48020 ** The Expr.token field might be a string literal that is quoted.
48021 ** If so, remove the quotation marks.
48022 */
48023 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
48024   if( ExprHasAnyProperty(p, EP_Dequoted) ){
48025     return;
48026   }
48027   ExprSetProperty(p, EP_Dequoted);
48028   if( p->token.dyn==0 ){
48029     sqlite3TokenCopy(db, &p->token, &p->token);
48030   }
48031   sqlite3Dequote((char*)p->token.z);
48032 }
48033
48034
48035 /*
48036 ** The following group of routines make deep copies of expressions,
48037 ** expression lists, ID lists, and select statements.  The copies can
48038 ** be deleted (by being passed to their respective ...Delete() routines)
48039 ** without effecting the originals.
48040 **
48041 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
48042 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
48043 ** by subsequent calls to sqlite*ListAppend() routines.
48044 **
48045 ** Any tables that the SrcList might point to are not duplicated.
48046 */
48047 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
48048   Expr *pNew;
48049   if( p==0 ) return 0;
48050   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
48051   if( pNew==0 ) return 0;
48052   memcpy(pNew, p, sizeof(*pNew));
48053   if( p->token.z!=0 ){
48054     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
48055     pNew->token.dyn = 1;
48056   }else{
48057     assert( pNew->token.z==0 );
48058   }
48059   pNew->span.z = 0;
48060   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
48061   pNew->pRight = sqlite3ExprDup(db, p->pRight);
48062   pNew->pList = sqlite3ExprListDup(db, p->pList);
48063   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
48064   return pNew;
48065 }
48066 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
48067   if( pTo->dyn ) sqlite3_free((char*)pTo->z);
48068   if( pFrom->z ){
48069     pTo->n = pFrom->n;
48070     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
48071     pTo->dyn = 1;
48072   }else{
48073     pTo->z = 0;
48074   }
48075 }
48076 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
48077   ExprList *pNew;
48078   struct ExprList_item *pItem, *pOldItem;
48079   int i;
48080   if( p==0 ) return 0;
48081   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
48082   if( pNew==0 ) return 0;
48083   pNew->iECursor = 0;
48084   pNew->nExpr = pNew->nAlloc = p->nExpr;
48085   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
48086   if( pItem==0 ){
48087     sqlite3_free(pNew);
48088     return 0;
48089   } 
48090   pOldItem = p->a;
48091   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
48092     Expr *pNewExpr, *pOldExpr;
48093     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
48094     if( pOldExpr->span.z!=0 && pNewExpr ){
48095       /* Always make a copy of the span for top-level expressions in the
48096       ** expression list.  The logic in SELECT processing that determines
48097       ** the names of columns in the result set needs this information */
48098       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
48099     }
48100     assert( pNewExpr==0 || pNewExpr->span.z!=0 
48101             || pOldExpr->span.z==0
48102             || db->mallocFailed );
48103     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
48104     pItem->sortOrder = pOldItem->sortOrder;
48105     pItem->isAgg = pOldItem->isAgg;
48106     pItem->done = 0;
48107   }
48108   return pNew;
48109 }
48110
48111 /*
48112 ** If cursors, triggers, views and subqueries are all omitted from
48113 ** the build, then none of the following routines, except for 
48114 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
48115 ** called with a NULL argument.
48116 */
48117 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
48118  || !defined(SQLITE_OMIT_SUBQUERY)
48119 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
48120   SrcList *pNew;
48121   int i;
48122   int nByte;
48123   if( p==0 ) return 0;
48124   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
48125   pNew = sqlite3DbMallocRaw(db, nByte );
48126   if( pNew==0 ) return 0;
48127   pNew->nSrc = pNew->nAlloc = p->nSrc;
48128   for(i=0; i<p->nSrc; i++){
48129     struct SrcList_item *pNewItem = &pNew->a[i];
48130     struct SrcList_item *pOldItem = &p->a[i];
48131     Table *pTab;
48132     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
48133     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
48134     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
48135     pNewItem->jointype = pOldItem->jointype;
48136     pNewItem->iCursor = pOldItem->iCursor;
48137     pNewItem->isPopulated = pOldItem->isPopulated;
48138     pTab = pNewItem->pTab = pOldItem->pTab;
48139     if( pTab ){
48140       pTab->nRef++;
48141     }
48142     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
48143     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
48144     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
48145     pNewItem->colUsed = pOldItem->colUsed;
48146   }
48147   return pNew;
48148 }
48149 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
48150   IdList *pNew;
48151   int i;
48152   if( p==0 ) return 0;
48153   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
48154   if( pNew==0 ) return 0;
48155   pNew->nId = pNew->nAlloc = p->nId;
48156   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
48157   if( pNew->a==0 ){
48158     sqlite3_free(pNew);
48159     return 0;
48160   }
48161   for(i=0; i<p->nId; i++){
48162     struct IdList_item *pNewItem = &pNew->a[i];
48163     struct IdList_item *pOldItem = &p->a[i];
48164     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
48165     pNewItem->idx = pOldItem->idx;
48166   }
48167   return pNew;
48168 }
48169 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
48170   Select *pNew;
48171   if( p==0 ) return 0;
48172   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
48173   if( pNew==0 ) return 0;
48174   pNew->isDistinct = p->isDistinct;
48175   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
48176   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
48177   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
48178   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
48179   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
48180   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
48181   pNew->op = p->op;
48182   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
48183   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
48184   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
48185   pNew->iLimit = -1;
48186   pNew->iOffset = -1;
48187   pNew->isResolved = p->isResolved;
48188   pNew->isAgg = p->isAgg;
48189   pNew->usesEphm = 0;
48190   pNew->disallowOrderBy = 0;
48191   pNew->pRightmost = 0;
48192   pNew->addrOpenEphm[0] = -1;
48193   pNew->addrOpenEphm[1] = -1;
48194   pNew->addrOpenEphm[2] = -1;
48195   return pNew;
48196 }
48197 #else
48198 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
48199   assert( p==0 );
48200   return 0;
48201 }
48202 #endif
48203
48204
48205 /*
48206 ** Add a new element to the end of an expression list.  If pList is
48207 ** initially NULL, then create a new expression list.
48208 */
48209 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
48210   Parse *pParse,          /* Parsing context */
48211   ExprList *pList,        /* List to which to append. Might be NULL */
48212   Expr *pExpr,            /* Expression to be appended */
48213   Token *pName            /* AS keyword for the expression */
48214 ){
48215   sqlite3 *db = pParse->db;
48216   if( pList==0 ){
48217     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
48218     if( pList==0 ){
48219       goto no_mem;
48220     }
48221     assert( pList->nAlloc==0 );
48222   }
48223   if( pList->nAlloc<=pList->nExpr ){
48224     struct ExprList_item *a;
48225     int n = pList->nAlloc*2 + 4;
48226     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
48227     if( a==0 ){
48228       goto no_mem;
48229     }
48230     pList->a = a;
48231     pList->nAlloc = n;
48232   }
48233   assert( pList->a!=0 );
48234   if( pExpr || pName ){
48235     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
48236     memset(pItem, 0, sizeof(*pItem));
48237     pItem->zName = sqlite3NameFromToken(db, pName);
48238     pItem->pExpr = pExpr;
48239   }
48240   return pList;
48241
48242 no_mem:     
48243   /* Avoid leaking memory if malloc has failed. */
48244   sqlite3ExprDelete(pExpr);
48245   sqlite3ExprListDelete(pList);
48246   return 0;
48247 }
48248
48249 /*
48250 ** If the expression list pEList contains more than iLimit elements,
48251 ** leave an error message in pParse.
48252 */
48253 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
48254   Parse *pParse,
48255   ExprList *pEList,
48256   const char *zObject
48257 ){
48258   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
48259   testcase( pEList && pEList->nExpr==mx );
48260   testcase( pEList && pEList->nExpr==mx+1 );
48261   if( pEList && pEList->nExpr>mx ){
48262     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
48263   }
48264 }
48265
48266
48267 /* The following three functions, heightOfExpr(), heightOfExprList()
48268 ** and heightOfSelect(), are used to determine the maximum height
48269 ** of any expression tree referenced by the structure passed as the
48270 ** first argument.
48271 **
48272 ** If this maximum height is greater than the current value pointed
48273 ** to by pnHeight, the second parameter, then set *pnHeight to that
48274 ** value.
48275 */
48276 static void heightOfExpr(Expr *p, int *pnHeight){
48277   if( p ){
48278     if( p->nHeight>*pnHeight ){
48279       *pnHeight = p->nHeight;
48280     }
48281   }
48282 }
48283 static void heightOfExprList(ExprList *p, int *pnHeight){
48284   if( p ){
48285     int i;
48286     for(i=0; i<p->nExpr; i++){
48287       heightOfExpr(p->a[i].pExpr, pnHeight);
48288     }
48289   }
48290 }
48291 static void heightOfSelect(Select *p, int *pnHeight){
48292   if( p ){
48293     heightOfExpr(p->pWhere, pnHeight);
48294     heightOfExpr(p->pHaving, pnHeight);
48295     heightOfExpr(p->pLimit, pnHeight);
48296     heightOfExpr(p->pOffset, pnHeight);
48297     heightOfExprList(p->pEList, pnHeight);
48298     heightOfExprList(p->pGroupBy, pnHeight);
48299     heightOfExprList(p->pOrderBy, pnHeight);
48300     heightOfSelect(p->pPrior, pnHeight);
48301   }
48302 }
48303
48304 /*
48305 ** Set the Expr.nHeight variable in the structure passed as an 
48306 ** argument. An expression with no children, Expr.pList or 
48307 ** Expr.pSelect member has a height of 1. Any other expression
48308 ** has a height equal to the maximum height of any other 
48309 ** referenced Expr plus one.
48310 */
48311 SQLITE_PRIVATE void sqlite3ExprSetHeight(Expr *p){
48312   int nHeight = 0;
48313   heightOfExpr(p->pLeft, &nHeight);
48314   heightOfExpr(p->pRight, &nHeight);
48315   heightOfExprList(p->pList, &nHeight);
48316   heightOfSelect(p->pSelect, &nHeight);
48317   p->nHeight = nHeight + 1;
48318 }
48319
48320 /*
48321 ** Return the maximum height of any expression tree referenced
48322 ** by the select statement passed as an argument.
48323 */
48324 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
48325   int nHeight = 0;
48326   heightOfSelect(p, &nHeight);
48327   return nHeight;
48328 }
48329
48330 /*
48331 ** Delete an entire expression list.
48332 */
48333 SQLITE_PRIVATE void sqlite3ExprListDelete(ExprList *pList){
48334   int i;
48335   struct ExprList_item *pItem;
48336   if( pList==0 ) return;
48337   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
48338   assert( pList->nExpr<=pList->nAlloc );
48339   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
48340     sqlite3ExprDelete(pItem->pExpr);
48341     sqlite3_free(pItem->zName);
48342   }
48343   sqlite3_free(pList->a);
48344   sqlite3_free(pList);
48345 }
48346
48347 /*
48348 ** Walk an expression tree.  Call xFunc for each node visited.  xFunc
48349 ** is called on the node before xFunc is called on the nodes children.
48350 **
48351 ** The return value from xFunc determines whether the tree walk continues.
48352 ** 0 means continue walking the tree.  1 means do not walk children
48353 ** of the current node but continue with siblings.  2 means abandon
48354 ** the tree walk completely.
48355 **
48356 ** The return value from this routine is 1 to abandon the tree walk
48357 ** and 0 to continue.
48358 **
48359 ** NOTICE:  This routine does *not* descend into subqueries.
48360 */
48361 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
48362 static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
48363   int rc;
48364   if( pExpr==0 ) return 0;
48365   rc = (*xFunc)(pArg, pExpr);
48366   if( rc==0 ){
48367     if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
48368     if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
48369     if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
48370   }
48371   return rc>1;
48372 }
48373
48374 /*
48375 ** Call walkExprTree() for every expression in list p.
48376 */
48377 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
48378   int i;
48379   struct ExprList_item *pItem;
48380   if( !p ) return 0;
48381   for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
48382     if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
48383   }
48384   return 0;
48385 }
48386
48387 /*
48388 ** Call walkExprTree() for every expression in Select p, not including
48389 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
48390 ** or OFFSET expressions..
48391 */
48392 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
48393   walkExprList(p->pEList, xFunc, pArg);
48394   walkExprTree(p->pWhere, xFunc, pArg);
48395   walkExprList(p->pGroupBy, xFunc, pArg);
48396   walkExprTree(p->pHaving, xFunc, pArg);
48397   walkExprList(p->pOrderBy, xFunc, pArg);
48398   if( p->pPrior ){
48399     walkSelectExpr(p->pPrior, xFunc, pArg);
48400   }
48401   return 0;
48402 }
48403
48404
48405 /*
48406 ** This routine is designed as an xFunc for walkExprTree().
48407 **
48408 ** pArg is really a pointer to an integer.  If we can tell by looking
48409 ** at pExpr that the expression that contains pExpr is not a constant
48410 ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
48411 ** If pExpr does does not disqualify the expression from being a constant
48412 ** then do nothing.
48413 **
48414 ** After walking the whole tree, if no nodes are found that disqualify
48415 ** the expression as constant, then we assume the whole expression
48416 ** is constant.  See sqlite3ExprIsConstant() for additional information.
48417 */
48418 static int exprNodeIsConstant(void *pArg, Expr *pExpr){
48419   int *pN = (int*)pArg;
48420
48421   /* If *pArg is 3 then any term of the expression that comes from
48422   ** the ON or USING clauses of a join disqualifies the expression
48423   ** from being considered constant. */
48424   if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
48425     *pN = 0;
48426     return 2;
48427   }
48428
48429   switch( pExpr->op ){
48430     /* Consider functions to be constant if all their arguments are constant
48431     ** and *pArg==2 */
48432     case TK_FUNCTION:
48433       if( (*pN)==2 ) return 0;
48434       /* Fall through */
48435     case TK_ID:
48436     case TK_COLUMN:
48437     case TK_DOT:
48438     case TK_AGG_FUNCTION:
48439     case TK_AGG_COLUMN:
48440 #ifndef SQLITE_OMIT_SUBQUERY
48441     case TK_SELECT:
48442     case TK_EXISTS:
48443       testcase( pExpr->op==TK_SELECT );
48444       testcase( pExpr->op==TK_EXISTS );
48445 #endif
48446       testcase( pExpr->op==TK_ID );
48447       testcase( pExpr->op==TK_COLUMN );
48448       testcase( pExpr->op==TK_DOT );
48449       testcase( pExpr->op==TK_AGG_FUNCTION );
48450       testcase( pExpr->op==TK_AGG_COLUMN );
48451       *pN = 0;
48452       return 2;
48453     case TK_IN:
48454       if( pExpr->pSelect ){
48455         *pN = 0;
48456         return 2;
48457       }
48458     default:
48459       return 0;
48460   }
48461 }
48462
48463 /*
48464 ** Walk an expression tree.  Return 1 if the expression is constant
48465 ** and 0 if it involves variables or function calls.
48466 **
48467 ** For the purposes of this function, a double-quoted string (ex: "abc")
48468 ** is considered a variable but a single-quoted string (ex: 'abc') is
48469 ** a constant.
48470 */
48471 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
48472   int isConst = 1;
48473   walkExprTree(p, exprNodeIsConstant, &isConst);
48474   return isConst;
48475 }
48476
48477 /*
48478 ** Walk an expression tree.  Return 1 if the expression is constant
48479 ** that does no originate from the ON or USING clauses of a join.
48480 ** Return 0 if it involves variables or function calls or terms from
48481 ** an ON or USING clause.
48482 */
48483 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
48484   int isConst = 3;
48485   walkExprTree(p, exprNodeIsConstant, &isConst);
48486   return isConst!=0;
48487 }
48488
48489 /*
48490 ** Walk an expression tree.  Return 1 if the expression is constant
48491 ** or a function call with constant arguments.  Return and 0 if there
48492 ** are any variables.
48493 **
48494 ** For the purposes of this function, a double-quoted string (ex: "abc")
48495 ** is considered a variable but a single-quoted string (ex: 'abc') is
48496 ** a constant.
48497 */
48498 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
48499   int isConst = 2;
48500   walkExprTree(p, exprNodeIsConstant, &isConst);
48501   return isConst!=0;
48502 }
48503
48504 /*
48505 ** If the expression p codes a constant integer that is small enough
48506 ** to fit in a 32-bit integer, return 1 and put the value of the integer
48507 ** in *pValue.  If the expression is not an integer or if it is too big
48508 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
48509 */
48510 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
48511   switch( p->op ){
48512     case TK_INTEGER: {
48513       if( sqlite3GetInt32((char*)p->token.z, pValue) ){
48514         return 1;
48515       }
48516       break;
48517     }
48518     case TK_UPLUS: {
48519       return sqlite3ExprIsInteger(p->pLeft, pValue);
48520     }
48521     case TK_UMINUS: {
48522       int v;
48523       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
48524         *pValue = -v;
48525         return 1;
48526       }
48527       break;
48528     }
48529     default: break;
48530   }
48531   return 0;
48532 }
48533
48534 /*
48535 ** Return TRUE if the given string is a row-id column name.
48536 */
48537 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
48538   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
48539   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
48540   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
48541   return 0;
48542 }
48543
48544 /*
48545 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
48546 ** that name in the set of source tables in pSrcList and make the pExpr 
48547 ** expression node refer back to that source column.  The following changes
48548 ** are made to pExpr:
48549 **
48550 **    pExpr->iDb           Set the index in db->aDb[] of the database holding
48551 **                         the table.
48552 **    pExpr->iTable        Set to the cursor number for the table obtained
48553 **                         from pSrcList.
48554 **    pExpr->iColumn       Set to the column number within the table.
48555 **    pExpr->op            Set to TK_COLUMN.
48556 **    pExpr->pLeft         Any expression this points to is deleted
48557 **    pExpr->pRight        Any expression this points to is deleted.
48558 **
48559 ** The pDbToken is the name of the database (the "X").  This value may be
48560 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
48561 ** can be used.  The pTableToken is the name of the table (the "Y").  This
48562 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
48563 ** means that the form of the name is Z and that columns from any table
48564 ** can be used.
48565 **
48566 ** If the name cannot be resolved unambiguously, leave an error message
48567 ** in pParse and return non-zero.  Return zero on success.
48568 */
48569 static int lookupName(
48570   Parse *pParse,       /* The parsing context */
48571   Token *pDbToken,     /* Name of the database containing table, or NULL */
48572   Token *pTableToken,  /* Name of table containing column, or NULL */
48573   Token *pColumnToken, /* Name of the column. */
48574   NameContext *pNC,    /* The name context used to resolve the name */
48575   Expr *pExpr          /* Make this EXPR node point to the selected column */
48576 ){
48577   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
48578   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
48579   char *zCol = 0;      /* Name of the column.  The "Z" */
48580   int i, j;            /* Loop counters */
48581   int cnt = 0;         /* Number of matching column names */
48582   int cntTab = 0;      /* Number of matching table names */
48583   sqlite3 *db = pParse->db;  /* The database */
48584   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
48585   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
48586   NameContext *pTopNC = pNC;        /* First namecontext in the list */
48587   Schema *pSchema = 0;              /* Schema of the expression */
48588
48589   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
48590   zDb = sqlite3NameFromToken(db, pDbToken);
48591   zTab = sqlite3NameFromToken(db, pTableToken);
48592   zCol = sqlite3NameFromToken(db, pColumnToken);
48593   if( db->mallocFailed ){
48594     goto lookupname_end;
48595   }
48596
48597   pExpr->iTable = -1;
48598   while( pNC && cnt==0 ){
48599     ExprList *pEList;
48600     SrcList *pSrcList = pNC->pSrcList;
48601
48602     if( pSrcList ){
48603       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
48604         Table *pTab;
48605         int iDb;
48606         Column *pCol;
48607   
48608         pTab = pItem->pTab;
48609         assert( pTab!=0 );
48610         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
48611         assert( pTab->nCol>0 );
48612         if( zTab ){
48613           if( pItem->zAlias ){
48614             char *zTabName = pItem->zAlias;
48615             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
48616           }else{
48617             char *zTabName = pTab->zName;
48618             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
48619             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
48620               continue;
48621             }
48622           }
48623         }
48624         if( 0==(cntTab++) ){
48625           pExpr->iTable = pItem->iCursor;
48626           pSchema = pTab->pSchema;
48627           pMatch = pItem;
48628         }
48629         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
48630           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
48631             const char *zColl = pTab->aCol[j].zColl;
48632             IdList *pUsing;
48633             cnt++;
48634             pExpr->iTable = pItem->iCursor;
48635             pMatch = pItem;
48636             pSchema = pTab->pSchema;
48637             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
48638             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
48639             pExpr->affinity = pTab->aCol[j].affinity;
48640             if( (pExpr->flags & EP_ExpCollate)==0 ){
48641               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
48642             }
48643             if( i<pSrcList->nSrc-1 ){
48644               if( pItem[1].jointype & JT_NATURAL ){
48645                 /* If this match occurred in the left table of a natural join,
48646                 ** then skip the right table to avoid a duplicate match */
48647                 pItem++;
48648                 i++;
48649               }else if( (pUsing = pItem[1].pUsing)!=0 ){
48650                 /* If this match occurs on a column that is in the USING clause
48651                 ** of a join, skip the search of the right table of the join
48652                 ** to avoid a duplicate match there. */
48653                 int k;
48654                 for(k=0; k<pUsing->nId; k++){
48655                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
48656                     pItem++;
48657                     i++;
48658                     break;
48659                   }
48660                 }
48661               }
48662             }
48663             break;
48664           }
48665         }
48666       }
48667     }
48668
48669 #ifndef SQLITE_OMIT_TRIGGER
48670     /* If we have not already resolved the name, then maybe 
48671     ** it is a new.* or old.* trigger argument reference
48672     */
48673     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
48674       TriggerStack *pTriggerStack = pParse->trigStack;
48675       Table *pTab = 0;
48676       u32 *piColMask;
48677       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
48678         pExpr->iTable = pTriggerStack->newIdx;
48679         assert( pTriggerStack->pTab );
48680         pTab = pTriggerStack->pTab;
48681         piColMask = &(pTriggerStack->newColMask);
48682       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
48683         pExpr->iTable = pTriggerStack->oldIdx;
48684         assert( pTriggerStack->pTab );
48685         pTab = pTriggerStack->pTab;
48686         piColMask = &(pTriggerStack->oldColMask);
48687       }
48688
48689       if( pTab ){ 
48690         int iCol;
48691         Column *pCol = pTab->aCol;
48692
48693         pSchema = pTab->pSchema;
48694         cntTab++;
48695         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
48696           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
48697             const char *zColl = pTab->aCol[iCol].zColl;
48698             cnt++;
48699             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
48700             pExpr->affinity = pTab->aCol[iCol].affinity;
48701             if( (pExpr->flags & EP_ExpCollate)==0 ){
48702               pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
48703             }
48704             pExpr->pTab = pTab;
48705             if( iCol>=0 ){
48706               testcase( iCol==31 );
48707               testcase( iCol==32 );
48708               *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
48709             }
48710             break;
48711           }
48712         }
48713       }
48714     }
48715 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
48716
48717     /*
48718     ** Perhaps the name is a reference to the ROWID
48719     */
48720     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
48721       cnt = 1;
48722       pExpr->iColumn = -1;
48723       pExpr->affinity = SQLITE_AFF_INTEGER;
48724     }
48725
48726     /*
48727     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
48728     ** might refer to an result-set alias.  This happens, for example, when
48729     ** we are resolving names in the WHERE clause of the following command:
48730     **
48731     **     SELECT a+b AS x FROM table WHERE x<10;
48732     **
48733     ** In cases like this, replace pExpr with a copy of the expression that
48734     ** forms the result set entry ("a+b" in the example) and return immediately.
48735     ** Note that the expression in the result set should have already been
48736     ** resolved by the time the WHERE clause is resolved.
48737     */
48738     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
48739       for(j=0; j<pEList->nExpr; j++){
48740         char *zAs = pEList->a[j].zName;
48741         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
48742           Expr *pDup, *pOrig;
48743           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
48744           assert( pExpr->pList==0 );
48745           assert( pExpr->pSelect==0 );
48746           pOrig = pEList->a[j].pExpr;
48747           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
48748             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
48749             sqlite3_free(zCol);
48750             return 2;
48751           }
48752           pDup = sqlite3ExprDup(db, pOrig);
48753           if( pExpr->flags & EP_ExpCollate ){
48754             pDup->pColl = pExpr->pColl;
48755             pDup->flags |= EP_ExpCollate;
48756           }
48757           if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z);
48758           if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z);
48759           memcpy(pExpr, pDup, sizeof(*pExpr));
48760           sqlite3_free(pDup);
48761           cnt = 1;
48762           pMatch = 0;
48763           assert( zTab==0 && zDb==0 );
48764           goto lookupname_end_2;
48765         }
48766       } 
48767     }
48768
48769     /* Advance to the next name context.  The loop will exit when either
48770     ** we have a match (cnt>0) or when we run out of name contexts.
48771     */
48772     if( cnt==0 ){
48773       pNC = pNC->pNext;
48774     }
48775   }
48776
48777   /*
48778   ** If X and Y are NULL (in other words if only the column name Z is
48779   ** supplied) and the value of Z is enclosed in double-quotes, then
48780   ** Z is a string literal if it doesn't match any column names.  In that
48781   ** case, we need to return right away and not make any changes to
48782   ** pExpr.
48783   **
48784   ** Because no reference was made to outer contexts, the pNC->nRef
48785   ** fields are not changed in any context.
48786   */
48787   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
48788     sqlite3_free(zCol);
48789     return 0;
48790   }
48791
48792   /*
48793   ** cnt==0 means there was not match.  cnt>1 means there were two or
48794   ** more matches.  Either way, we have an error.
48795   */
48796   if( cnt!=1 ){
48797     const char *zErr;
48798     zErr = cnt==0 ? "no such column" : "ambiguous column name";
48799     if( zDb ){
48800       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
48801     }else if( zTab ){
48802       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
48803     }else{
48804       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
48805     }
48806     pTopNC->nErr++;
48807   }
48808
48809   /* If a column from a table in pSrcList is referenced, then record
48810   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
48811   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
48812   ** column number is greater than the number of bits in the bitmask
48813   ** then set the high-order bit of the bitmask.
48814   */
48815   if( pExpr->iColumn>=0 && pMatch!=0 ){
48816     int n = pExpr->iColumn;
48817     testcase( n==sizeof(Bitmask)*8-1 );
48818     if( n>=sizeof(Bitmask)*8 ){
48819       n = sizeof(Bitmask)*8-1;
48820     }
48821     assert( pMatch->iCursor==pExpr->iTable );
48822     pMatch->colUsed |= ((Bitmask)1)<<n;
48823   }
48824
48825 lookupname_end:
48826   /* Clean up and return
48827   */
48828   sqlite3_free(zDb);
48829   sqlite3_free(zTab);
48830   sqlite3ExprDelete(pExpr->pLeft);
48831   pExpr->pLeft = 0;
48832   sqlite3ExprDelete(pExpr->pRight);
48833   pExpr->pRight = 0;
48834   pExpr->op = TK_COLUMN;
48835 lookupname_end_2:
48836   sqlite3_free(zCol);
48837   if( cnt==1 ){
48838     assert( pNC!=0 );
48839     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
48840     if( pMatch && !pMatch->pSelect ){
48841       pExpr->pTab = pMatch->pTab;
48842     }
48843     /* Increment the nRef value on all name contexts from TopNC up to
48844     ** the point where the name matched. */
48845     for(;;){
48846       assert( pTopNC!=0 );
48847       pTopNC->nRef++;
48848       if( pTopNC==pNC ) break;
48849       pTopNC = pTopNC->pNext;
48850     }
48851     return 0;
48852   } else {
48853     return 1;
48854   }
48855 }
48856
48857 /*
48858 ** This routine is designed as an xFunc for walkExprTree().
48859 **
48860 ** Resolve symbolic names into TK_COLUMN operators for the current
48861 ** node in the expression tree.  Return 0 to continue the search down
48862 ** the tree or 2 to abort the tree walk.
48863 **
48864 ** This routine also does error checking and name resolution for
48865 ** function names.  The operator for aggregate functions is changed
48866 ** to TK_AGG_FUNCTION.
48867 */
48868 static int nameResolverStep(void *pArg, Expr *pExpr){
48869   NameContext *pNC = (NameContext*)pArg;
48870   Parse *pParse;
48871
48872   if( pExpr==0 ) return 1;
48873   assert( pNC!=0 );
48874   pParse = pNC->pParse;
48875
48876   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
48877   ExprSetProperty(pExpr, EP_Resolved);
48878 #ifndef NDEBUG
48879   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
48880     SrcList *pSrcList = pNC->pSrcList;
48881     int i;
48882     for(i=0; i<pNC->pSrcList->nSrc; i++){
48883       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
48884     }
48885   }
48886 #endif
48887   switch( pExpr->op ){
48888     /* Double-quoted strings (ex: "abc") are used as identifiers if
48889     ** possible.  Otherwise they remain as strings.  Single-quoted
48890     ** strings (ex: 'abc') are always string literals.
48891     */
48892     case TK_STRING: {
48893       if( pExpr->token.z[0]=='\'' ) break;
48894       /* Fall thru into the TK_ID case if this is a double-quoted string */
48895     }
48896     /* A lone identifier is the name of a column.
48897     */
48898     case TK_ID: {
48899       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
48900       return 1;
48901     }
48902   
48903     /* A table name and column name:     ID.ID
48904     ** Or a database, table and column:  ID.ID.ID
48905     */
48906     case TK_DOT: {
48907       Token *pColumn;
48908       Token *pTable;
48909       Token *pDb;
48910       Expr *pRight;
48911
48912       /* if( pSrcList==0 ) break; */
48913       pRight = pExpr->pRight;
48914       if( pRight->op==TK_ID ){
48915         pDb = 0;
48916         pTable = &pExpr->pLeft->token;
48917         pColumn = &pRight->token;
48918       }else{
48919         assert( pRight->op==TK_DOT );
48920         pDb = &pExpr->pLeft->token;
48921         pTable = &pRight->pLeft->token;
48922         pColumn = &pRight->pRight->token;
48923       }
48924       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
48925       return 1;
48926     }
48927
48928     /* Resolve function names
48929     */
48930     case TK_CONST_FUNC:
48931     case TK_FUNCTION: {
48932       ExprList *pList = pExpr->pList;    /* The argument list */
48933       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
48934       int no_such_func = 0;       /* True if no such function exists */
48935       int wrong_num_args = 0;     /* True if wrong number of arguments */
48936       int is_agg = 0;             /* True if is an aggregate function */
48937       int i;
48938       int auth;                   /* Authorization to use the function */
48939       int nId;                    /* Number of characters in function name */
48940       const char *zId;            /* The function name. */
48941       FuncDef *pDef;              /* Information about the function */
48942       int enc = ENC(pParse->db);  /* The database encoding */
48943
48944       zId = (char*)pExpr->token.z;
48945       nId = pExpr->token.n;
48946       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
48947       if( pDef==0 ){
48948         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
48949         if( pDef==0 ){
48950           no_such_func = 1;
48951         }else{
48952           wrong_num_args = 1;
48953         }
48954       }else{
48955         is_agg = pDef->xFunc==0;
48956       }
48957 #ifndef SQLITE_OMIT_AUTHORIZATION
48958       if( pDef ){
48959         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
48960         if( auth!=SQLITE_OK ){
48961           if( auth==SQLITE_DENY ){
48962             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
48963                                     pDef->zName);
48964             pNC->nErr++;
48965           }
48966           pExpr->op = TK_NULL;
48967           return 1;
48968         }
48969       }
48970 #endif
48971       if( is_agg && !pNC->allowAgg ){
48972         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
48973         pNC->nErr++;
48974         is_agg = 0;
48975       }else if( no_such_func ){
48976         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
48977         pNC->nErr++;
48978       }else if( wrong_num_args ){
48979         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
48980              nId, zId);
48981         pNC->nErr++;
48982       }
48983       if( is_agg ){
48984         pExpr->op = TK_AGG_FUNCTION;
48985         pNC->hasAgg = 1;
48986       }
48987       if( is_agg ) pNC->allowAgg = 0;
48988       for(i=0; pNC->nErr==0 && i<n; i++){
48989         walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
48990       }
48991       if( is_agg ) pNC->allowAgg = 1;
48992       /* FIX ME:  Compute pExpr->affinity based on the expected return
48993       ** type of the function 
48994       */
48995       return is_agg;
48996     }
48997 #ifndef SQLITE_OMIT_SUBQUERY
48998     case TK_SELECT:
48999     case TK_EXISTS:
49000 #endif
49001     case TK_IN: {
49002       if( pExpr->pSelect ){
49003         int nRef = pNC->nRef;
49004 #ifndef SQLITE_OMIT_CHECK
49005         if( pNC->isCheck ){
49006           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
49007         }
49008 #endif
49009         sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
49010         assert( pNC->nRef>=nRef );
49011         if( nRef!=pNC->nRef ){
49012           ExprSetProperty(pExpr, EP_VarSelect);
49013         }
49014       }
49015       break;
49016     }
49017 #ifndef SQLITE_OMIT_CHECK
49018     case TK_VARIABLE: {
49019       if( pNC->isCheck ){
49020         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
49021       }
49022       break;
49023     }
49024 #endif
49025   }
49026   return 0;
49027 }
49028
49029 /*
49030 ** This routine walks an expression tree and resolves references to
49031 ** table columns.  Nodes of the form ID.ID or ID resolve into an
49032 ** index to the table in the table list and a column offset.  The 
49033 ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
49034 ** value is changed to the index of the referenced table in pTabList
49035 ** plus the "base" value.  The base value will ultimately become the
49036 ** VDBE cursor number for a cursor that is pointing into the referenced
49037 ** table.  The Expr.iColumn value is changed to the index of the column 
49038 ** of the referenced table.  The Expr.iColumn value for the special
49039 ** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
49040 ** alias for ROWID.
49041 **
49042 ** Also resolve function names and check the functions for proper
49043 ** usage.  Make sure all function names are recognized and all functions
49044 ** have the correct number of arguments.  Leave an error message
49045 ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
49046 **
49047 ** If the expression contains aggregate functions then set the EP_Agg
49048 ** property on the expression.
49049 */
49050 SQLITE_PRIVATE int sqlite3ExprResolveNames( 
49051   NameContext *pNC,       /* Namespace to resolve expressions in. */
49052   Expr *pExpr             /* The expression to be analyzed. */
49053 ){
49054   int savedHasAgg;
49055
49056   if( pExpr==0 ) return 0;
49057 #if SQLITE_MAX_EXPR_DEPTH>0
49058   {
49059     int mxDepth = pNC->pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
49060     if( (pExpr->nHeight+pNC->pParse->nHeight)>mxDepth ){
49061       sqlite3ErrorMsg(pNC->pParse, 
49062          "Expression tree is too large (maximum depth %d)", mxDepth
49063       );
49064       return 1;
49065     }
49066     pNC->pParse->nHeight += pExpr->nHeight;
49067   }
49068 #endif
49069   savedHasAgg = pNC->hasAgg;
49070   pNC->hasAgg = 0;
49071   walkExprTree(pExpr, nameResolverStep, pNC);
49072 #if SQLITE_MAX_EXPR_DEPTH>0
49073   pNC->pParse->nHeight -= pExpr->nHeight;
49074 #endif
49075   if( pNC->nErr>0 ){
49076     ExprSetProperty(pExpr, EP_Error);
49077   }
49078   if( pNC->hasAgg ){
49079     ExprSetProperty(pExpr, EP_Agg);
49080   }else if( savedHasAgg ){
49081     pNC->hasAgg = 1;
49082   }
49083   return ExprHasProperty(pExpr, EP_Error);
49084 }
49085
49086 /*
49087 ** A pointer instance of this structure is used to pass information
49088 ** through walkExprTree into codeSubqueryStep().
49089 */
49090 typedef struct QueryCoder QueryCoder;
49091 struct QueryCoder {
49092   Parse *pParse;       /* The parsing context */
49093   NameContext *pNC;    /* Namespace of first enclosing query */
49094 };
49095
49096 #ifdef SQLITE_TEST
49097   int sqlite3_enable_in_opt = 1;
49098 #else
49099   #define sqlite3_enable_in_opt 1
49100 #endif
49101
49102 /*
49103 ** Return true if the IN operator optimization is enabled and
49104 ** the SELECT statement p exists and is of the
49105 ** simple form:
49106 **
49107 **     SELECT <column> FROM <table>
49108 **
49109 ** If this is the case, it may be possible to use an existing table
49110 ** or index instead of generating an epheremal table.
49111 */
49112 #ifndef SQLITE_OMIT_SUBQUERY
49113 static int isCandidateForInOpt(Select *p){
49114   SrcList *pSrc;
49115   ExprList *pEList;
49116   Table *pTab;
49117   if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
49118   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
49119   if( p->pPrior ) return 0;              /* Not a compound SELECT */
49120   if( p->isDistinct ) return 0;          /* No DISTINCT keyword */
49121   if( p->isAgg ) return 0;               /* Contains no aggregate functions */
49122   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
49123   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
49124   if( p->pOffset ) return 0;
49125   if( p->pWhere ) return 0;              /* Has no WHERE clause */
49126   pSrc = p->pSrc;
49127   if( pSrc==0 ) return 0;                /* A single table in the FROM clause */
49128   if( pSrc->nSrc!=1 ) return 0;
49129   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
49130   pTab = pSrc->a[0].pTab;
49131   if( pTab==0 ) return 0;
49132   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
49133   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
49134   pEList = p->pEList;
49135   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
49136   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
49137   return 1;
49138 }
49139 #endif /* SQLITE_OMIT_SUBQUERY */
49140
49141 /*
49142 ** This function is used by the implementation of the IN (...) operator.
49143 ** It's job is to find or create a b-tree structure that may be used
49144 ** either to test for membership of the (...) set or to iterate through
49145 ** its members, skipping duplicates.
49146 **
49147 ** The cursor opened on the structure (database table, database index 
49148 ** or ephermal table) is stored in pX->iTable before this function returns.
49149 ** The returned value indicates the structure type, as follows:
49150 **
49151 **   IN_INDEX_ROWID - The cursor was opened on a database table.
49152 **   IN_INDEX_INDEX - The cursor was opened on a database index.
49153 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
49154 **                    populated epheremal table.
49155 **
49156 ** An existing structure may only be used if the SELECT is of the simple
49157 ** form:
49158 **
49159 **     SELECT <column> FROM <table>
49160 **
49161 ** If the mustBeUnique parameter is false, the structure will be used 
49162 ** for fast set membership tests. In this case an epheremal table must 
49163 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
49164 ** be found with <column> as its left-most column.
49165 **
49166 ** If mustBeUnique is true, then the structure will be used to iterate
49167 ** through the set members, skipping any duplicates. In this case an
49168 ** epheremal table must be used unless the selected <column> is guaranteed
49169 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
49170 ** is unique by virtue of a constraint or implicit index.
49171 */
49172 #ifndef SQLITE_OMIT_SUBQUERY
49173 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int mustBeUnique){
49174   Select *p;
49175   int eType = 0;
49176   int iTab = pParse->nTab++;
49177
49178   /* The follwing if(...) expression is true if the SELECT is of the 
49179   ** simple form:
49180   **
49181   **     SELECT <column> FROM <table>
49182   **
49183   ** If this is the case, it may be possible to use an existing table
49184   ** or index instead of generating an epheremal table.
49185   */
49186   p = pX->pSelect;
49187   if( isCandidateForInOpt(p) ){
49188     sqlite3 *db = pParse->db;
49189     Index *pIdx;
49190     Expr *pExpr = p->pEList->a[0].pExpr;
49191     int iCol = pExpr->iColumn;
49192     Vdbe *v = sqlite3GetVdbe(pParse);
49193
49194     /* This function is only called from two places. In both cases the vdbe
49195     ** has already been allocated. So assume sqlite3GetVdbe() is always
49196     ** successful here.
49197     */
49198     assert(v);
49199     if( iCol<0 ){
49200       int iMem = ++pParse->nMem;
49201       int iAddr;
49202       Table *pTab = p->pSrc->a[0].pTab;
49203       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
49204       sqlite3VdbeUsesBtree(v, iDb);
49205
49206       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
49207       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
49208
49209       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
49210       eType = IN_INDEX_ROWID;
49211
49212       sqlite3VdbeJumpHere(v, iAddr);
49213     }else{
49214       /* The collation sequence used by the comparison. If an index is to 
49215       ** be used in place of a temp-table, it must be ordered according
49216       ** to this collation sequence.
49217       */
49218       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
49219
49220       /* Check that the affinity that will be used to perform the 
49221       ** comparison is the same as the affinity of the column. If
49222       ** it is not, it is not possible to use any index.
49223       */
49224       Table *pTab = p->pSrc->a[0].pTab;
49225       char aff = comparisonAffinity(pX);
49226       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
49227
49228       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
49229         if( (pIdx->aiColumn[0]==iCol)
49230          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
49231          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
49232         ){
49233           int iDb;
49234           int iMem = ++pParse->nMem;
49235           int iAddr;
49236           char *pKey;
49237   
49238           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
49239           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
49240           sqlite3VdbeUsesBtree(v, iDb);
49241
49242           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
49243           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
49244   
49245           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
49246           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
49247                                pKey,P4_KEYINFO_HANDOFF);
49248           VdbeComment((v, "%s", pIdx->zName));
49249           eType = IN_INDEX_INDEX;
49250
49251           sqlite3VdbeJumpHere(v, iAddr);
49252         }
49253       }
49254     }
49255   }
49256
49257   if( eType==0 ){
49258     sqlite3CodeSubselect(pParse, pX);
49259     eType = IN_INDEX_EPH;
49260   }else{
49261     pX->iTable = iTab;
49262   }
49263   return eType;
49264 }
49265 #endif
49266
49267 /*
49268 ** Generate code for scalar subqueries used as an expression
49269 ** and IN operators.  Examples:
49270 **
49271 **     (SELECT a FROM b)          -- subquery
49272 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
49273 **     x IN (4,5,11)              -- IN operator with list on right-hand side
49274 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
49275 **
49276 ** The pExpr parameter describes the expression that contains the IN
49277 ** operator or subquery.
49278 */
49279 #ifndef SQLITE_OMIT_SUBQUERY
49280 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
49281   int testAddr = 0;                       /* One-time test address */
49282   Vdbe *v = sqlite3GetVdbe(pParse);
49283   if( v==0 ) return;
49284
49285
49286   /* This code must be run in its entirety every time it is encountered
49287   ** if any of the following is true:
49288   **
49289   **    *  The right-hand side is a correlated subquery
49290   **    *  The right-hand side is an expression list containing variables
49291   **    *  We are inside a trigger
49292   **
49293   ** If all of the above are false, then we can run this code just once
49294   ** save the results, and reuse the same result on subsequent invocations.
49295   */
49296   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
49297     int mem = ++pParse->nMem;
49298     sqlite3VdbeAddOp1(v, OP_If, mem);
49299     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
49300     assert( testAddr>0 || pParse->db->mallocFailed );
49301   }
49302
49303   switch( pExpr->op ){
49304     case TK_IN: {
49305       char affinity;
49306       KeyInfo keyInfo;
49307       int addr;        /* Address of OP_OpenEphemeral instruction */
49308
49309       affinity = sqlite3ExprAffinity(pExpr->pLeft);
49310
49311       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
49312       ** expression it is handled the same way. A virtual table is 
49313       ** filled with single-field index keys representing the results
49314       ** from the SELECT or the <exprlist>.
49315       **
49316       ** If the 'x' expression is a column value, or the SELECT...
49317       ** statement returns a column value, then the affinity of that
49318       ** column is used to build the index keys. If both 'x' and the
49319       ** SELECT... statement are columns, then numeric affinity is used
49320       ** if either column has NUMERIC or INTEGER affinity. If neither
49321       ** 'x' nor the SELECT... statement are columns, then numeric affinity
49322       ** is used.
49323       */
49324       pExpr->iTable = pParse->nTab++;
49325       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, 1);
49326       memset(&keyInfo, 0, sizeof(keyInfo));
49327       keyInfo.nField = 1;
49328
49329       if( pExpr->pSelect ){
49330         /* Case 1:     expr IN (SELECT ...)
49331         **
49332         ** Generate code to write the results of the select into the temporary
49333         ** table allocated and opened above.
49334         */
49335         SelectDest dest;
49336         ExprList *pEList;
49337
49338         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
49339         dest.affinity = (int)affinity;
49340         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
49341         if( sqlite3Select(pParse, pExpr->pSelect, &dest, 0, 0, 0, 0) ){
49342           return;
49343         }
49344         pEList = pExpr->pSelect->pEList;
49345         if( pEList && pEList->nExpr>0 ){ 
49346           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
49347               pEList->a[0].pExpr);
49348         }
49349       }else if( pExpr->pList ){
49350         /* Case 2:     expr IN (exprlist)
49351         **
49352         ** For each expression, build an index key from the evaluation and
49353         ** store it in the temporary table. If <expr> is a column, then use
49354         ** that columns affinity when building index keys. If <expr> is not
49355         ** a column, use numeric affinity.
49356         */
49357         int i;
49358         ExprList *pList = pExpr->pList;
49359         struct ExprList_item *pItem;
49360         int r1, r2;
49361
49362         if( !affinity ){
49363           affinity = SQLITE_AFF_NONE;
49364         }
49365         keyInfo.aColl[0] = pExpr->pLeft->pColl;
49366
49367         /* Loop through each expression in <exprlist>. */
49368         r1 = sqlite3GetTempReg(pParse);
49369         r2 = sqlite3GetTempReg(pParse);
49370         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
49371           Expr *pE2 = pItem->pExpr;
49372
49373           /* If the expression is not constant then we will need to
49374           ** disable the test that was generated above that makes sure
49375           ** this code only executes once.  Because for a non-constant
49376           ** expression we need to rerun this code each time.
49377           */
49378           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
49379             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
49380             testAddr = 0;
49381           }
49382
49383           /* Evaluate the expression and insert it into the temp table */
49384           pParse->disableColCache++;
49385           sqlite3ExprCode(pParse, pE2, r1);
49386           assert( pParse->disableColCache>0 );
49387           pParse->disableColCache--;
49388           sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
49389           sqlite3ExprCacheAffinityChange(pParse, r1, 1);
49390           sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
49391         }
49392         sqlite3ReleaseTempReg(pParse, r1);
49393         sqlite3ReleaseTempReg(pParse, r2);
49394       }
49395       sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
49396       break;
49397     }
49398
49399     case TK_EXISTS:
49400     case TK_SELECT: {
49401       /* This has to be a scalar SELECT.  Generate code to put the
49402       ** value of this select in a memory cell and record the number
49403       ** of the memory cell in iColumn.
49404       */
49405       static const Token one = { (u8*)"1", 0, 1 };
49406       Select *pSel;
49407       SelectDest dest;
49408
49409       pSel = pExpr->pSelect;
49410       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
49411       if( pExpr->op==TK_SELECT ){
49412         dest.eDest = SRT_Mem;
49413         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
49414         VdbeComment((v, "Init subquery result"));
49415       }else{
49416         dest.eDest = SRT_Exists;
49417         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
49418         VdbeComment((v, "Init EXISTS result"));
49419       }
49420       sqlite3ExprDelete(pSel->pLimit);
49421       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
49422       if( sqlite3Select(pParse, pSel, &dest, 0, 0, 0, 0) ){
49423         return;
49424       }
49425       pExpr->iColumn = dest.iParm;
49426       break;
49427     }
49428   }
49429
49430   if( testAddr ){
49431     sqlite3VdbeJumpHere(v, testAddr-1);
49432   }
49433
49434   return;
49435 }
49436 #endif /* SQLITE_OMIT_SUBQUERY */
49437
49438 /*
49439 ** Duplicate an 8-byte value
49440 */
49441 static char *dup8bytes(Vdbe *v, const char *in){
49442   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
49443   if( out ){
49444     memcpy(out, in, 8);
49445   }
49446   return out;
49447 }
49448
49449 /*
49450 ** Generate an instruction that will put the floating point
49451 ** value described by z[0..n-1] into register iMem.
49452 **
49453 ** The z[] string will probably not be zero-terminated.  But the 
49454 ** z[n] character is guaranteed to be something that does not look
49455 ** like the continuation of the number.
49456 */
49457 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
49458   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
49459   if( z ){
49460     double value;
49461     char *zV;
49462     assert( !isdigit(z[n]) );
49463     sqlite3AtoF(z, &value);
49464     if( sqlite3IsNaN(value) ){
49465       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
49466     }else{
49467       if( negateFlag ) value = -value;
49468       zV = dup8bytes(v, (char*)&value);
49469       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
49470     }
49471   }
49472 }
49473
49474
49475 /*
49476 ** Generate an instruction that will put the integer describe by
49477 ** text z[0..n-1] into register iMem.
49478 **
49479 ** The z[] string will probably not be zero-terminated.  But the 
49480 ** z[n] character is guaranteed to be something that does not look
49481 ** like the continuation of the number.
49482 */
49483 static void codeInteger(Vdbe *v, const char *z, int n, int negFlag, int iMem){
49484   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
49485   if( z ){
49486     int i;
49487     assert( !isdigit(z[n]) );
49488     if( sqlite3GetInt32(z, &i) ){
49489       if( negFlag ) i = -i;
49490       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
49491     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
49492       i64 value;
49493       char *zV;
49494       sqlite3Atoi64(z, &value);
49495       if( negFlag ) value = -value;
49496       zV = dup8bytes(v, (char*)&value);
49497       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
49498     }else{
49499       codeReal(v, z, n, negFlag, iMem);
49500     }
49501   }
49502 }
49503
49504
49505 /*
49506 ** Generate code that will extract the iColumn-th column from
49507 ** table pTab and store the column value in a register.  An effort
49508 ** is made to store the column value in register iReg, but this is
49509 ** not guaranteed.  The location of the column value is returned.
49510 **
49511 ** There must be an open cursor to pTab in iTable when this routine
49512 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
49513 **
49514 ** This routine might attempt to reuse the value of the column that
49515 ** has already been loaded into a register.  The value will always
49516 ** be used if it has not undergone any affinity changes.  But if
49517 ** an affinity change has occurred, then the cached value will only be
49518 ** used if allowAffChng is true.
49519 */
49520 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
49521   Parse *pParse,   /* Parsing and code generating context */
49522   Table *pTab,     /* Description of the table we are reading from */
49523   int iColumn,     /* Index of the table column */
49524   int iTable,      /* The cursor pointing to the table */
49525   int iReg,        /* Store results here */
49526   int allowAffChng /* True if prior affinity changes are OK */
49527 ){
49528   Vdbe *v = pParse->pVdbe;
49529   int i;
49530   struct yColCache *p;
49531
49532   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
49533     if( p->iTable==iTable && p->iColumn==iColumn
49534            && (!p->affChange || allowAffChng) ){
49535 #if 0
49536       sqlite3VdbeAddOp0(v, OP_Noop);
49537       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
49538 #endif
49539       return p->iReg;
49540     }
49541   }  
49542   assert( v!=0 );
49543   if( iColumn<0 ){
49544     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
49545     sqlite3VdbeAddOp2(v, op, iTable, iReg);
49546   }else if( pTab==0 ){
49547     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
49548   }else{
49549     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
49550     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
49551     sqlite3ColumnDefault(v, pTab, iColumn);
49552 #ifndef SQLITE_OMIT_FLOATING_POINT
49553     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
49554       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
49555     }
49556 #endif
49557   }
49558   if( pParse->disableColCache==0 ){
49559     i = pParse->iColCache;
49560     p = &pParse->aColCache[i];
49561     p->iTable = iTable;
49562     p->iColumn = iColumn;
49563     p->iReg = iReg;
49564     p->affChange = 0;
49565     i++;
49566     if( i>=ArraySize(pParse->aColCache) ) i = 0;
49567     if( i>pParse->nColCache ) pParse->nColCache = i;
49568     pParse->iColCache = i;
49569   }
49570   return iReg;
49571 }
49572
49573 /*
49574 ** Clear all column cache entries associated with the vdbe
49575 ** cursor with cursor number iTable.
49576 */
49577 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
49578   if( iTable<0 ){
49579     pParse->nColCache = 0;
49580     pParse->iColCache = 0;
49581   }else{
49582     int i;
49583     for(i=0; i<pParse->nColCache; i++){
49584       if( pParse->aColCache[i].iTable==iTable ){
49585         testcase( i==pParse->nColCache-1 );
49586         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
49587         pParse->iColCache = pParse->nColCache;
49588       }
49589     }
49590   }
49591 }
49592
49593 /*
49594 ** Record the fact that an affinity change has occurred on iCount
49595 ** registers starting with iStart.
49596 */
49597 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
49598   int iEnd = iStart + iCount - 1;
49599   int i;
49600   for(i=0; i<pParse->nColCache; i++){
49601     int r = pParse->aColCache[i].iReg;
49602     if( r>=iStart && r<=iEnd ){
49603       pParse->aColCache[i].affChange = 1;
49604     }
49605   }
49606 }
49607
49608 /*
49609 ** Generate code to moves content from one register to another.
49610 ** Keep the column cache up-to-date.
49611 */
49612 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo){
49613   int i;
49614   if( iFrom==iTo ) return;
49615   sqlite3VdbeAddOp2(pParse->pVdbe, OP_Move, iFrom, iTo);
49616   for(i=0; i<pParse->nColCache; i++){
49617     if( pParse->aColCache[i].iReg==iFrom ){
49618       pParse->aColCache[i].iReg = iTo;
49619     }
49620   }
49621 }
49622
49623 /*
49624 ** Return true if any register in the range iFrom..iTo (inclusive)
49625 ** is used as part of the column cache.
49626 */
49627 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
49628   int i;
49629   for(i=0; i<pParse->nColCache; i++){
49630     int r = pParse->aColCache[i].iReg;
49631     if( r>=iFrom && r<=iTo ) return 1;
49632   }
49633   return 0;
49634 }
49635
49636 /*
49637 ** Theres is a value in register iCurrent.  We ultimately want
49638 ** the value to be in register iTarget.  It might be that
49639 ** iCurrent and iTarget are the same register.
49640 **
49641 ** We are going to modify the value, so we need to make sure it
49642 ** is not a cached register.  If iCurrent is a cached register,
49643 ** then try to move the value over to iTarget.  If iTarget is a
49644 ** cached register, then clear the corresponding cache line.
49645 **
49646 ** Return the register that the value ends up in.
49647 */
49648 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
49649   int i;
49650   assert( pParse->pVdbe!=0 );
49651   if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
49652     return iCurrent;
49653   }
49654   if( iCurrent!=iTarget ){
49655     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
49656   }
49657   for(i=0; i<pParse->nColCache; i++){
49658     if( pParse->aColCache[i].iReg==iTarget ){
49659       pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
49660       pParse->iColCache = pParse->nColCache;
49661     }
49662   }
49663   return iTarget;
49664 }
49665
49666 /*
49667 ** If the last instruction coded is an ephemeral copy of any of
49668 ** the registers in the nReg registers beginning with iReg, then
49669 ** convert the last instruction from OP_SCopy to OP_Copy.
49670 */
49671 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
49672   int addr;
49673   VdbeOp *pOp;
49674   Vdbe *v;
49675
49676   v = pParse->pVdbe;
49677   addr = sqlite3VdbeCurrentAddr(v);
49678   pOp = sqlite3VdbeGetOp(v, addr-1);
49679   assert( pOp || pParse->db->mallocFailed );
49680   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
49681     pOp->opcode = OP_Copy;
49682   }
49683 }
49684
49685 /*
49686 ** Generate code into the current Vdbe to evaluate the given
49687 ** expression.  Attempt to store the results in register "target".
49688 ** Return the register where results are stored.
49689 **
49690 ** With this routine, there is no guaranteed that results will
49691 ** be stored in target.  The result might be stored in some other
49692 ** register if it is convenient to do so.  The calling function
49693 ** must check the return code and move the results to the desired
49694 ** register.
49695 */
49696 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
49697   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
49698   int op;                   /* The opcode being coded */
49699   int inReg = target;       /* Results stored in register inReg */
49700   int regFree1 = 0;         /* If non-zero free this temporary register */
49701   int regFree2 = 0;         /* If non-zero free this temporary register */
49702   int r1, r2, r3, r4;       /* Various register numbers */
49703
49704   assert( v!=0 || pParse->db->mallocFailed );
49705   assert( target>0 && target<=pParse->nMem );
49706   if( v==0 ) return 0;
49707
49708   if( pExpr==0 ){
49709     op = TK_NULL;
49710   }else{
49711     op = pExpr->op;
49712   }
49713   switch( op ){
49714     case TK_AGG_COLUMN: {
49715       AggInfo *pAggInfo = pExpr->pAggInfo;
49716       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
49717       if( !pAggInfo->directMode ){
49718         assert( pCol->iMem>0 );
49719         inReg = pCol->iMem;
49720         break;
49721       }else if( pAggInfo->useSortingIdx ){
49722         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
49723                               pCol->iSorterColumn, target);
49724         break;
49725       }
49726       /* Otherwise, fall thru into the TK_COLUMN case */
49727     }
49728     case TK_COLUMN: {
49729       if( pExpr->iTable<0 ){
49730         /* This only happens when coding check constraints */
49731         assert( pParse->ckBase>0 );
49732         inReg = pExpr->iColumn + pParse->ckBase;
49733       }else{
49734         testcase( (pExpr->flags & EP_AnyAff)!=0 );
49735         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
49736                                  pExpr->iColumn, pExpr->iTable, target,
49737                                  pExpr->flags & EP_AnyAff);
49738       }
49739       break;
49740     }
49741     case TK_INTEGER: {
49742       codeInteger(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
49743       break;
49744     }
49745     case TK_FLOAT: {
49746       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
49747       break;
49748     }
49749     case TK_STRING: {
49750       sqlite3DequoteExpr(pParse->db, pExpr);
49751       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
49752                         (char*)pExpr->token.z, pExpr->token.n);
49753       break;
49754     }
49755     case TK_NULL: {
49756       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
49757       break;
49758     }
49759 #ifndef SQLITE_OMIT_BLOB_LITERAL
49760     case TK_BLOB: {
49761       int n;
49762       const char *z;
49763       char *zBlob;
49764       assert( pExpr->token.n>=3 );
49765       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
49766       assert( pExpr->token.z[1]=='\'' );
49767       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
49768       n = pExpr->token.n - 3;
49769       z = (char*)pExpr->token.z + 2;
49770       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
49771       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
49772       break;
49773     }
49774 #endif
49775     case TK_VARIABLE: {
49776       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
49777       if( pExpr->token.n>1 ){
49778         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
49779       }
49780       break;
49781     }
49782     case TK_REGISTER: {
49783       inReg = pExpr->iTable;
49784       break;
49785     }
49786 #ifndef SQLITE_OMIT_CAST
49787     case TK_CAST: {
49788       /* Expressions of the form:   CAST(pLeft AS token) */
49789       int aff, to_op;
49790       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
49791       aff = sqlite3AffinityType(&pExpr->token);
49792       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
49793       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
49794       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
49795       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
49796       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
49797       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
49798       testcase( to_op==OP_ToText );
49799       testcase( to_op==OP_ToBlob );
49800       testcase( to_op==OP_ToNumeric );
49801       testcase( to_op==OP_ToInt );
49802       testcase( to_op==OP_ToReal );
49803       sqlite3VdbeAddOp1(v, to_op, inReg);
49804       testcase( usedAsColumnCache(pParse, inReg, inReg) );
49805       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
49806       break;
49807     }
49808 #endif /* SQLITE_OMIT_CAST */
49809     case TK_LT:
49810     case TK_LE:
49811     case TK_GT:
49812     case TK_GE:
49813     case TK_NE:
49814     case TK_EQ: {
49815       assert( TK_LT==OP_Lt );
49816       assert( TK_LE==OP_Le );
49817       assert( TK_GT==OP_Gt );
49818       assert( TK_GE==OP_Ge );
49819       assert( TK_EQ==OP_Eq );
49820       assert( TK_NE==OP_Ne );
49821       testcase( op==TK_LT );
49822       testcase( op==TK_LE );
49823       testcase( op==TK_GT );
49824       testcase( op==TK_GE );
49825       testcase( op==TK_EQ );
49826       testcase( op==TK_NE );
49827       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
49828                                   pExpr->pRight, &r2, &regFree2);
49829       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
49830                   r1, r2, inReg, SQLITE_STOREP2);
49831       testcase( regFree1==0 );
49832       testcase( regFree2==0 );
49833       break;
49834     }
49835     case TK_AND:
49836     case TK_OR:
49837     case TK_PLUS:
49838     case TK_STAR:
49839     case TK_MINUS:
49840     case TK_REM:
49841     case TK_BITAND:
49842     case TK_BITOR:
49843     case TK_SLASH:
49844     case TK_LSHIFT:
49845     case TK_RSHIFT: 
49846     case TK_CONCAT: {
49847       assert( TK_AND==OP_And );
49848       assert( TK_OR==OP_Or );
49849       assert( TK_PLUS==OP_Add );
49850       assert( TK_MINUS==OP_Subtract );
49851       assert( TK_REM==OP_Remainder );
49852       assert( TK_BITAND==OP_BitAnd );
49853       assert( TK_BITOR==OP_BitOr );
49854       assert( TK_SLASH==OP_Divide );
49855       assert( TK_LSHIFT==OP_ShiftLeft );
49856       assert( TK_RSHIFT==OP_ShiftRight );
49857       assert( TK_CONCAT==OP_Concat );
49858       testcase( op==TK_AND );
49859       testcase( op==TK_OR );
49860       testcase( op==TK_PLUS );
49861       testcase( op==TK_MINUS );
49862       testcase( op==TK_REM );
49863       testcase( op==TK_BITAND );
49864       testcase( op==TK_BITOR );
49865       testcase( op==TK_SLASH );
49866       testcase( op==TK_LSHIFT );
49867       testcase( op==TK_RSHIFT );
49868       testcase( op==TK_CONCAT );
49869       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
49870       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
49871       sqlite3VdbeAddOp3(v, op, r2, r1, target);
49872       testcase( regFree1==0 );
49873       testcase( regFree2==0 );
49874       break;
49875     }
49876     case TK_UMINUS: {
49877       Expr *pLeft = pExpr->pLeft;
49878       assert( pLeft );
49879       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
49880         Token *p = &pLeft->token;
49881         if( pLeft->op==TK_FLOAT ){
49882           codeReal(v, (char*)p->z, p->n, 1, target);
49883         }else{
49884           codeInteger(v, (char*)p->z, p->n, 1, target);
49885         }
49886       }else{
49887         regFree1 = r1 = sqlite3GetTempReg(pParse);
49888         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
49889         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
49890         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
49891         testcase( regFree2==0 );
49892       }
49893       inReg = target;
49894       break;
49895     }
49896     case TK_BITNOT:
49897     case TK_NOT: {
49898       assert( TK_BITNOT==OP_BitNot );
49899       assert( TK_NOT==OP_Not );
49900       testcase( op==TK_BITNOT );
49901       testcase( op==TK_NOT );
49902       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
49903       testcase( inReg==target );
49904       testcase( usedAsColumnCache(pParse, inReg, inReg) );
49905       inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
49906       sqlite3VdbeAddOp1(v, op, inReg);
49907       break;
49908     }
49909     case TK_ISNULL:
49910     case TK_NOTNULL: {
49911       int addr;
49912       assert( TK_ISNULL==OP_IsNull );
49913       assert( TK_NOTNULL==OP_NotNull );
49914       testcase( op==TK_ISNULL );
49915       testcase( op==TK_NOTNULL );
49916       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
49917       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
49918       testcase( regFree1==0 );
49919       addr = sqlite3VdbeAddOp1(v, op, r1);
49920       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
49921       sqlite3VdbeJumpHere(v, addr);
49922       break;
49923     }
49924     case TK_AGG_FUNCTION: {
49925       AggInfo *pInfo = pExpr->pAggInfo;
49926       if( pInfo==0 ){
49927         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
49928             &pExpr->span);
49929       }else{
49930         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
49931       }
49932       break;
49933     }
49934     case TK_CONST_FUNC:
49935     case TK_FUNCTION: {
49936       ExprList *pList = pExpr->pList;
49937       int nExpr = pList ? pList->nExpr : 0;
49938       FuncDef *pDef;
49939       int nId;
49940       const char *zId;
49941       int constMask = 0;
49942       int i;
49943       sqlite3 *db = pParse->db;
49944       u8 enc = ENC(db);
49945       CollSeq *pColl = 0;
49946
49947       testcase( op==TK_CONST_FUNC );
49948       testcase( op==TK_FUNCTION );
49949       zId = (char*)pExpr->token.z;
49950       nId = pExpr->token.n;
49951       pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
49952       assert( pDef!=0 );
49953       if( pList ){
49954         nExpr = pList->nExpr;
49955         r1 = sqlite3GetTempRange(pParse, nExpr);
49956         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
49957       }else{
49958         nExpr = r1 = 0;
49959       }
49960 #ifndef SQLITE_OMIT_VIRTUALTABLE
49961       /* Possibly overload the function if the first argument is
49962       ** a virtual table column.
49963       **
49964       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
49965       ** second argument, not the first, as the argument to test to
49966       ** see if it is a column in a virtual table.  This is done because
49967       ** the left operand of infix functions (the operand we want to
49968       ** control overloading) ends up as the second argument to the
49969       ** function.  The expression "A glob B" is equivalent to 
49970       ** "glob(B,A).  We want to use the A in "A glob B" to test
49971       ** for function overloading.  But we use the B term in "glob(B,A)".
49972       */
49973       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
49974         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
49975       }else if( nExpr>0 ){
49976         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
49977       }
49978 #endif
49979       for(i=0; i<nExpr && i<32; i++){
49980         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
49981           constMask |= (1<<i);
49982         }
49983         if( pDef->needCollSeq && !pColl ){
49984           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
49985         }
49986       }
49987       if( pDef->needCollSeq ){
49988         if( !pColl ) pColl = pParse->db->pDfltColl; 
49989         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
49990       }
49991       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
49992                         (char*)pDef, P4_FUNCDEF);
49993       sqlite3VdbeChangeP5(v, nExpr);
49994       if( nExpr ){
49995         sqlite3ReleaseTempRange(pParse, r1, nExpr);
49996       }
49997       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
49998       break;
49999     }
50000 #ifndef SQLITE_OMIT_SUBQUERY
50001     case TK_EXISTS:
50002     case TK_SELECT: {
50003       testcase( op==TK_EXISTS );
50004       testcase( op==TK_SELECT );
50005       if( pExpr->iColumn==0 ){
50006         sqlite3CodeSubselect(pParse, pExpr);
50007       }
50008       inReg = pExpr->iColumn;
50009       break;
50010     }
50011     case TK_IN: {
50012       int j1, j2, j3, j4, j5;
50013       char affinity;
50014       int eType;
50015
50016       eType = sqlite3FindInIndex(pParse, pExpr, 0);
50017
50018       /* Figure out the affinity to use to create a key from the results
50019       ** of the expression. affinityStr stores a static string suitable for
50020       ** P4 of OP_MakeRecord.
50021       */
50022       affinity = comparisonAffinity(pExpr);
50023
50024       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
50025
50026       /* Code the <expr> from "<expr> IN (...)". The temporary table
50027       ** pExpr->iTable contains the values that make up the (...) set.
50028       */
50029       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
50030       testcase( regFree1==0 );
50031       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
50032       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
50033       j2  = sqlite3VdbeAddOp0(v, OP_Goto);
50034       sqlite3VdbeJumpHere(v, j1);
50035       if( eType==IN_INDEX_ROWID ){
50036         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, r1);
50037         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, r1);
50038         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
50039         sqlite3VdbeJumpHere(v, j3);
50040         sqlite3VdbeJumpHere(v, j4);
50041       }else{
50042         r2 = regFree2 = sqlite3GetTempReg(pParse);
50043         sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
50044         sqlite3ExprCacheAffinityChange(pParse, r1, 1);
50045         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
50046       }
50047       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
50048       sqlite3VdbeJumpHere(v, j2);
50049       sqlite3VdbeJumpHere(v, j5);
50050       break;
50051     }
50052 #endif
50053     /*
50054     **    x BETWEEN y AND z
50055     **
50056     ** This is equivalent to
50057     **
50058     **    x>=y AND x<=z
50059     **
50060     ** X is stored in pExpr->pLeft.
50061     ** Y is stored in pExpr->pList->a[0].pExpr.
50062     ** Z is stored in pExpr->pList->a[1].pExpr.
50063     */
50064     case TK_BETWEEN: {
50065       Expr *pLeft = pExpr->pLeft;
50066       struct ExprList_item *pLItem = pExpr->pList->a;
50067       Expr *pRight = pLItem->pExpr;
50068
50069       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
50070                                   pRight, &r2, &regFree2);
50071       testcase( regFree1==0 );
50072       testcase( regFree2==0 );
50073       r3 = sqlite3GetTempReg(pParse);
50074       r4 = sqlite3GetTempReg(pParse);
50075       codeCompare(pParse, pLeft, pRight, OP_Ge,
50076                   r1, r2, r3, SQLITE_STOREP2);
50077       pLItem++;
50078       pRight = pLItem->pExpr;
50079       sqlite3ReleaseTempReg(pParse, regFree2);
50080       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
50081       testcase( regFree2==0 );
50082       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
50083       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
50084       sqlite3ReleaseTempReg(pParse, r3);
50085       sqlite3ReleaseTempReg(pParse, r4);
50086       break;
50087     }
50088     case TK_UPLUS: {
50089       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
50090       break;
50091     }
50092
50093     /*
50094     ** Form A:
50095     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
50096     **
50097     ** Form B:
50098     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
50099     **
50100     ** Form A is can be transformed into the equivalent form B as follows:
50101     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
50102     **        WHEN x=eN THEN rN ELSE y END
50103     **
50104     ** X (if it exists) is in pExpr->pLeft.
50105     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
50106     ** ELSE clause and no other term matches, then the result of the
50107     ** exprssion is NULL.
50108     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
50109     **
50110     ** The result of the expression is the Ri for the first matching Ei,
50111     ** or if there is no matching Ei, the ELSE term Y, or if there is
50112     ** no ELSE term, NULL.
50113     */
50114     case TK_CASE: {
50115       int endLabel;                     /* GOTO label for end of CASE stmt */
50116       int nextCase;                     /* GOTO label for next WHEN clause */
50117       int nExpr;                        /* 2x number of WHEN terms */
50118       int i;                            /* Loop counter */
50119       ExprList *pEList;                 /* List of WHEN terms */
50120       struct ExprList_item *aListelem;  /* Array of WHEN terms */
50121       Expr opCompare;                   /* The X==Ei expression */
50122       Expr cacheX;                      /* Cached expression X */
50123       Expr *pX;                         /* The X expression */
50124       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
50125
50126       assert(pExpr->pList);
50127       assert((pExpr->pList->nExpr % 2) == 0);
50128       assert(pExpr->pList->nExpr > 0);
50129       pEList = pExpr->pList;
50130       aListelem = pEList->a;
50131       nExpr = pEList->nExpr;
50132       endLabel = sqlite3VdbeMakeLabel(v);
50133       if( (pX = pExpr->pLeft)!=0 ){
50134         cacheX = *pX;
50135         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
50136         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
50137         testcase( regFree1==0 );
50138         cacheX.op = TK_REGISTER;
50139         cacheX.iColumn = 0;
50140         opCompare.op = TK_EQ;
50141         opCompare.pLeft = &cacheX;
50142         pTest = &opCompare;
50143       }
50144       pParse->disableColCache++;
50145       for(i=0; i<nExpr; i=i+2){
50146         if( pX ){
50147           opCompare.pRight = aListelem[i].pExpr;
50148         }else{
50149           pTest = aListelem[i].pExpr;
50150         }
50151         nextCase = sqlite3VdbeMakeLabel(v);
50152         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
50153         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
50154         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
50155         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
50156         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
50157         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
50158         sqlite3VdbeResolveLabel(v, nextCase);
50159       }
50160       if( pExpr->pRight ){
50161         sqlite3ExprCode(pParse, pExpr->pRight, target);
50162       }else{
50163         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
50164       }
50165       sqlite3VdbeResolveLabel(v, endLabel);
50166       assert( pParse->disableColCache>0 );
50167       pParse->disableColCache--;
50168       break;
50169     }
50170 #ifndef SQLITE_OMIT_TRIGGER
50171     case TK_RAISE: {
50172       if( !pParse->trigStack ){
50173         sqlite3ErrorMsg(pParse,
50174                        "RAISE() may only be used within a trigger-program");
50175         return 0;
50176       }
50177       if( pExpr->iColumn!=OE_Ignore ){
50178          assert( pExpr->iColumn==OE_Rollback ||
50179                  pExpr->iColumn == OE_Abort ||
50180                  pExpr->iColumn == OE_Fail );
50181          sqlite3DequoteExpr(pParse->db, pExpr);
50182          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
50183                         (char*)pExpr->token.z, pExpr->token.n);
50184       } else {
50185          assert( pExpr->iColumn == OE_Ignore );
50186          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
50187          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
50188          VdbeComment((v, "raise(IGNORE)"));
50189       }
50190       break;
50191     }
50192 #endif
50193   }
50194   sqlite3ReleaseTempReg(pParse, regFree1);
50195   sqlite3ReleaseTempReg(pParse, regFree2);
50196   return inReg;
50197 }
50198
50199 /*
50200 ** Generate code to evaluate an expression and store the results
50201 ** into a register.  Return the register number where the results
50202 ** are stored.
50203 **
50204 ** If the register is a temporary register that can be deallocated,
50205 ** then write its number into *pReg.  If the result register is not
50206 ** a temporary, then set *pReg to zero.
50207 */
50208 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
50209   int r1 = sqlite3GetTempReg(pParse);
50210   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
50211   if( r2==r1 ){
50212     *pReg = r1;
50213   }else{
50214     sqlite3ReleaseTempReg(pParse, r1);
50215     *pReg = 0;
50216   }
50217   return r2;
50218 }
50219
50220 /*
50221 ** Generate code that will evaluate expression pExpr and store the
50222 ** results in register target.  The results are guaranteed to appear
50223 ** in register target.
50224 */
50225 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
50226   int inReg;
50227
50228   assert( target>0 && target<=pParse->nMem );
50229   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
50230   assert( pParse->pVdbe || pParse->db->mallocFailed );
50231   if( inReg!=target && pParse->pVdbe ){
50232     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
50233   }
50234   return target;
50235 }
50236
50237 /*
50238 ** Generate code that evalutes the given expression and puts the result
50239 ** in register target.
50240 **
50241 ** Also make a copy of the expression results into another "cache" register
50242 ** and modify the expression so that the next time it is evaluated,
50243 ** the result is a copy of the cache register.
50244 **
50245 ** This routine is used for expressions that are used multiple 
50246 ** times.  They are evaluated once and the results of the expression
50247 ** are reused.
50248 */
50249 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
50250   Vdbe *v = pParse->pVdbe;
50251   int inReg;
50252   inReg = sqlite3ExprCode(pParse, pExpr, target);
50253   assert( target>0 );
50254   if( pExpr->op!=TK_REGISTER ){  
50255     int iMem;
50256     iMem = ++pParse->nMem;
50257     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
50258     pExpr->iTable = iMem;
50259     pExpr->iColumn = pExpr->op;
50260     pExpr->op = TK_REGISTER;
50261   }
50262   return inReg;
50263 }
50264
50265 /*
50266 ** Return TRUE if pExpr is an constant expression that is appropriate
50267 ** for factoring out of a loop.  Appropriate expressions are:
50268 **
50269 **    *  Any expression that evaluates to two or more opcodes.
50270 **
50271 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
50272 **       or OP_Variable that does not need to be placed in a 
50273 **       specific register.
50274 **
50275 ** There is no point in factoring out single-instruction constant
50276 ** expressions that need to be placed in a particular register.  
50277 ** We could factor them out, but then we would end up adding an
50278 ** OP_SCopy instruction to move the value into the correct register
50279 ** later.  We might as well just use the original instruction and
50280 ** avoid the OP_SCopy.
50281 */
50282 static int isAppropriateForFactoring(Expr *p){
50283   if( !sqlite3ExprIsConstantNotJoin(p) ){
50284     return 0;  /* Only constant expressions are appropriate for factoring */
50285   }
50286   if( (p->flags & EP_FixedDest)==0 ){
50287     return 1;  /* Any constant without a fixed destination is appropriate */
50288   }
50289   while( p->op==TK_UPLUS ) p = p->pLeft;
50290   switch( p->op ){
50291 #ifndef SQLITE_OMIT_BLOB_LITERAL
50292     case TK_BLOB:
50293 #endif
50294     case TK_VARIABLE:
50295     case TK_INTEGER:
50296     case TK_FLOAT:
50297     case TK_NULL:
50298     case TK_STRING: {
50299       testcase( p->op==TK_BLOB );
50300       testcase( p->op==TK_VARIABLE );
50301       testcase( p->op==TK_INTEGER );
50302       testcase( p->op==TK_FLOAT );
50303       testcase( p->op==TK_NULL );
50304       testcase( p->op==TK_STRING );
50305       /* Single-instruction constants with a fixed destination are
50306       ** better done in-line.  If we factor them, they will just end
50307       ** up generating an OP_SCopy to move the value to the destination
50308       ** register. */
50309       return 0;
50310     }
50311     case TK_UMINUS: {
50312        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
50313          return 0;
50314        }
50315        break;
50316     }
50317     default: {
50318       break;
50319     }
50320   }
50321   return 1;
50322 }
50323
50324 /*
50325 ** If pExpr is a constant expression that is appropriate for
50326 ** factoring out of a loop, then evaluate the expression
50327 ** into a register and convert the expression into a TK_REGISTER
50328 ** expression.
50329 */
50330 static int evalConstExpr(void *pArg, Expr *pExpr){
50331   Parse *pParse = (Parse*)pArg;
50332   switch( pExpr->op ){
50333     case TK_REGISTER: {
50334       return 1;
50335     }
50336     case TK_FUNCTION:
50337     case TK_AGG_FUNCTION:
50338     case TK_CONST_FUNC: {
50339       /* The arguments to a function have a fixed destination.
50340       ** Mark them this way to avoid generated unneeded OP_SCopy
50341       ** instructions. 
50342       */
50343       ExprList *pList = pExpr->pList;
50344       if( pList ){
50345         int i = pList->nExpr;
50346         struct ExprList_item *pItem = pList->a;
50347         for(; i>0; i--, pItem++){
50348           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
50349         }
50350       }
50351       break;
50352     }
50353   }
50354   if( isAppropriateForFactoring(pExpr) ){
50355     int r1 = ++pParse->nMem;
50356     int r2;
50357     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
50358     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
50359     pExpr->iColumn = pExpr->op;
50360     pExpr->op = TK_REGISTER;
50361     pExpr->iTable = r2;
50362     return 1;
50363   }
50364   return 0;
50365 }
50366
50367 /*
50368 ** Preevaluate constant subexpressions within pExpr and store the
50369 ** results in registers.  Modify pExpr so that the constant subexpresions
50370 ** are TK_REGISTER opcodes that refer to the precomputed values.
50371 */
50372 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
50373    walkExprTree(pExpr, evalConstExpr, pParse);
50374 }
50375
50376
50377 /*
50378 ** Generate code that pushes the value of every element of the given
50379 ** expression list into a sequence of registers beginning at target.
50380 **
50381 ** Return the number of elements evaluated.
50382 */
50383 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
50384   Parse *pParse,     /* Parsing context */
50385   ExprList *pList,   /* The expression list to be coded */
50386   int target,        /* Where to write results */
50387   int doHardCopy     /* Call sqlite3ExprHardCopy on each element if true */
50388 ){
50389   struct ExprList_item *pItem;
50390   int i, n;
50391   assert( pList!=0 || pParse->db->mallocFailed );
50392   if( pList==0 ){
50393     return 0;
50394   }
50395   assert( target>0 );
50396   n = pList->nExpr;
50397   for(pItem=pList->a, i=0; i<n; i++, pItem++){
50398     sqlite3ExprCode(pParse, pItem->pExpr, target+i);
50399     if( doHardCopy ) sqlite3ExprHardCopy(pParse, target, n);
50400   }
50401   return n;
50402 }
50403
50404 /*
50405 ** Generate code for a boolean expression such that a jump is made
50406 ** to the label "dest" if the expression is true but execution
50407 ** continues straight thru if the expression is false.
50408 **
50409 ** If the expression evaluates to NULL (neither true nor false), then
50410 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
50411 **
50412 ** This code depends on the fact that certain token values (ex: TK_EQ)
50413 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
50414 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
50415 ** the make process cause these values to align.  Assert()s in the code
50416 ** below verify that the numbers are aligned correctly.
50417 */
50418 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
50419   Vdbe *v = pParse->pVdbe;
50420   int op = 0;
50421   int regFree1 = 0;
50422   int regFree2 = 0;
50423   int r1, r2;
50424
50425   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
50426   if( v==0 || pExpr==0 ) return;
50427   op = pExpr->op;
50428   switch( op ){
50429     case TK_AND: {
50430       int d2 = sqlite3VdbeMakeLabel(v);
50431       testcase( jumpIfNull==0 );
50432       testcase( pParse->disableColCache==0 );
50433       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
50434       pParse->disableColCache++;
50435       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
50436       assert( pParse->disableColCache>0 );
50437       pParse->disableColCache--;
50438       sqlite3VdbeResolveLabel(v, d2);
50439       break;
50440     }
50441     case TK_OR: {
50442       testcase( jumpIfNull==0 );
50443       testcase( pParse->disableColCache==0 );
50444       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
50445       pParse->disableColCache++;
50446       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
50447       assert( pParse->disableColCache>0 );
50448       pParse->disableColCache--;
50449       break;
50450     }
50451     case TK_NOT: {
50452       testcase( jumpIfNull==0 );
50453       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
50454       break;
50455     }
50456     case TK_LT:
50457     case TK_LE:
50458     case TK_GT:
50459     case TK_GE:
50460     case TK_NE:
50461     case TK_EQ: {
50462       assert( TK_LT==OP_Lt );
50463       assert( TK_LE==OP_Le );
50464       assert( TK_GT==OP_Gt );
50465       assert( TK_GE==OP_Ge );
50466       assert( TK_EQ==OP_Eq );
50467       assert( TK_NE==OP_Ne );
50468       testcase( op==TK_LT );
50469       testcase( op==TK_LE );
50470       testcase( op==TK_GT );
50471       testcase( op==TK_GE );
50472       testcase( op==TK_EQ );
50473       testcase( op==TK_NE );
50474       testcase( jumpIfNull==0 );
50475       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
50476                                   pExpr->pRight, &r2, &regFree2);
50477       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
50478                   r1, r2, dest, jumpIfNull);
50479       testcase( regFree1==0 );
50480       testcase( regFree2==0 );
50481       break;
50482     }
50483     case TK_ISNULL:
50484     case TK_NOTNULL: {
50485       assert( TK_ISNULL==OP_IsNull );
50486       assert( TK_NOTNULL==OP_NotNull );
50487       testcase( op==TK_ISNULL );
50488       testcase( op==TK_NOTNULL );
50489       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
50490       sqlite3VdbeAddOp2(v, op, r1, dest);
50491       testcase( regFree1==0 );
50492       break;
50493     }
50494     case TK_BETWEEN: {
50495       /*    x BETWEEN y AND z
50496       **
50497       ** Is equivalent to 
50498       **
50499       **    x>=y AND x<=z
50500       **
50501       ** Code it as such, taking care to do the common subexpression
50502       ** elementation of x.
50503       */
50504       Expr exprAnd;
50505       Expr compLeft;
50506       Expr compRight;
50507       Expr exprX;
50508
50509       exprX = *pExpr->pLeft;
50510       exprAnd.op = TK_AND;
50511       exprAnd.pLeft = &compLeft;
50512       exprAnd.pRight = &compRight;
50513       compLeft.op = TK_GE;
50514       compLeft.pLeft = &exprX;
50515       compLeft.pRight = pExpr->pList->a[0].pExpr;
50516       compRight.op = TK_LE;
50517       compRight.pLeft = &exprX;
50518       compRight.pRight = pExpr->pList->a[1].pExpr;
50519       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
50520       testcase( regFree1==0 );
50521       exprX.op = TK_REGISTER;
50522       testcase( jumpIfNull==0 );
50523       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
50524       break;
50525     }
50526     default: {
50527       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
50528       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
50529       testcase( regFree1==0 );
50530       testcase( jumpIfNull==0 );
50531       break;
50532     }
50533   }
50534   sqlite3ReleaseTempReg(pParse, regFree1);
50535   sqlite3ReleaseTempReg(pParse, regFree2);  
50536 }
50537
50538 /*
50539 ** Generate code for a boolean expression such that a jump is made
50540 ** to the label "dest" if the expression is false but execution
50541 ** continues straight thru if the expression is true.
50542 **
50543 ** If the expression evaluates to NULL (neither true nor false) then
50544 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
50545 ** is 0.
50546 */
50547 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
50548   Vdbe *v = pParse->pVdbe;
50549   int op = 0;
50550   int regFree1 = 0;
50551   int regFree2 = 0;
50552   int r1, r2;
50553
50554   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
50555   if( v==0 || pExpr==0 ) return;
50556
50557   /* The value of pExpr->op and op are related as follows:
50558   **
50559   **       pExpr->op            op
50560   **       ---------          ----------
50561   **       TK_ISNULL          OP_NotNull
50562   **       TK_NOTNULL         OP_IsNull
50563   **       TK_NE              OP_Eq
50564   **       TK_EQ              OP_Ne
50565   **       TK_GT              OP_Le
50566   **       TK_LE              OP_Gt
50567   **       TK_GE              OP_Lt
50568   **       TK_LT              OP_Ge
50569   **
50570   ** For other values of pExpr->op, op is undefined and unused.
50571   ** The value of TK_ and OP_ constants are arranged such that we
50572   ** can compute the mapping above using the following expression.
50573   ** Assert()s verify that the computation is correct.
50574   */
50575   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
50576
50577   /* Verify correct alignment of TK_ and OP_ constants
50578   */
50579   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
50580   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
50581   assert( pExpr->op!=TK_NE || op==OP_Eq );
50582   assert( pExpr->op!=TK_EQ || op==OP_Ne );
50583   assert( pExpr->op!=TK_LT || op==OP_Ge );
50584   assert( pExpr->op!=TK_LE || op==OP_Gt );
50585   assert( pExpr->op!=TK_GT || op==OP_Le );
50586   assert( pExpr->op!=TK_GE || op==OP_Lt );
50587
50588   switch( pExpr->op ){
50589     case TK_AND: {
50590       testcase( jumpIfNull==0 );
50591       testcase( pParse->disableColCache==0 );
50592       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
50593       pParse->disableColCache++;
50594       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
50595       assert( pParse->disableColCache>0 );
50596       pParse->disableColCache--;
50597       break;
50598     }
50599     case TK_OR: {
50600       int d2 = sqlite3VdbeMakeLabel(v);
50601       testcase( jumpIfNull==0 );
50602       testcase( pParse->disableColCache==0 );
50603       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
50604       pParse->disableColCache++;
50605       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
50606       assert( pParse->disableColCache>0 );
50607       pParse->disableColCache--;
50608       sqlite3VdbeResolveLabel(v, d2);
50609       break;
50610     }
50611     case TK_NOT: {
50612       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
50613       break;
50614     }
50615     case TK_LT:
50616     case TK_LE:
50617     case TK_GT:
50618     case TK_GE:
50619     case TK_NE:
50620     case TK_EQ: {
50621       testcase( op==TK_LT );
50622       testcase( op==TK_LE );
50623       testcase( op==TK_GT );
50624       testcase( op==TK_GE );
50625       testcase( op==TK_EQ );
50626       testcase( op==TK_NE );
50627       testcase( jumpIfNull==0 );
50628       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
50629                                   pExpr->pRight, &r2, &regFree2);
50630       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
50631                   r1, r2, dest, jumpIfNull);
50632       testcase( regFree1==0 );
50633       testcase( regFree2==0 );
50634       break;
50635     }
50636     case TK_ISNULL:
50637     case TK_NOTNULL: {
50638       testcase( op==TK_ISNULL );
50639       testcase( op==TK_NOTNULL );
50640       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
50641       sqlite3VdbeAddOp2(v, op, r1, dest);
50642       testcase( regFree1==0 );
50643       break;
50644     }
50645     case TK_BETWEEN: {
50646       /*    x BETWEEN y AND z
50647       **
50648       ** Is equivalent to 
50649       **
50650       **    x>=y AND x<=z
50651       **
50652       ** Code it as such, taking care to do the common subexpression
50653       ** elementation of x.
50654       */
50655       Expr exprAnd;
50656       Expr compLeft;
50657       Expr compRight;
50658       Expr exprX;
50659
50660       exprX = *pExpr->pLeft;
50661       exprAnd.op = TK_AND;
50662       exprAnd.pLeft = &compLeft;
50663       exprAnd.pRight = &compRight;
50664       compLeft.op = TK_GE;
50665       compLeft.pLeft = &exprX;
50666       compLeft.pRight = pExpr->pList->a[0].pExpr;
50667       compRight.op = TK_LE;
50668       compRight.pLeft = &exprX;
50669       compRight.pRight = pExpr->pList->a[1].pExpr;
50670       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
50671       testcase( regFree1==0 );
50672       exprX.op = TK_REGISTER;
50673       testcase( jumpIfNull==0 );
50674       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
50675       break;
50676     }
50677     default: {
50678       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
50679       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
50680       testcase( regFree1==0 );
50681       testcase( jumpIfNull==0 );
50682       break;
50683     }
50684   }
50685   sqlite3ReleaseTempReg(pParse, regFree1);
50686   sqlite3ReleaseTempReg(pParse, regFree2);
50687 }
50688
50689 /*
50690 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
50691 ** if they are identical and return FALSE if they differ in any way.
50692 **
50693 ** Sometimes this routine will return FALSE even if the two expressions
50694 ** really are equivalent.  If we cannot prove that the expressions are
50695 ** identical, we return FALSE just to be safe.  So if this routine
50696 ** returns false, then you do not really know for certain if the two
50697 ** expressions are the same.  But if you get a TRUE return, then you
50698 ** can be sure the expressions are the same.  In the places where
50699 ** this routine is used, it does not hurt to get an extra FALSE - that
50700 ** just might result in some slightly slower code.  But returning
50701 ** an incorrect TRUE could lead to a malfunction.
50702 */
50703 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
50704   int i;
50705   if( pA==0||pB==0 ){
50706     return pB==pA;
50707   }
50708   if( pA->op!=pB->op ) return 0;
50709   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
50710   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
50711   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
50712   if( pA->pList ){
50713     if( pB->pList==0 ) return 0;
50714     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
50715     for(i=0; i<pA->pList->nExpr; i++){
50716       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
50717         return 0;
50718       }
50719     }
50720   }else if( pB->pList ){
50721     return 0;
50722   }
50723   if( pA->pSelect || pB->pSelect ) return 0;
50724   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
50725   if( pA->op!=TK_COLUMN && pA->token.z ){
50726     if( pB->token.z==0 ) return 0;
50727     if( pB->token.n!=pA->token.n ) return 0;
50728     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
50729       return 0;
50730     }
50731   }
50732   return 1;
50733 }
50734
50735
50736 /*
50737 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
50738 ** the new element.  Return a negative number if malloc fails.
50739 */
50740 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
50741   int i;
50742   pInfo->aCol = sqlite3ArrayAllocate(
50743        db,
50744        pInfo->aCol,
50745        sizeof(pInfo->aCol[0]),
50746        3,
50747        &pInfo->nColumn,
50748        &pInfo->nColumnAlloc,
50749        &i
50750   );
50751   return i;
50752 }    
50753
50754 /*
50755 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
50756 ** the new element.  Return a negative number if malloc fails.
50757 */
50758 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
50759   int i;
50760   pInfo->aFunc = sqlite3ArrayAllocate(
50761        db, 
50762        pInfo->aFunc,
50763        sizeof(pInfo->aFunc[0]),
50764        3,
50765        &pInfo->nFunc,
50766        &pInfo->nFuncAlloc,
50767        &i
50768   );
50769   return i;
50770 }    
50771
50772 /*
50773 ** This is an xFunc for walkExprTree() used to implement 
50774 ** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
50775 ** for additional information.
50776 **
50777 ** This routine analyzes the aggregate function at pExpr.
50778 */
50779 static int analyzeAggregate(void *pArg, Expr *pExpr){
50780   int i;
50781   NameContext *pNC = (NameContext *)pArg;
50782   Parse *pParse = pNC->pParse;
50783   SrcList *pSrcList = pNC->pSrcList;
50784   AggInfo *pAggInfo = pNC->pAggInfo;
50785
50786   switch( pExpr->op ){
50787     case TK_AGG_COLUMN:
50788     case TK_COLUMN: {
50789       /* Check to see if the column is in one of the tables in the FROM
50790       ** clause of the aggregate query */
50791       if( pSrcList ){
50792         struct SrcList_item *pItem = pSrcList->a;
50793         for(i=0; i<pSrcList->nSrc; i++, pItem++){
50794           struct AggInfo_col *pCol;
50795           if( pExpr->iTable==pItem->iCursor ){
50796             /* If we reach this point, it means that pExpr refers to a table
50797             ** that is in the FROM clause of the aggregate query.  
50798             **
50799             ** Make an entry for the column in pAggInfo->aCol[] if there
50800             ** is not an entry there already.
50801             */
50802             int k;
50803             pCol = pAggInfo->aCol;
50804             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
50805               if( pCol->iTable==pExpr->iTable &&
50806                   pCol->iColumn==pExpr->iColumn ){
50807                 break;
50808               }
50809             }
50810             if( (k>=pAggInfo->nColumn)
50811              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
50812             ){
50813               pCol = &pAggInfo->aCol[k];
50814               pCol->pTab = pExpr->pTab;
50815               pCol->iTable = pExpr->iTable;
50816               pCol->iColumn = pExpr->iColumn;
50817               pCol->iMem = ++pParse->nMem;
50818               pCol->iSorterColumn = -1;
50819               pCol->pExpr = pExpr;
50820               if( pAggInfo->pGroupBy ){
50821                 int j, n;
50822                 ExprList *pGB = pAggInfo->pGroupBy;
50823                 struct ExprList_item *pTerm = pGB->a;
50824                 n = pGB->nExpr;
50825                 for(j=0; j<n; j++, pTerm++){
50826                   Expr *pE = pTerm->pExpr;
50827                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
50828                       pE->iColumn==pExpr->iColumn ){
50829                     pCol->iSorterColumn = j;
50830                     break;
50831                   }
50832                 }
50833               }
50834               if( pCol->iSorterColumn<0 ){
50835                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
50836               }
50837             }
50838             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
50839             ** because it was there before or because we just created it).
50840             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
50841             ** pAggInfo->aCol[] entry.
50842             */
50843             pExpr->pAggInfo = pAggInfo;
50844             pExpr->op = TK_AGG_COLUMN;
50845             pExpr->iAgg = k;
50846             break;
50847           } /* endif pExpr->iTable==pItem->iCursor */
50848         } /* end loop over pSrcList */
50849       }
50850       return 1;
50851     }
50852     case TK_AGG_FUNCTION: {
50853       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
50854       ** to be ignored */
50855       if( pNC->nDepth==0 ){
50856         /* Check to see if pExpr is a duplicate of another aggregate 
50857         ** function that is already in the pAggInfo structure
50858         */
50859         struct AggInfo_func *pItem = pAggInfo->aFunc;
50860         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
50861           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
50862             break;
50863           }
50864         }
50865         if( i>=pAggInfo->nFunc ){
50866           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
50867           */
50868           u8 enc = ENC(pParse->db);
50869           i = addAggInfoFunc(pParse->db, pAggInfo);
50870           if( i>=0 ){
50871             pItem = &pAggInfo->aFunc[i];
50872             pItem->pExpr = pExpr;
50873             pItem->iMem = ++pParse->nMem;
50874             pItem->pFunc = sqlite3FindFunction(pParse->db,
50875                    (char*)pExpr->token.z, pExpr->token.n,
50876                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
50877             if( pExpr->flags & EP_Distinct ){
50878               pItem->iDistinct = pParse->nTab++;
50879             }else{
50880               pItem->iDistinct = -1;
50881             }
50882           }
50883         }
50884         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
50885         */
50886         pExpr->iAgg = i;
50887         pExpr->pAggInfo = pAggInfo;
50888         return 1;
50889       }
50890     }
50891   }
50892
50893   /* Recursively walk subqueries looking for TK_COLUMN nodes that need
50894   ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
50895   ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
50896   */
50897   if( pExpr->pSelect ){
50898     pNC->nDepth++;
50899     walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
50900     pNC->nDepth--;
50901   }
50902   return 0;
50903 }
50904
50905 /*
50906 ** Analyze the given expression looking for aggregate functions and
50907 ** for variables that need to be added to the pParse->aAgg[] array.
50908 ** Make additional entries to the pParse->aAgg[] array as necessary.
50909 **
50910 ** This routine should only be called after the expression has been
50911 ** analyzed by sqlite3ExprResolveNames().
50912 */
50913 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
50914   walkExprTree(pExpr, analyzeAggregate, pNC);
50915 }
50916
50917 /*
50918 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
50919 ** expression list.  Return the number of errors.
50920 **
50921 ** If an error is found, the analysis is cut short.
50922 */
50923 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
50924   struct ExprList_item *pItem;
50925   int i;
50926   if( pList ){
50927     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
50928       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
50929     }
50930   }
50931 }
50932
50933 /*
50934 ** Allocate or deallocate temporary use registers during code generation.
50935 */
50936 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
50937   int i, r;
50938   if( pParse->nTempReg==0 ){
50939     return ++pParse->nMem;
50940   }
50941   for(i=0; i<pParse->nTempReg; i++){
50942     r = pParse->aTempReg[i];
50943     if( usedAsColumnCache(pParse, r, r) ) continue;
50944   }
50945   if( i>=pParse->nTempReg ){
50946     return ++pParse->nMem;
50947   }
50948   while( i<pParse->nTempReg-1 ){
50949     pParse->aTempReg[i] = pParse->aTempReg[i+1];
50950   }
50951   pParse->nTempReg--;
50952   return r;
50953 }
50954 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
50955   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
50956     pParse->aTempReg[pParse->nTempReg++] = iReg;
50957   }
50958 }
50959
50960 /*
50961 ** Allocate or deallocate a block of nReg consecutive registers
50962 */
50963 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
50964   int i, n;
50965   i = pParse->iRangeReg;
50966   n = pParse->nRangeReg;
50967   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
50968     pParse->iRangeReg += nReg;
50969     pParse->nRangeReg -= nReg;
50970   }else{
50971     i = pParse->nMem+1;
50972     pParse->nMem += nReg;
50973   }
50974   return i;
50975 }
50976 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
50977   if( nReg>pParse->nRangeReg ){
50978     pParse->nRangeReg = nReg;
50979     pParse->iRangeReg = iReg;
50980   }
50981 }
50982
50983 /************** End of expr.c ************************************************/
50984 /************** Begin file alter.c *******************************************/
50985 /*
50986 ** 2005 February 15
50987 **
50988 ** The author disclaims copyright to this source code.  In place of
50989 ** a legal notice, here is a blessing:
50990 **
50991 **    May you do good and not evil.
50992 **    May you find forgiveness for yourself and forgive others.
50993 **    May you share freely, never taking more than you give.
50994 **
50995 *************************************************************************
50996 ** This file contains C code routines that used to generate VDBE code
50997 ** that implements the ALTER TABLE command.
50998 **
50999 ** $Id: alter.c,v 1.44 2008/05/09 14:17:52 drh Exp $
51000 */
51001
51002 /*
51003 ** The code in this file only exists if we are not omitting the
51004 ** ALTER TABLE logic from the build.
51005 */
51006 #ifndef SQLITE_OMIT_ALTERTABLE
51007
51008
51009 /*
51010 ** This function is used by SQL generated to implement the 
51011 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
51012 ** CREATE INDEX command. The second is a table name. The table name in 
51013 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
51014 ** argument and the result returned. Examples:
51015 **
51016 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
51017 **     -> 'CREATE TABLE def(a, b, c)'
51018 **
51019 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
51020 **     -> 'CREATE INDEX i ON def(a, b, c)'
51021 */
51022 static void renameTableFunc(
51023   sqlite3_context *context,
51024   int argc,
51025   sqlite3_value **argv
51026 ){
51027   unsigned char const *zSql = sqlite3_value_text(argv[0]);
51028   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
51029
51030   int token;
51031   Token tname;
51032   unsigned char const *zCsr = zSql;
51033   int len = 0;
51034   char *zRet;
51035
51036   sqlite3 *db = sqlite3_context_db_handle(context);
51037
51038   /* The principle used to locate the table name in the CREATE TABLE 
51039   ** statement is that the table name is the first non-space token that
51040   ** is immediately followed by a left parenthesis - TK_LP - or "USING" TK_USING.
51041   */
51042   if( zSql ){
51043     do {
51044       if( !*zCsr ){
51045         /* Ran out of input before finding an opening bracket. Return NULL. */
51046         return;
51047       }
51048
51049       /* Store the token that zCsr points to in tname. */
51050       tname.z = zCsr;
51051       tname.n = len;
51052
51053       /* Advance zCsr to the next token. Store that token type in 'token',
51054       ** and its length in 'len' (to be used next iteration of this loop).
51055       */
51056       do {
51057         zCsr += len;
51058         len = sqlite3GetToken(zCsr, &token);
51059       } while( token==TK_SPACE || token==TK_COMMENT );
51060       assert( len>0 );
51061     } while( token!=TK_LP && token!=TK_USING );
51062
51063     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
51064        zTableName, tname.z+tname.n);
51065     sqlite3_result_text(context, zRet, -1, sqlite3_free);
51066   }
51067 }
51068
51069 #ifndef SQLITE_OMIT_TRIGGER
51070 /* This function is used by SQL generated to implement the
51071 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
51072 ** statement. The second is a table name. The table name in the CREATE 
51073 ** TRIGGER statement is replaced with the third argument and the result 
51074 ** returned. This is analagous to renameTableFunc() above, except for CREATE
51075 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
51076 */
51077 static void renameTriggerFunc(
51078   sqlite3_context *context,
51079   int argc,
51080   sqlite3_value **argv
51081 ){
51082   unsigned char const *zSql = sqlite3_value_text(argv[0]);
51083   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
51084
51085   int token;
51086   Token tname;
51087   int dist = 3;
51088   unsigned char const *zCsr = zSql;
51089   int len = 0;
51090   char *zRet;
51091
51092   sqlite3 *db = sqlite3_context_db_handle(context);
51093
51094   /* The principle used to locate the table name in the CREATE TRIGGER 
51095   ** statement is that the table name is the first token that is immediatedly
51096   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
51097   ** of TK_WHEN, TK_BEGIN or TK_FOR.
51098   */
51099   if( zSql ){
51100     do {
51101
51102       if( !*zCsr ){
51103         /* Ran out of input before finding the table name. Return NULL. */
51104         return;
51105       }
51106
51107       /* Store the token that zCsr points to in tname. */
51108       tname.z = zCsr;
51109       tname.n = len;
51110
51111       /* Advance zCsr to the next token. Store that token type in 'token',
51112       ** and its length in 'len' (to be used next iteration of this loop).
51113       */
51114       do {
51115         zCsr += len;
51116         len = sqlite3GetToken(zCsr, &token);
51117       }while( token==TK_SPACE );
51118       assert( len>0 );
51119
51120       /* Variable 'dist' stores the number of tokens read since the most
51121       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
51122       ** token is read and 'dist' equals 2, the condition stated above
51123       ** to be met.
51124       **
51125       ** Note that ON cannot be a database, table or column name, so
51126       ** there is no need to worry about syntax like 
51127       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
51128       */
51129       dist++;
51130       if( token==TK_DOT || token==TK_ON ){
51131         dist = 0;
51132       }
51133     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
51134
51135     /* Variable tname now contains the token that is the old table-name
51136     ** in the CREATE TRIGGER statement.
51137     */
51138     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
51139        zTableName, tname.z+tname.n);
51140     sqlite3_result_text(context, zRet, -1, sqlite3_free);
51141   }
51142 }
51143 #endif   /* !SQLITE_OMIT_TRIGGER */
51144
51145 /*
51146 ** Register built-in functions used to help implement ALTER TABLE
51147 */
51148 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
51149   static const struct {
51150      char *zName;
51151      signed char nArg;
51152      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
51153   } aFuncs[] = {
51154     { "sqlite_rename_table",    2, renameTableFunc},
51155 #ifndef SQLITE_OMIT_TRIGGER
51156     { "sqlite_rename_trigger",  2, renameTriggerFunc},
51157 #endif
51158   };
51159   int i;
51160
51161   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
51162     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
51163         SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
51164   }
51165 }
51166
51167 /*
51168 ** Generate the text of a WHERE expression which can be used to select all
51169 ** temporary triggers on table pTab from the sqlite_temp_master table. If
51170 ** table pTab has no temporary triggers, or is itself stored in the 
51171 ** temporary database, NULL is returned.
51172 */
51173 static char *whereTempTriggers(Parse *pParse, Table *pTab){
51174   Trigger *pTrig;
51175   char *zWhere = 0;
51176   char *tmp = 0;
51177   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
51178
51179   /* If the table is not located in the temp-db (in which case NULL is 
51180   ** returned, loop through the tables list of triggers. For each trigger
51181   ** that is not part of the temp-db schema, add a clause to the WHERE 
51182   ** expression being built up in zWhere.
51183   */
51184   if( pTab->pSchema!=pTempSchema ){
51185     sqlite3 *db = pParse->db;
51186     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
51187       if( pTrig->pSchema==pTempSchema ){
51188         if( !zWhere ){
51189           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
51190         }else{
51191           tmp = zWhere;
51192           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
51193           sqlite3_free(tmp);
51194         }
51195       }
51196     }
51197   }
51198   return zWhere;
51199 }
51200
51201 /*
51202 ** Generate code to drop and reload the internal representation of table
51203 ** pTab from the database, including triggers and temporary triggers.
51204 ** Argument zName is the name of the table in the database schema at
51205 ** the time the generated code is executed. This can be different from
51206 ** pTab->zName if this function is being called to code part of an 
51207 ** "ALTER TABLE RENAME TO" statement.
51208 */
51209 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
51210   Vdbe *v;
51211   char *zWhere;
51212   int iDb;                   /* Index of database containing pTab */
51213 #ifndef SQLITE_OMIT_TRIGGER
51214   Trigger *pTrig;
51215 #endif
51216
51217   v = sqlite3GetVdbe(pParse);
51218   if( !v ) return;
51219   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
51220   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
51221   assert( iDb>=0 );
51222
51223 #ifndef SQLITE_OMIT_TRIGGER
51224   /* Drop any table triggers from the internal schema. */
51225   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
51226     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
51227     assert( iTrigDb==iDb || iTrigDb==1 );
51228     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
51229   }
51230 #endif
51231
51232   /* Drop the table and index from the internal schema */
51233   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
51234
51235   /* Reload the table, index and permanent trigger schemas. */
51236   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
51237   if( !zWhere ) return;
51238   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
51239
51240 #ifndef SQLITE_OMIT_TRIGGER
51241   /* Now, if the table is not stored in the temp database, reload any temp 
51242   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
51243   */
51244   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
51245     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
51246   }
51247 #endif
51248 }
51249
51250 /*
51251 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
51252 ** command. 
51253 */
51254 SQLITE_PRIVATE void sqlite3AlterRenameTable(
51255   Parse *pParse,            /* Parser context. */
51256   SrcList *pSrc,            /* The table to rename. */
51257   Token *pName              /* The new table name. */
51258 ){
51259   int iDb;                  /* Database that contains the table */
51260   char *zDb;                /* Name of database iDb */
51261   Table *pTab;              /* Table being renamed */
51262   char *zName = 0;          /* NULL-terminated version of pName */ 
51263   sqlite3 *db = pParse->db; /* Database connection */
51264   int nTabName;             /* Number of UTF-8 characters in zTabName */
51265   const char *zTabName;     /* Original name of the table */
51266   Vdbe *v;
51267 #ifndef SQLITE_OMIT_TRIGGER
51268   char *zWhere = 0;         /* Where clause to locate temp triggers */
51269 #endif
51270   int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
51271   
51272   if( db->mallocFailed ) goto exit_rename_table;
51273   assert( pSrc->nSrc==1 );
51274   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
51275
51276   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
51277   if( !pTab ) goto exit_rename_table;
51278   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
51279   zDb = db->aDb[iDb].zName;
51280
51281   /* Get a NULL terminated version of the new table name. */
51282   zName = sqlite3NameFromToken(db, pName);
51283   if( !zName ) goto exit_rename_table;
51284
51285   /* Check that a table or index named 'zName' does not already exist
51286   ** in database iDb. If so, this is an error.
51287   */
51288   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
51289     sqlite3ErrorMsg(pParse, 
51290         "there is already another table or index with this name: %s", zName);
51291     goto exit_rename_table;
51292   }
51293
51294   /* Make sure it is not a system table being altered, or a reserved name
51295   ** that the table is being renamed to.
51296   */
51297   if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
51298     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
51299     goto exit_rename_table;
51300   }
51301   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
51302     goto exit_rename_table;
51303   }
51304
51305 #ifndef SQLITE_OMIT_VIEW
51306   if( pTab->pSelect ){
51307     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
51308     goto exit_rename_table;
51309   }
51310 #endif
51311
51312 #ifndef SQLITE_OMIT_AUTHORIZATION
51313   /* Invoke the authorization callback. */
51314   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
51315     goto exit_rename_table;
51316   }
51317 #endif
51318
51319 #ifndef SQLITE_OMIT_VIRTUALTABLE
51320   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
51321     goto exit_rename_table;
51322   }
51323   if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
51324     isVirtualRename = 1;
51325   }
51326 #endif
51327
51328   /* Begin a transaction and code the VerifyCookie for database iDb. 
51329   ** Then modify the schema cookie (since the ALTER TABLE modifies the
51330   ** schema). Open a statement transaction if the table is a virtual
51331   ** table.
51332   */
51333   v = sqlite3GetVdbe(pParse);
51334   if( v==0 ){
51335     goto exit_rename_table;
51336   }
51337   sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
51338   sqlite3ChangeCookie(pParse, iDb);
51339
51340   /* If this is a virtual table, invoke the xRename() function if
51341   ** one is defined. The xRename() callback will modify the names
51342   ** of any resources used by the v-table implementation (including other
51343   ** SQLite tables) that are identified by the name of the virtual table.
51344   */
51345 #ifndef SQLITE_OMIT_VIRTUALTABLE
51346   if( isVirtualRename ){
51347     int i = ++pParse->nMem;
51348     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
51349     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
51350   }
51351 #endif
51352
51353   /* figure out how many UTF-8 characters are in zName */
51354   zTabName = pTab->zName;
51355   nTabName = sqlite3Utf8CharLen(zTabName, -1);
51356
51357   /* Modify the sqlite_master table to use the new table name. */
51358   sqlite3NestedParse(pParse,
51359       "UPDATE %Q.%s SET "
51360 #ifdef SQLITE_OMIT_TRIGGER
51361           "sql = sqlite_rename_table(sql, %Q), "
51362 #else
51363           "sql = CASE "
51364             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
51365             "ELSE sqlite_rename_table(sql, %Q) END, "
51366 #endif
51367           "tbl_name = %Q, "
51368           "name = CASE "
51369             "WHEN type='table' THEN %Q "
51370             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
51371              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
51372             "ELSE name END "
51373       "WHERE tbl_name=%Q AND "
51374           "(type='table' OR type='index' OR type='trigger');", 
51375       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
51376 #ifndef SQLITE_OMIT_TRIGGER
51377       zName,
51378 #endif
51379       zName, nTabName, zTabName
51380   );
51381
51382 #ifndef SQLITE_OMIT_AUTOINCREMENT
51383   /* If the sqlite_sequence table exists in this database, then update 
51384   ** it with the new table name.
51385   */
51386   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
51387     sqlite3NestedParse(pParse,
51388         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
51389         zDb, zName, pTab->zName);
51390   }
51391 #endif
51392
51393 #ifndef SQLITE_OMIT_TRIGGER
51394   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
51395   ** table. Don't do this if the table being ALTERed is itself located in
51396   ** the temp database.
51397   */
51398   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
51399     sqlite3NestedParse(pParse, 
51400         "UPDATE sqlite_temp_master SET "
51401             "sql = sqlite_rename_trigger(sql, %Q), "
51402             "tbl_name = %Q "
51403             "WHERE %s;", zName, zName, zWhere);
51404     sqlite3_free(zWhere);
51405   }
51406 #endif
51407
51408   /* Drop and reload the internal table schema. */
51409   reloadTableSchema(pParse, pTab, zName);
51410
51411 exit_rename_table:
51412   sqlite3SrcListDelete(pSrc);
51413   sqlite3_free(zName);
51414 }
51415
51416
51417 /*
51418 ** This function is called after an "ALTER TABLE ... ADD" statement
51419 ** has been parsed. Argument pColDef contains the text of the new
51420 ** column definition.
51421 **
51422 ** The Table structure pParse->pNewTable was extended to include
51423 ** the new column during parsing.
51424 */
51425 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
51426   Table *pNew;              /* Copy of pParse->pNewTable */
51427   Table *pTab;              /* Table being altered */
51428   int iDb;                  /* Database number */
51429   const char *zDb;          /* Database name */
51430   const char *zTab;         /* Table name */
51431   char *zCol;               /* Null-terminated column definition */
51432   Column *pCol;             /* The new column */
51433   Expr *pDflt;              /* Default value for the new column */
51434   sqlite3 *db;              /* The database connection; */
51435
51436   if( pParse->nErr ) return;
51437   pNew = pParse->pNewTable;
51438   assert( pNew );
51439
51440   db = pParse->db;
51441   assert( sqlite3BtreeHoldsAllMutexes(db) );
51442   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
51443   zDb = db->aDb[iDb].zName;
51444   zTab = pNew->zName;
51445   pCol = &pNew->aCol[pNew->nCol-1];
51446   pDflt = pCol->pDflt;
51447   pTab = sqlite3FindTable(db, zTab, zDb);
51448   assert( pTab );
51449
51450 #ifndef SQLITE_OMIT_AUTHORIZATION
51451   /* Invoke the authorization callback. */
51452   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
51453     return;
51454   }
51455 #endif
51456
51457   /* If the default value for the new column was specified with a 
51458   ** literal NULL, then set pDflt to 0. This simplifies checking
51459   ** for an SQL NULL default below.
51460   */
51461   if( pDflt && pDflt->op==TK_NULL ){
51462     pDflt = 0;
51463   }
51464
51465   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
51466   ** If there is a NOT NULL constraint, then the default value for the
51467   ** column must not be NULL.
51468   */
51469   if( pCol->isPrimKey ){
51470     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
51471     return;
51472   }
51473   if( pNew->pIndex ){
51474     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
51475     return;
51476   }
51477   if( pCol->notNull && !pDflt ){
51478     sqlite3ErrorMsg(pParse, 
51479         "Cannot add a NOT NULL column with default value NULL");
51480     return;
51481   }
51482
51483   /* Ensure the default expression is something that sqlite3ValueFromExpr()
51484   ** can handle (i.e. not CURRENT_TIME etc.)
51485   */
51486   if( pDflt ){
51487     sqlite3_value *pVal;
51488     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
51489       db->mallocFailed = 1;
51490       return;
51491     }
51492     if( !pVal ){
51493       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
51494       return;
51495     }
51496     sqlite3ValueFree(pVal);
51497   }
51498
51499   /* Modify the CREATE TABLE statement. */
51500   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
51501   if( zCol ){
51502     char *zEnd = &zCol[pColDef->n-1];
51503     while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
51504       *zEnd-- = '\0';
51505     }
51506     sqlite3NestedParse(pParse, 
51507         "UPDATE \"%w\".%s SET "
51508           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
51509         "WHERE type = 'table' AND name = %Q", 
51510       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
51511       zTab
51512     );
51513     sqlite3_free(zCol);
51514   }
51515
51516   /* If the default value of the new column is NULL, then set the file
51517   ** format to 2. If the default value of the new column is not NULL,
51518   ** the file format becomes 3.
51519   */
51520   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
51521
51522   /* Reload the schema of the modified table. */
51523   reloadTableSchema(pParse, pTab, pTab->zName);
51524 }
51525
51526 /*
51527 ** This function is called by the parser after the table-name in
51528 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
51529 ** pSrc is the full-name of the table being altered.
51530 **
51531 ** This routine makes a (partial) copy of the Table structure
51532 ** for the table being altered and sets Parse.pNewTable to point
51533 ** to it. Routines called by the parser as the column definition
51534 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
51535 ** the copy. The copy of the Table structure is deleted by tokenize.c 
51536 ** after parsing is finished.
51537 **
51538 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
51539 ** coding the "ALTER TABLE ... ADD" statement.
51540 */
51541 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
51542   Table *pNew;
51543   Table *pTab;
51544   Vdbe *v;
51545   int iDb;
51546   int i;
51547   int nAlloc;
51548   sqlite3 *db = pParse->db;
51549
51550   /* Look up the table being altered. */
51551   assert( pParse->pNewTable==0 );
51552   assert( sqlite3BtreeHoldsAllMutexes(db) );
51553   if( db->mallocFailed ) goto exit_begin_add_column;
51554   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
51555   if( !pTab ) goto exit_begin_add_column;
51556
51557 #ifndef SQLITE_OMIT_VIRTUALTABLE
51558   if( IsVirtual(pTab) ){
51559     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
51560     goto exit_begin_add_column;
51561   }
51562 #endif
51563
51564   /* Make sure this is not an attempt to ALTER a view. */
51565   if( pTab->pSelect ){
51566     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
51567     goto exit_begin_add_column;
51568   }
51569
51570   assert( pTab->addColOffset>0 );
51571   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
51572
51573   /* Put a copy of the Table struct in Parse.pNewTable for the
51574   ** sqlite3AddColumn() function and friends to modify.
51575   */
51576   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
51577   if( !pNew ) goto exit_begin_add_column;
51578   pParse->pNewTable = pNew;
51579   pNew->nRef = 1;
51580   pNew->nCol = pTab->nCol;
51581   assert( pNew->nCol>0 );
51582   nAlloc = (((pNew->nCol-1)/8)*8)+8;
51583   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
51584   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
51585   pNew->zName = sqlite3DbStrDup(db, pTab->zName);
51586   if( !pNew->aCol || !pNew->zName ){
51587     db->mallocFailed = 1;
51588     goto exit_begin_add_column;
51589   }
51590   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
51591   for(i=0; i<pNew->nCol; i++){
51592     Column *pCol = &pNew->aCol[i];
51593     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
51594     pCol->zColl = 0;
51595     pCol->zType = 0;
51596     pCol->pDflt = 0;
51597   }
51598   pNew->pSchema = db->aDb[iDb].pSchema;
51599   pNew->addColOffset = pTab->addColOffset;
51600   pNew->nRef = 1;
51601
51602   /* Begin a transaction and increment the schema cookie.  */
51603   sqlite3BeginWriteOperation(pParse, 0, iDb);
51604   v = sqlite3GetVdbe(pParse);
51605   if( !v ) goto exit_begin_add_column;
51606   sqlite3ChangeCookie(pParse, iDb);
51607
51608 exit_begin_add_column:
51609   sqlite3SrcListDelete(pSrc);
51610   return;
51611 }
51612 #endif  /* SQLITE_ALTER_TABLE */
51613
51614 /************** End of alter.c ***********************************************/
51615 /************** Begin file analyze.c *****************************************/
51616 /*
51617 ** 2005 July 8
51618 **
51619 ** The author disclaims copyright to this source code.  In place of
51620 ** a legal notice, here is a blessing:
51621 **
51622 **    May you do good and not evil.
51623 **    May you find forgiveness for yourself and forgive others.
51624 **    May you share freely, never taking more than you give.
51625 **
51626 *************************************************************************
51627 ** This file contains code associated with the ANALYZE command.
51628 **
51629 ** @(#) $Id: analyze.c,v 1.42 2008/03/25 09:47:35 danielk1977 Exp $
51630 */
51631 #ifndef SQLITE_OMIT_ANALYZE
51632
51633 /*
51634 ** This routine generates code that opens the sqlite_stat1 table on cursor
51635 ** iStatCur.
51636 **
51637 ** If the sqlite_stat1 tables does not previously exist, it is created.
51638 ** If it does previously exist, all entires associated with table zWhere
51639 ** are removed.  If zWhere==0 then all entries are removed.
51640 */
51641 static void openStatTable(
51642   Parse *pParse,          /* Parsing context */
51643   int iDb,                /* The database we are looking in */
51644   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
51645   const char *zWhere      /* Delete entries associated with this table */
51646 ){
51647   sqlite3 *db = pParse->db;
51648   Db *pDb;
51649   int iRootPage;
51650   int createStat1 = 0;
51651   Table *pStat;
51652   Vdbe *v = sqlite3GetVdbe(pParse);
51653
51654   if( v==0 ) return;
51655   assert( sqlite3BtreeHoldsAllMutexes(db) );
51656   assert( sqlite3VdbeDb(v)==db );
51657   pDb = &db->aDb[iDb];
51658   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
51659     /* The sqlite_stat1 tables does not exist.  Create it.  
51660     ** Note that a side-effect of the CREATE TABLE statement is to leave
51661     ** the rootpage of the new table in register pParse->regRoot.  This is
51662     ** important because the OpenWrite opcode below will be needing it. */
51663     sqlite3NestedParse(pParse,
51664       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
51665       pDb->zName
51666     );
51667     iRootPage = pParse->regRoot;
51668     createStat1 = 1;  /* Cause rootpage to be taken from top of stack */
51669   }else if( zWhere ){
51670     /* The sqlite_stat1 table exists.  Delete all entries associated with
51671     ** the table zWhere. */
51672     sqlite3NestedParse(pParse,
51673        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
51674        pDb->zName, zWhere
51675     );
51676     iRootPage = pStat->tnum;
51677   }else{
51678     /* The sqlite_stat1 table already exists.  Delete all rows. */
51679     iRootPage = pStat->tnum;
51680     sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
51681   }
51682
51683   /* Open the sqlite_stat1 table for writing. Unless it was created
51684   ** by this vdbe program, lock it for writing at the shared-cache level. 
51685   ** If this vdbe did create the sqlite_stat1 table, then it must have 
51686   ** already obtained a schema-lock, making the write-lock redundant.
51687   */
51688   if( !createStat1 ){
51689     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
51690   }
51691   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3);
51692   sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
51693   sqlite3VdbeChangeP5(v, createStat1);
51694 }
51695
51696 /*
51697 ** Generate code to do an analysis of all indices associated with
51698 ** a single table.
51699 */
51700 static void analyzeOneTable(
51701   Parse *pParse,   /* Parser context */
51702   Table *pTab,     /* Table whose indices are to be analyzed */
51703   int iStatCur,    /* Cursor that writes to the sqlite_stat1 table */
51704   int iMem         /* Available memory locations begin here */
51705 ){
51706   Index *pIdx;     /* An index to being analyzed */
51707   int iIdxCur;     /* Cursor number for index being analyzed */
51708   int nCol;        /* Number of columns in the index */
51709   Vdbe *v;         /* The virtual machine being built up */
51710   int i;           /* Loop counter */
51711   int topOfLoop;   /* The top of the loop */
51712   int endOfLoop;   /* The end of the loop */
51713   int addr;        /* The address of an instruction */
51714   int iDb;         /* Index of database containing pTab */
51715
51716   v = sqlite3GetVdbe(pParse);
51717   if( v==0 || pTab==0 || pTab->pIndex==0 ){
51718     /* Do no analysis for tables that have no indices */
51719     return;
51720   }
51721   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
51722   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
51723   assert( iDb>=0 );
51724 #ifndef SQLITE_OMIT_AUTHORIZATION
51725   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
51726       pParse->db->aDb[iDb].zName ) ){
51727     return;
51728   }
51729 #endif
51730
51731   /* Establish a read-lock on the table at the shared-cache level. */
51732   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
51733
51734   iIdxCur = pParse->nTab;
51735   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
51736     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
51737     int regFields;    /* Register block for building records */
51738     int regRec;       /* Register holding completed record */
51739     int regTemp;      /* Temporary use register */
51740     int regCol;       /* Content of a column from the table being analyzed */
51741     int regRowid;     /* Rowid for the inserted record */
51742     int regF2;
51743
51744     /* Open a cursor to the index to be analyzed
51745     */
51746     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
51747     nCol = pIdx->nColumn;
51748     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1);
51749     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
51750         (char *)pKey, P4_KEYINFO_HANDOFF);
51751     VdbeComment((v, "%s", pIdx->zName));
51752     regFields = iMem+nCol*2;
51753     regTemp = regRowid = regCol = regFields+3;
51754     regRec = regCol+1;
51755     if( regRec>pParse->nMem ){
51756       pParse->nMem = regRec;
51757     }
51758
51759     /* Memory cells are used as follows:
51760     **
51761     **    mem[iMem]:             The total number of rows in the table.
51762     **    mem[iMem+1]:           Number of distinct values in column 1
51763     **    ...
51764     **    mem[iMem+nCol]:        Number of distinct values in column N
51765     **    mem[iMem+nCol+1]       Last observed value of column 1
51766     **    ...
51767     **    mem[iMem+nCol+nCol]:   Last observed value of column N
51768     **
51769     ** Cells iMem through iMem+nCol are initialized to 0.  The others
51770     ** are initialized to NULL.
51771     */
51772     for(i=0; i<=nCol; i++){
51773       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
51774     }
51775     for(i=0; i<nCol; i++){
51776       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
51777     }
51778
51779     /* Do the analysis.
51780     */
51781     endOfLoop = sqlite3VdbeMakeLabel(v);
51782     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
51783     topOfLoop = sqlite3VdbeCurrentAddr(v);
51784     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
51785     for(i=0; i<nCol; i++){
51786       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
51787       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
51788       /**** TODO:  add collating sequence *****/
51789       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
51790     }
51791     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
51792     for(i=0; i<nCol; i++){
51793       sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
51794       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
51795       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
51796     }
51797     sqlite3VdbeResolveLabel(v, endOfLoop);
51798     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
51799     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
51800
51801     /* Store the results.  
51802     **
51803     ** The result is a single row of the sqlite_stat1 table.  The first
51804     ** two columns are the names of the table and index.  The third column
51805     ** is a string composed of a list of integer statistics about the
51806     ** index.  The first integer in the list is the total number of entires
51807     ** in the index.  There is one additional integer in the list for each
51808     ** column of the table.  This additional integer is a guess of how many
51809     ** rows of the table the index will select.  If D is the count of distinct
51810     ** values and K is the total number of rows, then the integer is computed
51811     ** as:
51812     **
51813     **        I = (K+D-1)/D
51814     **
51815     ** If K==0 then no entry is made into the sqlite_stat1 table.  
51816     ** If K>0 then it is always the case the D>0 so division by zero
51817     ** is never possible.
51818     */
51819     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
51820     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
51821     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
51822     regF2 = regFields+2;
51823     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
51824     for(i=0; i<nCol; i++){
51825       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
51826       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
51827       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
51828       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
51829       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
51830       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
51831       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
51832     }
51833     sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
51834     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
51835     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
51836     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
51837     sqlite3VdbeJumpHere(v, addr);
51838   }
51839 }
51840
51841 /*
51842 ** Generate code that will cause the most recent index analysis to
51843 ** be laoded into internal hash tables where is can be used.
51844 */
51845 static void loadAnalysis(Parse *pParse, int iDb){
51846   Vdbe *v = sqlite3GetVdbe(pParse);
51847   if( v ){
51848     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
51849   }
51850 }
51851
51852 /*
51853 ** Generate code that will do an analysis of an entire database
51854 */
51855 static void analyzeDatabase(Parse *pParse, int iDb){
51856   sqlite3 *db = pParse->db;
51857   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
51858   HashElem *k;
51859   int iStatCur;
51860   int iMem;
51861
51862   sqlite3BeginWriteOperation(pParse, 0, iDb);
51863   iStatCur = pParse->nTab++;
51864   openStatTable(pParse, iDb, iStatCur, 0);
51865   iMem = pParse->nMem+1;
51866   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
51867     Table *pTab = (Table*)sqliteHashData(k);
51868     analyzeOneTable(pParse, pTab, iStatCur, iMem);
51869   }
51870   loadAnalysis(pParse, iDb);
51871 }
51872
51873 /*
51874 ** Generate code that will do an analysis of a single table in
51875 ** a database.
51876 */
51877 static void analyzeTable(Parse *pParse, Table *pTab){
51878   int iDb;
51879   int iStatCur;
51880
51881   assert( pTab!=0 );
51882   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
51883   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
51884   sqlite3BeginWriteOperation(pParse, 0, iDb);
51885   iStatCur = pParse->nTab++;
51886   openStatTable(pParse, iDb, iStatCur, pTab->zName);
51887   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
51888   loadAnalysis(pParse, iDb);
51889 }
51890
51891 /*
51892 ** Generate code for the ANALYZE command.  The parser calls this routine
51893 ** when it recognizes an ANALYZE command.
51894 **
51895 **        ANALYZE                            -- 1
51896 **        ANALYZE  <database>                -- 2
51897 **        ANALYZE  ?<database>.?<tablename>  -- 3
51898 **
51899 ** Form 1 causes all indices in all attached databases to be analyzed.
51900 ** Form 2 analyzes all indices the single database named.
51901 ** Form 3 analyzes all indices associated with the named table.
51902 */
51903 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
51904   sqlite3 *db = pParse->db;
51905   int iDb;
51906   int i;
51907   char *z, *zDb;
51908   Table *pTab;
51909   Token *pTableName;
51910
51911   /* Read the database schema. If an error occurs, leave an error message
51912   ** and code in pParse and return NULL. */
51913   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
51914   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
51915     return;
51916   }
51917
51918   if( pName1==0 ){
51919     /* Form 1:  Analyze everything */
51920     for(i=0; i<db->nDb; i++){
51921       if( i==1 ) continue;  /* Do not analyze the TEMP database */
51922       analyzeDatabase(pParse, i);
51923     }
51924   }else if( pName2==0 || pName2->n==0 ){
51925     /* Form 2:  Analyze the database or table named */
51926     iDb = sqlite3FindDb(db, pName1);
51927     if( iDb>=0 ){
51928       analyzeDatabase(pParse, iDb);
51929     }else{
51930       z = sqlite3NameFromToken(db, pName1);
51931       if( z ){
51932         pTab = sqlite3LocateTable(pParse, 0, z, 0);
51933         sqlite3_free(z);
51934         if( pTab ){
51935           analyzeTable(pParse, pTab);
51936         }
51937       }
51938     }
51939   }else{
51940     /* Form 3: Analyze the fully qualified table name */
51941     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
51942     if( iDb>=0 ){
51943       zDb = db->aDb[iDb].zName;
51944       z = sqlite3NameFromToken(db, pTableName);
51945       if( z ){
51946         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
51947         sqlite3_free(z);
51948         if( pTab ){
51949           analyzeTable(pParse, pTab);
51950         }
51951       }
51952     }   
51953   }
51954 }
51955
51956 /*
51957 ** Used to pass information from the analyzer reader through to the
51958 ** callback routine.
51959 */
51960 typedef struct analysisInfo analysisInfo;
51961 struct analysisInfo {
51962   sqlite3 *db;
51963   const char *zDatabase;
51964 };
51965
51966 /*
51967 ** This callback is invoked once for each index when reading the
51968 ** sqlite_stat1 table.  
51969 **
51970 **     argv[0] = name of the index
51971 **     argv[1] = results of analysis - on integer for each column
51972 */
51973 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
51974   analysisInfo *pInfo = (analysisInfo*)pData;
51975   Index *pIndex;
51976   int i, c;
51977   unsigned int v;
51978   const char *z;
51979
51980   assert( argc==2 );
51981   if( argv==0 || argv[0]==0 || argv[1]==0 ){
51982     return 0;
51983   }
51984   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
51985   if( pIndex==0 ){
51986     return 0;
51987   }
51988   z = argv[1];
51989   for(i=0; *z && i<=pIndex->nColumn; i++){
51990     v = 0;
51991     while( (c=z[0])>='0' && c<='9' ){
51992       v = v*10 + c - '0';
51993       z++;
51994     }
51995     pIndex->aiRowEst[i] = v;
51996     if( *z==' ' ) z++;
51997   }
51998   return 0;
51999 }
52000
52001 /*
52002 ** Load the content of the sqlite_stat1 table into the index hash tables.
52003 */
52004 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
52005   analysisInfo sInfo;
52006   HashElem *i;
52007   char *zSql;
52008   int rc;
52009
52010   assert( iDb>=0 && iDb<db->nDb );
52011   assert( db->aDb[iDb].pBt!=0 );
52012   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
52013
52014   /* Clear any prior statistics */
52015   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
52016     Index *pIdx = sqliteHashData(i);
52017     sqlite3DefaultRowEst(pIdx);
52018   }
52019
52020   /* Check to make sure the sqlite_stat1 table existss */
52021   sInfo.db = db;
52022   sInfo.zDatabase = db->aDb[iDb].zName;
52023   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
52024      return SQLITE_ERROR;
52025   }
52026
52027
52028   /* Load new statistics out of the sqlite_stat1 table */
52029   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
52030                         sInfo.zDatabase);
52031   (void)sqlite3SafetyOff(db);
52032   rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
52033   (void)sqlite3SafetyOn(db);
52034   sqlite3_free(zSql);
52035   return rc;
52036 }
52037
52038
52039 #endif /* SQLITE_OMIT_ANALYZE */
52040
52041 /************** End of analyze.c *********************************************/
52042 /************** Begin file attach.c ******************************************/
52043 /*
52044 ** 2003 April 6
52045 **
52046 ** The author disclaims copyright to this source code.  In place of
52047 ** a legal notice, here is a blessing:
52048 **
52049 **    May you do good and not evil.
52050 **    May you find forgiveness for yourself and forgive others.
52051 **    May you share freely, never taking more than you give.
52052 **
52053 *************************************************************************
52054 ** This file contains code used to implement the ATTACH and DETACH commands.
52055 **
52056 ** $Id: attach.c,v 1.75 2008/04/17 17:02:01 drh Exp $
52057 */
52058
52059 #ifndef SQLITE_OMIT_ATTACH
52060 /*
52061 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
52062 ** is slightly different from resolving a normal SQL expression, because simple
52063 ** identifiers are treated as strings, not possible column names or aliases.
52064 **
52065 ** i.e. if the parser sees:
52066 **
52067 **     ATTACH DATABASE abc AS def
52068 **
52069 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
52070 ** looking for columns of the same name.
52071 **
52072 ** This only applies to the root node of pExpr, so the statement:
52073 **
52074 **     ATTACH DATABASE abc||def AS 'db2'
52075 **
52076 ** will fail because neither abc or def can be resolved.
52077 */
52078 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
52079 {
52080   int rc = SQLITE_OK;
52081   if( pExpr ){
52082     if( pExpr->op!=TK_ID ){
52083       rc = sqlite3ExprResolveNames(pName, pExpr);
52084       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
52085         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
52086         return SQLITE_ERROR;
52087       }
52088     }else{
52089       pExpr->op = TK_STRING;
52090     }
52091   }
52092   return rc;
52093 }
52094
52095 /*
52096 ** An SQL user-function registered to do the work of an ATTACH statement. The
52097 ** three arguments to the function come directly from an attach statement:
52098 **
52099 **     ATTACH DATABASE x AS y KEY z
52100 **
52101 **     SELECT sqlite_attach(x, y, z)
52102 **
52103 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
52104 ** third argument.
52105 */
52106 static void attachFunc(
52107   sqlite3_context *context,
52108   int argc,
52109   sqlite3_value **argv
52110 ){
52111   int i;
52112   int rc = 0;
52113   sqlite3 *db = sqlite3_context_db_handle(context);
52114   const char *zName;
52115   const char *zFile;
52116   Db *aNew;
52117   char *zErrDyn = 0;
52118   char zErr[128];
52119
52120   zFile = (const char *)sqlite3_value_text(argv[0]);
52121   zName = (const char *)sqlite3_value_text(argv[1]);
52122   if( zFile==0 ) zFile = "";
52123   if( zName==0 ) zName = "";
52124
52125   /* Check for the following errors:
52126   **
52127   **     * Too many attached databases,
52128   **     * Transaction currently open
52129   **     * Specified database name already being used.
52130   */
52131   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
52132     sqlite3_snprintf(
52133       sizeof(zErr), zErr, "too many attached databases - max %d", 
52134       db->aLimit[SQLITE_LIMIT_ATTACHED]
52135     );
52136     goto attach_error;
52137   }
52138   if( !db->autoCommit ){
52139     sqlite3_snprintf(sizeof(zErr), zErr,
52140                      "cannot ATTACH database within transaction");
52141     goto attach_error;
52142   }
52143   for(i=0; i<db->nDb; i++){
52144     char *z = db->aDb[i].zName;
52145     if( z && zName && sqlite3StrICmp(z, zName)==0 ){
52146       sqlite3_snprintf(sizeof(zErr), zErr, 
52147                        "database %s is already in use", zName);
52148       goto attach_error;
52149     }
52150   }
52151
52152   /* Allocate the new entry in the db->aDb[] array and initialise the schema
52153   ** hash tables.
52154   */
52155   if( db->aDb==db->aDbStatic ){
52156     aNew = sqlite3_malloc( sizeof(db->aDb[0])*3 );
52157     if( aNew==0 ){
52158       db->mallocFailed = 1;
52159       return;
52160     }
52161     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
52162   }else{
52163     aNew = sqlite3_realloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
52164     if( aNew==0 ){
52165       db->mallocFailed = 1;
52166       return;
52167     } 
52168   }
52169   db->aDb = aNew;
52170   aNew = &db->aDb[db->nDb++];
52171   memset(aNew, 0, sizeof(*aNew));
52172
52173   /* Open the database file. If the btree is successfully opened, use
52174   ** it to obtain the database schema. At this point the schema may
52175   ** or may not be initialised.
52176   */
52177   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
52178                            db->openFlags | SQLITE_OPEN_MAIN_DB,
52179                            &aNew->pBt);
52180   if( rc==SQLITE_OK ){
52181     Pager *pPager;
52182     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
52183     if( !aNew->pSchema ){
52184       rc = SQLITE_NOMEM;
52185     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
52186       sqlite3_snprintf(sizeof(zErr), zErr, 
52187         "attached databases must use the same text encoding as main database");
52188       goto attach_error;
52189     }
52190     pPager = sqlite3BtreePager(aNew->pBt);
52191     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
52192     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
52193   }
52194   aNew->zName = sqlite3DbStrDup(db, zName);
52195   aNew->safety_level = 3;
52196
52197 #if SQLITE_HAS_CODEC
52198   {
52199     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
52200     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
52201     int nKey;
52202     char *zKey;
52203     int t = sqlite3_value_type(argv[2]);
52204     switch( t ){
52205       case SQLITE_INTEGER:
52206       case SQLITE_FLOAT:
52207         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
52208         rc = SQLITE_ERROR;
52209         break;
52210         
52211       case SQLITE_TEXT:
52212       case SQLITE_BLOB:
52213         nKey = sqlite3_value_bytes(argv[2]);
52214         zKey = (char *)sqlite3_value_blob(argv[2]);
52215         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
52216         break;
52217
52218       case SQLITE_NULL:
52219         /* No key specified.  Use the key from the main database */
52220         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
52221         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
52222         break;
52223     }
52224   }
52225 #endif
52226
52227   /* If the file was opened successfully, read the schema for the new database.
52228   ** If this fails, or if opening the file failed, then close the file and 
52229   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
52230   ** we found it.
52231   */
52232   if( rc==SQLITE_OK ){
52233     (void)sqlite3SafetyOn(db);
52234     sqlite3BtreeEnterAll(db);
52235     rc = sqlite3Init(db, &zErrDyn);
52236     sqlite3BtreeLeaveAll(db);
52237     (void)sqlite3SafetyOff(db);
52238   }
52239   if( rc ){
52240     int iDb = db->nDb - 1;
52241     assert( iDb>=2 );
52242     if( db->aDb[iDb].pBt ){
52243       sqlite3BtreeClose(db->aDb[iDb].pBt);
52244       db->aDb[iDb].pBt = 0;
52245       db->aDb[iDb].pSchema = 0;
52246     }
52247     sqlite3ResetInternalSchema(db, 0);
52248     db->nDb = iDb;
52249     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
52250       db->mallocFailed = 1;
52251       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
52252     }else{
52253       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
52254     }
52255     goto attach_error;
52256   }
52257   
52258   return;
52259
52260 attach_error:
52261   /* Return an error if we get here */
52262   if( zErrDyn ){
52263     sqlite3_result_error(context, zErrDyn, -1);
52264     sqlite3_free(zErrDyn);
52265   }else{
52266     zErr[sizeof(zErr)-1] = 0;
52267     sqlite3_result_error(context, zErr, -1);
52268   }
52269   if( rc ) sqlite3_result_error_code(context, rc);
52270 }
52271
52272 /*
52273 ** An SQL user-function registered to do the work of an DETACH statement. The
52274 ** three arguments to the function come directly from a detach statement:
52275 **
52276 **     DETACH DATABASE x
52277 **
52278 **     SELECT sqlite_detach(x)
52279 */
52280 static void detachFunc(
52281   sqlite3_context *context,
52282   int argc,
52283   sqlite3_value **argv
52284 ){
52285   const char *zName = (const char *)sqlite3_value_text(argv[0]);
52286   sqlite3 *db = sqlite3_context_db_handle(context);
52287   int i;
52288   Db *pDb = 0;
52289   char zErr[128];
52290
52291   if( zName==0 ) zName = "";
52292   for(i=0; i<db->nDb; i++){
52293     pDb = &db->aDb[i];
52294     if( pDb->pBt==0 ) continue;
52295     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
52296   }
52297
52298   if( i>=db->nDb ){
52299     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
52300     goto detach_error;
52301   }
52302   if( i<2 ){
52303     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
52304     goto detach_error;
52305   }
52306   if( !db->autoCommit ){
52307     sqlite3_snprintf(sizeof(zErr), zErr,
52308                      "cannot DETACH database within transaction");
52309     goto detach_error;
52310   }
52311   if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
52312     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
52313     goto detach_error;
52314   }
52315
52316   sqlite3BtreeClose(pDb->pBt);
52317   pDb->pBt = 0;
52318   pDb->pSchema = 0;
52319   sqlite3ResetInternalSchema(db, 0);
52320   return;
52321
52322 detach_error:
52323   sqlite3_result_error(context, zErr, -1);
52324 }
52325
52326 /*
52327 ** This procedure generates VDBE code for a single invocation of either the
52328 ** sqlite_detach() or sqlite_attach() SQL user functions.
52329 */
52330 static void codeAttach(
52331   Parse *pParse,       /* The parser context */
52332   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
52333   const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
52334   int nFunc,           /* Number of args to pass to zFunc */
52335   Expr *pAuthArg,      /* Expression to pass to authorization callback */
52336   Expr *pFilename,     /* Name of database file */
52337   Expr *pDbname,       /* Name of the database to use internally */
52338   Expr *pKey           /* Database key for encryption extension */
52339 ){
52340   int rc;
52341   NameContext sName;
52342   Vdbe *v;
52343   FuncDef *pFunc;
52344   sqlite3* db = pParse->db;
52345   int regArgs;
52346
52347 #ifndef SQLITE_OMIT_AUTHORIZATION
52348   assert( db->mallocFailed || pAuthArg );
52349   if( pAuthArg ){
52350     char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
52351     if( !zAuthArg ){
52352       goto attach_end;
52353     }
52354     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
52355     sqlite3_free(zAuthArg);
52356     if(rc!=SQLITE_OK ){
52357       goto attach_end;
52358     }
52359   }
52360 #endif /* SQLITE_OMIT_AUTHORIZATION */
52361
52362   memset(&sName, 0, sizeof(NameContext));
52363   sName.pParse = pParse;
52364
52365   if( 
52366       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
52367       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
52368       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
52369   ){
52370     pParse->nErr++;
52371     goto attach_end;
52372   }
52373
52374   v = sqlite3GetVdbe(pParse);
52375   regArgs = sqlite3GetTempRange(pParse, 4);
52376   sqlite3ExprCode(pParse, pFilename, regArgs);
52377   sqlite3ExprCode(pParse, pDbname, regArgs+1);
52378   sqlite3ExprCode(pParse, pKey, regArgs+2);
52379
52380   assert( v || db->mallocFailed );
52381   if( v ){
52382     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-nFunc, regArgs+3);
52383     sqlite3VdbeChangeP5(v, nFunc);
52384     pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
52385     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
52386
52387     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
52388     ** statement only). For DETACH, set it to false (expire all existing
52389     ** statements).
52390     */
52391     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
52392   }
52393   
52394 attach_end:
52395   sqlite3ExprDelete(pFilename);
52396   sqlite3ExprDelete(pDbname);
52397   sqlite3ExprDelete(pKey);
52398 }
52399
52400 /*
52401 ** Called by the parser to compile a DETACH statement.
52402 **
52403 **     DETACH pDbname
52404 */
52405 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
52406   codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
52407 }
52408
52409 /*
52410 ** Called by the parser to compile an ATTACH statement.
52411 **
52412 **     ATTACH p AS pDbname KEY pKey
52413 */
52414 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
52415   codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
52416 }
52417 #endif /* SQLITE_OMIT_ATTACH */
52418
52419 /*
52420 ** Register the functions sqlite_attach and sqlite_detach.
52421 */
52422 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *db){
52423 #ifndef SQLITE_OMIT_ATTACH
52424   static const int enc = SQLITE_UTF8;
52425   sqlite3CreateFunc(db, "sqlite_attach", 3, enc, 0, attachFunc, 0, 0);
52426   sqlite3CreateFunc(db, "sqlite_detach", 1, enc, 0, detachFunc, 0, 0);
52427 #endif
52428 }
52429
52430 /*
52431 ** Initialize a DbFixer structure.  This routine must be called prior
52432 ** to passing the structure to one of the sqliteFixAAAA() routines below.
52433 **
52434 ** The return value indicates whether or not fixation is required.  TRUE
52435 ** means we do need to fix the database references, FALSE means we do not.
52436 */
52437 SQLITE_PRIVATE int sqlite3FixInit(
52438   DbFixer *pFix,      /* The fixer to be initialized */
52439   Parse *pParse,      /* Error messages will be written here */
52440   int iDb,            /* This is the database that must be used */
52441   const char *zType,  /* "view", "trigger", or "index" */
52442   const Token *pName  /* Name of the view, trigger, or index */
52443 ){
52444   sqlite3 *db;
52445
52446   if( iDb<0 || iDb==1 ) return 0;
52447   db = pParse->db;
52448   assert( db->nDb>iDb );
52449   pFix->pParse = pParse;
52450   pFix->zDb = db->aDb[iDb].zName;
52451   pFix->zType = zType;
52452   pFix->pName = pName;
52453   return 1;
52454 }
52455
52456 /*
52457 ** The following set of routines walk through the parse tree and assign
52458 ** a specific database to all table references where the database name
52459 ** was left unspecified in the original SQL statement.  The pFix structure
52460 ** must have been initialized by a prior call to sqlite3FixInit().
52461 **
52462 ** These routines are used to make sure that an index, trigger, or
52463 ** view in one database does not refer to objects in a different database.
52464 ** (Exception: indices, triggers, and views in the TEMP database are
52465 ** allowed to refer to anything.)  If a reference is explicitly made
52466 ** to an object in a different database, an error message is added to
52467 ** pParse->zErrMsg and these routines return non-zero.  If everything
52468 ** checks out, these routines return 0.
52469 */
52470 SQLITE_PRIVATE int sqlite3FixSrcList(
52471   DbFixer *pFix,       /* Context of the fixation */
52472   SrcList *pList       /* The Source list to check and modify */
52473 ){
52474   int i;
52475   const char *zDb;
52476   struct SrcList_item *pItem;
52477
52478   if( pList==0 ) return 0;
52479   zDb = pFix->zDb;
52480   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
52481     if( pItem->zDatabase==0 ){
52482       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
52483     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
52484       sqlite3ErrorMsg(pFix->pParse,
52485          "%s %T cannot reference objects in database %s",
52486          pFix->zType, pFix->pName, pItem->zDatabase);
52487       return 1;
52488     }
52489 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
52490     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
52491     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
52492 #endif
52493   }
52494   return 0;
52495 }
52496 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
52497 SQLITE_PRIVATE int sqlite3FixSelect(
52498   DbFixer *pFix,       /* Context of the fixation */
52499   Select *pSelect      /* The SELECT statement to be fixed to one database */
52500 ){
52501   while( pSelect ){
52502     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
52503       return 1;
52504     }
52505     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
52506       return 1;
52507     }
52508     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
52509       return 1;
52510     }
52511     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
52512       return 1;
52513     }
52514     pSelect = pSelect->pPrior;
52515   }
52516   return 0;
52517 }
52518 SQLITE_PRIVATE int sqlite3FixExpr(
52519   DbFixer *pFix,     /* Context of the fixation */
52520   Expr *pExpr        /* The expression to be fixed to one database */
52521 ){
52522   while( pExpr ){
52523     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
52524       return 1;
52525     }
52526     if( sqlite3FixExprList(pFix, pExpr->pList) ){
52527       return 1;
52528     }
52529     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
52530       return 1;
52531     }
52532     pExpr = pExpr->pLeft;
52533   }
52534   return 0;
52535 }
52536 SQLITE_PRIVATE int sqlite3FixExprList(
52537   DbFixer *pFix,     /* Context of the fixation */
52538   ExprList *pList    /* The expression to be fixed to one database */
52539 ){
52540   int i;
52541   struct ExprList_item *pItem;
52542   if( pList==0 ) return 0;
52543   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
52544     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
52545       return 1;
52546     }
52547   }
52548   return 0;
52549 }
52550 #endif
52551
52552 #ifndef SQLITE_OMIT_TRIGGER
52553 SQLITE_PRIVATE int sqlite3FixTriggerStep(
52554   DbFixer *pFix,     /* Context of the fixation */
52555   TriggerStep *pStep /* The trigger step be fixed to one database */
52556 ){
52557   while( pStep ){
52558     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
52559       return 1;
52560     }
52561     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
52562       return 1;
52563     }
52564     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
52565       return 1;
52566     }
52567     pStep = pStep->pNext;
52568   }
52569   return 0;
52570 }
52571 #endif
52572
52573 /************** End of attach.c **********************************************/
52574 /************** Begin file auth.c ********************************************/
52575 /*
52576 ** 2003 January 11
52577 **
52578 ** The author disclaims copyright to this source code.  In place of
52579 ** a legal notice, here is a blessing:
52580 **
52581 **    May you do good and not evil.
52582 **    May you find forgiveness for yourself and forgive others.
52583 **    May you share freely, never taking more than you give.
52584 **
52585 *************************************************************************
52586 ** This file contains code used to implement the sqlite3_set_authorizer()
52587 ** API.  This facility is an optional feature of the library.  Embedded
52588 ** systems that do not need this facility may omit it by recompiling
52589 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
52590 **
52591 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
52592 */
52593
52594 /*
52595 ** All of the code in this file may be omitted by defining a single
52596 ** macro.
52597 */
52598 #ifndef SQLITE_OMIT_AUTHORIZATION
52599
52600 /*
52601 ** Set or clear the access authorization function.
52602 **
52603 ** The access authorization function is be called during the compilation
52604 ** phase to verify that the user has read and/or write access permission on
52605 ** various fields of the database.  The first argument to the auth function
52606 ** is a copy of the 3rd argument to this routine.  The second argument
52607 ** to the auth function is one of these constants:
52608 **
52609 **       SQLITE_CREATE_INDEX
52610 **       SQLITE_CREATE_TABLE
52611 **       SQLITE_CREATE_TEMP_INDEX
52612 **       SQLITE_CREATE_TEMP_TABLE
52613 **       SQLITE_CREATE_TEMP_TRIGGER
52614 **       SQLITE_CREATE_TEMP_VIEW
52615 **       SQLITE_CREATE_TRIGGER
52616 **       SQLITE_CREATE_VIEW
52617 **       SQLITE_DELETE
52618 **       SQLITE_DROP_INDEX
52619 **       SQLITE_DROP_TABLE
52620 **       SQLITE_DROP_TEMP_INDEX
52621 **       SQLITE_DROP_TEMP_TABLE
52622 **       SQLITE_DROP_TEMP_TRIGGER
52623 **       SQLITE_DROP_TEMP_VIEW
52624 **       SQLITE_DROP_TRIGGER
52625 **       SQLITE_DROP_VIEW
52626 **       SQLITE_INSERT
52627 **       SQLITE_PRAGMA
52628 **       SQLITE_READ
52629 **       SQLITE_SELECT
52630 **       SQLITE_TRANSACTION
52631 **       SQLITE_UPDATE
52632 **
52633 ** The third and fourth arguments to the auth function are the name of
52634 ** the table and the column that are being accessed.  The auth function
52635 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
52636 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
52637 ** means that the SQL statement will never-run - the sqlite3_exec() call
52638 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
52639 ** should run but attempts to read the specified column will return NULL
52640 ** and attempts to write the column will be ignored.
52641 **
52642 ** Setting the auth function to NULL disables this hook.  The default
52643 ** setting of the auth function is NULL.
52644 */
52645 SQLITE_API int sqlite3_set_authorizer(
52646   sqlite3 *db,
52647   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
52648   void *pArg
52649 ){
52650   sqlite3_mutex_enter(db->mutex);
52651   db->xAuth = xAuth;
52652   db->pAuthArg = pArg;
52653   sqlite3ExpirePreparedStatements(db);
52654   sqlite3_mutex_leave(db->mutex);
52655   return SQLITE_OK;
52656 }
52657
52658 /*
52659 ** Write an error message into pParse->zErrMsg that explains that the
52660 ** user-supplied authorization function returned an illegal value.
52661 */
52662 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
52663   sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
52664     "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
52665     "or SQLITE_DENY", rc);
52666   pParse->rc = SQLITE_ERROR;
52667 }
52668
52669 /*
52670 ** The pExpr should be a TK_COLUMN expression.  The table referred to
52671 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
52672 ** Check to see if it is OK to read this particular column.
52673 **
52674 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
52675 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
52676 ** then generate an error.
52677 */
52678 SQLITE_PRIVATE void sqlite3AuthRead(
52679   Parse *pParse,        /* The parser context */
52680   Expr *pExpr,          /* The expression to check authorization on */
52681   Schema *pSchema,      /* The schema of the expression */
52682   SrcList *pTabList     /* All table that pExpr might refer to */
52683 ){
52684   sqlite3 *db = pParse->db;
52685   int rc;
52686   Table *pTab = 0;      /* The table being read */
52687   const char *zCol;     /* Name of the column of the table */
52688   int iSrc;             /* Index in pTabList->a[] of table being read */
52689   const char *zDBase;   /* Name of database being accessed */
52690   TriggerStack *pStack; /* The stack of current triggers */
52691   int iDb;              /* The index of the database the expression refers to */
52692
52693   if( db->xAuth==0 ) return;
52694   if( pExpr->op!=TK_COLUMN ) return;
52695   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
52696   if( iDb<0 ){
52697     /* An attempt to read a column out of a subquery or other
52698     ** temporary table. */
52699     return;
52700   }
52701   for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
52702     if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
52703   }
52704   if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
52705     pTab = pTabList->a[iSrc].pTab;
52706   }else if( (pStack = pParse->trigStack)!=0 ){
52707     /* This must be an attempt to read the NEW or OLD pseudo-tables
52708     ** of a trigger.
52709     */
52710     assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
52711     pTab = pStack->pTab;
52712   }
52713   if( pTab==0 ) return;
52714   if( pExpr->iColumn>=0 ){
52715     assert( pExpr->iColumn<pTab->nCol );
52716     zCol = pTab->aCol[pExpr->iColumn].zName;
52717   }else if( pTab->iPKey>=0 ){
52718     assert( pTab->iPKey<pTab->nCol );
52719     zCol = pTab->aCol[pTab->iPKey].zName;
52720   }else{
52721     zCol = "ROWID";
52722   }
52723   assert( iDb>=0 && iDb<db->nDb );
52724   zDBase = db->aDb[iDb].zName;
52725   rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
52726                  pParse->zAuthContext);
52727   if( rc==SQLITE_IGNORE ){
52728     pExpr->op = TK_NULL;
52729   }else if( rc==SQLITE_DENY ){
52730     if( db->nDb>2 || iDb!=0 ){
52731       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
52732          zDBase, pTab->zName, zCol);
52733     }else{
52734       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
52735     }
52736     pParse->rc = SQLITE_AUTH;
52737   }else if( rc!=SQLITE_OK ){
52738     sqliteAuthBadReturnCode(pParse, rc);
52739   }
52740 }
52741
52742 /*
52743 ** Do an authorization check using the code and arguments given.  Return
52744 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
52745 ** is returned, then the error count and error message in pParse are
52746 ** modified appropriately.
52747 */
52748 SQLITE_PRIVATE int sqlite3AuthCheck(
52749   Parse *pParse,
52750   int code,
52751   const char *zArg1,
52752   const char *zArg2,
52753   const char *zArg3
52754 ){
52755   sqlite3 *db = pParse->db;
52756   int rc;
52757
52758   /* Don't do any authorization checks if the database is initialising
52759   ** or if the parser is being invoked from within sqlite3_declare_vtab.
52760   */
52761   if( db->init.busy || IN_DECLARE_VTAB ){
52762     return SQLITE_OK;
52763   }
52764
52765   if( db->xAuth==0 ){
52766     return SQLITE_OK;
52767   }
52768   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
52769   if( rc==SQLITE_DENY ){
52770     sqlite3ErrorMsg(pParse, "not authorized");
52771     pParse->rc = SQLITE_AUTH;
52772   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
52773     rc = SQLITE_DENY;
52774     sqliteAuthBadReturnCode(pParse, rc);
52775   }
52776   return rc;
52777 }
52778
52779 /*
52780 ** Push an authorization context.  After this routine is called, the
52781 ** zArg3 argument to authorization callbacks will be zContext until
52782 ** popped.  Or if pParse==0, this routine is a no-op.
52783 */
52784 SQLITE_PRIVATE void sqlite3AuthContextPush(
52785   Parse *pParse,
52786   AuthContext *pContext, 
52787   const char *zContext
52788 ){
52789   pContext->pParse = pParse;
52790   if( pParse ){
52791     pContext->zAuthContext = pParse->zAuthContext;
52792     pParse->zAuthContext = zContext;
52793   }
52794 }
52795
52796 /*
52797 ** Pop an authorization context that was previously pushed
52798 ** by sqlite3AuthContextPush
52799 */
52800 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
52801   if( pContext->pParse ){
52802     pContext->pParse->zAuthContext = pContext->zAuthContext;
52803     pContext->pParse = 0;
52804   }
52805 }
52806
52807 #endif /* SQLITE_OMIT_AUTHORIZATION */
52808
52809 /************** End of auth.c ************************************************/
52810 /************** Begin file build.c *******************************************/
52811 /*
52812 ** 2001 September 15
52813 **
52814 ** The author disclaims copyright to this source code.  In place of
52815 ** a legal notice, here is a blessing:
52816 **
52817 **    May you do good and not evil.
52818 **    May you find forgiveness for yourself and forgive others.
52819 **    May you share freely, never taking more than you give.
52820 **
52821 *************************************************************************
52822 ** This file contains C code routines that are called by the SQLite parser
52823 ** when syntax rules are reduced.  The routines in this file handle the
52824 ** following kinds of SQL syntax:
52825 **
52826 **     CREATE TABLE
52827 **     DROP TABLE
52828 **     CREATE INDEX
52829 **     DROP INDEX
52830 **     creating ID lists
52831 **     BEGIN TRANSACTION
52832 **     COMMIT
52833 **     ROLLBACK
52834 **
52835 ** $Id: build.c,v 1.484 2008/05/01 17:16:53 drh Exp $
52836 */
52837
52838 /*
52839 ** This routine is called when a new SQL statement is beginning to
52840 ** be parsed.  Initialize the pParse structure as needed.
52841 */
52842 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
52843   pParse->explain = explainFlag;
52844   pParse->nVar = 0;
52845 }
52846
52847 #ifndef SQLITE_OMIT_SHARED_CACHE
52848 /*
52849 ** The TableLock structure is only used by the sqlite3TableLock() and
52850 ** codeTableLocks() functions.
52851 */
52852 struct TableLock {
52853   int iDb;             /* The database containing the table to be locked */
52854   int iTab;            /* The root page of the table to be locked */
52855   u8 isWriteLock;      /* True for write lock.  False for a read lock */
52856   const char *zName;   /* Name of the table */
52857 };
52858
52859 /*
52860 ** Record the fact that we want to lock a table at run-time.  
52861 **
52862 ** The table to be locked has root page iTab and is found in database iDb.
52863 ** A read or a write lock can be taken depending on isWritelock.
52864 **
52865 ** This routine just records the fact that the lock is desired.  The
52866 ** code to make the lock occur is generated by a later call to
52867 ** codeTableLocks() which occurs during sqlite3FinishCoding().
52868 */
52869 SQLITE_PRIVATE void sqlite3TableLock(
52870   Parse *pParse,     /* Parsing context */
52871   int iDb,           /* Index of the database containing the table to lock */
52872   int iTab,          /* Root page number of the table to be locked */
52873   u8 isWriteLock,    /* True for a write lock */
52874   const char *zName  /* Name of the table to be locked */
52875 ){
52876   int i;
52877   int nBytes;
52878   TableLock *p;
52879
52880   if( iDb<0 ){
52881     return;
52882   }
52883
52884   for(i=0; i<pParse->nTableLock; i++){
52885     p = &pParse->aTableLock[i];
52886     if( p->iDb==iDb && p->iTab==iTab ){
52887       p->isWriteLock = (p->isWriteLock || isWriteLock);
52888       return;
52889     }
52890   }
52891
52892   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
52893   pParse->aTableLock = 
52894       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
52895   if( pParse->aTableLock ){
52896     p = &pParse->aTableLock[pParse->nTableLock++];
52897     p->iDb = iDb;
52898     p->iTab = iTab;
52899     p->isWriteLock = isWriteLock;
52900     p->zName = zName;
52901   }else{
52902     pParse->nTableLock = 0;
52903     pParse->db->mallocFailed = 1;
52904   }
52905 }
52906
52907 /*
52908 ** Code an OP_TableLock instruction for each table locked by the
52909 ** statement (configured by calls to sqlite3TableLock()).
52910 */
52911 static void codeTableLocks(Parse *pParse){
52912   int i;
52913   Vdbe *pVdbe; 
52914
52915   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
52916     return;
52917   }
52918
52919   for(i=0; i<pParse->nTableLock; i++){
52920     TableLock *p = &pParse->aTableLock[i];
52921     int p1 = p->iDb;
52922     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
52923                       p->zName, P4_STATIC);
52924   }
52925 }
52926 #else
52927   #define codeTableLocks(x)
52928 #endif
52929
52930 /*
52931 ** This routine is called after a single SQL statement has been
52932 ** parsed and a VDBE program to execute that statement has been
52933 ** prepared.  This routine puts the finishing touches on the
52934 ** VDBE program and resets the pParse structure for the next
52935 ** parse.
52936 **
52937 ** Note that if an error occurred, it might be the case that
52938 ** no VDBE code was generated.
52939 */
52940 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
52941   sqlite3 *db;
52942   Vdbe *v;
52943
52944   db = pParse->db;
52945   if( db->mallocFailed ) return;
52946   if( pParse->nested ) return;
52947   if( pParse->nErr ) return;
52948   if( !pParse->pVdbe ){
52949     if( pParse->rc==SQLITE_OK && pParse->nErr ){
52950       pParse->rc = SQLITE_ERROR;
52951       return;
52952     }
52953   }
52954
52955   /* Begin by generating some termination code at the end of the
52956   ** vdbe program
52957   */
52958   v = sqlite3GetVdbe(pParse);
52959   if( v ){
52960     sqlite3VdbeAddOp0(v, OP_Halt);
52961
52962     /* The cookie mask contains one bit for each database file open.
52963     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
52964     ** set for each database that is used.  Generate code to start a
52965     ** transaction on each used database and to verify the schema cookie
52966     ** on each used database.
52967     */
52968     if( pParse->cookieGoto>0 ){
52969       u32 mask;
52970       int iDb;
52971       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
52972       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
52973         if( (mask & pParse->cookieMask)==0 ) continue;
52974         sqlite3VdbeUsesBtree(v, iDb);
52975         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
52976         sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
52977       }
52978 #ifndef SQLITE_OMIT_VIRTUALTABLE
52979       {
52980         int i;
52981         for(i=0; i<pParse->nVtabLock; i++){
52982           char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
52983           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
52984         }
52985         pParse->nVtabLock = 0;
52986       }
52987 #endif
52988
52989       /* Once all the cookies have been verified and transactions opened, 
52990       ** obtain the required table-locks. This is a no-op unless the 
52991       ** shared-cache feature is enabled.
52992       */
52993       codeTableLocks(pParse);
52994       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
52995     }
52996
52997 #ifndef SQLITE_OMIT_TRACE
52998     if( !db->init.busy ){
52999       /* Change the P4 argument of the first opcode (which will always be
53000       ** an OP_Trace) to be the complete text of the current SQL statement.
53001       */
53002       VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
53003       if( pOp && pOp->opcode==OP_Trace ){
53004         sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
53005       }
53006     }
53007 #endif /* SQLITE_OMIT_TRACE */
53008   }
53009
53010
53011   /* Get the VDBE program ready for execution
53012   */
53013   if( v && pParse->nErr==0 && !db->mallocFailed ){
53014 #ifdef SQLITE_DEBUG
53015     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
53016     sqlite3VdbeTrace(v, trace);
53017 #endif
53018     assert( pParse->disableColCache==0 );  /* Disables and re-enables match */
53019     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
53020                          pParse->nTab+3, pParse->explain);
53021     pParse->rc = SQLITE_DONE;
53022     pParse->colNamesSet = 0;
53023   }else if( pParse->rc==SQLITE_OK ){
53024     pParse->rc = SQLITE_ERROR;
53025   }
53026   pParse->nTab = 0;
53027   pParse->nMem = 0;
53028   pParse->nSet = 0;
53029   pParse->nVar = 0;
53030   pParse->cookieMask = 0;
53031   pParse->cookieGoto = 0;
53032 }
53033
53034 /*
53035 ** Run the parser and code generator recursively in order to generate
53036 ** code for the SQL statement given onto the end of the pParse context
53037 ** currently under construction.  When the parser is run recursively
53038 ** this way, the final OP_Halt is not appended and other initialization
53039 ** and finalization steps are omitted because those are handling by the
53040 ** outermost parser.
53041 **
53042 ** Not everything is nestable.  This facility is designed to permit
53043 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
53044 ** care if you decide to try to use this routine for some other purposes.
53045 */
53046 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
53047   va_list ap;
53048   char *zSql;
53049 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
53050   char saveBuf[SAVE_SZ];
53051
53052   if( pParse->nErr ) return;
53053   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
53054   va_start(ap, zFormat);
53055   zSql = sqlite3VMPrintf(pParse->db, zFormat, ap);
53056   va_end(ap);
53057   if( zSql==0 ){
53058     pParse->db->mallocFailed = 1;
53059     return;   /* A malloc must have failed */
53060   }
53061   pParse->nested++;
53062   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
53063   memset(&pParse->nVar, 0, SAVE_SZ);
53064   sqlite3RunParser(pParse, zSql, 0);
53065   sqlite3_free(zSql);
53066   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
53067   pParse->nested--;
53068 }
53069
53070 /*
53071 ** Locate the in-memory structure that describes a particular database
53072 ** table given the name of that table and (optionally) the name of the
53073 ** database containing the table.  Return NULL if not found.
53074 **
53075 ** If zDatabase is 0, all databases are searched for the table and the
53076 ** first matching table is returned.  (No checking for duplicate table
53077 ** names is done.)  The search order is TEMP first, then MAIN, then any
53078 ** auxiliary databases added using the ATTACH command.
53079 **
53080 ** See also sqlite3LocateTable().
53081 */
53082 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
53083   Table *p = 0;
53084   int i;
53085   assert( zName!=0 );
53086   for(i=OMIT_TEMPDB; i<db->nDb; i++){
53087     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
53088     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
53089     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
53090     if( p ) break;
53091   }
53092   return p;
53093 }
53094
53095 /*
53096 ** Locate the in-memory structure that describes a particular database
53097 ** table given the name of that table and (optionally) the name of the
53098 ** database containing the table.  Return NULL if not found.  Also leave an
53099 ** error message in pParse->zErrMsg.
53100 **
53101 ** The difference between this routine and sqlite3FindTable() is that this
53102 ** routine leaves an error message in pParse->zErrMsg where
53103 ** sqlite3FindTable() does not.
53104 */
53105 SQLITE_PRIVATE Table *sqlite3LocateTable(
53106   Parse *pParse,         /* context in which to report errors */
53107   int isView,            /* True if looking for a VIEW rather than a TABLE */
53108   const char *zName,     /* Name of the table we are looking for */
53109   const char *zDbase     /* Name of the database.  Might be NULL */
53110 ){
53111   Table *p;
53112
53113   /* Read the database schema. If an error occurs, leave an error message
53114   ** and code in pParse and return NULL. */
53115   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
53116     return 0;
53117   }
53118
53119   p = sqlite3FindTable(pParse->db, zName, zDbase);
53120   if( p==0 ){
53121     const char *zMsg = isView ? "no such view" : "no such table";
53122     if( zDbase ){
53123       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
53124     }else{
53125       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
53126     }
53127     pParse->checkSchema = 1;
53128   }
53129   return p;
53130 }
53131
53132 /*
53133 ** Locate the in-memory structure that describes 
53134 ** a particular index given the name of that index
53135 ** and the name of the database that contains the index.
53136 ** Return NULL if not found.
53137 **
53138 ** If zDatabase is 0, all databases are searched for the
53139 ** table and the first matching index is returned.  (No checking
53140 ** for duplicate index names is done.)  The search order is
53141 ** TEMP first, then MAIN, then any auxiliary databases added
53142 ** using the ATTACH command.
53143 */
53144 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
53145   Index *p = 0;
53146   int i;
53147   for(i=OMIT_TEMPDB; i<db->nDb; i++){
53148     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
53149     Schema *pSchema = db->aDb[j].pSchema;
53150     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
53151     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
53152     if( pSchema ){
53153       p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
53154     }
53155     if( p ) break;
53156   }
53157   return p;
53158 }
53159
53160 /*
53161 ** Reclaim the memory used by an index
53162 */
53163 static void freeIndex(Index *p){
53164   sqlite3_free(p->zColAff);
53165   sqlite3_free(p);
53166 }
53167
53168 /*
53169 ** Remove the given index from the index hash table, and free
53170 ** its memory structures.
53171 **
53172 ** The index is removed from the database hash tables but
53173 ** it is not unlinked from the Table that it indexes.
53174 ** Unlinking from the Table must be done by the calling function.
53175 */
53176 static void sqliteDeleteIndex(Index *p){
53177   Index *pOld;
53178   const char *zName = p->zName;
53179
53180   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
53181   assert( pOld==0 || pOld==p );
53182   freeIndex(p);
53183 }
53184
53185 /*
53186 ** For the index called zIdxName which is found in the database iDb,
53187 ** unlike that index from its Table then remove the index from
53188 ** the index hash table and free all memory structures associated
53189 ** with the index.
53190 */
53191 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
53192   Index *pIndex;
53193   int len;
53194   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
53195
53196   len = strlen(zIdxName);
53197   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
53198   if( pIndex ){
53199     if( pIndex->pTable->pIndex==pIndex ){
53200       pIndex->pTable->pIndex = pIndex->pNext;
53201     }else{
53202       Index *p;
53203       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
53204       if( p && p->pNext==pIndex ){
53205         p->pNext = pIndex->pNext;
53206       }
53207     }
53208     freeIndex(pIndex);
53209   }
53210   db->flags |= SQLITE_InternChanges;
53211 }
53212
53213 /*
53214 ** Erase all schema information from the in-memory hash tables of
53215 ** a single database.  This routine is called to reclaim memory
53216 ** before the database closes.  It is also called during a rollback
53217 ** if there were schema changes during the transaction or if a
53218 ** schema-cookie mismatch occurs.
53219 **
53220 ** If iDb<=0 then reset the internal schema tables for all database
53221 ** files.  If iDb>=2 then reset the internal schema for only the
53222 ** single file indicated.
53223 */
53224 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
53225   int i, j;
53226   assert( iDb>=0 && iDb<db->nDb );
53227
53228   if( iDb==0 ){
53229     sqlite3BtreeEnterAll(db);
53230   }
53231   for(i=iDb; i<db->nDb; i++){
53232     Db *pDb = &db->aDb[i];
53233     if( pDb->pSchema ){
53234       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
53235       sqlite3SchemaFree(pDb->pSchema);
53236     }
53237     if( iDb>0 ) return;
53238   }
53239   assert( iDb==0 );
53240   db->flags &= ~SQLITE_InternChanges;
53241   sqlite3BtreeLeaveAll(db);
53242
53243   /* If one or more of the auxiliary database files has been closed,
53244   ** then remove them from the auxiliary database list.  We take the
53245   ** opportunity to do this here since we have just deleted all of the
53246   ** schema hash tables and therefore do not have to make any changes
53247   ** to any of those tables.
53248   */
53249   for(i=0; i<db->nDb; i++){
53250     struct Db *pDb = &db->aDb[i];
53251     if( pDb->pBt==0 ){
53252       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
53253       pDb->pAux = 0;
53254     }
53255   }
53256   for(i=j=2; i<db->nDb; i++){
53257     struct Db *pDb = &db->aDb[i];
53258     if( pDb->pBt==0 ){
53259       sqlite3_free(pDb->zName);
53260       pDb->zName = 0;
53261       continue;
53262     }
53263     if( j<i ){
53264       db->aDb[j] = db->aDb[i];
53265     }
53266     j++;
53267   }
53268   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
53269   db->nDb = j;
53270   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
53271     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
53272     sqlite3_free(db->aDb);
53273     db->aDb = db->aDbStatic;
53274   }
53275 }
53276
53277 /*
53278 ** This routine is called when a commit occurs.
53279 */
53280 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
53281   db->flags &= ~SQLITE_InternChanges;
53282 }
53283
53284 /*
53285 ** Clear the column names from a table or view.
53286 */
53287 static void sqliteResetColumnNames(Table *pTable){
53288   int i;
53289   Column *pCol;
53290   assert( pTable!=0 );
53291   if( (pCol = pTable->aCol)!=0 ){
53292     for(i=0; i<pTable->nCol; i++, pCol++){
53293       sqlite3_free(pCol->zName);
53294       sqlite3ExprDelete(pCol->pDflt);
53295       sqlite3_free(pCol->zType);
53296       sqlite3_free(pCol->zColl);
53297     }
53298     sqlite3_free(pTable->aCol);
53299   }
53300   pTable->aCol = 0;
53301   pTable->nCol = 0;
53302 }
53303
53304 /*
53305 ** Remove the memory data structures associated with the given
53306 ** Table.  No changes are made to disk by this routine.
53307 **
53308 ** This routine just deletes the data structure.  It does not unlink
53309 ** the table data structure from the hash table.  Nor does it remove
53310 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
53311 ** memory structures of the indices and foreign keys associated with 
53312 ** the table.
53313 */
53314 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
53315   Index *pIndex, *pNext;
53316   FKey *pFKey, *pNextFKey;
53317
53318   if( pTable==0 ) return;
53319
53320   /* Do not delete the table until the reference count reaches zero. */
53321   pTable->nRef--;
53322   if( pTable->nRef>0 ){
53323     return;
53324   }
53325   assert( pTable->nRef==0 );
53326
53327   /* Delete all indices associated with this table
53328   */
53329   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
53330     pNext = pIndex->pNext;
53331     assert( pIndex->pSchema==pTable->pSchema );
53332     sqliteDeleteIndex(pIndex);
53333   }
53334
53335 #ifndef SQLITE_OMIT_FOREIGN_KEY
53336   /* Delete all foreign keys associated with this table.  The keys
53337   ** should have already been unlinked from the pSchema->aFKey hash table 
53338   */
53339   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
53340     pNextFKey = pFKey->pNextFrom;
53341     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
53342                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
53343     sqlite3_free(pFKey);
53344   }
53345 #endif
53346
53347   /* Delete the Table structure itself.
53348   */
53349   sqliteResetColumnNames(pTable);
53350   sqlite3_free(pTable->zName);
53351   sqlite3_free(pTable->zColAff);
53352   sqlite3SelectDelete(pTable->pSelect);
53353 #ifndef SQLITE_OMIT_CHECK
53354   sqlite3ExprDelete(pTable->pCheck);
53355 #endif
53356   sqlite3VtabClear(pTable);
53357   sqlite3_free(pTable);
53358 }
53359
53360 /*
53361 ** Unlink the given table from the hash tables and the delete the
53362 ** table structure with all its indices and foreign keys.
53363 */
53364 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
53365   Table *p;
53366   FKey *pF1, *pF2;
53367   Db *pDb;
53368
53369   assert( db!=0 );
53370   assert( iDb>=0 && iDb<db->nDb );
53371   assert( zTabName && zTabName[0] );
53372   pDb = &db->aDb[iDb];
53373   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
53374   if( p ){
53375 #ifndef SQLITE_OMIT_FOREIGN_KEY
53376     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
53377       int nTo = strlen(pF1->zTo) + 1;
53378       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
53379       if( pF2==pF1 ){
53380         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
53381       }else{
53382         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
53383         if( pF2 ){
53384           pF2->pNextTo = pF1->pNextTo;
53385         }
53386       }
53387     }
53388 #endif
53389     sqlite3DeleteTable(p);
53390   }
53391   db->flags |= SQLITE_InternChanges;
53392 }
53393
53394 /*
53395 ** Given a token, return a string that consists of the text of that
53396 ** token with any quotations removed.  Space to hold the returned string
53397 ** is obtained from sqliteMalloc() and must be freed by the calling
53398 ** function.
53399 **
53400 ** Tokens are often just pointers into the original SQL text and so
53401 ** are not \000 terminated and are not persistent.  The returned string
53402 ** is \000 terminated and is persistent.
53403 */
53404 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
53405   char *zName;
53406   if( pName ){
53407     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
53408     sqlite3Dequote(zName);
53409   }else{
53410     zName = 0;
53411   }
53412   return zName;
53413 }
53414
53415 /*
53416 ** Open the sqlite_master table stored in database number iDb for
53417 ** writing. The table is opened using cursor 0.
53418 */
53419 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
53420   Vdbe *v = sqlite3GetVdbe(p);
53421   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
53422   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
53423   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
53424 }
53425
53426 /*
53427 ** The token *pName contains the name of a database (either "main" or
53428 ** "temp" or the name of an attached db). This routine returns the
53429 ** index of the named database in db->aDb[], or -1 if the named db 
53430 ** does not exist.
53431 */
53432 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
53433   int i = -1;    /* Database number */
53434   int n;         /* Number of characters in the name */
53435   Db *pDb;       /* A database whose name space is being searched */
53436   char *zName;   /* Name we are searching for */
53437
53438   zName = sqlite3NameFromToken(db, pName);
53439   if( zName ){
53440     n = strlen(zName);
53441     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
53442       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
53443           0==sqlite3StrICmp(pDb->zName, zName) ){
53444         break;
53445       }
53446     }
53447     sqlite3_free(zName);
53448   }
53449   return i;
53450 }
53451
53452 /* The table or view or trigger name is passed to this routine via tokens
53453 ** pName1 and pName2. If the table name was fully qualified, for example:
53454 **
53455 ** CREATE TABLE xxx.yyy (...);
53456 ** 
53457 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
53458 ** the table name is not fully qualified, i.e.:
53459 **
53460 ** CREATE TABLE yyy(...);
53461 **
53462 ** Then pName1 is set to "yyy" and pName2 is "".
53463 **
53464 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
53465 ** pName2) that stores the unqualified table name.  The index of the
53466 ** database "xxx" is returned.
53467 */
53468 SQLITE_PRIVATE int sqlite3TwoPartName(
53469   Parse *pParse,      /* Parsing and code generating context */
53470   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
53471   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
53472   Token **pUnqual     /* Write the unqualified object name here */
53473 ){
53474   int iDb;                    /* Database holding the object */
53475   sqlite3 *db = pParse->db;
53476
53477   if( pName2 && pName2->n>0 ){
53478     assert( !db->init.busy );
53479     *pUnqual = pName2;
53480     iDb = sqlite3FindDb(db, pName1);
53481     if( iDb<0 ){
53482       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
53483       pParse->nErr++;
53484       return -1;
53485     }
53486   }else{
53487     assert( db->init.iDb==0 || db->init.busy );
53488     iDb = db->init.iDb;
53489     *pUnqual = pName1;
53490   }
53491   return iDb;
53492 }
53493
53494 /*
53495 ** This routine is used to check if the UTF-8 string zName is a legal
53496 ** unqualified name for a new schema object (table, index, view or
53497 ** trigger). All names are legal except those that begin with the string
53498 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
53499 ** is reserved for internal use.
53500 */
53501 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
53502   if( !pParse->db->init.busy && pParse->nested==0 
53503           && (pParse->db->flags & SQLITE_WriteSchema)==0
53504           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
53505     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
53506     return SQLITE_ERROR;
53507   }
53508   return SQLITE_OK;
53509 }
53510
53511 /*
53512 ** Begin constructing a new table representation in memory.  This is
53513 ** the first of several action routines that get called in response
53514 ** to a CREATE TABLE statement.  In particular, this routine is called
53515 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
53516 ** flag is true if the table should be stored in the auxiliary database
53517 ** file instead of in the main database file.  This is normally the case
53518 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
53519 ** CREATE and TABLE.
53520 **
53521 ** The new table record is initialized and put in pParse->pNewTable.
53522 ** As more of the CREATE TABLE statement is parsed, additional action
53523 ** routines will be called to add more information to this record.
53524 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
53525 ** is called to complete the construction of the new table record.
53526 */
53527 SQLITE_PRIVATE void sqlite3StartTable(
53528   Parse *pParse,   /* Parser context */
53529   Token *pName1,   /* First part of the name of the table or view */
53530   Token *pName2,   /* Second part of the name of the table or view */
53531   int isTemp,      /* True if this is a TEMP table */
53532   int isView,      /* True if this is a VIEW */
53533   int isVirtual,   /* True if this is a VIRTUAL table */
53534   int noErr        /* Do nothing if table already exists */
53535 ){
53536   Table *pTable;
53537   char *zName = 0; /* The name of the new table */
53538   sqlite3 *db = pParse->db;
53539   Vdbe *v;
53540   int iDb;         /* Database number to create the table in */
53541   Token *pName;    /* Unqualified name of the table to create */
53542
53543   /* The table or view name to create is passed to this routine via tokens
53544   ** pName1 and pName2. If the table name was fully qualified, for example:
53545   **
53546   ** CREATE TABLE xxx.yyy (...);
53547   ** 
53548   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
53549   ** the table name is not fully qualified, i.e.:
53550   **
53551   ** CREATE TABLE yyy(...);
53552   **
53553   ** Then pName1 is set to "yyy" and pName2 is "".
53554   **
53555   ** The call below sets the pName pointer to point at the token (pName1 or
53556   ** pName2) that stores the unqualified table name. The variable iDb is
53557   ** set to the index of the database that the table or view is to be
53558   ** created in.
53559   */
53560   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
53561   if( iDb<0 ) return;
53562   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
53563     /* If creating a temp table, the name may not be qualified */
53564     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
53565     return;
53566   }
53567   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
53568
53569   pParse->sNameToken = *pName;
53570   zName = sqlite3NameFromToken(db, pName);
53571   if( zName==0 ) return;
53572   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
53573     goto begin_table_error;
53574   }
53575   if( db->init.iDb==1 ) isTemp = 1;
53576 #ifndef SQLITE_OMIT_AUTHORIZATION
53577   assert( (isTemp & 1)==isTemp );
53578   {
53579     int code;
53580     char *zDb = db->aDb[iDb].zName;
53581     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
53582       goto begin_table_error;
53583     }
53584     if( isView ){
53585       if( !OMIT_TEMPDB && isTemp ){
53586         code = SQLITE_CREATE_TEMP_VIEW;
53587       }else{
53588         code = SQLITE_CREATE_VIEW;
53589       }
53590     }else{
53591       if( !OMIT_TEMPDB && isTemp ){
53592         code = SQLITE_CREATE_TEMP_TABLE;
53593       }else{
53594         code = SQLITE_CREATE_TABLE;
53595       }
53596     }
53597     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
53598       goto begin_table_error;
53599     }
53600   }
53601 #endif
53602
53603   /* Make sure the new table name does not collide with an existing
53604   ** index or table name in the same database.  Issue an error message if
53605   ** it does. The exception is if the statement being parsed was passed
53606   ** to an sqlite3_declare_vtab() call. In that case only the column names
53607   ** and types will be used, so there is no need to test for namespace
53608   ** collisions.
53609   */
53610   if( !IN_DECLARE_VTAB ){
53611     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
53612       goto begin_table_error;
53613     }
53614     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
53615     if( pTable ){
53616       if( !noErr ){
53617         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
53618       }
53619       goto begin_table_error;
53620     }
53621     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
53622       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
53623       goto begin_table_error;
53624     }
53625   }
53626
53627   pTable = sqlite3DbMallocZero(db, sizeof(Table));
53628   if( pTable==0 ){
53629     db->mallocFailed = 1;
53630     pParse->rc = SQLITE_NOMEM;
53631     pParse->nErr++;
53632     goto begin_table_error;
53633   }
53634   pTable->zName = zName;
53635   pTable->iPKey = -1;
53636   pTable->pSchema = db->aDb[iDb].pSchema;
53637   pTable->nRef = 1;
53638   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
53639   pParse->pNewTable = pTable;
53640
53641   /* If this is the magic sqlite_sequence table used by autoincrement,
53642   ** then record a pointer to this table in the main database structure
53643   ** so that INSERT can find the table easily.
53644   */
53645 #ifndef SQLITE_OMIT_AUTOINCREMENT
53646   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
53647     pTable->pSchema->pSeqTab = pTable;
53648   }
53649 #endif
53650
53651   /* Begin generating the code that will insert the table record into
53652   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
53653   ** and allocate the record number for the table entry now.  Before any
53654   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
53655   ** indices to be created and the table record must come before the 
53656   ** indices.  Hence, the record number for the table must be allocated
53657   ** now.
53658   */
53659   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
53660     int j1;
53661     int fileFormat;
53662     int reg1, reg2, reg3;
53663     sqlite3BeginWriteOperation(pParse, 0, iDb);
53664
53665 #ifndef SQLITE_OMIT_VIRTUALTABLE
53666     if( isVirtual ){
53667       sqlite3VdbeAddOp0(v, OP_VBegin);
53668     }
53669 #endif
53670
53671     /* If the file format and encoding in the database have not been set, 
53672     ** set them now.
53673     */
53674     reg1 = pParse->regRowid = ++pParse->nMem;
53675     reg2 = pParse->regRoot = ++pParse->nMem;
53676     reg3 = ++pParse->nMem;
53677     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
53678     sqlite3VdbeUsesBtree(v, iDb);
53679     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
53680     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
53681                   1 : SQLITE_MAX_FILE_FORMAT;
53682     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
53683     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
53684     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
53685     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
53686     sqlite3VdbeJumpHere(v, j1);
53687
53688     /* This just creates a place-holder record in the sqlite_master table.
53689     ** The record created does not contain anything yet.  It will be replaced
53690     ** by the real entry in code generated at sqlite3EndTable().
53691     **
53692     ** The rowid for the new entry is left on the top of the stack.
53693     ** The rowid value is needed by the code that sqlite3EndTable will
53694     ** generate.
53695     */
53696 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
53697     if( isView || isVirtual ){
53698       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
53699     }else
53700 #endif
53701     {
53702       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
53703     }
53704     sqlite3OpenMasterTable(pParse, iDb);
53705     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
53706     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
53707     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
53708     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
53709     sqlite3VdbeAddOp0(v, OP_Close);
53710   }
53711
53712   /* Normal (non-error) return. */
53713   return;
53714
53715   /* If an error occurs, we jump here */
53716 begin_table_error:
53717   sqlite3_free(zName);
53718   return;
53719 }
53720
53721 /*
53722 ** This macro is used to compare two strings in a case-insensitive manner.
53723 ** It is slightly faster than calling sqlite3StrICmp() directly, but
53724 ** produces larger code.
53725 **
53726 ** WARNING: This macro is not compatible with the strcmp() family. It
53727 ** returns true if the two strings are equal, otherwise false.
53728 */
53729 #define STRICMP(x, y) (\
53730 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
53731 sqlite3UpperToLower[*(unsigned char *)(y)]     \
53732 && sqlite3StrICmp((x)+1,(y)+1)==0 )
53733
53734 /*
53735 ** Add a new column to the table currently being constructed.
53736 **
53737 ** The parser calls this routine once for each column declaration
53738 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
53739 ** first to get things going.  Then this routine is called for each
53740 ** column.
53741 */
53742 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
53743   Table *p;
53744   int i;
53745   char *z;
53746   Column *pCol;
53747   sqlite3 *db = pParse->db;
53748   if( (p = pParse->pNewTable)==0 ) return;
53749 #if SQLITE_MAX_COLUMN
53750   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
53751     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
53752     return;
53753   }
53754 #endif
53755   z = sqlite3NameFromToken(pParse->db, pName);
53756   if( z==0 ) return;
53757   for(i=0; i<p->nCol; i++){
53758     if( STRICMP(z, p->aCol[i].zName) ){
53759       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
53760       sqlite3_free(z);
53761       return;
53762     }
53763   }
53764   if( (p->nCol & 0x7)==0 ){
53765     Column *aNew;
53766     aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
53767     if( aNew==0 ){
53768       sqlite3_free(z);
53769       return;
53770     }
53771     p->aCol = aNew;
53772   }
53773   pCol = &p->aCol[p->nCol];
53774   memset(pCol, 0, sizeof(p->aCol[0]));
53775   pCol->zName = z;
53776  
53777   /* If there is no type specified, columns have the default affinity
53778   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
53779   ** be called next to set pCol->affinity correctly.
53780   */
53781   pCol->affinity = SQLITE_AFF_NONE;
53782   p->nCol++;
53783 }
53784
53785 /*
53786 ** This routine is called by the parser while in the middle of
53787 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
53788 ** been seen on a column.  This routine sets the notNull flag on
53789 ** the column currently under construction.
53790 */
53791 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
53792   Table *p;
53793   int i;
53794   if( (p = pParse->pNewTable)==0 ) return;
53795   i = p->nCol-1;
53796   if( i>=0 ) p->aCol[i].notNull = onError;
53797 }
53798
53799 /*
53800 ** Scan the column type name zType (length nType) and return the
53801 ** associated affinity type.
53802 **
53803 ** This routine does a case-independent search of zType for the 
53804 ** substrings in the following table. If one of the substrings is
53805 ** found, the corresponding affinity is returned. If zType contains
53806 ** more than one of the substrings, entries toward the top of 
53807 ** the table take priority. For example, if zType is 'BLOBINT', 
53808 ** SQLITE_AFF_INTEGER is returned.
53809 **
53810 ** Substring     | Affinity
53811 ** --------------------------------
53812 ** 'INT'         | SQLITE_AFF_INTEGER
53813 ** 'CHAR'        | SQLITE_AFF_TEXT
53814 ** 'CLOB'        | SQLITE_AFF_TEXT
53815 ** 'TEXT'        | SQLITE_AFF_TEXT
53816 ** 'BLOB'        | SQLITE_AFF_NONE
53817 ** 'REAL'        | SQLITE_AFF_REAL
53818 ** 'FLOA'        | SQLITE_AFF_REAL
53819 ** 'DOUB'        | SQLITE_AFF_REAL
53820 **
53821 ** If none of the substrings in the above table are found,
53822 ** SQLITE_AFF_NUMERIC is returned.
53823 */
53824 SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
53825   u32 h = 0;
53826   char aff = SQLITE_AFF_NUMERIC;
53827   const unsigned char *zIn = pType->z;
53828   const unsigned char *zEnd = &pType->z[pType->n];
53829
53830   while( zIn!=zEnd ){
53831     h = (h<<8) + sqlite3UpperToLower[*zIn];
53832     zIn++;
53833     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
53834       aff = SQLITE_AFF_TEXT; 
53835     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
53836       aff = SQLITE_AFF_TEXT;
53837     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
53838       aff = SQLITE_AFF_TEXT;
53839     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
53840         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
53841       aff = SQLITE_AFF_NONE;
53842 #ifndef SQLITE_OMIT_FLOATING_POINT
53843     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
53844         && aff==SQLITE_AFF_NUMERIC ){
53845       aff = SQLITE_AFF_REAL;
53846     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
53847         && aff==SQLITE_AFF_NUMERIC ){
53848       aff = SQLITE_AFF_REAL;
53849     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
53850         && aff==SQLITE_AFF_NUMERIC ){
53851       aff = SQLITE_AFF_REAL;
53852 #endif
53853     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
53854       aff = SQLITE_AFF_INTEGER;
53855       break;
53856     }
53857   }
53858
53859   return aff;
53860 }
53861
53862 /*
53863 ** This routine is called by the parser while in the middle of
53864 ** parsing a CREATE TABLE statement.  The pFirst token is the first
53865 ** token in the sequence of tokens that describe the type of the
53866 ** column currently under construction.   pLast is the last token
53867 ** in the sequence.  Use this information to construct a string
53868 ** that contains the typename of the column and store that string
53869 ** in zType.
53870 */ 
53871 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
53872   Table *p;
53873   int i;
53874   Column *pCol;
53875
53876   if( (p = pParse->pNewTable)==0 ) return;
53877   i = p->nCol-1;
53878   if( i<0 ) return;
53879   pCol = &p->aCol[i];
53880   sqlite3_free(pCol->zType);
53881   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
53882   pCol->affinity = sqlite3AffinityType(pType);
53883 }
53884
53885 /*
53886 ** The expression is the default value for the most recently added column
53887 ** of the table currently under construction.
53888 **
53889 ** Default value expressions must be constant.  Raise an exception if this
53890 ** is not the case.
53891 **
53892 ** This routine is called by the parser while in the middle of
53893 ** parsing a CREATE TABLE statement.
53894 */
53895 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
53896   Table *p;
53897   Column *pCol;
53898   if( (p = pParse->pNewTable)!=0 ){
53899     pCol = &(p->aCol[p->nCol-1]);
53900     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
53901       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
53902           pCol->zName);
53903     }else{
53904       Expr *pCopy;
53905       sqlite3 *db = pParse->db;
53906       sqlite3ExprDelete(pCol->pDflt);
53907       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
53908       if( pCopy ){
53909         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
53910       }
53911     }
53912   }
53913   sqlite3ExprDelete(pExpr);
53914 }
53915
53916 /*
53917 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
53918 ** of columns that form the primary key.  If pList is NULL, then the
53919 ** most recently added column of the table is the primary key.
53920 **
53921 ** A table can have at most one primary key.  If the table already has
53922 ** a primary key (and this is the second primary key) then create an
53923 ** error.
53924 **
53925 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
53926 ** then we will try to use that column as the rowid.  Set the Table.iPKey
53927 ** field of the table under construction to be the index of the
53928 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
53929 ** no INTEGER PRIMARY KEY.
53930 **
53931 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
53932 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
53933 */
53934 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
53935   Parse *pParse,    /* Parsing context */
53936   ExprList *pList,  /* List of field names to be indexed */
53937   int onError,      /* What to do with a uniqueness conflict */
53938   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
53939   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
53940 ){
53941   Table *pTab = pParse->pNewTable;
53942   char *zType = 0;
53943   int iCol = -1, i;
53944   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
53945   if( pTab->hasPrimKey ){
53946     sqlite3ErrorMsg(pParse, 
53947       "table \"%s\" has more than one primary key", pTab->zName);
53948     goto primary_key_exit;
53949   }
53950   pTab->hasPrimKey = 1;
53951   if( pList==0 ){
53952     iCol = pTab->nCol - 1;
53953     pTab->aCol[iCol].isPrimKey = 1;
53954   }else{
53955     for(i=0; i<pList->nExpr; i++){
53956       for(iCol=0; iCol<pTab->nCol; iCol++){
53957         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
53958           break;
53959         }
53960       }
53961       if( iCol<pTab->nCol ){
53962         pTab->aCol[iCol].isPrimKey = 1;
53963       }
53964     }
53965     if( pList->nExpr>1 ) iCol = -1;
53966   }
53967   if( iCol>=0 && iCol<pTab->nCol ){
53968     zType = pTab->aCol[iCol].zType;
53969   }
53970   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
53971         && sortOrder==SQLITE_SO_ASC ){
53972     pTab->iPKey = iCol;
53973     pTab->keyConf = onError;
53974     pTab->autoInc = autoInc;
53975   }else if( autoInc ){
53976 #ifndef SQLITE_OMIT_AUTOINCREMENT
53977     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
53978        "INTEGER PRIMARY KEY");
53979 #endif
53980   }else{
53981     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
53982     pList = 0;
53983   }
53984
53985 primary_key_exit:
53986   sqlite3ExprListDelete(pList);
53987   return;
53988 }
53989
53990 /*
53991 ** Add a new CHECK constraint to the table currently under construction.
53992 */
53993 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
53994   Parse *pParse,    /* Parsing context */
53995   Expr *pCheckExpr  /* The check expression */
53996 ){
53997 #ifndef SQLITE_OMIT_CHECK
53998   Table *pTab = pParse->pNewTable;
53999   sqlite3 *db = pParse->db;
54000   if( pTab && !IN_DECLARE_VTAB ){
54001     /* The CHECK expression must be duplicated so that tokens refer
54002     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
54003     ** statement */
54004     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
54005                                   sqlite3ExprDup(db, pCheckExpr));
54006   }
54007 #endif
54008   sqlite3ExprDelete(pCheckExpr);
54009 }
54010
54011 /*
54012 ** Set the collation function of the most recently parsed table column
54013 ** to the CollSeq given.
54014 */
54015 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
54016   Table *p;
54017   int i;
54018   char *zColl;              /* Dequoted name of collation sequence */
54019
54020   if( (p = pParse->pNewTable)==0 ) return;
54021   i = p->nCol-1;
54022
54023   zColl = sqlite3NameFromToken(pParse->db, pToken);
54024   if( !zColl ) return;
54025
54026   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
54027     Index *pIdx;
54028     p->aCol[i].zColl = zColl;
54029   
54030     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
54031     ** then an index may have been created on this column before the
54032     ** collation type was added. Correct this if it is the case.
54033     */
54034     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
54035       assert( pIdx->nColumn==1 );
54036       if( pIdx->aiColumn[0]==i ){
54037         pIdx->azColl[0] = p->aCol[i].zColl;
54038       }
54039     }
54040   }else{
54041     sqlite3_free(zColl);
54042   }
54043 }
54044
54045 /*
54046 ** This function returns the collation sequence for database native text
54047 ** encoding identified by the string zName, length nName.
54048 **
54049 ** If the requested collation sequence is not available, or not available
54050 ** in the database native encoding, the collation factory is invoked to
54051 ** request it. If the collation factory does not supply such a sequence,
54052 ** and the sequence is available in another text encoding, then that is
54053 ** returned instead.
54054 **
54055 ** If no versions of the requested collations sequence are available, or
54056 ** another error occurs, NULL is returned and an error message written into
54057 ** pParse.
54058 **
54059 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
54060 ** invokes the collation factory if the named collation cannot be found
54061 ** and generates an error message.
54062 */
54063 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
54064   sqlite3 *db = pParse->db;
54065   u8 enc = ENC(db);
54066   u8 initbusy = db->init.busy;
54067   CollSeq *pColl;
54068
54069   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
54070   if( !initbusy && (!pColl || !pColl->xCmp) ){
54071     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
54072     if( !pColl ){
54073       if( nName<0 ){
54074         nName = strlen(zName);
54075       }
54076       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
54077       pColl = 0;
54078     }
54079   }
54080
54081   return pColl;
54082 }
54083
54084
54085 /*
54086 ** Generate code that will increment the schema cookie.
54087 **
54088 ** The schema cookie is used to determine when the schema for the
54089 ** database changes.  After each schema change, the cookie value
54090 ** changes.  When a process first reads the schema it records the
54091 ** cookie.  Thereafter, whenever it goes to access the database,
54092 ** it checks the cookie to make sure the schema has not changed
54093 ** since it was last read.
54094 **
54095 ** This plan is not completely bullet-proof.  It is possible for
54096 ** the schema to change multiple times and for the cookie to be
54097 ** set back to prior value.  But schema changes are infrequent
54098 ** and the probability of hitting the same cookie value is only
54099 ** 1 chance in 2^32.  So we're safe enough.
54100 */
54101 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
54102   int r1 = sqlite3GetTempReg(pParse);
54103   sqlite3 *db = pParse->db;
54104   Vdbe *v = pParse->pVdbe;
54105   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
54106   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
54107   sqlite3ReleaseTempReg(pParse, r1);
54108 }
54109
54110 /*
54111 ** Measure the number of characters needed to output the given
54112 ** identifier.  The number returned includes any quotes used
54113 ** but does not include the null terminator.
54114 **
54115 ** The estimate is conservative.  It might be larger that what is
54116 ** really needed.
54117 */
54118 static int identLength(const char *z){
54119   int n;
54120   for(n=0; *z; n++, z++){
54121     if( *z=='"' ){ n++; }
54122   }
54123   return n + 2;
54124 }
54125
54126 /*
54127 ** Write an identifier onto the end of the given string.  Add
54128 ** quote characters as needed.
54129 */
54130 static void identPut(char *z, int *pIdx, char *zSignedIdent){
54131   unsigned char *zIdent = (unsigned char*)zSignedIdent;
54132   int i, j, needQuote;
54133   i = *pIdx;
54134   for(j=0; zIdent[j]; j++){
54135     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
54136   }
54137   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
54138                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
54139   if( needQuote ) z[i++] = '"';
54140   for(j=0; zIdent[j]; j++){
54141     z[i++] = zIdent[j];
54142     if( zIdent[j]=='"' ) z[i++] = '"';
54143   }
54144   if( needQuote ) z[i++] = '"';
54145   z[i] = 0;
54146   *pIdx = i;
54147 }
54148
54149 /*
54150 ** Generate a CREATE TABLE statement appropriate for the given
54151 ** table.  Memory to hold the text of the statement is obtained
54152 ** from sqliteMalloc() and must be freed by the calling function.
54153 */
54154 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
54155   int i, k, n;
54156   char *zStmt;
54157   char *zSep, *zSep2, *zEnd, *z;
54158   Column *pCol;
54159   n = 0;
54160   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
54161     n += identLength(pCol->zName);
54162     z = pCol->zType;
54163     if( z ){
54164       n += (strlen(z) + 1);
54165     }
54166   }
54167   n += identLength(p->zName);
54168   if( n<50 ){
54169     zSep = "";
54170     zSep2 = ",";
54171     zEnd = ")";
54172   }else{
54173     zSep = "\n  ";
54174     zSep2 = ",\n  ";
54175     zEnd = "\n)";
54176   }
54177   n += 35 + 6*p->nCol;
54178   zStmt = sqlite3_malloc( n );
54179   if( zStmt==0 ){
54180     db->mallocFailed = 1;
54181     return 0;
54182   }
54183   sqlite3_snprintf(n, zStmt,
54184                   !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
54185   k = strlen(zStmt);
54186   identPut(zStmt, &k, p->zName);
54187   zStmt[k++] = '(';
54188   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
54189     sqlite3_snprintf(n-k, &zStmt[k], zSep);
54190     k += strlen(&zStmt[k]);
54191     zSep = zSep2;
54192     identPut(zStmt, &k, pCol->zName);
54193     if( (z = pCol->zType)!=0 ){
54194       zStmt[k++] = ' ';
54195       assert( strlen(z)+k+1<=n );
54196       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
54197       k += strlen(z);
54198     }
54199   }
54200   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
54201   return zStmt;
54202 }
54203
54204 /*
54205 ** This routine is called to report the final ")" that terminates
54206 ** a CREATE TABLE statement.
54207 **
54208 ** The table structure that other action routines have been building
54209 ** is added to the internal hash tables, assuming no errors have
54210 ** occurred.
54211 **
54212 ** An entry for the table is made in the master table on disk, unless
54213 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
54214 ** it means we are reading the sqlite_master table because we just
54215 ** connected to the database or because the sqlite_master table has
54216 ** recently changed, so the entry for this table already exists in
54217 ** the sqlite_master table.  We do not want to create it again.
54218 **
54219 ** If the pSelect argument is not NULL, it means that this routine
54220 ** was called to create a table generated from a 
54221 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
54222 ** the new table will match the result set of the SELECT.
54223 */
54224 SQLITE_PRIVATE void sqlite3EndTable(
54225   Parse *pParse,          /* Parse context */
54226   Token *pCons,           /* The ',' token after the last column defn. */
54227   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
54228   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
54229 ){
54230   Table *p;
54231   sqlite3 *db = pParse->db;
54232   int iDb;
54233
54234   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
54235     return;
54236   }
54237   p = pParse->pNewTable;
54238   if( p==0 ) return;
54239
54240   assert( !db->init.busy || !pSelect );
54241
54242   iDb = sqlite3SchemaToIndex(db, p->pSchema);
54243
54244 #ifndef SQLITE_OMIT_CHECK
54245   /* Resolve names in all CHECK constraint expressions.
54246   */
54247   if( p->pCheck ){
54248     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
54249     NameContext sNC;                /* Name context for pParse->pNewTable */
54250
54251     memset(&sNC, 0, sizeof(sNC));
54252     memset(&sSrc, 0, sizeof(sSrc));
54253     sSrc.nSrc = 1;
54254     sSrc.a[0].zName = p->zName;
54255     sSrc.a[0].pTab = p;
54256     sSrc.a[0].iCursor = -1;
54257     sNC.pParse = pParse;
54258     sNC.pSrcList = &sSrc;
54259     sNC.isCheck = 1;
54260     if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
54261       return;
54262     }
54263   }
54264 #endif /* !defined(SQLITE_OMIT_CHECK) */
54265
54266   /* If the db->init.busy is 1 it means we are reading the SQL off the
54267   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
54268   ** So do not write to the disk again.  Extract the root page number
54269   ** for the table from the db->init.newTnum field.  (The page number
54270   ** should have been put there by the sqliteOpenCb routine.)
54271   */
54272   if( db->init.busy ){
54273     p->tnum = db->init.newTnum;
54274   }
54275
54276   /* If not initializing, then create a record for the new table
54277   ** in the SQLITE_MASTER table of the database.  The record number
54278   ** for the new table entry should already be on the stack.
54279   **
54280   ** If this is a TEMPORARY table, write the entry into the auxiliary
54281   ** file instead of into the main database file.
54282   */
54283   if( !db->init.busy ){
54284     int n;
54285     Vdbe *v;
54286     char *zType;    /* "view" or "table" */
54287     char *zType2;   /* "VIEW" or "TABLE" */
54288     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
54289
54290     v = sqlite3GetVdbe(pParse);
54291     if( v==0 ) return;
54292
54293     sqlite3VdbeAddOp1(v, OP_Close, 0);
54294
54295     /* Create the rootpage for the new table and push it onto the stack.
54296     ** A view has no rootpage, so just push a zero onto the stack for
54297     ** views.  Initialize zType at the same time.
54298     */
54299     if( p->pSelect==0 ){
54300       /* A regular table */
54301       zType = "table";
54302       zType2 = "TABLE";
54303 #ifndef SQLITE_OMIT_VIEW
54304     }else{
54305       /* A view */
54306       zType = "view";
54307       zType2 = "VIEW";
54308 #endif
54309     }
54310
54311     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
54312     ** statement to populate the new table. The root-page number for the
54313     ** new table is on the top of the vdbe stack.
54314     **
54315     ** Once the SELECT has been coded by sqlite3Select(), it is in a
54316     ** suitable state to query for the column names and types to be used
54317     ** by the new table.
54318     **
54319     ** A shared-cache write-lock is not required to write to the new table,
54320     ** as a schema-lock must have already been obtained to create it. Since
54321     ** a schema-lock excludes all other database users, the write-lock would
54322     ** be redundant.
54323     */
54324     if( pSelect ){
54325       SelectDest dest;
54326       Table *pSelTab;
54327
54328       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
54329       sqlite3VdbeChangeP5(v, 1);
54330       pParse->nTab = 2;
54331       sqlite3SelectDestInit(&dest, SRT_Table, 1);
54332       sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
54333       sqlite3VdbeAddOp1(v, OP_Close, 1);
54334       if( pParse->nErr==0 ){
54335         pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
54336         if( pSelTab==0 ) return;
54337         assert( p->aCol==0 );
54338         p->nCol = pSelTab->nCol;
54339         p->aCol = pSelTab->aCol;
54340         pSelTab->nCol = 0;
54341         pSelTab->aCol = 0;
54342         sqlite3DeleteTable(pSelTab);
54343       }
54344     }
54345
54346     /* Compute the complete text of the CREATE statement */
54347     if( pSelect ){
54348       zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
54349     }else{
54350       n = pEnd->z - pParse->sNameToken.z + 1;
54351       zStmt = sqlite3MPrintf(db, 
54352           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
54353       );
54354     }
54355
54356     /* A slot for the record has already been allocated in the 
54357     ** SQLITE_MASTER table.  We just need to update that slot with all
54358     ** the information we've collected.  The rowid for the preallocated
54359     ** slot is the 2nd item on the stack.  The top of the stack is the
54360     ** root page for the new table (or a 0 if this is a view).
54361     */
54362     sqlite3NestedParse(pParse,
54363       "UPDATE %Q.%s "
54364          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
54365        "WHERE rowid=#%d",
54366       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
54367       zType,
54368       p->zName,
54369       p->zName,
54370       pParse->regRoot,
54371       zStmt,
54372       pParse->regRowid
54373     );
54374     sqlite3_free(zStmt);
54375     sqlite3ChangeCookie(pParse, iDb);
54376
54377 #ifndef SQLITE_OMIT_AUTOINCREMENT
54378     /* Check to see if we need to create an sqlite_sequence table for
54379     ** keeping track of autoincrement keys.
54380     */
54381     if( p->autoInc ){
54382       Db *pDb = &db->aDb[iDb];
54383       if( pDb->pSchema->pSeqTab==0 ){
54384         sqlite3NestedParse(pParse,
54385           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
54386           pDb->zName
54387         );
54388       }
54389     }
54390 #endif
54391
54392     /* Reparse everything to update our internal data structures */
54393     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
54394         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
54395   }
54396
54397
54398   /* Add the table to the in-memory representation of the database.
54399   */
54400   if( db->init.busy && pParse->nErr==0 ){
54401     Table *pOld;
54402     FKey *pFKey; 
54403     Schema *pSchema = p->pSchema;
54404     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
54405     if( pOld ){
54406       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
54407       db->mallocFailed = 1;
54408       return;
54409     }
54410 #ifndef SQLITE_OMIT_FOREIGN_KEY
54411     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
54412       void *data;
54413       int nTo = strlen(pFKey->zTo) + 1;
54414       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
54415       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
54416       if( data==(void *)pFKey ){
54417         db->mallocFailed = 1;
54418       }
54419     }
54420 #endif
54421     pParse->pNewTable = 0;
54422     db->nTable++;
54423     db->flags |= SQLITE_InternChanges;
54424
54425 #ifndef SQLITE_OMIT_ALTERTABLE
54426     if( !p->pSelect ){
54427       const char *zName = (const char *)pParse->sNameToken.z;
54428       int nName;
54429       assert( !pSelect && pCons && pEnd );
54430       if( pCons->z==0 ){
54431         pCons = pEnd;
54432       }
54433       nName = (const char *)pCons->z - zName;
54434       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
54435     }
54436 #endif
54437   }
54438 }
54439
54440 #ifndef SQLITE_OMIT_VIEW
54441 /*
54442 ** The parser calls this routine in order to create a new VIEW
54443 */
54444 SQLITE_PRIVATE void sqlite3CreateView(
54445   Parse *pParse,     /* The parsing context */
54446   Token *pBegin,     /* The CREATE token that begins the statement */
54447   Token *pName1,     /* The token that holds the name of the view */
54448   Token *pName2,     /* The token that holds the name of the view */
54449   Select *pSelect,   /* A SELECT statement that will become the new view */
54450   int isTemp,        /* TRUE for a TEMPORARY view */
54451   int noErr          /* Suppress error messages if VIEW already exists */
54452 ){
54453   Table *p;
54454   int n;
54455   const unsigned char *z;
54456   Token sEnd;
54457   DbFixer sFix;
54458   Token *pName;
54459   int iDb;
54460   sqlite3 *db = pParse->db;
54461
54462   if( pParse->nVar>0 ){
54463     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
54464     sqlite3SelectDelete(pSelect);
54465     return;
54466   }
54467   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
54468   p = pParse->pNewTable;
54469   if( p==0 || pParse->nErr ){
54470     sqlite3SelectDelete(pSelect);
54471     return;
54472   }
54473   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
54474   iDb = sqlite3SchemaToIndex(db, p->pSchema);
54475   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
54476     && sqlite3FixSelect(&sFix, pSelect)
54477   ){
54478     sqlite3SelectDelete(pSelect);
54479     return;
54480   }
54481
54482   /* Make a copy of the entire SELECT statement that defines the view.
54483   ** This will force all the Expr.token.z values to be dynamically
54484   ** allocated rather than point to the input string - which means that
54485   ** they will persist after the current sqlite3_exec() call returns.
54486   */
54487   p->pSelect = sqlite3SelectDup(db, pSelect);
54488   sqlite3SelectDelete(pSelect);
54489   if( db->mallocFailed ){
54490     return;
54491   }
54492   if( !db->init.busy ){
54493     sqlite3ViewGetColumnNames(pParse, p);
54494   }
54495
54496   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
54497   ** the end.
54498   */
54499   sEnd = pParse->sLastToken;
54500   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
54501     sEnd.z += sEnd.n;
54502   }
54503   sEnd.n = 0;
54504   n = sEnd.z - pBegin->z;
54505   z = (const unsigned char*)pBegin->z;
54506   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
54507   sEnd.z = &z[n-1];
54508   sEnd.n = 1;
54509
54510   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
54511   sqlite3EndTable(pParse, 0, &sEnd, 0);
54512   return;
54513 }
54514 #endif /* SQLITE_OMIT_VIEW */
54515
54516 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
54517 /*
54518 ** The Table structure pTable is really a VIEW.  Fill in the names of
54519 ** the columns of the view in the pTable structure.  Return the number
54520 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
54521 */
54522 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
54523   Table *pSelTab;   /* A fake table from which we get the result set */
54524   Select *pSel;     /* Copy of the SELECT that implements the view */
54525   int nErr = 0;     /* Number of errors encountered */
54526   int n;            /* Temporarily holds the number of cursors assigned */
54527   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
54528   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
54529
54530   assert( pTable );
54531
54532 #ifndef SQLITE_OMIT_VIRTUALTABLE
54533   if( sqlite3VtabCallConnect(pParse, pTable) ){
54534     return SQLITE_ERROR;
54535   }
54536   if( IsVirtual(pTable) ) return 0;
54537 #endif
54538
54539 #ifndef SQLITE_OMIT_VIEW
54540   /* A positive nCol means the columns names for this view are
54541   ** already known.
54542   */
54543   if( pTable->nCol>0 ) return 0;
54544
54545   /* A negative nCol is a special marker meaning that we are currently
54546   ** trying to compute the column names.  If we enter this routine with
54547   ** a negative nCol, it means two or more views form a loop, like this:
54548   **
54549   **     CREATE VIEW one AS SELECT * FROM two;
54550   **     CREATE VIEW two AS SELECT * FROM one;
54551   **
54552   ** Actually, this error is caught previously and so the following test
54553   ** should always fail.  But we will leave it in place just to be safe.
54554   */
54555   if( pTable->nCol<0 ){
54556     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
54557     return 1;
54558   }
54559   assert( pTable->nCol>=0 );
54560
54561   /* If we get this far, it means we need to compute the table names.
54562   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
54563   ** "*" elements in the results set of the view and will assign cursors
54564   ** to the elements of the FROM clause.  But we do not want these changes
54565   ** to be permanent.  So the computation is done on a copy of the SELECT
54566   ** statement that defines the view.
54567   */
54568   assert( pTable->pSelect );
54569   pSel = sqlite3SelectDup(db, pTable->pSelect);
54570   if( pSel ){
54571     n = pParse->nTab;
54572     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
54573     pTable->nCol = -1;
54574 #ifndef SQLITE_OMIT_AUTHORIZATION
54575     xAuth = db->xAuth;
54576     db->xAuth = 0;
54577     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
54578     db->xAuth = xAuth;
54579 #else
54580     pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
54581 #endif
54582     pParse->nTab = n;
54583     if( pSelTab ){
54584       assert( pTable->aCol==0 );
54585       pTable->nCol = pSelTab->nCol;
54586       pTable->aCol = pSelTab->aCol;
54587       pSelTab->nCol = 0;
54588       pSelTab->aCol = 0;
54589       sqlite3DeleteTable(pSelTab);
54590       pTable->pSchema->flags |= DB_UnresetViews;
54591     }else{
54592       pTable->nCol = 0;
54593       nErr++;
54594     }
54595     sqlite3SelectDelete(pSel);
54596   } else {
54597     nErr++;
54598   }
54599 #endif /* SQLITE_OMIT_VIEW */
54600   return nErr;  
54601 }
54602 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
54603
54604 #ifndef SQLITE_OMIT_VIEW
54605 /*
54606 ** Clear the column names from every VIEW in database idx.
54607 */
54608 static void sqliteViewResetAll(sqlite3 *db, int idx){
54609   HashElem *i;
54610   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
54611   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
54612     Table *pTab = sqliteHashData(i);
54613     if( pTab->pSelect ){
54614       sqliteResetColumnNames(pTab);
54615     }
54616   }
54617   DbClearProperty(db, idx, DB_UnresetViews);
54618 }
54619 #else
54620 # define sqliteViewResetAll(A,B)
54621 #endif /* SQLITE_OMIT_VIEW */
54622
54623 /*
54624 ** This function is called by the VDBE to adjust the internal schema
54625 ** used by SQLite when the btree layer moves a table root page. The
54626 ** root-page of a table or index in database iDb has changed from iFrom
54627 ** to iTo.
54628 **
54629 ** Ticket #1728:  The symbol table might still contain information
54630 ** on tables and/or indices that are the process of being deleted.
54631 ** If you are unlucky, one of those deleted indices or tables might
54632 ** have the same rootpage number as the real table or index that is
54633 ** being moved.  So we cannot stop searching after the first match 
54634 ** because the first match might be for one of the deleted indices
54635 ** or tables and not the table/index that is actually being moved.
54636 ** We must continue looping until all tables and indices with
54637 ** rootpage==iFrom have been converted to have a rootpage of iTo
54638 ** in order to be certain that we got the right one.
54639 */
54640 #ifndef SQLITE_OMIT_AUTOVACUUM
54641 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
54642   HashElem *pElem;
54643   Hash *pHash;
54644
54645   pHash = &pDb->pSchema->tblHash;
54646   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
54647     Table *pTab = sqliteHashData(pElem);
54648     if( pTab->tnum==iFrom ){
54649       pTab->tnum = iTo;
54650     }
54651   }
54652   pHash = &pDb->pSchema->idxHash;
54653   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
54654     Index *pIdx = sqliteHashData(pElem);
54655     if( pIdx->tnum==iFrom ){
54656       pIdx->tnum = iTo;
54657     }
54658   }
54659 }
54660 #endif
54661
54662 /*
54663 ** Write code to erase the table with root-page iTable from database iDb.
54664 ** Also write code to modify the sqlite_master table and internal schema
54665 ** if a root-page of another table is moved by the btree-layer whilst
54666 ** erasing iTable (this can happen with an auto-vacuum database).
54667 */ 
54668 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
54669   Vdbe *v = sqlite3GetVdbe(pParse);
54670   int r1 = sqlite3GetTempReg(pParse);
54671   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
54672 #ifndef SQLITE_OMIT_AUTOVACUUM
54673   /* OP_Destroy stores an in integer r1. If this integer
54674   ** is non-zero, then it is the root page number of a table moved to
54675   ** location iTable. The following code modifies the sqlite_master table to
54676   ** reflect this.
54677   **
54678   ** The "#%d" in the SQL is a special constant that means whatever value
54679   ** is on the top of the stack.  See sqlite3RegisterExpr().
54680   */
54681   sqlite3NestedParse(pParse, 
54682      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
54683      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
54684 #endif
54685   sqlite3ReleaseTempReg(pParse, r1);
54686 }
54687
54688 /*
54689 ** Write VDBE code to erase table pTab and all associated indices on disk.
54690 ** Code to update the sqlite_master tables and internal schema definitions
54691 ** in case a root-page belonging to another table is moved by the btree layer
54692 ** is also added (this can happen with an auto-vacuum database).
54693 */
54694 static void destroyTable(Parse *pParse, Table *pTab){
54695 #ifdef SQLITE_OMIT_AUTOVACUUM
54696   Index *pIdx;
54697   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
54698   destroyRootPage(pParse, pTab->tnum, iDb);
54699   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
54700     destroyRootPage(pParse, pIdx->tnum, iDb);
54701   }
54702 #else
54703   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
54704   ** is not defined), then it is important to call OP_Destroy on the
54705   ** table and index root-pages in order, starting with the numerically 
54706   ** largest root-page number. This guarantees that none of the root-pages
54707   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
54708   ** following were coded:
54709   **
54710   ** OP_Destroy 4 0
54711   ** ...
54712   ** OP_Destroy 5 0
54713   **
54714   ** and root page 5 happened to be the largest root-page number in the
54715   ** database, then root page 5 would be moved to page 4 by the 
54716   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
54717   ** a free-list page.
54718   */
54719   int iTab = pTab->tnum;
54720   int iDestroyed = 0;
54721
54722   while( 1 ){
54723     Index *pIdx;
54724     int iLargest = 0;
54725
54726     if( iDestroyed==0 || iTab<iDestroyed ){
54727       iLargest = iTab;
54728     }
54729     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
54730       int iIdx = pIdx->tnum;
54731       assert( pIdx->pSchema==pTab->pSchema );
54732       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
54733         iLargest = iIdx;
54734       }
54735     }
54736     if( iLargest==0 ){
54737       return;
54738     }else{
54739       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
54740       destroyRootPage(pParse, iLargest, iDb);
54741       iDestroyed = iLargest;
54742     }
54743   }
54744 #endif
54745 }
54746
54747 /*
54748 ** This routine is called to do the work of a DROP TABLE statement.
54749 ** pName is the name of the table to be dropped.
54750 */
54751 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
54752   Table *pTab;
54753   Vdbe *v;
54754   sqlite3 *db = pParse->db;
54755   int iDb;
54756
54757   if( pParse->nErr || db->mallocFailed ){
54758     goto exit_drop_table;
54759   }
54760   assert( pName->nSrc==1 );
54761   pTab = sqlite3LocateTable(pParse, isView, 
54762                             pName->a[0].zName, pName->a[0].zDatabase);
54763
54764   if( pTab==0 ){
54765     if( noErr ){
54766       sqlite3ErrorClear(pParse);
54767     }
54768     goto exit_drop_table;
54769   }
54770   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
54771   assert( iDb>=0 && iDb<db->nDb );
54772
54773   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
54774   ** it is initialized.
54775   */
54776   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
54777     goto exit_drop_table;
54778   }
54779 #ifndef SQLITE_OMIT_AUTHORIZATION
54780   {
54781     int code;
54782     const char *zTab = SCHEMA_TABLE(iDb);
54783     const char *zDb = db->aDb[iDb].zName;
54784     const char *zArg2 = 0;
54785     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
54786       goto exit_drop_table;
54787     }
54788     if( isView ){
54789       if( !OMIT_TEMPDB && iDb==1 ){
54790         code = SQLITE_DROP_TEMP_VIEW;
54791       }else{
54792         code = SQLITE_DROP_VIEW;
54793       }
54794 #ifndef SQLITE_OMIT_VIRTUALTABLE
54795     }else if( IsVirtual(pTab) ){
54796       code = SQLITE_DROP_VTABLE;
54797       zArg2 = pTab->pMod->zName;
54798 #endif
54799     }else{
54800       if( !OMIT_TEMPDB && iDb==1 ){
54801         code = SQLITE_DROP_TEMP_TABLE;
54802       }else{
54803         code = SQLITE_DROP_TABLE;
54804       }
54805     }
54806     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
54807       goto exit_drop_table;
54808     }
54809     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
54810       goto exit_drop_table;
54811     }
54812   }
54813 #endif
54814   if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
54815     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
54816     goto exit_drop_table;
54817   }
54818
54819 #ifndef SQLITE_OMIT_VIEW
54820   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
54821   ** on a table.
54822   */
54823   if( isView && pTab->pSelect==0 ){
54824     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
54825     goto exit_drop_table;
54826   }
54827   if( !isView && pTab->pSelect ){
54828     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
54829     goto exit_drop_table;
54830   }
54831 #endif
54832
54833   /* Generate code to remove the table from the master table
54834   ** on disk.
54835   */
54836   v = sqlite3GetVdbe(pParse);
54837   if( v ){
54838     Trigger *pTrigger;
54839     Db *pDb = &db->aDb[iDb];
54840     sqlite3BeginWriteOperation(pParse, 1, iDb);
54841
54842 #ifndef SQLITE_OMIT_VIRTUALTABLE
54843     if( IsVirtual(pTab) ){
54844       Vdbe *v = sqlite3GetVdbe(pParse);
54845       if( v ){
54846         sqlite3VdbeAddOp0(v, OP_VBegin);
54847       }
54848     }
54849 #endif
54850
54851     /* Drop all triggers associated with the table being dropped. Code
54852     ** is generated to remove entries from sqlite_master and/or
54853     ** sqlite_temp_master if required.
54854     */
54855     pTrigger = pTab->pTrigger;
54856     while( pTrigger ){
54857       assert( pTrigger->pSchema==pTab->pSchema || 
54858           pTrigger->pSchema==db->aDb[1].pSchema );
54859       sqlite3DropTriggerPtr(pParse, pTrigger);
54860       pTrigger = pTrigger->pNext;
54861     }
54862
54863 #ifndef SQLITE_OMIT_AUTOINCREMENT
54864     /* Remove any entries of the sqlite_sequence table associated with
54865     ** the table being dropped. This is done before the table is dropped
54866     ** at the btree level, in case the sqlite_sequence table needs to
54867     ** move as a result of the drop (can happen in auto-vacuum mode).
54868     */
54869     if( pTab->autoInc ){
54870       sqlite3NestedParse(pParse,
54871         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
54872         pDb->zName, pTab->zName
54873       );
54874     }
54875 #endif
54876
54877     /* Drop all SQLITE_MASTER table and index entries that refer to the
54878     ** table. The program name loops through the master table and deletes
54879     ** every row that refers to a table of the same name as the one being
54880     ** dropped. Triggers are handled seperately because a trigger can be
54881     ** created in the temp database that refers to a table in another
54882     ** database.
54883     */
54884     sqlite3NestedParse(pParse, 
54885         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
54886         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
54887
54888     /* Drop any statistics from the sqlite_stat1 table, if it exists */
54889     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
54890       sqlite3NestedParse(pParse,
54891         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
54892       );
54893     }
54894
54895     if( !isView && !IsVirtual(pTab) ){
54896       destroyTable(pParse, pTab);
54897     }
54898
54899     /* Remove the table entry from SQLite's internal schema and modify
54900     ** the schema cookie.
54901     */
54902     if( IsVirtual(pTab) ){
54903       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
54904     }
54905     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
54906     sqlite3ChangeCookie(pParse, iDb);
54907   }
54908   sqliteViewResetAll(db, iDb);
54909
54910 exit_drop_table:
54911   sqlite3SrcListDelete(pName);
54912 }
54913
54914 /*
54915 ** This routine is called to create a new foreign key on the table
54916 ** currently under construction.  pFromCol determines which columns
54917 ** in the current table point to the foreign key.  If pFromCol==0 then
54918 ** connect the key to the last column inserted.  pTo is the name of
54919 ** the table referred to.  pToCol is a list of tables in the other
54920 ** pTo table that the foreign key points to.  flags contains all
54921 ** information about the conflict resolution algorithms specified
54922 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
54923 **
54924 ** An FKey structure is created and added to the table currently
54925 ** under construction in the pParse->pNewTable field.  The new FKey
54926 ** is not linked into db->aFKey at this point - that does not happen
54927 ** until sqlite3EndTable().
54928 **
54929 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
54930 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
54931 */
54932 SQLITE_PRIVATE void sqlite3CreateForeignKey(
54933   Parse *pParse,       /* Parsing context */
54934   ExprList *pFromCol,  /* Columns in this table that point to other table */
54935   Token *pTo,          /* Name of the other table */
54936   ExprList *pToCol,    /* Columns in the other table */
54937   int flags            /* Conflict resolution algorithms. */
54938 ){
54939 #ifndef SQLITE_OMIT_FOREIGN_KEY
54940   FKey *pFKey = 0;
54941   Table *p = pParse->pNewTable;
54942   int nByte;
54943   int i;
54944   int nCol;
54945   char *z;
54946
54947   assert( pTo!=0 );
54948   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
54949   if( pFromCol==0 ){
54950     int iCol = p->nCol-1;
54951     if( iCol<0 ) goto fk_end;
54952     if( pToCol && pToCol->nExpr!=1 ){
54953       sqlite3ErrorMsg(pParse, "foreign key on %s"
54954          " should reference only one column of table %T",
54955          p->aCol[iCol].zName, pTo);
54956       goto fk_end;
54957     }
54958     nCol = 1;
54959   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
54960     sqlite3ErrorMsg(pParse,
54961         "number of columns in foreign key does not match the number of "
54962         "columns in the referenced table");
54963     goto fk_end;
54964   }else{
54965     nCol = pFromCol->nExpr;
54966   }
54967   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
54968   if( pToCol ){
54969     for(i=0; i<pToCol->nExpr; i++){
54970       nByte += strlen(pToCol->a[i].zName) + 1;
54971     }
54972   }
54973   pFKey = sqlite3DbMallocZero(pParse->db, nByte );
54974   if( pFKey==0 ){
54975     goto fk_end;
54976   }
54977   pFKey->pFrom = p;
54978   pFKey->pNextFrom = p->pFKey;
54979   z = (char*)&pFKey[1];
54980   pFKey->aCol = (struct sColMap*)z;
54981   z += sizeof(struct sColMap)*nCol;
54982   pFKey->zTo = z;
54983   memcpy(z, pTo->z, pTo->n);
54984   z[pTo->n] = 0;
54985   z += pTo->n+1;
54986   pFKey->pNextTo = 0;
54987   pFKey->nCol = nCol;
54988   if( pFromCol==0 ){
54989     pFKey->aCol[0].iFrom = p->nCol-1;
54990   }else{
54991     for(i=0; i<nCol; i++){
54992       int j;
54993       for(j=0; j<p->nCol; j++){
54994         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
54995           pFKey->aCol[i].iFrom = j;
54996           break;
54997         }
54998       }
54999       if( j>=p->nCol ){
55000         sqlite3ErrorMsg(pParse, 
55001           "unknown column \"%s\" in foreign key definition", 
55002           pFromCol->a[i].zName);
55003         goto fk_end;
55004       }
55005     }
55006   }
55007   if( pToCol ){
55008     for(i=0; i<nCol; i++){
55009       int n = strlen(pToCol->a[i].zName);
55010       pFKey->aCol[i].zCol = z;
55011       memcpy(z, pToCol->a[i].zName, n);
55012       z[n] = 0;
55013       z += n+1;
55014     }
55015   }
55016   pFKey->isDeferred = 0;
55017   pFKey->deleteConf = flags & 0xff;
55018   pFKey->updateConf = (flags >> 8 ) & 0xff;
55019   pFKey->insertConf = (flags >> 16 ) & 0xff;
55020
55021   /* Link the foreign key to the table as the last step.
55022   */
55023   p->pFKey = pFKey;
55024   pFKey = 0;
55025
55026 fk_end:
55027   sqlite3_free(pFKey);
55028 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
55029   sqlite3ExprListDelete(pFromCol);
55030   sqlite3ExprListDelete(pToCol);
55031 }
55032
55033 /*
55034 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
55035 ** clause is seen as part of a foreign key definition.  The isDeferred
55036 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
55037 ** The behavior of the most recently created foreign key is adjusted
55038 ** accordingly.
55039 */
55040 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
55041 #ifndef SQLITE_OMIT_FOREIGN_KEY
55042   Table *pTab;
55043   FKey *pFKey;
55044   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
55045   pFKey->isDeferred = isDeferred;
55046 #endif
55047 }
55048
55049 /*
55050 ** Generate code that will erase and refill index *pIdx.  This is
55051 ** used to initialize a newly created index or to recompute the
55052 ** content of an index in response to a REINDEX command.
55053 **
55054 ** if memRootPage is not negative, it means that the index is newly
55055 ** created.  The register specified by memRootPage contains the
55056 ** root page number of the index.  If memRootPage is negative, then
55057 ** the index already exists and must be cleared before being refilled and
55058 ** the root page number of the index is taken from pIndex->tnum.
55059 */
55060 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
55061   Table *pTab = pIndex->pTable;  /* The table that is indexed */
55062   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
55063   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
55064   int addr1;                     /* Address of top of loop */
55065   int tnum;                      /* Root page of index */
55066   Vdbe *v;                       /* Generate code into this virtual machine */
55067   KeyInfo *pKey;                 /* KeyInfo for index */
55068   int regIdxKey;                 /* Registers containing the index key */
55069   int regRecord;                 /* Register holding assemblied index record */
55070   sqlite3 *db = pParse->db;      /* The database connection */
55071   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
55072
55073 #ifndef SQLITE_OMIT_AUTHORIZATION
55074   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
55075       db->aDb[iDb].zName ) ){
55076     return;
55077   }
55078 #endif
55079
55080   /* Require a write-lock on the table to perform this operation */
55081   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
55082
55083   v = sqlite3GetVdbe(pParse);
55084   if( v==0 ) return;
55085   if( memRootPage>=0 ){
55086     tnum = memRootPage;
55087   }else{
55088     tnum = pIndex->tnum;
55089     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
55090   }
55091   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
55092   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
55093                     (char *)pKey, P4_KEYINFO_HANDOFF);
55094   if( memRootPage>=0 ){
55095     sqlite3VdbeChangeP5(v, 1);
55096   }
55097   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
55098   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
55099   regRecord = sqlite3GetTempReg(pParse);
55100   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
55101   if( pIndex->onError!=OE_None ){
55102     int j1, j2;
55103     int regRowid;
55104
55105     regRowid = regIdxKey + pIndex->nColumn;
55106     j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
55107     j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
55108                            0, regRowid, (char*)regRecord, P4_INT32);
55109     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
55110                     "indexed columns are not unique", P4_STATIC);
55111     sqlite3VdbeJumpHere(v, j1);
55112     sqlite3VdbeJumpHere(v, j2);
55113   }
55114   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
55115   sqlite3ReleaseTempReg(pParse, regRecord);
55116   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
55117   sqlite3VdbeJumpHere(v, addr1);
55118   sqlite3VdbeAddOp1(v, OP_Close, iTab);
55119   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
55120 }
55121
55122 /*
55123 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
55124 ** and pTblList is the name of the table that is to be indexed.  Both will 
55125 ** be NULL for a primary key or an index that is created to satisfy a
55126 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
55127 ** as the table to be indexed.  pParse->pNewTable is a table that is
55128 ** currently being constructed by a CREATE TABLE statement.
55129 **
55130 ** pList is a list of columns to be indexed.  pList will be NULL if this
55131 ** is a primary key or unique-constraint on the most recent column added
55132 ** to the table currently under construction.  
55133 */
55134 SQLITE_PRIVATE void sqlite3CreateIndex(
55135   Parse *pParse,     /* All information about this parse */
55136   Token *pName1,     /* First part of index name. May be NULL */
55137   Token *pName2,     /* Second part of index name. May be NULL */
55138   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
55139   ExprList *pList,   /* A list of columns to be indexed */
55140   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
55141   Token *pStart,     /* The CREATE token that begins this statement */
55142   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
55143   int sortOrder,     /* Sort order of primary key when pList==NULL */
55144   int ifNotExist     /* Omit error if index already exists */
55145 ){
55146   Table *pTab = 0;     /* Table to be indexed */
55147   Index *pIndex = 0;   /* The index to be created */
55148   char *zName = 0;     /* Name of the index */
55149   int nName;           /* Number of characters in zName */
55150   int i, j;
55151   Token nullId;        /* Fake token for an empty ID list */
55152   DbFixer sFix;        /* For assigning database names to pTable */
55153   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
55154   sqlite3 *db = pParse->db;
55155   Db *pDb;             /* The specific table containing the indexed database */
55156   int iDb;             /* Index of the database that is being written */
55157   Token *pName = 0;    /* Unqualified name of the index to create */
55158   struct ExprList_item *pListItem; /* For looping over pList */
55159   int nCol;
55160   int nExtra = 0;
55161   char *zExtra;
55162
55163   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
55164     goto exit_create_index;
55165   }
55166
55167   /*
55168   ** Find the table that is to be indexed.  Return early if not found.
55169   */
55170   if( pTblName!=0 ){
55171
55172     /* Use the two-part index name to determine the database 
55173     ** to search for the table. 'Fix' the table name to this db
55174     ** before looking up the table.
55175     */
55176     assert( pName1 && pName2 );
55177     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
55178     if( iDb<0 ) goto exit_create_index;
55179
55180 #ifndef SQLITE_OMIT_TEMPDB
55181     /* If the index name was unqualified, check if the the table
55182     ** is a temp table. If so, set the database to 1. Do not do this
55183     ** if initialising a database schema.
55184     */
55185     if( !db->init.busy ){
55186       pTab = sqlite3SrcListLookup(pParse, pTblName);
55187       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
55188         iDb = 1;
55189       }
55190     }
55191 #endif
55192
55193     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
55194         sqlite3FixSrcList(&sFix, pTblName)
55195     ){
55196       /* Because the parser constructs pTblName from a single identifier,
55197       ** sqlite3FixSrcList can never fail. */
55198       assert(0);
55199     }
55200     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
55201         pTblName->a[0].zDatabase);
55202     if( !pTab ) goto exit_create_index;
55203     assert( db->aDb[iDb].pSchema==pTab->pSchema );
55204   }else{
55205     assert( pName==0 );
55206     pTab = pParse->pNewTable;
55207     if( !pTab ) goto exit_create_index;
55208     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
55209   }
55210   pDb = &db->aDb[iDb];
55211
55212   if( pTab==0 || pParse->nErr ) goto exit_create_index;
55213   if( pTab->readOnly ){
55214     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
55215     goto exit_create_index;
55216   }
55217 #ifndef SQLITE_OMIT_VIEW
55218   if( pTab->pSelect ){
55219     sqlite3ErrorMsg(pParse, "views may not be indexed");
55220     goto exit_create_index;
55221   }
55222 #endif
55223 #ifndef SQLITE_OMIT_VIRTUALTABLE
55224   if( IsVirtual(pTab) ){
55225     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
55226     goto exit_create_index;
55227   }
55228 #endif
55229
55230   /*
55231   ** Find the name of the index.  Make sure there is not already another
55232   ** index or table with the same name.  
55233   **
55234   ** Exception:  If we are reading the names of permanent indices from the
55235   ** sqlite_master table (because some other process changed the schema) and
55236   ** one of the index names collides with the name of a temporary table or
55237   ** index, then we will continue to process this index.
55238   **
55239   ** If pName==0 it means that we are
55240   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
55241   ** own name.
55242   */
55243   if( pName ){
55244     zName = sqlite3NameFromToken(db, pName);
55245     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
55246     if( zName==0 ) goto exit_create_index;
55247     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
55248       goto exit_create_index;
55249     }
55250     if( !db->init.busy ){
55251       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
55252       if( sqlite3FindTable(db, zName, 0)!=0 ){
55253         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
55254         goto exit_create_index;
55255       }
55256     }
55257     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
55258       if( !ifNotExist ){
55259         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
55260       }
55261       goto exit_create_index;
55262     }
55263   }else{
55264     char zBuf[30];
55265     int n;
55266     Index *pLoop;
55267     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
55268     sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n);
55269     zName = 0;
55270     sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
55271     if( zName==0 ){
55272       db->mallocFailed = 1;
55273       goto exit_create_index;
55274     }
55275   }
55276
55277   /* Check for authorization to create an index.
55278   */
55279 #ifndef SQLITE_OMIT_AUTHORIZATION
55280   {
55281     const char *zDb = pDb->zName;
55282     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
55283       goto exit_create_index;
55284     }
55285     i = SQLITE_CREATE_INDEX;
55286     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
55287     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
55288       goto exit_create_index;
55289     }
55290   }
55291 #endif
55292
55293   /* If pList==0, it means this routine was called to make a primary
55294   ** key out of the last column added to the table under construction.
55295   ** So create a fake list to simulate this.
55296   */
55297   if( pList==0 ){
55298     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
55299     nullId.n = strlen((char*)nullId.z);
55300     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
55301     if( pList==0 ) goto exit_create_index;
55302     pList->a[0].sortOrder = sortOrder;
55303   }
55304
55305   /* Figure out how many bytes of space are required to store explicitly
55306   ** specified collation sequence names.
55307   */
55308   for(i=0; i<pList->nExpr; i++){
55309     Expr *pExpr = pList->a[i].pExpr;
55310     if( pExpr ){
55311       nExtra += (1 + strlen(pExpr->pColl->zName));
55312     }
55313   }
55314
55315   /* 
55316   ** Allocate the index structure. 
55317   */
55318   nName = strlen(zName);
55319   nCol = pList->nExpr;
55320   pIndex = sqlite3DbMallocZero(db, 
55321       sizeof(Index) +              /* Index structure  */
55322       sizeof(int)*nCol +           /* Index.aiColumn   */
55323       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
55324       sizeof(char *)*nCol +        /* Index.azColl     */
55325       sizeof(u8)*nCol +            /* Index.aSortOrder */
55326       nName + 1 +                  /* Index.zName      */
55327       nExtra                       /* Collation sequence names */
55328   );
55329   if( db->mallocFailed ){
55330     goto exit_create_index;
55331   }
55332   pIndex->azColl = (char**)(&pIndex[1]);
55333   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
55334   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
55335   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
55336   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
55337   zExtra = (char *)(&pIndex->zName[nName+1]);
55338   memcpy(pIndex->zName, zName, nName+1);
55339   pIndex->pTable = pTab;
55340   pIndex->nColumn = pList->nExpr;
55341   pIndex->onError = onError;
55342   pIndex->autoIndex = pName==0;
55343   pIndex->pSchema = db->aDb[iDb].pSchema;
55344
55345   /* Check to see if we should honor DESC requests on index columns
55346   */
55347   if( pDb->pSchema->file_format>=4 ){
55348     sortOrderMask = -1;   /* Honor DESC */
55349   }else{
55350     sortOrderMask = 0;    /* Ignore DESC */
55351   }
55352
55353   /* Scan the names of the columns of the table to be indexed and
55354   ** load the column indices into the Index structure.  Report an error
55355   ** if any column is not found.
55356   */
55357   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
55358     const char *zColName = pListItem->zName;
55359     Column *pTabCol;
55360     int requestedSortOrder;
55361     char *zColl;                   /* Collation sequence name */
55362
55363     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
55364       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
55365     }
55366     if( j>=pTab->nCol ){
55367       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
55368         pTab->zName, zColName);
55369       goto exit_create_index;
55370     }
55371     /* TODO:  Add a test to make sure that the same column is not named
55372     ** more than once within the same index.  Only the first instance of
55373     ** the column will ever be used by the optimizer.  Note that using the
55374     ** same column more than once cannot be an error because that would 
55375     ** break backwards compatibility - it needs to be a warning.
55376     */
55377     pIndex->aiColumn[i] = j;
55378     if( pListItem->pExpr ){
55379       assert( pListItem->pExpr->pColl );
55380       zColl = zExtra;
55381       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
55382       zExtra += (strlen(zColl) + 1);
55383     }else{
55384       zColl = pTab->aCol[j].zColl;
55385       if( !zColl ){
55386         zColl = db->pDfltColl->zName;
55387       }
55388     }
55389     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
55390       goto exit_create_index;
55391     }
55392     pIndex->azColl[i] = zColl;
55393     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
55394     pIndex->aSortOrder[i] = requestedSortOrder;
55395   }
55396   sqlite3DefaultRowEst(pIndex);
55397
55398   if( pTab==pParse->pNewTable ){
55399     /* This routine has been called to create an automatic index as a
55400     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
55401     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
55402     ** i.e. one of:
55403     **
55404     ** CREATE TABLE t(x PRIMARY KEY, y);
55405     ** CREATE TABLE t(x, y, UNIQUE(x, y));
55406     **
55407     ** Either way, check to see if the table already has such an index. If
55408     ** so, don't bother creating this one. This only applies to
55409     ** automatically created indices. Users can do as they wish with
55410     ** explicit indices.
55411     */
55412     Index *pIdx;
55413     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
55414       int k;
55415       assert( pIdx->onError!=OE_None );
55416       assert( pIdx->autoIndex );
55417       assert( pIndex->onError!=OE_None );
55418
55419       if( pIdx->nColumn!=pIndex->nColumn ) continue;
55420       for(k=0; k<pIdx->nColumn; k++){
55421         const char *z1 = pIdx->azColl[k];
55422         const char *z2 = pIndex->azColl[k];
55423         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
55424         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
55425         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
55426       }
55427       if( k==pIdx->nColumn ){
55428         if( pIdx->onError!=pIndex->onError ){
55429           /* This constraint creates the same index as a previous
55430           ** constraint specified somewhere in the CREATE TABLE statement.
55431           ** However the ON CONFLICT clauses are different. If both this 
55432           ** constraint and the previous equivalent constraint have explicit
55433           ** ON CONFLICT clauses this is an error. Otherwise, use the
55434           ** explicitly specified behaviour for the index.
55435           */
55436           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
55437             sqlite3ErrorMsg(pParse, 
55438                 "conflicting ON CONFLICT clauses specified", 0);
55439           }
55440           if( pIdx->onError==OE_Default ){
55441             pIdx->onError = pIndex->onError;
55442           }
55443         }
55444         goto exit_create_index;
55445       }
55446     }
55447   }
55448
55449   /* Link the new Index structure to its table and to the other
55450   ** in-memory database structures. 
55451   */
55452   if( db->init.busy ){
55453     Index *p;
55454     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
55455                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
55456     if( p ){
55457       assert( p==pIndex );  /* Malloc must have failed */
55458       db->mallocFailed = 1;
55459       goto exit_create_index;
55460     }
55461     db->flags |= SQLITE_InternChanges;
55462     if( pTblName!=0 ){
55463       pIndex->tnum = db->init.newTnum;
55464     }
55465   }
55466
55467   /* If the db->init.busy is 0 then create the index on disk.  This
55468   ** involves writing the index into the master table and filling in the
55469   ** index with the current table contents.
55470   **
55471   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
55472   ** command.  db->init.busy is 1 when a database is opened and 
55473   ** CREATE INDEX statements are read out of the master table.  In
55474   ** the latter case the index already exists on disk, which is why
55475   ** we don't want to recreate it.
55476   **
55477   ** If pTblName==0 it means this index is generated as a primary key
55478   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
55479   ** has just been created, it contains no data and the index initialization
55480   ** step can be skipped.
55481   */
55482   else if( db->init.busy==0 ){
55483     Vdbe *v;
55484     char *zStmt;
55485     int iMem = ++pParse->nMem;
55486
55487     v = sqlite3GetVdbe(pParse);
55488     if( v==0 ) goto exit_create_index;
55489
55490
55491     /* Create the rootpage for the index
55492     */
55493     sqlite3BeginWriteOperation(pParse, 1, iDb);
55494     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
55495
55496     /* Gather the complete text of the CREATE INDEX statement into
55497     ** the zStmt variable
55498     */
55499     if( pStart && pEnd ){
55500       /* A named index with an explicit CREATE INDEX statement */
55501       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
55502         onError==OE_None ? "" : " UNIQUE",
55503         pEnd->z - pName->z + 1,
55504         pName->z);
55505     }else{
55506       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
55507       /* zStmt = sqlite3MPrintf(""); */
55508       zStmt = 0;
55509     }
55510
55511     /* Add an entry in sqlite_master for this index
55512     */
55513     sqlite3NestedParse(pParse, 
55514         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
55515         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
55516         pIndex->zName,
55517         pTab->zName,
55518         iMem,
55519         zStmt
55520     );
55521     sqlite3_free(zStmt);
55522
55523     /* Fill the index with data and reparse the schema. Code an OP_Expire
55524     ** to invalidate all pre-compiled statements.
55525     */
55526     if( pTblName ){
55527       sqlite3RefillIndex(pParse, pIndex, iMem);
55528       sqlite3ChangeCookie(pParse, iDb);
55529       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
55530          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
55531       sqlite3VdbeAddOp1(v, OP_Expire, 0);
55532     }
55533   }
55534
55535   /* When adding an index to the list of indices for a table, make
55536   ** sure all indices labeled OE_Replace come after all those labeled
55537   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
55538   ** and INSERT.
55539   */
55540   if( db->init.busy || pTblName==0 ){
55541     if( onError!=OE_Replace || pTab->pIndex==0
55542          || pTab->pIndex->onError==OE_Replace){
55543       pIndex->pNext = pTab->pIndex;
55544       pTab->pIndex = pIndex;
55545     }else{
55546       Index *pOther = pTab->pIndex;
55547       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
55548         pOther = pOther->pNext;
55549       }
55550       pIndex->pNext = pOther->pNext;
55551       pOther->pNext = pIndex;
55552     }
55553     pIndex = 0;
55554   }
55555
55556   /* Clean up before exiting */
55557 exit_create_index:
55558   if( pIndex ){
55559     freeIndex(pIndex);
55560   }
55561   sqlite3ExprListDelete(pList);
55562   sqlite3SrcListDelete(pTblName);
55563   sqlite3_free(zName);
55564   return;
55565 }
55566
55567 /*
55568 ** Generate code to make sure the file format number is at least minFormat.
55569 ** The generated code will increase the file format number if necessary.
55570 */
55571 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
55572   Vdbe *v;
55573   v = sqlite3GetVdbe(pParse);
55574   if( v ){
55575     int r1 = sqlite3GetTempReg(pParse);
55576     int r2 = sqlite3GetTempReg(pParse);
55577     int j1;
55578     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
55579     sqlite3VdbeUsesBtree(v, iDb);
55580     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
55581     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
55582     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
55583     sqlite3VdbeJumpHere(v, j1);
55584     sqlite3ReleaseTempReg(pParse, r1);
55585     sqlite3ReleaseTempReg(pParse, r2);
55586   }
55587 }
55588
55589 /*
55590 ** Fill the Index.aiRowEst[] array with default information - information
55591 ** to be used when we have not run the ANALYZE command.
55592 **
55593 ** aiRowEst[0] is suppose to contain the number of elements in the index.
55594 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
55595 ** number of rows in the table that match any particular value of the
55596 ** first column of the index.  aiRowEst[2] is an estimate of the number
55597 ** of rows that match any particular combiniation of the first 2 columns
55598 ** of the index.  And so forth.  It must always be the case that
55599 *
55600 **           aiRowEst[N]<=aiRowEst[N-1]
55601 **           aiRowEst[N]>=1
55602 **
55603 ** Apart from that, we have little to go on besides intuition as to
55604 ** how aiRowEst[] should be initialized.  The numbers generated here
55605 ** are based on typical values found in actual indices.
55606 */
55607 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
55608   unsigned *a = pIdx->aiRowEst;
55609   int i;
55610   assert( a!=0 );
55611   a[0] = 1000000;
55612   for(i=pIdx->nColumn; i>=5; i--){
55613     a[i] = 5;
55614   }
55615   while( i>=1 ){
55616     a[i] = 11 - i;
55617     i--;
55618   }
55619   if( pIdx->onError!=OE_None ){
55620     a[pIdx->nColumn] = 1;
55621   }
55622 }
55623
55624 /*
55625 ** This routine will drop an existing named index.  This routine
55626 ** implements the DROP INDEX statement.
55627 */
55628 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
55629   Index *pIndex;
55630   Vdbe *v;
55631   sqlite3 *db = pParse->db;
55632   int iDb;
55633
55634   if( pParse->nErr || db->mallocFailed ){
55635     goto exit_drop_index;
55636   }
55637   assert( pName->nSrc==1 );
55638   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
55639     goto exit_drop_index;
55640   }
55641   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
55642   if( pIndex==0 ){
55643     if( !ifExists ){
55644       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
55645     }
55646     pParse->checkSchema = 1;
55647     goto exit_drop_index;
55648   }
55649   if( pIndex->autoIndex ){
55650     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
55651       "or PRIMARY KEY constraint cannot be dropped", 0);
55652     goto exit_drop_index;
55653   }
55654   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
55655 #ifndef SQLITE_OMIT_AUTHORIZATION
55656   {
55657     int code = SQLITE_DROP_INDEX;
55658     Table *pTab = pIndex->pTable;
55659     const char *zDb = db->aDb[iDb].zName;
55660     const char *zTab = SCHEMA_TABLE(iDb);
55661     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
55662       goto exit_drop_index;
55663     }
55664     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
55665     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
55666       goto exit_drop_index;
55667     }
55668   }
55669 #endif
55670
55671   /* Generate code to remove the index and from the master table */
55672   v = sqlite3GetVdbe(pParse);
55673   if( v ){
55674     sqlite3BeginWriteOperation(pParse, 1, iDb);
55675     sqlite3NestedParse(pParse,
55676        "DELETE FROM %Q.%s WHERE name=%Q",
55677        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
55678        pIndex->zName
55679     );
55680     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
55681       sqlite3NestedParse(pParse,
55682         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
55683         db->aDb[iDb].zName, pIndex->zName
55684       );
55685     }
55686     sqlite3ChangeCookie(pParse, iDb);
55687     destroyRootPage(pParse, pIndex->tnum, iDb);
55688     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
55689   }
55690
55691 exit_drop_index:
55692   sqlite3SrcListDelete(pName);
55693 }
55694
55695 /*
55696 ** pArray is a pointer to an array of objects.  Each object in the
55697 ** array is szEntry bytes in size.  This routine allocates a new
55698 ** object on the end of the array.
55699 **
55700 ** *pnEntry is the number of entries already in use.  *pnAlloc is
55701 ** the previously allocated size of the array.  initSize is the
55702 ** suggested initial array size allocation.
55703 **
55704 ** The index of the new entry is returned in *pIdx.
55705 **
55706 ** This routine returns a pointer to the array of objects.  This
55707 ** might be the same as the pArray parameter or it might be a different
55708 ** pointer if the array was resized.
55709 */
55710 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
55711   sqlite3 *db,      /* Connection to notify of malloc failures */
55712   void *pArray,     /* Array of objects.  Might be reallocated */
55713   int szEntry,      /* Size of each object in the array */
55714   int initSize,     /* Suggested initial allocation, in elements */
55715   int *pnEntry,     /* Number of objects currently in use */
55716   int *pnAlloc,     /* Current size of the allocation, in elements */
55717   int *pIdx         /* Write the index of a new slot here */
55718 ){
55719   char *z;
55720   if( *pnEntry >= *pnAlloc ){
55721     void *pNew;
55722     int newSize;
55723     newSize = (*pnAlloc)*2 + initSize;
55724     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
55725     if( pNew==0 ){
55726       *pIdx = -1;
55727       return pArray;
55728     }
55729     *pnAlloc = newSize;
55730     pArray = pNew;
55731   }
55732   z = (char*)pArray;
55733   memset(&z[*pnEntry * szEntry], 0, szEntry);
55734   *pIdx = *pnEntry;
55735   ++*pnEntry;
55736   return pArray;
55737 }
55738
55739 /*
55740 ** Append a new element to the given IdList.  Create a new IdList if
55741 ** need be.
55742 **
55743 ** A new IdList is returned, or NULL if malloc() fails.
55744 */
55745 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
55746   int i;
55747   if( pList==0 ){
55748     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
55749     if( pList==0 ) return 0;
55750     pList->nAlloc = 0;
55751   }
55752   pList->a = sqlite3ArrayAllocate(
55753       db,
55754       pList->a,
55755       sizeof(pList->a[0]),
55756       5,
55757       &pList->nId,
55758       &pList->nAlloc,
55759       &i
55760   );
55761   if( i<0 ){
55762     sqlite3IdListDelete(pList);
55763     return 0;
55764   }
55765   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
55766   return pList;
55767 }
55768
55769 /*
55770 ** Delete an IdList.
55771 */
55772 SQLITE_PRIVATE void sqlite3IdListDelete(IdList *pList){
55773   int i;
55774   if( pList==0 ) return;
55775   for(i=0; i<pList->nId; i++){
55776     sqlite3_free(pList->a[i].zName);
55777   }
55778   sqlite3_free(pList->a);
55779   sqlite3_free(pList);
55780 }
55781
55782 /*
55783 ** Return the index in pList of the identifier named zId.  Return -1
55784 ** if not found.
55785 */
55786 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
55787   int i;
55788   if( pList==0 ) return -1;
55789   for(i=0; i<pList->nId; i++){
55790     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
55791   }
55792   return -1;
55793 }
55794
55795 /*
55796 ** Append a new table name to the given SrcList.  Create a new SrcList if
55797 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
55798 **
55799 ** A new SrcList is returned, or NULL if malloc() fails.
55800 **
55801 ** If pDatabase is not null, it means that the table has an optional
55802 ** database name prefix.  Like this:  "database.table".  The pDatabase
55803 ** points to the table name and the pTable points to the database name.
55804 ** The SrcList.a[].zName field is filled with the table name which might
55805 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
55806 ** SrcList.a[].zDatabase is filled with the database name from pTable,
55807 ** or with NULL if no database is specified.
55808 **
55809 ** In other words, if call like this:
55810 **
55811 **         sqlite3SrcListAppend(D,A,B,0);
55812 **
55813 ** Then B is a table name and the database name is unspecified.  If called
55814 ** like this:
55815 **
55816 **         sqlite3SrcListAppend(D,A,B,C);
55817 **
55818 ** Then C is the table name and B is the database name.
55819 */
55820 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
55821   sqlite3 *db,        /* Connection to notify of malloc failures */
55822   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
55823   Token *pTable,      /* Table to append */
55824   Token *pDatabase    /* Database of the table */
55825 ){
55826   struct SrcList_item *pItem;
55827   if( pList==0 ){
55828     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
55829     if( pList==0 ) return 0;
55830     pList->nAlloc = 1;
55831   }
55832   if( pList->nSrc>=pList->nAlloc ){
55833     SrcList *pNew;
55834     pList->nAlloc *= 2;
55835     pNew = sqlite3DbRealloc(db, pList,
55836                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
55837     if( pNew==0 ){
55838       sqlite3SrcListDelete(pList);
55839       return 0;
55840     }
55841     pList = pNew;
55842   }
55843   pItem = &pList->a[pList->nSrc];
55844   memset(pItem, 0, sizeof(pList->a[0]));
55845   if( pDatabase && pDatabase->z==0 ){
55846     pDatabase = 0;
55847   }
55848   if( pDatabase && pTable ){
55849     Token *pTemp = pDatabase;
55850     pDatabase = pTable;
55851     pTable = pTemp;
55852   }
55853   pItem->zName = sqlite3NameFromToken(db, pTable);
55854   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
55855   pItem->iCursor = -1;
55856   pItem->isPopulated = 0;
55857   pList->nSrc++;
55858   return pList;
55859 }
55860
55861 /*
55862 ** Assign cursors to all tables in a SrcList
55863 */
55864 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
55865   int i;
55866   struct SrcList_item *pItem;
55867   assert(pList || pParse->db->mallocFailed );
55868   if( pList ){
55869     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
55870       if( pItem->iCursor>=0 ) break;
55871       pItem->iCursor = pParse->nTab++;
55872       if( pItem->pSelect ){
55873         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
55874       }
55875     }
55876   }
55877 }
55878
55879 /*
55880 ** Delete an entire SrcList including all its substructure.
55881 */
55882 SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList *pList){
55883   int i;
55884   struct SrcList_item *pItem;
55885   if( pList==0 ) return;
55886   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
55887     sqlite3_free(pItem->zDatabase);
55888     sqlite3_free(pItem->zName);
55889     sqlite3_free(pItem->zAlias);
55890     sqlite3DeleteTable(pItem->pTab);
55891     sqlite3SelectDelete(pItem->pSelect);
55892     sqlite3ExprDelete(pItem->pOn);
55893     sqlite3IdListDelete(pItem->pUsing);
55894   }
55895   sqlite3_free(pList);
55896 }
55897
55898 /*
55899 ** This routine is called by the parser to add a new term to the
55900 ** end of a growing FROM clause.  The "p" parameter is the part of
55901 ** the FROM clause that has already been constructed.  "p" is NULL
55902 ** if this is the first term of the FROM clause.  pTable and pDatabase
55903 ** are the name of the table and database named in the FROM clause term.
55904 ** pDatabase is NULL if the database name qualifier is missing - the
55905 ** usual case.  If the term has a alias, then pAlias points to the
55906 ** alias token.  If the term is a subquery, then pSubquery is the
55907 ** SELECT statement that the subquery encodes.  The pTable and
55908 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
55909 ** parameters are the content of the ON and USING clauses.
55910 **
55911 ** Return a new SrcList which encodes is the FROM with the new
55912 ** term added.
55913 */
55914 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
55915   Parse *pParse,          /* Parsing context */
55916   SrcList *p,             /* The left part of the FROM clause already seen */
55917   Token *pTable,          /* Name of the table to add to the FROM clause */
55918   Token *pDatabase,       /* Name of the database containing pTable */
55919   Token *pAlias,          /* The right-hand side of the AS subexpression */
55920   Select *pSubquery,      /* A subquery used in place of a table name */
55921   Expr *pOn,              /* The ON clause of a join */
55922   IdList *pUsing          /* The USING clause of a join */
55923 ){
55924   struct SrcList_item *pItem;
55925   sqlite3 *db = pParse->db;
55926   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
55927   if( p==0 || p->nSrc==0 ){
55928     sqlite3ExprDelete(pOn);
55929     sqlite3IdListDelete(pUsing);
55930     sqlite3SelectDelete(pSubquery);
55931     return p;
55932   }
55933   pItem = &p->a[p->nSrc-1];
55934   if( pAlias && pAlias->n ){
55935     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
55936   }
55937   pItem->pSelect = pSubquery;
55938   pItem->pOn = pOn;
55939   pItem->pUsing = pUsing;
55940   return p;
55941 }
55942
55943 /*
55944 ** When building up a FROM clause in the parser, the join operator
55945 ** is initially attached to the left operand.  But the code generator
55946 ** expects the join operator to be on the right operand.  This routine
55947 ** Shifts all join operators from left to right for an entire FROM
55948 ** clause.
55949 **
55950 ** Example: Suppose the join is like this:
55951 **
55952 **           A natural cross join B
55953 **
55954 ** The operator is "natural cross join".  The A and B operands are stored
55955 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
55956 ** operator with A.  This routine shifts that operator over to B.
55957 */
55958 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
55959   if( p && p->a ){
55960     int i;
55961     for(i=p->nSrc-1; i>0; i--){
55962       p->a[i].jointype = p->a[i-1].jointype;
55963     }
55964     p->a[0].jointype = 0;
55965   }
55966 }
55967
55968 /*
55969 ** Begin a transaction
55970 */
55971 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
55972   sqlite3 *db;
55973   Vdbe *v;
55974   int i;
55975
55976   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
55977   if( pParse->nErr || db->mallocFailed ) return;
55978   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
55979
55980   v = sqlite3GetVdbe(pParse);
55981   if( !v ) return;
55982   if( type!=TK_DEFERRED ){
55983     for(i=0; i<db->nDb; i++){
55984       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
55985       sqlite3VdbeUsesBtree(v, i);
55986     }
55987   }
55988   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
55989 }
55990
55991 /*
55992 ** Commit a transaction
55993 */
55994 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
55995   sqlite3 *db;
55996   Vdbe *v;
55997
55998   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
55999   if( pParse->nErr || db->mallocFailed ) return;
56000   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
56001
56002   v = sqlite3GetVdbe(pParse);
56003   if( v ){
56004     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
56005   }
56006 }
56007
56008 /*
56009 ** Rollback a transaction
56010 */
56011 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
56012   sqlite3 *db;
56013   Vdbe *v;
56014
56015   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
56016   if( pParse->nErr || db->mallocFailed ) return;
56017   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
56018
56019   v = sqlite3GetVdbe(pParse);
56020   if( v ){
56021     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
56022   }
56023 }
56024
56025 /*
56026 ** Make sure the TEMP database is open and available for use.  Return
56027 ** the number of errors.  Leave any error messages in the pParse structure.
56028 */
56029 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
56030   sqlite3 *db = pParse->db;
56031   if( db->aDb[1].pBt==0 && !pParse->explain ){
56032     int rc;
56033     static const int flags = 
56034           SQLITE_OPEN_READWRITE |
56035           SQLITE_OPEN_CREATE |
56036           SQLITE_OPEN_EXCLUSIVE |
56037           SQLITE_OPEN_DELETEONCLOSE |
56038           SQLITE_OPEN_TEMP_DB;
56039
56040     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
56041                                  &db->aDb[1].pBt);
56042     if( rc!=SQLITE_OK ){
56043       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
56044         "file for storing temporary tables");
56045       pParse->rc = rc;
56046       return 1;
56047     }
56048     assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
56049     assert( db->aDb[1].pSchema );
56050     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
56051                             db->dfltJournalMode);
56052   }
56053   return 0;
56054 }
56055
56056 /*
56057 ** Generate VDBE code that will verify the schema cookie and start
56058 ** a read-transaction for all named database files.
56059 **
56060 ** It is important that all schema cookies be verified and all
56061 ** read transactions be started before anything else happens in
56062 ** the VDBE program.  But this routine can be called after much other
56063 ** code has been generated.  So here is what we do:
56064 **
56065 ** The first time this routine is called, we code an OP_Goto that
56066 ** will jump to a subroutine at the end of the program.  Then we
56067 ** record every database that needs its schema verified in the
56068 ** pParse->cookieMask field.  Later, after all other code has been
56069 ** generated, the subroutine that does the cookie verifications and
56070 ** starts the transactions will be coded and the OP_Goto P2 value
56071 ** will be made to point to that subroutine.  The generation of the
56072 ** cookie verification subroutine code happens in sqlite3FinishCoding().
56073 **
56074 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
56075 ** schema on any databases.  This can be used to position the OP_Goto
56076 ** early in the code, before we know if any database tables will be used.
56077 */
56078 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
56079   sqlite3 *db;
56080   Vdbe *v;
56081   int mask;
56082
56083   v = sqlite3GetVdbe(pParse);
56084   if( v==0 ) return;  /* This only happens if there was a prior error */
56085   db = pParse->db;
56086   if( pParse->cookieGoto==0 ){
56087     pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
56088   }
56089   if( iDb>=0 ){
56090     assert( iDb<db->nDb );
56091     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
56092     assert( iDb<SQLITE_MAX_ATTACHED+2 );
56093     mask = 1<<iDb;
56094     if( (pParse->cookieMask & mask)==0 ){
56095       pParse->cookieMask |= mask;
56096       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
56097       if( !OMIT_TEMPDB && iDb==1 ){
56098         sqlite3OpenTempDatabase(pParse);
56099       }
56100     }
56101   }
56102 }
56103
56104 /*
56105 ** Generate VDBE code that prepares for doing an operation that
56106 ** might change the database.
56107 **
56108 ** This routine starts a new transaction if we are not already within
56109 ** a transaction.  If we are already within a transaction, then a checkpoint
56110 ** is set if the setStatement parameter is true.  A checkpoint should
56111 ** be set for operations that might fail (due to a constraint) part of
56112 ** the way through and which will need to undo some writes without having to
56113 ** rollback the whole transaction.  For operations where all constraints
56114 ** can be checked before any changes are made to the database, it is never
56115 ** necessary to undo a write and the checkpoint should not be set.
56116 **
56117 ** Only database iDb and the temp database are made writable by this call.
56118 ** If iDb==0, then the main and temp databases are made writable.   If
56119 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
56120 ** specified auxiliary database and the temp database are made writable.
56121 */
56122 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
56123   Vdbe *v = sqlite3GetVdbe(pParse);
56124   if( v==0 ) return;
56125   sqlite3CodeVerifySchema(pParse, iDb);
56126   pParse->writeMask |= 1<<iDb;
56127   if( setStatement && pParse->nested==0 ){
56128     sqlite3VdbeAddOp1(v, OP_Statement, iDb);
56129   }
56130   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
56131     sqlite3BeginWriteOperation(pParse, setStatement, 1);
56132   }
56133 }
56134
56135 /*
56136 ** Check to see if pIndex uses the collating sequence pColl.  Return
56137 ** true if it does and false if it does not.
56138 */
56139 #ifndef SQLITE_OMIT_REINDEX
56140 static int collationMatch(const char *zColl, Index *pIndex){
56141   int i;
56142   for(i=0; i<pIndex->nColumn; i++){
56143     const char *z = pIndex->azColl[i];
56144     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
56145       return 1;
56146     }
56147   }
56148   return 0;
56149 }
56150 #endif
56151
56152 /*
56153 ** Recompute all indices of pTab that use the collating sequence pColl.
56154 ** If pColl==0 then recompute all indices of pTab.
56155 */
56156 #ifndef SQLITE_OMIT_REINDEX
56157 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
56158   Index *pIndex;              /* An index associated with pTab */
56159
56160   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
56161     if( zColl==0 || collationMatch(zColl, pIndex) ){
56162       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56163       sqlite3BeginWriteOperation(pParse, 0, iDb);
56164       sqlite3RefillIndex(pParse, pIndex, -1);
56165     }
56166   }
56167 }
56168 #endif
56169
56170 /*
56171 ** Recompute all indices of all tables in all databases where the
56172 ** indices use the collating sequence pColl.  If pColl==0 then recompute
56173 ** all indices everywhere.
56174 */
56175 #ifndef SQLITE_OMIT_REINDEX
56176 static void reindexDatabases(Parse *pParse, char const *zColl){
56177   Db *pDb;                    /* A single database */
56178   int iDb;                    /* The database index number */
56179   sqlite3 *db = pParse->db;   /* The database connection */
56180   HashElem *k;                /* For looping over tables in pDb */
56181   Table *pTab;                /* A table in the database */
56182
56183   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
56184     assert( pDb!=0 );
56185     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
56186       pTab = (Table*)sqliteHashData(k);
56187       reindexTable(pParse, pTab, zColl);
56188     }
56189   }
56190 }
56191 #endif
56192
56193 /*
56194 ** Generate code for the REINDEX command.
56195 **
56196 **        REINDEX                            -- 1
56197 **        REINDEX  <collation>               -- 2
56198 **        REINDEX  ?<database>.?<tablename>  -- 3
56199 **        REINDEX  ?<database>.?<indexname>  -- 4
56200 **
56201 ** Form 1 causes all indices in all attached databases to be rebuilt.
56202 ** Form 2 rebuilds all indices in all databases that use the named
56203 ** collating function.  Forms 3 and 4 rebuild the named index or all
56204 ** indices associated with the named table.
56205 */
56206 #ifndef SQLITE_OMIT_REINDEX
56207 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
56208   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
56209   char *z;                    /* Name of a table or index */
56210   const char *zDb;            /* Name of the database */
56211   Table *pTab;                /* A table in the database */
56212   Index *pIndex;              /* An index associated with pTab */
56213   int iDb;                    /* The database index number */
56214   sqlite3 *db = pParse->db;   /* The database connection */
56215   Token *pObjName;            /* Name of the table or index to be reindexed */
56216
56217   /* Read the database schema. If an error occurs, leave an error message
56218   ** and code in pParse and return NULL. */
56219   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
56220     return;
56221   }
56222
56223   if( pName1==0 || pName1->z==0 ){
56224     reindexDatabases(pParse, 0);
56225     return;
56226   }else if( pName2==0 || pName2->z==0 ){
56227     char *zColl;
56228     assert( pName1->z );
56229     zColl = sqlite3NameFromToken(pParse->db, pName1);
56230     if( !zColl ) return;
56231     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
56232     if( pColl ){
56233       if( zColl ){
56234         reindexDatabases(pParse, zColl);
56235         sqlite3_free(zColl);
56236       }
56237       return;
56238     }
56239     sqlite3_free(zColl);
56240   }
56241   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
56242   if( iDb<0 ) return;
56243   z = sqlite3NameFromToken(db, pObjName);
56244   if( z==0 ) return;
56245   zDb = db->aDb[iDb].zName;
56246   pTab = sqlite3FindTable(db, z, zDb);
56247   if( pTab ){
56248     reindexTable(pParse, pTab, 0);
56249     sqlite3_free(z);
56250     return;
56251   }
56252   pIndex = sqlite3FindIndex(db, z, zDb);
56253   sqlite3_free(z);
56254   if( pIndex ){
56255     sqlite3BeginWriteOperation(pParse, 0, iDb);
56256     sqlite3RefillIndex(pParse, pIndex, -1);
56257     return;
56258   }
56259   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
56260 }
56261 #endif
56262
56263 /*
56264 ** Return a dynamicly allocated KeyInfo structure that can be used
56265 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
56266 **
56267 ** If successful, a pointer to the new structure is returned. In this case
56268 ** the caller is responsible for calling sqlite3_free() on the returned 
56269 ** pointer. If an error occurs (out of memory or missing collation 
56270 ** sequence), NULL is returned and the state of pParse updated to reflect
56271 ** the error.
56272 */
56273 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
56274   int i;
56275   int nCol = pIdx->nColumn;
56276   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
56277   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(pParse->db, nBytes);
56278
56279   if( pKey ){
56280     pKey->db = pParse->db;
56281     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
56282     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
56283     for(i=0; i<nCol; i++){
56284       char *zColl = pIdx->azColl[i];
56285       assert( zColl );
56286       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
56287       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
56288     }
56289     pKey->nField = nCol;
56290   }
56291
56292   if( pParse->nErr ){
56293     sqlite3_free(pKey);
56294     pKey = 0;
56295   }
56296   return pKey;
56297 }
56298
56299 /************** End of build.c ***********************************************/
56300 /************** Begin file callback.c ****************************************/
56301 /*
56302 ** 2005 May 23 
56303 **
56304 ** The author disclaims copyright to this source code.  In place of
56305 ** a legal notice, here is a blessing:
56306 **
56307 **    May you do good and not evil.
56308 **    May you find forgiveness for yourself and forgive others.
56309 **    May you share freely, never taking more than you give.
56310 **
56311 *************************************************************************
56312 **
56313 ** This file contains functions used to access the internal hash tables
56314 ** of user defined functions and collation sequences.
56315 **
56316 ** $Id: callback.c,v 1.23 2007/08/29 12:31:26 danielk1977 Exp $
56317 */
56318
56319
56320 /*
56321 ** Invoke the 'collation needed' callback to request a collation sequence
56322 ** in the database text encoding of name zName, length nName.
56323 ** If the collation sequence
56324 */
56325 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
56326   assert( !db->xCollNeeded || !db->xCollNeeded16 );
56327   if( nName<0 ) nName = strlen(zName);
56328   if( db->xCollNeeded ){
56329     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
56330     if( !zExternal ) return;
56331     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
56332     sqlite3_free(zExternal);
56333   }
56334 #ifndef SQLITE_OMIT_UTF16
56335   if( db->xCollNeeded16 ){
56336     char const *zExternal;
56337     sqlite3_value *pTmp = sqlite3ValueNew(db);
56338     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
56339     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
56340     if( zExternal ){
56341       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
56342     }
56343     sqlite3ValueFree(pTmp);
56344   }
56345 #endif
56346 }
56347
56348 /*
56349 ** This routine is called if the collation factory fails to deliver a
56350 ** collation function in the best encoding but there may be other versions
56351 ** of this collation function (for other text encodings) available. Use one
56352 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
56353 ** possible.
56354 */
56355 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
56356   CollSeq *pColl2;
56357   char *z = pColl->zName;
56358   int n = strlen(z);
56359   int i;
56360   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
56361   for(i=0; i<3; i++){
56362     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
56363     if( pColl2->xCmp!=0 ){
56364       memcpy(pColl, pColl2, sizeof(CollSeq));
56365       pColl->xDel = 0;         /* Do not copy the destructor */
56366       return SQLITE_OK;
56367     }
56368   }
56369   return SQLITE_ERROR;
56370 }
56371
56372 /*
56373 ** This function is responsible for invoking the collation factory callback
56374 ** or substituting a collation sequence of a different encoding when the
56375 ** requested collation sequence is not available in the database native
56376 ** encoding.
56377 ** 
56378 ** If it is not NULL, then pColl must point to the database native encoding 
56379 ** collation sequence with name zName, length nName.
56380 **
56381 ** The return value is either the collation sequence to be used in database
56382 ** db for collation type name zName, length nName, or NULL, if no collation
56383 ** sequence can be found.
56384 */
56385 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
56386   sqlite3* db, 
56387   CollSeq *pColl, 
56388   const char *zName, 
56389   int nName
56390 ){
56391   CollSeq *p;
56392
56393   p = pColl;
56394   if( !p ){
56395     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
56396   }
56397   if( !p || !p->xCmp ){
56398     /* No collation sequence of this type for this encoding is registered.
56399     ** Call the collation factory to see if it can supply us with one.
56400     */
56401     callCollNeeded(db, zName, nName);
56402     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
56403   }
56404   if( p && !p->xCmp && synthCollSeq(db, p) ){
56405     p = 0;
56406   }
56407   assert( !p || p->xCmp );
56408   return p;
56409 }
56410
56411 /*
56412 ** This routine is called on a collation sequence before it is used to
56413 ** check that it is defined. An undefined collation sequence exists when
56414 ** a database is loaded that contains references to collation sequences
56415 ** that have not been defined by sqlite3_create_collation() etc.
56416 **
56417 ** If required, this routine calls the 'collation needed' callback to
56418 ** request a definition of the collating sequence. If this doesn't work, 
56419 ** an equivalent collating sequence that uses a text encoding different
56420 ** from the main database is substituted, if one is available.
56421 */
56422 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
56423   if( pColl ){
56424     const char *zName = pColl->zName;
56425     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
56426     if( !p ){
56427       if( pParse->nErr==0 ){
56428         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
56429       }
56430       pParse->nErr++;
56431       return SQLITE_ERROR;
56432     }
56433     assert( p==pColl );
56434   }
56435   return SQLITE_OK;
56436 }
56437
56438
56439
56440 /*
56441 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
56442 ** specified by zName and nName is not found and parameter 'create' is
56443 ** true, then create a new entry. Otherwise return NULL.
56444 **
56445 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
56446 ** array of three CollSeq structures. The first is the collation sequence
56447 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
56448 **
56449 ** Stored immediately after the three collation sequences is a copy of
56450 ** the collation sequence name. A pointer to this string is stored in
56451 ** each collation sequence structure.
56452 */
56453 static CollSeq *findCollSeqEntry(
56454   sqlite3 *db,
56455   const char *zName,
56456   int nName,
56457   int create
56458 ){
56459   CollSeq *pColl;
56460   if( nName<0 ) nName = strlen(zName);
56461   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
56462
56463   if( 0==pColl && create ){
56464     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
56465     if( pColl ){
56466       CollSeq *pDel = 0;
56467       pColl[0].zName = (char*)&pColl[3];
56468       pColl[0].enc = SQLITE_UTF8;
56469       pColl[1].zName = (char*)&pColl[3];
56470       pColl[1].enc = SQLITE_UTF16LE;
56471       pColl[2].zName = (char*)&pColl[3];
56472       pColl[2].enc = SQLITE_UTF16BE;
56473       memcpy(pColl[0].zName, zName, nName);
56474       pColl[0].zName[nName] = 0;
56475       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
56476
56477       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
56478       ** return the pColl pointer to be deleted (because it wasn't added
56479       ** to the hash table).
56480       */
56481       assert( pDel==0 || pDel==pColl );
56482       if( pDel!=0 ){
56483         db->mallocFailed = 1;
56484         sqlite3_free(pDel);
56485         pColl = 0;
56486       }
56487     }
56488   }
56489   return pColl;
56490 }
56491
56492 /*
56493 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
56494 ** Return the CollSeq* pointer for the collation sequence named zName
56495 ** for the encoding 'enc' from the database 'db'.
56496 **
56497 ** If the entry specified is not found and 'create' is true, then create a
56498 ** new entry.  Otherwise return NULL.
56499 **
56500 ** A separate function sqlite3LocateCollSeq() is a wrapper around
56501 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
56502 ** if necessary and generates an error message if the collating sequence
56503 ** cannot be found.
56504 */
56505 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
56506   sqlite3 *db,
56507   u8 enc,
56508   const char *zName,
56509   int nName,
56510   int create
56511 ){
56512   CollSeq *pColl;
56513   if( zName ){
56514     pColl = findCollSeqEntry(db, zName, nName, create);
56515   }else{
56516     pColl = db->pDfltColl;
56517   }
56518   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
56519   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
56520   if( pColl ) pColl += enc-1;
56521   return pColl;
56522 }
56523
56524 /*
56525 ** Locate a user function given a name, a number of arguments and a flag
56526 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
56527 ** pointer to the FuncDef structure that defines that function, or return
56528 ** NULL if the function does not exist.
56529 **
56530 ** If the createFlag argument is true, then a new (blank) FuncDef
56531 ** structure is created and liked into the "db" structure if a
56532 ** no matching function previously existed.  When createFlag is true
56533 ** and the nArg parameter is -1, then only a function that accepts
56534 ** any number of arguments will be returned.
56535 **
56536 ** If createFlag is false and nArg is -1, then the first valid
56537 ** function found is returned.  A function is valid if either xFunc
56538 ** or xStep is non-zero.
56539 **
56540 ** If createFlag is false, then a function with the required name and
56541 ** number of arguments may be returned even if the eTextRep flag does not
56542 ** match that requested.
56543 */
56544 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
56545   sqlite3 *db,       /* An open database */
56546   const char *zName, /* Name of the function.  Not null-terminated */
56547   int nName,         /* Number of characters in the name */
56548   int nArg,          /* Number of arguments.  -1 means any number */
56549   u8 enc,            /* Preferred text encoding */
56550   int createFlag     /* Create new entry if true and does not otherwise exist */
56551 ){
56552   FuncDef *p;         /* Iterator variable */
56553   FuncDef *pFirst;    /* First function with this name */
56554   FuncDef *pBest = 0; /* Best match found so far */
56555   int bestmatch = 0;  
56556
56557
56558   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
56559   if( nArg<-1 ) nArg = -1;
56560
56561   pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
56562   for(p=pFirst; p; p=p->pNext){
56563     /* During the search for the best function definition, bestmatch is set
56564     ** as follows to indicate the quality of the match with the definition
56565     ** pointed to by pBest:
56566     **
56567     ** 0: pBest is NULL. No match has been found.
56568     ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
56569     **    encoding is requested, or vice versa.
56570     ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
56571     **    requested, or vice versa.
56572     ** 3: A variable arguments function using the same text encoding.
56573     ** 4: A function with the exact number of arguments requested that
56574     **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
56575     ** 5: A function with the exact number of arguments requested that
56576     **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
56577     ** 6: An exact match.
56578     **
56579     ** A larger value of 'matchqual' indicates a more desirable match.
56580     */
56581     if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
56582       int match = 1;          /* Quality of this match */
56583       if( p->nArg==nArg || nArg==-1 ){
56584         match = 4;
56585       }
56586       if( enc==p->iPrefEnc ){
56587         match += 2;
56588       }
56589       else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
56590                (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
56591         match += 1;
56592       }
56593
56594       if( match>bestmatch ){
56595         pBest = p;
56596         bestmatch = match;
56597       }
56598     }
56599   }
56600
56601   /* If the createFlag parameter is true, and the seach did not reveal an
56602   ** exact match for the name, number of arguments and encoding, then add a
56603   ** new entry to the hash table and return it.
56604   */
56605   if( createFlag && bestmatch<6 && 
56606       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName))!=0 ){
56607     pBest->nArg = nArg;
56608     pBest->pNext = pFirst;
56609     pBest->iPrefEnc = enc;
56610     memcpy(pBest->zName, zName, nName);
56611     pBest->zName[nName] = 0;
56612     if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
56613       db->mallocFailed = 1;
56614       sqlite3_free(pBest);
56615       return 0;
56616     }
56617   }
56618
56619   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
56620     return pBest;
56621   }
56622   return 0;
56623 }
56624
56625 /*
56626 ** Free all resources held by the schema structure. The void* argument points
56627 ** at a Schema struct. This function does not call sqlite3_free() on the 
56628 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
56629 ** of the schema hash tables).
56630 */
56631 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
56632   Hash temp1;
56633   Hash temp2;
56634   HashElem *pElem;
56635   Schema *pSchema = (Schema *)p;
56636
56637   temp1 = pSchema->tblHash;
56638   temp2 = pSchema->trigHash;
56639   sqlite3HashInit(&pSchema->trigHash, SQLITE_HASH_STRING, 0);
56640   sqlite3HashClear(&pSchema->aFKey);
56641   sqlite3HashClear(&pSchema->idxHash);
56642   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
56643     sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
56644   }
56645   sqlite3HashClear(&temp2);
56646   sqlite3HashInit(&pSchema->tblHash, SQLITE_HASH_STRING, 0);
56647   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
56648     Table *pTab = sqliteHashData(pElem);
56649     sqlite3DeleteTable(pTab);
56650   }
56651   sqlite3HashClear(&temp1);
56652   pSchema->pSeqTab = 0;
56653   pSchema->flags &= ~DB_SchemaLoaded;
56654 }
56655
56656 /*
56657 ** Find and return the schema associated with a BTree.  Create
56658 ** a new one if necessary.
56659 */
56660 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
56661   Schema * p;
56662   if( pBt ){
56663     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
56664   }else{
56665     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
56666   }
56667   if( !p ){
56668     db->mallocFailed = 1;
56669   }else if ( 0==p->file_format ){
56670     sqlite3HashInit(&p->tblHash, SQLITE_HASH_STRING, 0);
56671     sqlite3HashInit(&p->idxHash, SQLITE_HASH_STRING, 0);
56672     sqlite3HashInit(&p->trigHash, SQLITE_HASH_STRING, 0);
56673     sqlite3HashInit(&p->aFKey, SQLITE_HASH_STRING, 1);
56674     p->enc = SQLITE_UTF8;
56675   }
56676   return p;
56677 }
56678
56679 /************** End of callback.c ********************************************/
56680 /************** Begin file delete.c ******************************************/
56681 /*
56682 ** 2001 September 15
56683 **
56684 ** The author disclaims copyright to this source code.  In place of
56685 ** a legal notice, here is a blessing:
56686 **
56687 **    May you do good and not evil.
56688 **    May you find forgiveness for yourself and forgive others.
56689 **    May you share freely, never taking more than you give.
56690 **
56691 *************************************************************************
56692 ** This file contains C code routines that are called by the parser
56693 ** in order to generate code for DELETE FROM statements.
56694 **
56695 ** $Id: delete.c,v 1.169 2008/04/28 18:46:43 drh Exp $
56696 */
56697
56698 /*
56699 ** Look up every table that is named in pSrc.  If any table is not found,
56700 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
56701 ** are found, return a pointer to the last table.
56702 */
56703 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
56704   Table *pTab = 0;
56705   int i;
56706   struct SrcList_item *pItem;
56707   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
56708     pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
56709     sqlite3DeleteTable(pItem->pTab);
56710     pItem->pTab = pTab;
56711     if( pTab ){
56712       pTab->nRef++;
56713     }
56714   }
56715   return pTab;
56716 }
56717
56718 /*
56719 ** Check to make sure the given table is writable.  If it is not
56720 ** writable, generate an error message and return 1.  If it is
56721 ** writable return 0;
56722 */
56723 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
56724   if( (pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
56725         && pParse->nested==0) 
56726 #ifndef SQLITE_OMIT_VIRTUALTABLE
56727       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
56728 #endif
56729   ){
56730     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
56731     return 1;
56732   }
56733 #ifndef SQLITE_OMIT_VIEW
56734   if( !viewOk && pTab->pSelect ){
56735     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
56736     return 1;
56737   }
56738 #endif
56739   return 0;
56740 }
56741
56742 /*
56743 ** Generate code that will open a table for reading.
56744 */
56745 SQLITE_PRIVATE void sqlite3OpenTable(
56746   Parse *p,       /* Generate code into this VDBE */
56747   int iCur,       /* The cursor number of the table */
56748   int iDb,        /* The database index in sqlite3.aDb[] */
56749   Table *pTab,    /* The table to be opened */
56750   int opcode      /* OP_OpenRead or OP_OpenWrite */
56751 ){
56752   Vdbe *v;
56753   if( IsVirtual(pTab) ) return;
56754   v = sqlite3GetVdbe(p);
56755   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
56756   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
56757   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
56758   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
56759   VdbeComment((v, "%s", pTab->zName));
56760 }
56761
56762
56763 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
56764 /*
56765 ** Evaluate a view and store its result in an ephemeral table.  The
56766 ** pWhere argument is an optional WHERE clause that restricts the
56767 ** set of rows in the view that are to be added to the ephemeral table.
56768 */
56769 SQLITE_PRIVATE void sqlite3MaterializeView(
56770   Parse *pParse,       /* Parsing context */
56771   Select *pView,       /* View definition */
56772   Expr *pWhere,        /* Optional WHERE clause to be added */
56773   int iCur             /* Cursor number for ephemerial table */
56774 ){
56775   SelectDest dest;
56776   Select *pDup;
56777   sqlite3 *db = pParse->db;
56778
56779   pDup = sqlite3SelectDup(db, pView);
56780   if( pWhere ){
56781     SrcList *pFrom;
56782     
56783     pWhere = sqlite3ExprDup(db, pWhere);
56784     pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, 0, pDup, 0, 0);
56785     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
56786   }
56787   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
56788   sqlite3Select(pParse, pDup, &dest, 0, 0, 0, 0);
56789   sqlite3SelectDelete(pDup);
56790 }
56791 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
56792
56793
56794 /*
56795 ** Generate code for a DELETE FROM statement.
56796 **
56797 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
56798 **                 \________/       \________________/
56799 **                  pTabList              pWhere
56800 */
56801 SQLITE_PRIVATE void sqlite3DeleteFrom(
56802   Parse *pParse,         /* The parser context */
56803   SrcList *pTabList,     /* The table from which we should delete things */
56804   Expr *pWhere           /* The WHERE clause.  May be null */
56805 ){
56806   Vdbe *v;               /* The virtual database engine */
56807   Table *pTab;           /* The table from which records will be deleted */
56808   const char *zDb;       /* Name of database holding pTab */
56809   int end, addr = 0;     /* A couple addresses of generated code */
56810   int i;                 /* Loop counter */
56811   WhereInfo *pWInfo;     /* Information about the WHERE clause */
56812   Index *pIdx;           /* For looping over indices of the table */
56813   int iCur;              /* VDBE Cursor number for pTab */
56814   sqlite3 *db;           /* Main database structure */
56815   AuthContext sContext;  /* Authorization context */
56816   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
56817   NameContext sNC;       /* Name context to resolve expressions in */
56818   int iDb;               /* Database number */
56819   int memCnt = 0;        /* Memory cell used for change counting */
56820
56821 #ifndef SQLITE_OMIT_TRIGGER
56822   int isView;                  /* True if attempting to delete from a view */
56823   int triggers_exist = 0;      /* True if any triggers exist */
56824 #endif
56825   int iBeginAfterTrigger;      /* Address of after trigger program */
56826   int iEndAfterTrigger;        /* Exit of after trigger program */
56827   int iBeginBeforeTrigger;     /* Address of before trigger program */
56828   int iEndBeforeTrigger;       /* Exit of before trigger program */
56829   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
56830
56831   sContext.pParse = 0;
56832   db = pParse->db;
56833   if( pParse->nErr || db->mallocFailed ){
56834     goto delete_from_cleanup;
56835   }
56836   assert( pTabList->nSrc==1 );
56837
56838   /* Locate the table which we want to delete.  This table has to be
56839   ** put in an SrcList structure because some of the subroutines we
56840   ** will be calling are designed to work with multiple tables and expect
56841   ** an SrcList* parameter instead of just a Table* parameter.
56842   */
56843   pTab = sqlite3SrcListLookup(pParse, pTabList);
56844   if( pTab==0 )  goto delete_from_cleanup;
56845
56846   /* Figure out if we have any triggers and if the table being
56847   ** deleted from is a view
56848   */
56849 #ifndef SQLITE_OMIT_TRIGGER
56850   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
56851   isView = pTab->pSelect!=0;
56852 #else
56853 # define triggers_exist 0
56854 # define isView 0
56855 #endif
56856 #ifdef SQLITE_OMIT_VIEW
56857 # undef isView
56858 # define isView 0
56859 #endif
56860
56861   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
56862     goto delete_from_cleanup;
56863   }
56864   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
56865   assert( iDb<db->nDb );
56866   zDb = db->aDb[iDb].zName;
56867   if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
56868     goto delete_from_cleanup;
56869   }
56870
56871   /* If pTab is really a view, make sure it has been initialized.
56872   */
56873   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
56874     goto delete_from_cleanup;
56875   }
56876
56877   /* Allocate a cursor used to store the old.* data for a trigger.
56878   */
56879   if( triggers_exist ){ 
56880     oldIdx = pParse->nTab++;
56881   }
56882
56883   /* Assign  cursor number to the table and all its indices.
56884   */
56885   assert( pTabList->nSrc==1 );
56886   iCur = pTabList->a[0].iCursor = pParse->nTab++;
56887   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
56888     pParse->nTab++;
56889   }
56890
56891   /* Start the view context
56892   */
56893   if( isView ){
56894     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
56895   }
56896
56897   /* Begin generating code.
56898   */
56899   v = sqlite3GetVdbe(pParse);
56900   if( v==0 ){
56901     goto delete_from_cleanup;
56902   }
56903   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
56904   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
56905
56906   if( triggers_exist ){
56907     int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
56908     int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
56909     addr = sqlite3VdbeMakeLabel(v);
56910
56911     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
56912     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
56913         -1, oldIdx, orconf, addr, &old_col_mask, 0);
56914     iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
56915
56916     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
56917     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
56918         oldIdx, orconf, addr, &old_col_mask, 0);
56919     iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
56920
56921     sqlite3VdbeJumpHere(v, iGoto);
56922   }
56923
56924   /* If we are trying to delete from a view, realize that view into
56925   ** a ephemeral table.
56926   */
56927   if( isView ){
56928     sqlite3MaterializeView(pParse, pTab->pSelect, pWhere, iCur);
56929   }
56930
56931   /* Resolve the column names in the WHERE clause.
56932   */
56933   memset(&sNC, 0, sizeof(sNC));
56934   sNC.pParse = pParse;
56935   sNC.pSrcList = pTabList;
56936   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
56937     goto delete_from_cleanup;
56938   }
56939
56940   /* Initialize the counter of the number of rows deleted, if
56941   ** we are counting rows.
56942   */
56943   if( db->flags & SQLITE_CountRows ){
56944     memCnt = ++pParse->nMem;
56945     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
56946   }
56947
56948   /* Special case: A DELETE without a WHERE clause deletes everything.
56949   ** It is easier just to erase the whole table.  Note, however, that
56950   ** this means that the row change count will be incorrect.
56951   */
56952   if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
56953     if( db->flags & SQLITE_CountRows ){
56954       /* If counting rows deleted, just count the total number of
56955       ** entries in the table. */
56956       int addr2;
56957       if( !isView ){
56958         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
56959       }
56960       sqlite3VdbeAddOp2(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
56961       addr2 = sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
56962       sqlite3VdbeAddOp2(v, OP_Next, iCur, addr2);
56963       sqlite3VdbeAddOp1(v, OP_Close, iCur);
56964     }
56965     if( !isView ){
56966       sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb);
56967       if( !pParse->nested ){
56968         sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
56969       }
56970       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
56971         assert( pIdx->pSchema==pTab->pSchema );
56972         sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
56973       }
56974     }
56975   } 
56976   /* The usual case: There is a WHERE clause so we have to scan through
56977   ** the table and pick which records to delete.
56978   */
56979   else{
56980     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
56981
56982     /* Begin the database scan
56983     */
56984     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
56985     if( pWInfo==0 ) goto delete_from_cleanup;
56986
56987     /* Remember the rowid of every item to be deleted.
56988     */
56989     sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid);
56990     sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid);
56991     if( db->flags & SQLITE_CountRows ){
56992       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
56993     }
56994
56995     /* End the database scan loop.
56996     */
56997     sqlite3WhereEnd(pWInfo);
56998
56999     /* Open the pseudo-table used to store OLD if there are triggers.
57000     */
57001     if( triggers_exist ){
57002       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
57003       sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
57004     }
57005
57006     /* Delete every item whose key was written to the list during the
57007     ** database scan.  We have to delete items after the scan is complete
57008     ** because deleting an item can change the scan order.
57009     */
57010     end = sqlite3VdbeMakeLabel(v);
57011
57012     if( !isView ){
57013       /* Open cursors for the table we are deleting from and 
57014       ** all its indices.
57015       */
57016       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
57017     }
57018
57019     /* This is the beginning of the delete loop. If a trigger encounters
57020     ** an IGNORE constraint, it jumps back to here.
57021     */
57022     if( triggers_exist ){
57023       sqlite3VdbeResolveLabel(v, addr);
57024     }
57025     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end);
57026
57027     if( triggers_exist ){
57028       int iData = ++pParse->nMem;   /* For storing row data of OLD table */
57029
57030       /* If the record is no longer present in the table, jump to the
57031       ** next iteration of the loop through the contents of the fifo.
57032       */
57033       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
57034
57035       /* Populate the OLD.* pseudo-table */
57036       if( old_col_mask ){
57037         sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
57038       }else{
57039         sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
57040       }
57041       sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
57042
57043       /* Jump back and run the BEFORE triggers */
57044       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
57045       sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
57046     }
57047
57048     if( !isView ){
57049       /* Delete the row */
57050 #ifndef SQLITE_OMIT_VIRTUALTABLE
57051       if( IsVirtual(pTab) ){
57052         const char *pVtab = (const char *)pTab->pVtab;
57053         sqlite3VtabMakeWritable(pParse, pTab);
57054         sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
57055       }else
57056 #endif
57057       {
57058         sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
57059       }
57060     }
57061
57062     /* If there are row triggers, close all cursors then invoke
57063     ** the AFTER triggers
57064     */
57065     if( triggers_exist ){
57066       /* Jump back and run the AFTER triggers */
57067       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
57068       sqlite3VdbeJumpHere(v, iEndAfterTrigger);
57069     }
57070
57071     /* End of the delete loop */
57072     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
57073     sqlite3VdbeResolveLabel(v, end);
57074
57075     /* Close the cursors after the loop if there are no row triggers */
57076     if( !isView  && !IsVirtual(pTab) ){
57077       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
57078         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
57079       }
57080       sqlite3VdbeAddOp1(v, OP_Close, iCur);
57081     }
57082   }
57083
57084   /*
57085   ** Return the number of rows that were deleted. If this routine is 
57086   ** generating code because of a call to sqlite3NestedParse(), do not
57087   ** invoke the callback function.
57088   */
57089   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
57090     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
57091     sqlite3VdbeSetNumCols(v, 1);
57092     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC);
57093   }
57094
57095 delete_from_cleanup:
57096   sqlite3AuthContextPop(&sContext);
57097   sqlite3SrcListDelete(pTabList);
57098   sqlite3ExprDelete(pWhere);
57099   return;
57100 }
57101
57102 /*
57103 ** This routine generates VDBE code that causes a single row of a
57104 ** single table to be deleted.
57105 **
57106 ** The VDBE must be in a particular state when this routine is called.
57107 ** These are the requirements:
57108 **
57109 **   1.  A read/write cursor pointing to pTab, the table containing the row
57110 **       to be deleted, must be opened as cursor number "base".
57111 **
57112 **   2.  Read/write cursors for all indices of pTab must be open as
57113 **       cursor number base+i for the i-th index.
57114 **
57115 **   3.  The record number of the row to be deleted must be stored in
57116 **       memory cell iRowid.
57117 **
57118 ** This routine pops the top of the stack to remove the record number
57119 ** and then generates code to remove both the table record and all index
57120 ** entries that point to that record.
57121 */
57122 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
57123   Parse *pParse,     /* Parsing context */
57124   Table *pTab,       /* Table containing the row to be deleted */
57125   int iCur,          /* Cursor number for the table */
57126   int iRowid,        /* Memory cell that contains the rowid to delete */
57127   int count          /* Increment the row change counter */
57128 ){
57129   int addr;
57130   Vdbe *v;
57131
57132   v = pParse->pVdbe;
57133   addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
57134   sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
57135   sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
57136   if( count ){
57137     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
57138   }
57139   sqlite3VdbeJumpHere(v, addr);
57140 }
57141
57142 /*
57143 ** This routine generates VDBE code that causes the deletion of all
57144 ** index entries associated with a single row of a single table.
57145 **
57146 ** The VDBE must be in a particular state when this routine is called.
57147 ** These are the requirements:
57148 **
57149 **   1.  A read/write cursor pointing to pTab, the table containing the row
57150 **       to be deleted, must be opened as cursor number "iCur".
57151 **
57152 **   2.  Read/write cursors for all indices of pTab must be open as
57153 **       cursor number iCur+i for the i-th index.
57154 **
57155 **   3.  The "iCur" cursor must be pointing to the row that is to be
57156 **       deleted.
57157 */
57158 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
57159   Parse *pParse,     /* Parsing and code generating context */
57160   Table *pTab,       /* Table containing the row to be deleted */
57161   int iCur,          /* Cursor number for the table */
57162   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
57163 ){
57164   int i;
57165   Index *pIdx;
57166   int r1;
57167
57168   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
57169     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
57170     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
57171     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
57172   }
57173 }
57174
57175 /*
57176 ** Generate code that will assemble an index key and put it in register
57177 ** regOut.  The key with be for index pIdx which is an index on pTab.
57178 ** iCur is the index of a cursor open on the pTab table and pointing to
57179 ** the entry that needs indexing.
57180 **
57181 ** Return a register number which is the first in a block of
57182 ** registers that holds the elements of the index key.  The
57183 ** block of registers has already been deallocated by the time
57184 ** this routine returns.
57185 */
57186 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
57187   Parse *pParse,     /* Parsing context */
57188   Index *pIdx,       /* The index for which to generate a key */
57189   int iCur,          /* Cursor number for the pIdx->pTable table */
57190   int regOut,        /* Write the new index key to this register */
57191   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
57192 ){
57193   Vdbe *v = pParse->pVdbe;
57194   int j;
57195   Table *pTab = pIdx->pTable;
57196   int regBase;
57197   int nCol;
57198
57199   nCol = pIdx->nColumn;
57200   regBase = sqlite3GetTempRange(pParse, nCol+1);
57201   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
57202   for(j=0; j<nCol; j++){
57203     int idx = pIdx->aiColumn[j];
57204     if( idx==pTab->iPKey ){
57205       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
57206     }else{
57207       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
57208       sqlite3ColumnDefault(v, pTab, idx);
57209     }
57210   }
57211   if( doMakeRec ){
57212     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
57213     sqlite3IndexAffinityStr(v, pIdx);
57214     sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
57215   }
57216   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
57217   return regBase;
57218 }
57219
57220 /* Make sure "isView" gets undefined in case this file becomes part of
57221 ** the amalgamation - so that subsequent files do not see isView as a
57222 ** macro. */
57223 #undef isView
57224
57225 /************** End of delete.c **********************************************/
57226 /************** Begin file func.c ********************************************/
57227 /*
57228 ** 2002 February 23
57229 **
57230 ** The author disclaims copyright to this source code.  In place of
57231 ** a legal notice, here is a blessing:
57232 **
57233 **    May you do good and not evil.
57234 **    May you find forgiveness for yourself and forgive others.
57235 **    May you share freely, never taking more than you give.
57236 **
57237 *************************************************************************
57238 ** This file contains the C functions that implement various SQL
57239 ** functions of SQLite.  
57240 **
57241 ** There is only one exported symbol in this file - the function
57242 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
57243 ** All other code has file scope.
57244 **
57245 ** $Id: func.c,v 1.192 2008/04/27 18:40:12 drh Exp $
57246 */
57247
57248
57249 /*
57250 ** Return the collating function associated with a function.
57251 */
57252 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
57253   return context->pColl;
57254 }
57255
57256 /*
57257 ** Implementation of the non-aggregate min() and max() functions
57258 */
57259 static void minmaxFunc(
57260   sqlite3_context *context,
57261   int argc,
57262   sqlite3_value **argv
57263 ){
57264   int i;
57265   int mask;    /* 0 for min() or 0xffffffff for max() */
57266   int iBest;
57267   CollSeq *pColl;
57268
57269   if( argc==0 ) return;
57270   mask = sqlite3_user_data(context)==0 ? 0 : -1;
57271   pColl = sqlite3GetFuncCollSeq(context);
57272   assert( pColl );
57273   assert( mask==-1 || mask==0 );
57274   iBest = 0;
57275   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
57276   for(i=1; i<argc; i++){
57277     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
57278     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
57279       iBest = i;
57280     }
57281   }
57282   sqlite3_result_value(context, argv[iBest]);
57283 }
57284
57285 /*
57286 ** Return the type of the argument.
57287 */
57288 static void typeofFunc(
57289   sqlite3_context *context,
57290   int argc,
57291   sqlite3_value **argv
57292 ){
57293   const char *z = 0;
57294   switch( sqlite3_value_type(argv[0]) ){
57295     case SQLITE_NULL:    z = "null";    break;
57296     case SQLITE_INTEGER: z = "integer"; break;
57297     case SQLITE_TEXT:    z = "text";    break;
57298     case SQLITE_FLOAT:   z = "real";    break;
57299     case SQLITE_BLOB:    z = "blob";    break;
57300   }
57301   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
57302 }
57303
57304
57305 /*
57306 ** Implementation of the length() function
57307 */
57308 static void lengthFunc(
57309   sqlite3_context *context,
57310   int argc,
57311   sqlite3_value **argv
57312 ){
57313   int len;
57314
57315   assert( argc==1 );
57316   switch( sqlite3_value_type(argv[0]) ){
57317     case SQLITE_BLOB:
57318     case SQLITE_INTEGER:
57319     case SQLITE_FLOAT: {
57320       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
57321       break;
57322     }
57323     case SQLITE_TEXT: {
57324       const unsigned char *z = sqlite3_value_text(argv[0]);
57325       if( z==0 ) return;
57326       len = 0;
57327       while( *z ){
57328         len++;
57329         SQLITE_SKIP_UTF8(z);
57330       }
57331       sqlite3_result_int(context, len);
57332       break;
57333     }
57334     default: {
57335       sqlite3_result_null(context);
57336       break;
57337     }
57338   }
57339 }
57340
57341 /*
57342 ** Implementation of the abs() function
57343 */
57344 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
57345   assert( argc==1 );
57346   switch( sqlite3_value_type(argv[0]) ){
57347     case SQLITE_INTEGER: {
57348       i64 iVal = sqlite3_value_int64(argv[0]);
57349       if( iVal<0 ){
57350         if( (iVal<<1)==0 ){
57351           sqlite3_result_error(context, "integer overflow", -1);
57352           return;
57353         }
57354         iVal = -iVal;
57355       } 
57356       sqlite3_result_int64(context, iVal);
57357       break;
57358     }
57359     case SQLITE_NULL: {
57360       sqlite3_result_null(context);
57361       break;
57362     }
57363     default: {
57364       double rVal = sqlite3_value_double(argv[0]);
57365       if( rVal<0 ) rVal = -rVal;
57366       sqlite3_result_double(context, rVal);
57367       break;
57368     }
57369   }
57370 }
57371
57372 /*
57373 ** Implementation of the substr() function.
57374 **
57375 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
57376 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
57377 ** of x.  If x is text, then we actually count UTF-8 characters.
57378 ** If x is a blob, then we count bytes.
57379 **
57380 ** If p1 is negative, then we begin abs(p1) from the end of x[].
57381 */
57382 static void substrFunc(
57383   sqlite3_context *context,
57384   int argc,
57385   sqlite3_value **argv
57386 ){
57387   const unsigned char *z;
57388   const unsigned char *z2;
57389   int len;
57390   int p0type;
57391   i64 p1, p2;
57392
57393   assert( argc==3 || argc==2 );
57394   p0type = sqlite3_value_type(argv[0]);
57395   if( p0type==SQLITE_BLOB ){
57396     len = sqlite3_value_bytes(argv[0]);
57397     z = sqlite3_value_blob(argv[0]);
57398     if( z==0 ) return;
57399     assert( len==sqlite3_value_bytes(argv[0]) );
57400   }else{
57401     z = sqlite3_value_text(argv[0]);
57402     if( z==0 ) return;
57403     len = 0;
57404     for(z2=z; *z2; len++){
57405       SQLITE_SKIP_UTF8(z2);
57406     }
57407   }
57408   p1 = sqlite3_value_int(argv[1]);
57409   if( argc==3 ){
57410     p2 = sqlite3_value_int(argv[2]);
57411   }else{
57412     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
57413   }
57414   if( p1<0 ){
57415     p1 += len;
57416     if( p1<0 ){
57417       p2 += p1;
57418       p1 = 0;
57419     }
57420   }else if( p1>0 ){
57421     p1--;
57422   }
57423   if( p1+p2>len ){
57424     p2 = len-p1;
57425   }
57426   if( p0type!=SQLITE_BLOB ){
57427     while( *z && p1 ){
57428       SQLITE_SKIP_UTF8(z);
57429       p1--;
57430     }
57431     for(z2=z; *z2 && p2; p2--){
57432       SQLITE_SKIP_UTF8(z2);
57433     }
57434     sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
57435   }else{
57436     if( p2<0 ) p2 = 0;
57437     sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
57438   }
57439 }
57440
57441 /*
57442 ** Implementation of the round() function
57443 */
57444 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
57445   int n = 0;
57446   double r;
57447   char zBuf[500];  /* larger than the %f representation of the largest double */
57448   assert( argc==1 || argc==2 );
57449   if( argc==2 ){
57450     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
57451     n = sqlite3_value_int(argv[1]);
57452     if( n>30 ) n = 30;
57453     if( n<0 ) n = 0;
57454   }
57455   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
57456   r = sqlite3_value_double(argv[0]);
57457   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
57458   sqlite3AtoF(zBuf, &r);
57459   sqlite3_result_double(context, r);
57460 }
57461
57462 /*
57463 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
57464 ** allocation fails, call sqlite3_result_error_nomem() to notify
57465 ** the database handle that malloc() has failed.
57466 */
57467 static void *contextMalloc(sqlite3_context *context, i64 nByte){
57468   char *z;
57469   if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
57470     sqlite3_result_error_toobig(context);
57471     z = 0;
57472   }else{
57473     z = sqlite3_malloc(nByte);
57474     if( !z && nByte>0 ){
57475       sqlite3_result_error_nomem(context);
57476     }
57477   }
57478   return z;
57479 }
57480
57481 /*
57482 ** Implementation of the upper() and lower() SQL functions.
57483 */
57484 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
57485   char *z1;
57486   const char *z2;
57487   int i, n;
57488   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
57489   z2 = (char*)sqlite3_value_text(argv[0]);
57490   n = sqlite3_value_bytes(argv[0]);
57491   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
57492   assert( z2==(char*)sqlite3_value_text(argv[0]) );
57493   if( z2 ){
57494     z1 = contextMalloc(context, ((i64)n)+1);
57495     if( z1 ){
57496       memcpy(z1, z2, n+1);
57497       for(i=0; z1[i]; i++){
57498         z1[i] = toupper(z1[i]);
57499       }
57500       sqlite3_result_text(context, z1, -1, sqlite3_free);
57501     }
57502   }
57503 }
57504 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
57505   char *z1;
57506   const char *z2;
57507   int i, n;
57508   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
57509   z2 = (char*)sqlite3_value_text(argv[0]);
57510   n = sqlite3_value_bytes(argv[0]);
57511   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
57512   assert( z2==(char*)sqlite3_value_text(argv[0]) );
57513   if( z2 ){
57514     z1 = contextMalloc(context, ((i64)n)+1);
57515     if( z1 ){
57516       memcpy(z1, z2, n+1);
57517       for(i=0; z1[i]; i++){
57518         z1[i] = tolower(z1[i]);
57519       }
57520       sqlite3_result_text(context, z1, -1, sqlite3_free);
57521     }
57522   }
57523 }
57524
57525 /*
57526 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
57527 ** All three do the same thing.  They return the first non-NULL
57528 ** argument.
57529 */
57530 static void ifnullFunc(
57531   sqlite3_context *context,
57532   int argc,
57533   sqlite3_value **argv
57534 ){
57535   int i;
57536   for(i=0; i<argc; i++){
57537     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
57538       sqlite3_result_value(context, argv[i]);
57539       break;
57540     }
57541   }
57542 }
57543
57544 /*
57545 ** Implementation of random().  Return a random integer.  
57546 */
57547 static void randomFunc(
57548   sqlite3_context *context,
57549   int argc,
57550   sqlite3_value **argv
57551 ){
57552   sqlite_int64 r;
57553   sqlite3_randomness(sizeof(r), &r);
57554   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
57555                           /* can always do abs() of the result */
57556   sqlite3_result_int64(context, r);
57557 }
57558
57559 /*
57560 ** Implementation of randomblob(N).  Return a random blob
57561 ** that is N bytes long.
57562 */
57563 static void randomBlob(
57564   sqlite3_context *context,
57565   int argc,
57566   sqlite3_value **argv
57567 ){
57568   int n;
57569   unsigned char *p;
57570   assert( argc==1 );
57571   n = sqlite3_value_int(argv[0]);
57572   if( n<1 ){
57573     n = 1;
57574   }
57575   p = contextMalloc(context, n);
57576   if( p ){
57577     sqlite3_randomness(n, p);
57578     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
57579   }
57580 }
57581
57582 /*
57583 ** Implementation of the last_insert_rowid() SQL function.  The return
57584 ** value is the same as the sqlite3_last_insert_rowid() API function.
57585 */
57586 static void last_insert_rowid(
57587   sqlite3_context *context, 
57588   int arg, 
57589   sqlite3_value **argv
57590 ){
57591   sqlite3 *db = sqlite3_context_db_handle(context);
57592   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
57593 }
57594
57595 /*
57596 ** Implementation of the changes() SQL function.  The return value is the
57597 ** same as the sqlite3_changes() API function.
57598 */
57599 static void changes(
57600   sqlite3_context *context,
57601   int arg,
57602   sqlite3_value **argv
57603 ){
57604   sqlite3 *db = sqlite3_context_db_handle(context);
57605   sqlite3_result_int(context, sqlite3_changes(db));
57606 }
57607
57608 /*
57609 ** Implementation of the total_changes() SQL function.  The return value is
57610 ** the same as the sqlite3_total_changes() API function.
57611 */
57612 static void total_changes(
57613   sqlite3_context *context,
57614   int arg,
57615   sqlite3_value **argv
57616 ){
57617   sqlite3 *db = sqlite3_context_db_handle(context);
57618   sqlite3_result_int(context, sqlite3_total_changes(db));
57619 }
57620
57621 /*
57622 ** A structure defining how to do GLOB-style comparisons.
57623 */
57624 struct compareInfo {
57625   u8 matchAll;
57626   u8 matchOne;
57627   u8 matchSet;
57628   u8 noCase;
57629 };
57630
57631 /*
57632 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
57633 ** character is exactly one byte in size.  Also, all characters are
57634 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
57635 ** whereas only characters less than 0x80 do in ASCII.
57636 */
57637 #if defined(SQLITE_EBCDIC)
57638 # define sqlite3Utf8Read(A,B,C)  (*(A++))
57639 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
57640 #else
57641 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
57642 #endif
57643
57644 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
57645 /* The correct SQL-92 behavior is for the LIKE operator to ignore
57646 ** case.  Thus  'a' LIKE 'A' would be true. */
57647 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
57648 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
57649 ** is case sensitive causing 'a' LIKE 'A' to be false */
57650 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
57651
57652 /*
57653 ** Compare two UTF-8 strings for equality where the first string can
57654 ** potentially be a "glob" expression.  Return true (1) if they
57655 ** are the same and false (0) if they are different.
57656 **
57657 ** Globbing rules:
57658 **
57659 **      '*'       Matches any sequence of zero or more characters.
57660 **
57661 **      '?'       Matches exactly one character.
57662 **
57663 **     [...]      Matches one character from the enclosed list of
57664 **                characters.
57665 **
57666 **     [^...]     Matches one character not in the enclosed list.
57667 **
57668 ** With the [...] and [^...] matching, a ']' character can be included
57669 ** in the list by making it the first character after '[' or '^'.  A
57670 ** range of characters can be specified using '-'.  Example:
57671 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
57672 ** it the last character in the list.
57673 **
57674 ** This routine is usually quick, but can be N**2 in the worst case.
57675 **
57676 ** Hints: to match '*' or '?', put them in "[]".  Like this:
57677 **
57678 **         abc[*]xyz        Matches "abc*xyz" only
57679 */
57680 static int patternCompare(
57681   const u8 *zPattern,              /* The glob pattern */
57682   const u8 *zString,               /* The string to compare against the glob */
57683   const struct compareInfo *pInfo, /* Information about how to do the compare */
57684   const int esc                    /* The escape character */
57685 ){
57686   int c, c2;
57687   int invert;
57688   int seen;
57689   u8 matchOne = pInfo->matchOne;
57690   u8 matchAll = pInfo->matchAll;
57691   u8 matchSet = pInfo->matchSet;
57692   u8 noCase = pInfo->noCase; 
57693   int prevEscape = 0;     /* True if the previous character was 'escape' */
57694
57695   while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
57696     if( !prevEscape && c==matchAll ){
57697       while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
57698                || c == matchOne ){
57699         if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
57700           return 0;
57701         }
57702       }
57703       if( c==0 ){
57704         return 1;
57705       }else if( c==esc ){
57706         c = sqlite3Utf8Read(zPattern, 0, &zPattern);
57707         if( c==0 ){
57708           return 0;
57709         }
57710       }else if( c==matchSet ){
57711         assert( esc==0 );         /* This is GLOB, not LIKE */
57712         assert( matchSet<0x80 );  /* '[' is a single-byte character */
57713         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
57714           SQLITE_SKIP_UTF8(zString);
57715         }
57716         return *zString!=0;
57717       }
57718       while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
57719         if( noCase ){
57720           GlogUpperToLower(c2);
57721           GlogUpperToLower(c);
57722           while( c2 != 0 && c2 != c ){
57723             c2 = sqlite3Utf8Read(zString, 0, &zString);
57724             GlogUpperToLower(c2);
57725           }
57726         }else{
57727           while( c2 != 0 && c2 != c ){
57728             c2 = sqlite3Utf8Read(zString, 0, &zString);
57729           }
57730         }
57731         if( c2==0 ) return 0;
57732         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
57733       }
57734       return 0;
57735     }else if( !prevEscape && c==matchOne ){
57736       if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
57737         return 0;
57738       }
57739     }else if( c==matchSet ){
57740       int prior_c = 0;
57741       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
57742       seen = 0;
57743       invert = 0;
57744       c = sqlite3Utf8Read(zString, 0, &zString);
57745       if( c==0 ) return 0;
57746       c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
57747       if( c2=='^' ){
57748         invert = 1;
57749         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
57750       }
57751       if( c2==']' ){
57752         if( c==']' ) seen = 1;
57753         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
57754       }
57755       while( c2 && c2!=']' ){
57756         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
57757           c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
57758           if( c>=prior_c && c<=c2 ) seen = 1;
57759           prior_c = 0;
57760         }else{
57761           if( c==c2 ){
57762             seen = 1;
57763           }
57764           prior_c = c2;
57765         }
57766         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
57767       }
57768       if( c2==0 || (seen ^ invert)==0 ){
57769         return 0;
57770       }
57771     }else if( esc==c && !prevEscape ){
57772       prevEscape = 1;
57773     }else{
57774       c2 = sqlite3Utf8Read(zString, 0, &zString);
57775       if( noCase ){
57776         GlogUpperToLower(c);
57777         GlogUpperToLower(c2);
57778       }
57779       if( c!=c2 ){
57780         return 0;
57781       }
57782       prevEscape = 0;
57783     }
57784   }
57785   return *zString==0;
57786 }
57787
57788 /*
57789 ** Count the number of times that the LIKE operator (or GLOB which is
57790 ** just a variation of LIKE) gets called.  This is used for testing
57791 ** only.
57792 */
57793 #ifdef SQLITE_TEST
57794 SQLITE_API int sqlite3_like_count = 0;
57795 #endif
57796
57797
57798 /*
57799 ** Implementation of the like() SQL function.  This function implements
57800 ** the build-in LIKE operator.  The first argument to the function is the
57801 ** pattern and the second argument is the string.  So, the SQL statements:
57802 **
57803 **       A LIKE B
57804 **
57805 ** is implemented as like(B,A).
57806 **
57807 ** This same function (with a different compareInfo structure) computes
57808 ** the GLOB operator.
57809 */
57810 static void likeFunc(
57811   sqlite3_context *context, 
57812   int argc, 
57813   sqlite3_value **argv
57814 ){
57815   const unsigned char *zA, *zB;
57816   int escape = 0;
57817   sqlite3 *db = sqlite3_context_db_handle(context);
57818
57819   zB = sqlite3_value_text(argv[0]);
57820   zA = sqlite3_value_text(argv[1]);
57821
57822   /* Limit the length of the LIKE or GLOB pattern to avoid problems
57823   ** of deep recursion and N*N behavior in patternCompare().
57824   */
57825   if( sqlite3_value_bytes(argv[0]) >
57826         db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
57827     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
57828     return;
57829   }
57830   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
57831
57832   if( argc==3 ){
57833     /* The escape character string must consist of a single UTF-8 character.
57834     ** Otherwise, return an error.
57835     */
57836     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
57837     if( zEsc==0 ) return;
57838     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
57839       sqlite3_result_error(context, 
57840           "ESCAPE expression must be a single character", -1);
57841       return;
57842     }
57843     escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
57844   }
57845   if( zA && zB ){
57846     struct compareInfo *pInfo = sqlite3_user_data(context);
57847 #ifdef SQLITE_TEST
57848     sqlite3_like_count++;
57849 #endif
57850     
57851     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
57852   }
57853 }
57854
57855 /*
57856 ** Implementation of the NULLIF(x,y) function.  The result is the first
57857 ** argument if the arguments are different.  The result is NULL if the
57858 ** arguments are equal to each other.
57859 */
57860 static void nullifFunc(
57861   sqlite3_context *context,
57862   int argc,
57863   sqlite3_value **argv
57864 ){
57865   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
57866   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
57867     sqlite3_result_value(context, argv[0]);
57868   }
57869 }
57870
57871 /*
57872 ** Implementation of the VERSION(*) function.  The result is the version
57873 ** of the SQLite library that is running.
57874 */
57875 static void versionFunc(
57876   sqlite3_context *context,
57877   int argc,
57878   sqlite3_value **argv
57879 ){
57880   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
57881 }
57882
57883 /* Array for converting from half-bytes (nybbles) into ASCII hex
57884 ** digits. */
57885 static const char hexdigits[] = {
57886   '0', '1', '2', '3', '4', '5', '6', '7',
57887   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
57888 };
57889
57890 /*
57891 ** EXPERIMENTAL - This is not an official function.  The interface may
57892 ** change.  This function may disappear.  Do not write code that depends
57893 ** on this function.
57894 **
57895 ** Implementation of the QUOTE() function.  This function takes a single
57896 ** argument.  If the argument is numeric, the return value is the same as
57897 ** the argument.  If the argument is NULL, the return value is the string
57898 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
57899 ** single-quote escapes.
57900 */
57901 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
57902   if( argc<1 ) return;
57903   switch( sqlite3_value_type(argv[0]) ){
57904     case SQLITE_NULL: {
57905       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
57906       break;
57907     }
57908     case SQLITE_INTEGER:
57909     case SQLITE_FLOAT: {
57910       sqlite3_result_value(context, argv[0]);
57911       break;
57912     }
57913     case SQLITE_BLOB: {
57914       char *zText = 0;
57915       char const *zBlob = sqlite3_value_blob(argv[0]);
57916       int nBlob = sqlite3_value_bytes(argv[0]);
57917       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
57918       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
57919       if( zText ){
57920         int i;
57921         for(i=0; i<nBlob; i++){
57922           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
57923           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
57924         }
57925         zText[(nBlob*2)+2] = '\'';
57926         zText[(nBlob*2)+3] = '\0';
57927         zText[0] = 'X';
57928         zText[1] = '\'';
57929         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
57930         sqlite3_free(zText);
57931       }
57932       break;
57933     }
57934     case SQLITE_TEXT: {
57935       int i,j;
57936       u64 n;
57937       const unsigned char *zArg = sqlite3_value_text(argv[0]);
57938       char *z;
57939
57940       if( zArg==0 ) return;
57941       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
57942       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
57943       if( z ){
57944         z[0] = '\'';
57945         for(i=0, j=1; zArg[i]; i++){
57946           z[j++] = zArg[i];
57947           if( zArg[i]=='\'' ){
57948             z[j++] = '\'';
57949           }
57950         }
57951         z[j++] = '\'';
57952         z[j] = 0;
57953         sqlite3_result_text(context, z, j, sqlite3_free);
57954       }
57955     }
57956   }
57957 }
57958
57959 /*
57960 ** The hex() function.  Interpret the argument as a blob.  Return
57961 ** a hexadecimal rendering as text.
57962 */
57963 static void hexFunc(
57964   sqlite3_context *context,
57965   int argc,
57966   sqlite3_value **argv
57967 ){
57968   int i, n;
57969   const unsigned char *pBlob;
57970   char *zHex, *z;
57971   assert( argc==1 );
57972   pBlob = sqlite3_value_blob(argv[0]);
57973   n = sqlite3_value_bytes(argv[0]);
57974   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
57975   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
57976   if( zHex ){
57977     for(i=0; i<n; i++, pBlob++){
57978       unsigned char c = *pBlob;
57979       *(z++) = hexdigits[(c>>4)&0xf];
57980       *(z++) = hexdigits[c&0xf];
57981     }
57982     *z = 0;
57983     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
57984   }
57985 }
57986
57987 /*
57988 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
57989 */
57990 static void zeroblobFunc(
57991   sqlite3_context *context,
57992   int argc,
57993   sqlite3_value **argv
57994 ){
57995   i64 n;
57996   assert( argc==1 );
57997   n = sqlite3_value_int64(argv[0]);
57998   if( n>SQLITE_MAX_LENGTH ){
57999     sqlite3_result_error_toobig(context);
58000   }else{
58001     sqlite3_result_zeroblob(context, n);
58002   }
58003 }
58004
58005 /*
58006 ** The replace() function.  Three arguments are all strings: call
58007 ** them A, B, and C. The result is also a string which is derived
58008 ** from A by replacing every occurance of B with C.  The match
58009 ** must be exact.  Collating sequences are not used.
58010 */
58011 static void replaceFunc(
58012   sqlite3_context *context,
58013   int argc,
58014   sqlite3_value **argv
58015 ){
58016   const unsigned char *zStr;        /* The input string A */
58017   const unsigned char *zPattern;    /* The pattern string B */
58018   const unsigned char *zRep;        /* The replacement string C */
58019   unsigned char *zOut;              /* The output */
58020   int nStr;                /* Size of zStr */
58021   int nPattern;            /* Size of zPattern */
58022   int nRep;                /* Size of zRep */
58023   i64 nOut;                /* Maximum size of zOut */
58024   int loopLimit;           /* Last zStr[] that might match zPattern[] */
58025   int i, j;                /* Loop counters */
58026
58027   assert( argc==3 );
58028   zStr = sqlite3_value_text(argv[0]);
58029   if( zStr==0 ) return;
58030   nStr = sqlite3_value_bytes(argv[0]);
58031   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
58032   zPattern = sqlite3_value_text(argv[1]);
58033   if( zPattern==0 || zPattern[0]==0 ) return;
58034   nPattern = sqlite3_value_bytes(argv[1]);
58035   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
58036   zRep = sqlite3_value_text(argv[2]);
58037   if( zRep==0 ) return;
58038   nRep = sqlite3_value_bytes(argv[2]);
58039   assert( zRep==sqlite3_value_text(argv[2]) );
58040   nOut = nStr + 1;
58041   assert( nOut<SQLITE_MAX_LENGTH );
58042   zOut = contextMalloc(context, (i64)nOut);
58043   if( zOut==0 ){
58044     return;
58045   }
58046   loopLimit = nStr - nPattern;  
58047   for(i=j=0; i<=loopLimit; i++){
58048     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
58049       zOut[j++] = zStr[i];
58050     }else{
58051       u8 *zOld;
58052       sqlite3 *db = sqlite3_context_db_handle(context);
58053       nOut += nRep - nPattern;
58054       if( nOut>=db->aLimit[SQLITE_LIMIT_LENGTH] ){
58055         sqlite3_result_error_toobig(context);
58056         sqlite3_free(zOut);
58057         return;
58058       }
58059       zOld = zOut;
58060       zOut = sqlite3_realloc(zOut, (int)nOut);
58061       if( zOut==0 ){
58062         sqlite3_result_error_nomem(context);
58063         sqlite3_free(zOld);
58064         return;
58065       }
58066       memcpy(&zOut[j], zRep, nRep);
58067       j += nRep;
58068       i += nPattern-1;
58069     }
58070   }
58071   assert( j+nStr-i+1==nOut );
58072   memcpy(&zOut[j], &zStr[i], nStr-i);
58073   j += nStr - i;
58074   assert( j<=nOut );
58075   zOut[j] = 0;
58076   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
58077 }
58078
58079 /*
58080 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
58081 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
58082 */
58083 static void trimFunc(
58084   sqlite3_context *context,
58085   int argc,
58086   sqlite3_value **argv
58087 ){
58088   const unsigned char *zIn;         /* Input string */
58089   const unsigned char *zCharSet;    /* Set of characters to trim */
58090   int nIn;                          /* Number of bytes in input */
58091   int flags;                        /* 1: trimleft  2: trimright  3: trim */
58092   int i;                            /* Loop counter */
58093   unsigned char *aLen;              /* Length of each character in zCharSet */
58094   unsigned char **azChar;           /* Individual characters in zCharSet */
58095   int nChar;                        /* Number of characters in zCharSet */
58096
58097   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
58098     return;
58099   }
58100   zIn = sqlite3_value_text(argv[0]);
58101   if( zIn==0 ) return;
58102   nIn = sqlite3_value_bytes(argv[0]);
58103   assert( zIn==sqlite3_value_text(argv[0]) );
58104   if( argc==1 ){
58105     static const unsigned char lenOne[] = { 1 };
58106     static const unsigned char *azOne[] = { (u8*)" " };
58107     nChar = 1;
58108     aLen = (u8*)lenOne;
58109     azChar = (unsigned char **)azOne;
58110     zCharSet = 0;
58111   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
58112     return;
58113   }else{
58114     const unsigned char *z;
58115     for(z=zCharSet, nChar=0; *z; nChar++){
58116       SQLITE_SKIP_UTF8(z);
58117     }
58118     if( nChar>0 ){
58119       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
58120       if( azChar==0 ){
58121         return;
58122       }
58123       aLen = (unsigned char*)&azChar[nChar];
58124       for(z=zCharSet, nChar=0; *z; nChar++){
58125         azChar[nChar] = (unsigned char *)z;
58126         SQLITE_SKIP_UTF8(z);
58127         aLen[nChar] = z - azChar[nChar];
58128       }
58129     }
58130   }
58131   if( nChar>0 ){
58132     flags = (int)sqlite3_user_data(context);
58133     if( flags & 1 ){
58134       while( nIn>0 ){
58135         int len;
58136         for(i=0; i<nChar; i++){
58137           len = aLen[i];
58138           if( memcmp(zIn, azChar[i], len)==0 ) break;
58139         }
58140         if( i>=nChar ) break;
58141         zIn += len;
58142         nIn -= len;
58143       }
58144     }
58145     if( flags & 2 ){
58146       while( nIn>0 ){
58147         int len;
58148         for(i=0; i<nChar; i++){
58149           len = aLen[i];
58150           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
58151         }
58152         if( i>=nChar ) break;
58153         nIn -= len;
58154       }
58155     }
58156     if( zCharSet ){
58157       sqlite3_free(azChar);
58158     }
58159   }
58160   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
58161 }
58162
58163 #ifdef SQLITE_SOUNDEX
58164 /*
58165 ** Compute the soundex encoding of a word.
58166 */
58167 static void soundexFunc(
58168   sqlite3_context *context,
58169   int argc,
58170   sqlite3_value **argv
58171 ){
58172   char zResult[8];
58173   const u8 *zIn;
58174   int i, j;
58175   static const unsigned char iCode[] = {
58176     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
58177     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
58178     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
58179     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
58180     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
58181     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
58182     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
58183     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
58184   };
58185   assert( argc==1 );
58186   zIn = (u8*)sqlite3_value_text(argv[0]);
58187   if( zIn==0 ) zIn = (u8*)"";
58188   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
58189   if( zIn[i] ){
58190     u8 prevcode = iCode[zIn[i]&0x7f];
58191     zResult[0] = toupper(zIn[i]);
58192     for(j=1; j<4 && zIn[i]; i++){
58193       int code = iCode[zIn[i]&0x7f];
58194       if( code>0 ){
58195         if( code!=prevcode ){
58196           prevcode = code;
58197           zResult[j++] = code + '0';
58198         }
58199       }else{
58200         prevcode = 0;
58201       }
58202     }
58203     while( j<4 ){
58204       zResult[j++] = '0';
58205     }
58206     zResult[j] = 0;
58207     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
58208   }else{
58209     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
58210   }
58211 }
58212 #endif
58213
58214 #ifndef SQLITE_OMIT_LOAD_EXTENSION
58215 /*
58216 ** A function that loads a shared-library extension then returns NULL.
58217 */
58218 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
58219   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
58220   const char *zProc;
58221   sqlite3 *db = sqlite3_context_db_handle(context);
58222   char *zErrMsg = 0;
58223
58224   if( argc==2 ){
58225     zProc = (const char *)sqlite3_value_text(argv[1]);
58226   }else{
58227     zProc = 0;
58228   }
58229   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
58230     sqlite3_result_error(context, zErrMsg, -1);
58231     sqlite3_free(zErrMsg);
58232   }
58233 }
58234 #endif
58235
58236
58237 /*
58238 ** An instance of the following structure holds the context of a
58239 ** sum() or avg() aggregate computation.
58240 */
58241 typedef struct SumCtx SumCtx;
58242 struct SumCtx {
58243   double rSum;      /* Floating point sum */
58244   i64 iSum;         /* Integer sum */   
58245   i64 cnt;          /* Number of elements summed */
58246   u8 overflow;      /* True if integer overflow seen */
58247   u8 approx;        /* True if non-integer value was input to the sum */
58248 };
58249
58250 /*
58251 ** Routines used to compute the sum, average, and total.
58252 **
58253 ** The SUM() function follows the (broken) SQL standard which means
58254 ** that it returns NULL if it sums over no inputs.  TOTAL returns
58255 ** 0.0 in that case.  In addition, TOTAL always returns a float where
58256 ** SUM might return an integer if it never encounters a floating point
58257 ** value.  TOTAL never fails, but SUM might through an exception if
58258 ** it overflows an integer.
58259 */
58260 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
58261   SumCtx *p;
58262   int type;
58263   assert( argc==1 );
58264   p = sqlite3_aggregate_context(context, sizeof(*p));
58265   type = sqlite3_value_numeric_type(argv[0]);
58266   if( p && type!=SQLITE_NULL ){
58267     p->cnt++;
58268     if( type==SQLITE_INTEGER ){
58269       i64 v = sqlite3_value_int64(argv[0]);
58270       p->rSum += v;
58271       if( (p->approx|p->overflow)==0 ){
58272         i64 iNewSum = p->iSum + v;
58273         int s1 = p->iSum >> (sizeof(i64)*8-1);
58274         int s2 = v       >> (sizeof(i64)*8-1);
58275         int s3 = iNewSum >> (sizeof(i64)*8-1);
58276         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
58277         p->iSum = iNewSum;
58278       }
58279     }else{
58280       p->rSum += sqlite3_value_double(argv[0]);
58281       p->approx = 1;
58282     }
58283   }
58284 }
58285 static void sumFinalize(sqlite3_context *context){
58286   SumCtx *p;
58287   p = sqlite3_aggregate_context(context, 0);
58288   if( p && p->cnt>0 ){
58289     if( p->overflow ){
58290       sqlite3_result_error(context,"integer overflow",-1);
58291     }else if( p->approx ){
58292       sqlite3_result_double(context, p->rSum);
58293     }else{
58294       sqlite3_result_int64(context, p->iSum);
58295     }
58296   }
58297 }
58298 static void avgFinalize(sqlite3_context *context){
58299   SumCtx *p;
58300   p = sqlite3_aggregate_context(context, 0);
58301   if( p && p->cnt>0 ){
58302     sqlite3_result_double(context, p->rSum/(double)p->cnt);
58303   }
58304 }
58305 static void totalFinalize(sqlite3_context *context){
58306   SumCtx *p;
58307   p = sqlite3_aggregate_context(context, 0);
58308   sqlite3_result_double(context, p ? p->rSum : 0.0);
58309 }
58310
58311 /*
58312 ** The following structure keeps track of state information for the
58313 ** count() aggregate function.
58314 */
58315 typedef struct CountCtx CountCtx;
58316 struct CountCtx {
58317   i64 n;
58318 };
58319
58320 /*
58321 ** Routines to implement the count() aggregate function.
58322 */
58323 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
58324   CountCtx *p;
58325   p = sqlite3_aggregate_context(context, sizeof(*p));
58326   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
58327     p->n++;
58328   }
58329 }   
58330 static void countFinalize(sqlite3_context *context){
58331   CountCtx *p;
58332   p = sqlite3_aggregate_context(context, 0);
58333   sqlite3_result_int64(context, p ? p->n : 0);
58334 }
58335
58336 /*
58337 ** Routines to implement min() and max() aggregate functions.
58338 */
58339 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
58340   Mem *pArg  = (Mem *)argv[0];
58341   Mem *pBest;
58342
58343   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
58344   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
58345   if( !pBest ) return;
58346
58347   if( pBest->flags ){
58348     int max;
58349     int cmp;
58350     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
58351     /* This step function is used for both the min() and max() aggregates,
58352     ** the only difference between the two being that the sense of the
58353     ** comparison is inverted. For the max() aggregate, the
58354     ** sqlite3_user_data() function returns (void *)-1. For min() it
58355     ** returns (void *)db, where db is the sqlite3* database pointer.
58356     ** Therefore the next statement sets variable 'max' to 1 for the max()
58357     ** aggregate, or 0 for min().
58358     */
58359     max = sqlite3_user_data(context)!=0;
58360     cmp = sqlite3MemCompare(pBest, pArg, pColl);
58361     if( (max && cmp<0) || (!max && cmp>0) ){
58362       sqlite3VdbeMemCopy(pBest, pArg);
58363     }
58364   }else{
58365     sqlite3VdbeMemCopy(pBest, pArg);
58366   }
58367 }
58368 static void minMaxFinalize(sqlite3_context *context){
58369   sqlite3_value *pRes;
58370   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
58371   if( pRes ){
58372     if( pRes->flags ){
58373       sqlite3_result_value(context, pRes);
58374     }
58375     sqlite3VdbeMemRelease(pRes);
58376   }
58377 }
58378
58379 /*
58380 ** group_concat(EXPR, ?SEPARATOR?)
58381 */
58382 static void groupConcatStep(
58383   sqlite3_context *context,
58384   int argc,
58385   sqlite3_value **argv
58386 ){
58387   const char *zVal;
58388   StrAccum *pAccum;
58389   const char *zSep;
58390   int nVal, nSep;
58391   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
58392   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
58393
58394   if( pAccum ){
58395     sqlite3 *db = sqlite3_context_db_handle(context);
58396     pAccum->useMalloc = 1;
58397     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
58398     if( pAccum->nChar ){
58399       if( argc==2 ){
58400         zSep = (char*)sqlite3_value_text(argv[1]);
58401         nSep = sqlite3_value_bytes(argv[1]);
58402       }else{
58403         zSep = ",";
58404         nSep = 1;
58405       }
58406       sqlite3StrAccumAppend(pAccum, zSep, nSep);
58407     }
58408     zVal = (char*)sqlite3_value_text(argv[0]);
58409     nVal = sqlite3_value_bytes(argv[0]);
58410     sqlite3StrAccumAppend(pAccum, zVal, nVal);
58411   }
58412 }
58413 static void groupConcatFinalize(sqlite3_context *context){
58414   StrAccum *pAccum;
58415   pAccum = sqlite3_aggregate_context(context, 0);
58416   if( pAccum ){
58417     if( pAccum->tooBig ){
58418       sqlite3_result_error_toobig(context);
58419     }else if( pAccum->mallocFailed ){
58420       sqlite3_result_error_nomem(context);
58421     }else{    
58422       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
58423                           sqlite3_free);
58424     }
58425   }
58426 }
58427
58428 /*
58429 ** This function registered all of the above C functions as SQL
58430 ** functions.  This should be the only routine in this file with
58431 ** external linkage.
58432 */
58433 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
58434   static const struct {
58435      char *zName;
58436      signed char nArg;
58437      u8 argType;           /* 1: 0, 2: 1, 3: 2,...  N:  N-1. */
58438      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
58439      u8 needCollSeq;
58440      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
58441   } aFuncs[] = {
58442     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
58443     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
58444     { "max",               -1, 1, SQLITE_UTF8,    1, minmaxFunc },
58445     { "max",                0, 1, SQLITE_UTF8,    1, 0          },
58446     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
58447     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
58448     { "substr",             2, 0, SQLITE_UTF8,    0, substrFunc },
58449     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
58450     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
58451     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
58452     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
58453     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
58454     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
58455     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
58456     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
58457     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
58458     { "hex",                1, 0, SQLITE_UTF8,    0, hexFunc    },
58459     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
58460     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
58461     { "randomblob",         1, 0, SQLITE_UTF8,    0, randomBlob },
58462     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
58463     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
58464     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
58465     { "last_insert_rowid",  0, 0, SQLITE_UTF8, 0, last_insert_rowid },
58466     { "changes",            0, 0, SQLITE_UTF8, 0, changes           },
58467     { "total_changes",      0, 0, SQLITE_UTF8, 0, total_changes     },
58468     { "replace",            3, 0, SQLITE_UTF8,    0, replaceFunc       },
58469     { "ltrim",              1, 1, SQLITE_UTF8,    0, trimFunc          },
58470     { "ltrim",              2, 1, SQLITE_UTF8,    0, trimFunc          },
58471     { "rtrim",              1, 2, SQLITE_UTF8,    0, trimFunc          },
58472     { "rtrim",              2, 2, SQLITE_UTF8,    0, trimFunc          },
58473     { "trim",               1, 3, SQLITE_UTF8,    0, trimFunc          },
58474     { "trim",               2, 3, SQLITE_UTF8,    0, trimFunc          },
58475     { "zeroblob",           1, 0, SQLITE_UTF8,    0, zeroblobFunc      },
58476 #ifdef SQLITE_SOUNDEX
58477     { "soundex",            1, 0, SQLITE_UTF8,    0, soundexFunc},
58478 #endif
58479 #ifndef SQLITE_OMIT_LOAD_EXTENSION
58480     { "load_extension",     1, 0, SQLITE_UTF8, 0, loadExt },
58481     { "load_extension",     2, 0, SQLITE_UTF8, 0, loadExt },
58482 #endif
58483   };
58484   static const struct {
58485     char *zName;
58486     signed char nArg;
58487     u8 argType;
58488     u8 needCollSeq;
58489     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
58490     void (*xFinalize)(sqlite3_context*);
58491   } aAggs[] = {
58492     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
58493     { "max",    1, 1, 1, minmaxStep,   minMaxFinalize },
58494     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
58495     { "total",  1, 0, 0, sumStep,      totalFinalize    },
58496     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
58497     { "count",  0, 0, 0, countStep,    countFinalize  },
58498     { "count",  1, 0, 0, countStep,    countFinalize  },
58499     { "group_concat", 1, 0, 0, groupConcatStep, groupConcatFinalize },
58500     { "group_concat", 2, 0, 0, groupConcatStep, groupConcatFinalize },
58501   };
58502   int i;
58503
58504   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
58505     void *pArg;
58506     u8 argType = aFuncs[i].argType;
58507     pArg = (void*)(int)argType;
58508     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
58509         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
58510     if( aFuncs[i].needCollSeq ){
58511       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName, 
58512           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
58513       if( pFunc && aFuncs[i].needCollSeq ){
58514         pFunc->needCollSeq = 1;
58515       }
58516     }
58517   }
58518 #ifndef SQLITE_OMIT_ALTERTABLE
58519   sqlite3AlterFunctions(db);
58520 #endif
58521 #ifndef SQLITE_OMIT_PARSER
58522   sqlite3AttachFunctions(db);
58523 #endif
58524   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
58525     void *pArg = (void*)(int)aAggs[i].argType;
58526     sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8, 
58527         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
58528     if( aAggs[i].needCollSeq ){
58529       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
58530           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
58531       if( pFunc && aAggs[i].needCollSeq ){
58532         pFunc->needCollSeq = 1;
58533       }
58534     }
58535   }
58536   sqlite3RegisterDateTimeFunctions(db);
58537   if( !db->mallocFailed ){
58538     int rc = sqlite3_overload_function(db, "MATCH", 2);
58539     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
58540     if( rc==SQLITE_NOMEM ){
58541       db->mallocFailed = 1;
58542     }
58543   }
58544 #ifdef SQLITE_SSE
58545   (void)sqlite3SseFunctions(db);
58546 #endif
58547 #ifdef SQLITE_CASE_SENSITIVE_LIKE
58548   sqlite3RegisterLikeFunctions(db, 1);
58549 #else
58550   sqlite3RegisterLikeFunctions(db, 0);
58551 #endif
58552 }
58553
58554 /*
58555 ** Set the LIKEOPT flag on the 2-argument function with the given name.
58556 */
58557 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
58558   FuncDef *pDef;
58559   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
58560   if( pDef ){
58561     pDef->flags = flagVal;
58562   }
58563 }
58564
58565 /*
58566 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
58567 ** parameter determines whether or not the LIKE operator is case
58568 ** sensitive.  GLOB is always case sensitive.
58569 */
58570 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
58571   struct compareInfo *pInfo;
58572   if( caseSensitive ){
58573     pInfo = (struct compareInfo*)&likeInfoAlt;
58574   }else{
58575     pInfo = (struct compareInfo*)&likeInfoNorm;
58576   }
58577   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
58578   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
58579   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
58580       (struct compareInfo*)&globInfo, likeFunc, 0,0);
58581   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
58582   setLikeOptFlag(db, "like", 
58583       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
58584 }
58585
58586 /*
58587 ** pExpr points to an expression which implements a function.  If
58588 ** it is appropriate to apply the LIKE optimization to that function
58589 ** then set aWc[0] through aWc[2] to the wildcard characters and
58590 ** return TRUE.  If the function is not a LIKE-style function then
58591 ** return FALSE.
58592 */
58593 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
58594   FuncDef *pDef;
58595   if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
58596     return 0;
58597   }
58598   if( pExpr->pList->nExpr!=2 ){
58599     return 0;
58600   }
58601   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
58602                              SQLITE_UTF8, 0);
58603   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
58604     return 0;
58605   }
58606
58607   /* The memcpy() statement assumes that the wildcard characters are
58608   ** the first three statements in the compareInfo structure.  The
58609   ** asserts() that follow verify that assumption
58610   */
58611   memcpy(aWc, pDef->pUserData, 3);
58612   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
58613   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
58614   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
58615   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
58616   return 1;
58617 }
58618
58619 /************** End of func.c ************************************************/
58620 /************** Begin file insert.c ******************************************/
58621 /*
58622 ** 2001 September 15
58623 **
58624 ** The author disclaims copyright to this source code.  In place of
58625 ** a legal notice, here is a blessing:
58626 **
58627 **    May you do good and not evil.
58628 **    May you find forgiveness for yourself and forgive others.
58629 **    May you share freely, never taking more than you give.
58630 **
58631 *************************************************************************
58632 ** This file contains C code routines that are called by the parser
58633 ** to handle INSERT statements in SQLite.
58634 **
58635 ** $Id: insert.c,v 1.238 2008/04/28 18:46:43 drh Exp $
58636 */
58637
58638 /*
58639 ** Set P4 of the most recently inserted opcode to a column affinity
58640 ** string for index pIdx. A column affinity string has one character
58641 ** for each column in the table, according to the affinity of the column:
58642 **
58643 **  Character      Column affinity
58644 **  ------------------------------
58645 **  'a'            TEXT
58646 **  'b'            NONE
58647 **  'c'            NUMERIC
58648 **  'd'            INTEGER
58649 **  'e'            REAL
58650 **
58651 ** An extra 'b' is appended to the end of the string to cover the
58652 ** rowid that appears as the last column in every index.
58653 */
58654 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
58655   if( !pIdx->zColAff ){
58656     /* The first time a column affinity string for a particular index is
58657     ** required, it is allocated and populated here. It is then stored as
58658     ** a member of the Index structure for subsequent use.
58659     **
58660     ** The column affinity string will eventually be deleted by
58661     ** sqliteDeleteIndex() when the Index structure itself is cleaned
58662     ** up.
58663     */
58664     int n;
58665     Table *pTab = pIdx->pTable;
58666     sqlite3 *db = sqlite3VdbeDb(v);
58667     pIdx->zColAff = (char *)sqlite3DbMallocRaw(db, pIdx->nColumn+2);
58668     if( !pIdx->zColAff ){
58669       return;
58670     }
58671     for(n=0; n<pIdx->nColumn; n++){
58672       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
58673     }
58674     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
58675     pIdx->zColAff[n] = 0;
58676   }
58677  
58678   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
58679 }
58680
58681 /*
58682 ** Set P4 of the most recently inserted opcode to a column affinity
58683 ** string for table pTab. A column affinity string has one character
58684 ** for each column indexed by the index, according to the affinity of the
58685 ** column:
58686 **
58687 **  Character      Column affinity
58688 **  ------------------------------
58689 **  'a'            TEXT
58690 **  'b'            NONE
58691 **  'c'            NUMERIC
58692 **  'd'            INTEGER
58693 **  'e'            REAL
58694 */
58695 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
58696   /* The first time a column affinity string for a particular table
58697   ** is required, it is allocated and populated here. It is then 
58698   ** stored as a member of the Table structure for subsequent use.
58699   **
58700   ** The column affinity string will eventually be deleted by
58701   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
58702   */
58703   if( !pTab->zColAff ){
58704     char *zColAff;
58705     int i;
58706     sqlite3 *db = sqlite3VdbeDb(v);
58707
58708     zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
58709     if( !zColAff ){
58710       return;
58711     }
58712
58713     for(i=0; i<pTab->nCol; i++){
58714       zColAff[i] = pTab->aCol[i].affinity;
58715     }
58716     zColAff[pTab->nCol] = '\0';
58717
58718     pTab->zColAff = zColAff;
58719   }
58720
58721   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
58722 }
58723
58724 /*
58725 ** Return non-zero if the table pTab in database iDb or any of its indices
58726 ** have been opened at any point in the VDBE program beginning at location
58727 ** iStartAddr throught the end of the program.  This is used to see if 
58728 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
58729 ** run without using temporary table for the results of the SELECT. 
58730 */
58731 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
58732   int i;
58733   int iEnd = sqlite3VdbeCurrentAddr(v);
58734   for(i=iStartAddr; i<iEnd; i++){
58735     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
58736     assert( pOp!=0 );
58737     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
58738       Index *pIndex;
58739       int tnum = pOp->p2;
58740       if( tnum==pTab->tnum ){
58741         return 1;
58742       }
58743       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
58744         if( tnum==pIndex->tnum ){
58745           return 1;
58746         }
58747       }
58748     }
58749 #ifndef SQLITE_OMIT_VIRTUALTABLE
58750     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
58751       assert( pOp->p4.pVtab!=0 );
58752       assert( pOp->p4type==P4_VTAB );
58753       return 1;
58754     }
58755 #endif
58756   }
58757   return 0;
58758 }
58759
58760 #ifndef SQLITE_OMIT_AUTOINCREMENT
58761 /*
58762 ** Write out code to initialize the autoincrement logic.  This code
58763 ** looks up the current autoincrement value in the sqlite_sequence
58764 ** table and stores that value in a register.  Code generated by
58765 ** autoIncStep() will keep that register holding the largest
58766 ** rowid value.  Code generated by autoIncEnd() will write the new
58767 ** largest value of the counter back into the sqlite_sequence table.
58768 **
58769 ** This routine returns the index of the mem[] cell that contains
58770 ** the maximum rowid counter.
58771 **
58772 ** Three consecutive registers are allocated by this routine.  The
58773 ** first two hold the name of the target table and the maximum rowid 
58774 ** inserted into the target table, respectively.
58775 ** The third holds the rowid in sqlite_sequence where we will
58776 ** write back the revised maximum rowid.  This routine returns the
58777 ** index of the second of these three registers.
58778 */
58779 static int autoIncBegin(
58780   Parse *pParse,      /* Parsing context */
58781   int iDb,            /* Index of the database holding pTab */
58782   Table *pTab         /* The table we are writing to */
58783 ){
58784   int memId = 0;      /* Register holding maximum rowid */
58785   if( pTab->autoInc ){
58786     Vdbe *v = pParse->pVdbe;
58787     Db *pDb = &pParse->db->aDb[iDb];
58788     int iCur = pParse->nTab;
58789     int addr;               /* Address of the top of the loop */
58790     assert( v );
58791     pParse->nMem++;         /* Holds name of table */
58792     memId = ++pParse->nMem;
58793     pParse->nMem++;
58794     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
58795     addr = sqlite3VdbeCurrentAddr(v);
58796     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
58797     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+8);
58798     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
58799     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
58800     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
58801     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
58802     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
58803     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+8);
58804     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
58805     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
58806   }
58807   return memId;
58808 }
58809
58810 /*
58811 ** Update the maximum rowid for an autoincrement calculation.
58812 **
58813 ** This routine should be called when the top of the stack holds a
58814 ** new rowid that is about to be inserted.  If that new rowid is
58815 ** larger than the maximum rowid in the memId memory cell, then the
58816 ** memory cell is updated.  The stack is unchanged.
58817 */
58818 static void autoIncStep(Parse *pParse, int memId, int regRowid){
58819   if( memId>0 ){
58820     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
58821   }
58822 }
58823
58824 /*
58825 ** After doing one or more inserts, the maximum rowid is stored
58826 ** in reg[memId].  Generate code to write this value back into the
58827 ** the sqlite_sequence table.
58828 */
58829 static void autoIncEnd(
58830   Parse *pParse,     /* The parsing context */
58831   int iDb,           /* Index of the database holding pTab */
58832   Table *pTab,       /* Table we are inserting into */
58833   int memId          /* Memory cell holding the maximum rowid */
58834 ){
58835   if( pTab->autoInc ){
58836     int iCur = pParse->nTab;
58837     Vdbe *v = pParse->pVdbe;
58838     Db *pDb = &pParse->db->aDb[iDb];
58839     int j1;
58840     int iRec = ++pParse->nMem;    /* Memory cell used for record */
58841
58842     assert( v );
58843     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
58844     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
58845     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
58846     sqlite3VdbeJumpHere(v, j1);
58847     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
58848     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
58849     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
58850     sqlite3VdbeAddOp1(v, OP_Close, iCur);
58851   }
58852 }
58853 #else
58854 /*
58855 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
58856 ** above are all no-ops
58857 */
58858 # define autoIncBegin(A,B,C) (0)
58859 # define autoIncStep(A,B,C)
58860 # define autoIncEnd(A,B,C,D)
58861 #endif /* SQLITE_OMIT_AUTOINCREMENT */
58862
58863
58864 /* Forward declaration */
58865 static int xferOptimization(
58866   Parse *pParse,        /* Parser context */
58867   Table *pDest,         /* The table we are inserting into */
58868   Select *pSelect,      /* A SELECT statement to use as the data source */
58869   int onError,          /* How to handle constraint errors */
58870   int iDbDest           /* The database of pDest */
58871 );
58872
58873 /*
58874 ** This routine is call to handle SQL of the following forms:
58875 **
58876 **    insert into TABLE (IDLIST) values(EXPRLIST)
58877 **    insert into TABLE (IDLIST) select
58878 **
58879 ** The IDLIST following the table name is always optional.  If omitted,
58880 ** then a list of all columns for the table is substituted.  The IDLIST
58881 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
58882 **
58883 ** The pList parameter holds EXPRLIST in the first form of the INSERT
58884 ** statement above, and pSelect is NULL.  For the second form, pList is
58885 ** NULL and pSelect is a pointer to the select statement used to generate
58886 ** data for the insert.
58887 **
58888 ** The code generated follows one of four templates.  For a simple
58889 ** select with data coming from a VALUES clause, the code executes
58890 ** once straight down through.  The template looks like this:
58891 **
58892 **         open write cursor to <table> and its indices
58893 **         puts VALUES clause expressions onto the stack
58894 **         write the resulting record into <table>
58895 **         cleanup
58896 **
58897 ** The three remaining templates assume the statement is of the form
58898 **
58899 **   INSERT INTO <table> SELECT ...
58900 **
58901 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
58902 ** in other words if the SELECT pulls all columns from a single table
58903 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
58904 ** if <table2> and <table1> are distinct tables but have identical
58905 ** schemas, including all the same indices, then a special optimization
58906 ** is invoked that copies raw records from <table2> over to <table1>.
58907 ** See the xferOptimization() function for the implementation of this
58908 ** template.  This is the second template.
58909 **
58910 **         open a write cursor to <table>
58911 **         open read cursor on <table2>
58912 **         transfer all records in <table2> over to <table>
58913 **         close cursors
58914 **         foreach index on <table>
58915 **           open a write cursor on the <table> index
58916 **           open a read cursor on the corresponding <table2> index
58917 **           transfer all records from the read to the write cursors
58918 **           close cursors
58919 **         end foreach
58920 **
58921 ** The third template is for when the second template does not apply
58922 ** and the SELECT clause does not read from <table> at any time.
58923 ** The generated code follows this template:
58924 **
58925 **         goto B
58926 **      A: setup for the SELECT
58927 **         loop over the rows in the SELECT
58928 **           gosub C
58929 **         end loop
58930 **         cleanup after the SELECT
58931 **         goto D
58932 **      B: open write cursor to <table> and its indices
58933 **         goto A
58934 **      C: insert the select result into <table>
58935 **         return
58936 **      D: cleanup
58937 **
58938 ** The fourth template is used if the insert statement takes its
58939 ** values from a SELECT but the data is being inserted into a table
58940 ** that is also read as part of the SELECT.  In the third form,
58941 ** we have to use a intermediate table to store the results of
58942 ** the select.  The template is like this:
58943 **
58944 **         goto B
58945 **      A: setup for the SELECT
58946 **         loop over the tables in the SELECT
58947 **           gosub C
58948 **         end loop
58949 **         cleanup after the SELECT
58950 **         goto D
58951 **      C: insert the select result into the intermediate table
58952 **         return
58953 **      B: open a cursor to an intermediate table
58954 **         goto A
58955 **      D: open write cursor to <table> and its indices
58956 **         loop over the intermediate table
58957 **           transfer values form intermediate table into <table>
58958 **         end the loop
58959 **         cleanup
58960 */
58961 SQLITE_PRIVATE void sqlite3Insert(
58962   Parse *pParse,        /* Parser context */
58963   SrcList *pTabList,    /* Name of table into which we are inserting */
58964   ExprList *pList,      /* List of values to be inserted */
58965   Select *pSelect,      /* A SELECT statement to use as the data source */
58966   IdList *pColumn,      /* Column names corresponding to IDLIST. */
58967   int onError           /* How to handle constraint errors */
58968 ){
58969   sqlite3 *db;          /* The main database structure */
58970   Table *pTab;          /* The table to insert into.  aka TABLE */
58971   char *zTab;           /* Name of the table into which we are inserting */
58972   const char *zDb;      /* Name of the database holding this table */
58973   int i, j, idx;        /* Loop counters */
58974   Vdbe *v;              /* Generate code into this virtual machine */
58975   Index *pIdx;          /* For looping over indices of the table */
58976   int nColumn;          /* Number of columns in the data */
58977   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
58978   int baseCur = 0;      /* VDBE Cursor number for pTab */
58979   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
58980   int endOfLoop;        /* Label for the end of the insertion loop */
58981   int useTempTable = 0; /* Store SELECT results in intermediate table */
58982   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
58983   int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
58984   int iSelectLoop = 0;  /* Address of code that implements the SELECT */
58985   int iCleanup = 0;     /* Address of the cleanup code */
58986   int iInsertBlock = 0; /* Address of the subroutine used to insert data */
58987   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
58988   int iDb;              /* Index of database holding TABLE */
58989   Db *pDb;              /* The database containing table being inserted into */
58990   int appendFlag = 0;   /* True if the insert is likely to be an append */
58991
58992   /* Register allocations */
58993   int regFromSelect;    /* Base register for data coming from SELECT */
58994   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
58995   int regRowCount = 0;  /* Memory cell used for the row counter */
58996   int regIns;           /* Block of regs holding rowid+data being inserted */
58997   int regRowid;         /* registers holding insert rowid */
58998   int regData;          /* register holding first column to insert */
58999   int regRecord;        /* Holds the assemblied row record */
59000   int *aRegIdx = 0;     /* One register allocated to each index */
59001
59002
59003 #ifndef SQLITE_OMIT_TRIGGER
59004   int isView;                 /* True if attempting to insert into a view */
59005   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
59006 #endif
59007
59008   db = pParse->db;
59009   if( pParse->nErr || db->mallocFailed ){
59010     goto insert_cleanup;
59011   }
59012
59013   /* Locate the table into which we will be inserting new information.
59014   */
59015   assert( pTabList->nSrc==1 );
59016   zTab = pTabList->a[0].zName;
59017   if( zTab==0 ) goto insert_cleanup;
59018   pTab = sqlite3SrcListLookup(pParse, pTabList);
59019   if( pTab==0 ){
59020     goto insert_cleanup;
59021   }
59022   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59023   assert( iDb<db->nDb );
59024   pDb = &db->aDb[iDb];
59025   zDb = pDb->zName;
59026   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
59027     goto insert_cleanup;
59028   }
59029
59030   /* Figure out if we have any triggers and if the table being
59031   ** inserted into is a view
59032   */
59033 #ifndef SQLITE_OMIT_TRIGGER
59034   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
59035   isView = pTab->pSelect!=0;
59036 #else
59037 # define triggers_exist 0
59038 # define isView 0
59039 #endif
59040 #ifdef SQLITE_OMIT_VIEW
59041 # undef isView
59042 # define isView 0
59043 #endif
59044
59045   /* Ensure that:
59046   *  (a) the table is not read-only, 
59047   *  (b) that if it is a view then ON INSERT triggers exist
59048   */
59049   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
59050     goto insert_cleanup;
59051   }
59052   assert( pTab!=0 );
59053
59054   /* If pTab is really a view, make sure it has been initialized.
59055   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
59056   ** module table).
59057   */
59058   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
59059     goto insert_cleanup;
59060   }
59061
59062   /* Allocate a VDBE
59063   */
59064   v = sqlite3GetVdbe(pParse);
59065   if( v==0 ) goto insert_cleanup;
59066   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
59067   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
59068
59069   /* if there are row triggers, allocate a temp table for new.* references. */
59070   if( triggers_exist ){
59071     newIdx = pParse->nTab++;
59072   }
59073
59074 #ifndef SQLITE_OMIT_XFER_OPT
59075   /* If the statement is of the form
59076   **
59077   **       INSERT INTO <table1> SELECT * FROM <table2>;
59078   **
59079   ** Then special optimizations can be applied that make the transfer
59080   ** very fast and which reduce fragmentation of indices.
59081   */
59082   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
59083     assert( !triggers_exist );
59084     assert( pList==0 );
59085     goto insert_cleanup;
59086   }
59087 #endif /* SQLITE_OMIT_XFER_OPT */
59088
59089   /* If this is an AUTOINCREMENT table, look up the sequence number in the
59090   ** sqlite_sequence table and store it in memory cell regAutoinc.
59091   */
59092   regAutoinc = autoIncBegin(pParse, iDb, pTab);
59093
59094   /* Figure out how many columns of data are supplied.  If the data
59095   ** is coming from a SELECT statement, then this step also generates
59096   ** all the code to implement the SELECT statement and invoke a subroutine
59097   ** to process each row of the result. (Template 2.) If the SELECT
59098   ** statement uses the the table that is being inserted into, then the
59099   ** subroutine is also coded here.  That subroutine stores the SELECT
59100   ** results in a temporary table. (Template 3.)
59101   */
59102   if( pSelect ){
59103     /* Data is coming from a SELECT.  Generate code to implement that SELECT
59104     */
59105     SelectDest dest;
59106     int rc, iInitCode;
59107
59108     iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
59109     iSelectLoop = sqlite3VdbeCurrentAddr(v);
59110     iInsertBlock = sqlite3VdbeMakeLabel(v);
59111     sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock);
59112
59113     /* Resolve the expressions in the SELECT statement and execute it. */
59114     rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
59115     if( rc || pParse->nErr || db->mallocFailed ){
59116       goto insert_cleanup;
59117     }
59118
59119     regFromSelect = dest.iMem;
59120     iCleanup = sqlite3VdbeMakeLabel(v);
59121     sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup);
59122     assert( pSelect->pEList );
59123     nColumn = pSelect->pEList->nExpr;
59124
59125     /* Set useTempTable to TRUE if the result of the SELECT statement
59126     ** should be written into a temporary table.  Set to FALSE if each
59127     ** row of the SELECT can be written directly into the result table.
59128     **
59129     ** A temp table must be used if the table being updated is also one
59130     ** of the tables being read by the SELECT statement.  Also use a 
59131     ** temp table in the case of row triggers.
59132     */
59133     if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){
59134       useTempTable = 1;
59135     }
59136
59137     if( useTempTable ){
59138       /* Generate the subroutine that SELECT calls to process each row of
59139       ** the result.  Store the result in a temporary table
59140       */
59141       int regRec, regRowid;
59142
59143       srcTab = pParse->nTab++;
59144       regRec = sqlite3GetTempReg(pParse);
59145       regRowid = sqlite3GetTempReg(pParse);
59146       sqlite3VdbeResolveLabel(v, iInsertBlock);
59147       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
59148       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
59149       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
59150       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
59151       sqlite3ReleaseTempReg(pParse, regRec);
59152       sqlite3ReleaseTempReg(pParse, regRowid);
59153
59154       /* The following code runs first because the GOTO at the very top
59155       ** of the program jumps to it.  Create the temporary table, then jump
59156       ** back up and execute the SELECT code above.
59157       */
59158       sqlite3VdbeJumpHere(v, iInitCode);
59159       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
59160       sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
59161       sqlite3VdbeResolveLabel(v, iCleanup);
59162     }else{
59163       sqlite3VdbeJumpHere(v, iInitCode);
59164     }
59165   }else{
59166     /* This is the case if the data for the INSERT is coming from a VALUES
59167     ** clause
59168     */
59169     NameContext sNC;
59170     memset(&sNC, 0, sizeof(sNC));
59171     sNC.pParse = pParse;
59172     srcTab = -1;
59173     assert( useTempTable==0 );
59174     nColumn = pList ? pList->nExpr : 0;
59175     for(i=0; i<nColumn; i++){
59176       if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
59177         goto insert_cleanup;
59178       }
59179     }
59180   }
59181
59182   /* Make sure the number of columns in the source data matches the number
59183   ** of columns to be inserted into the table.
59184   */
59185   if( IsVirtual(pTab) ){
59186     for(i=0; i<pTab->nCol; i++){
59187       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
59188     }
59189   }
59190   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
59191     sqlite3ErrorMsg(pParse, 
59192        "table %S has %d columns but %d values were supplied",
59193        pTabList, 0, pTab->nCol, nColumn);
59194     goto insert_cleanup;
59195   }
59196   if( pColumn!=0 && nColumn!=pColumn->nId ){
59197     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
59198     goto insert_cleanup;
59199   }
59200
59201   /* If the INSERT statement included an IDLIST term, then make sure
59202   ** all elements of the IDLIST really are columns of the table and 
59203   ** remember the column indices.
59204   **
59205   ** If the table has an INTEGER PRIMARY KEY column and that column
59206   ** is named in the IDLIST, then record in the keyColumn variable
59207   ** the index into IDLIST of the primary key column.  keyColumn is
59208   ** the index of the primary key as it appears in IDLIST, not as
59209   ** is appears in the original table.  (The index of the primary
59210   ** key in the original table is pTab->iPKey.)
59211   */
59212   if( pColumn ){
59213     for(i=0; i<pColumn->nId; i++){
59214       pColumn->a[i].idx = -1;
59215     }
59216     for(i=0; i<pColumn->nId; i++){
59217       for(j=0; j<pTab->nCol; j++){
59218         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
59219           pColumn->a[i].idx = j;
59220           if( j==pTab->iPKey ){
59221             keyColumn = i;
59222           }
59223           break;
59224         }
59225       }
59226       if( j>=pTab->nCol ){
59227         if( sqlite3IsRowid(pColumn->a[i].zName) ){
59228           keyColumn = i;
59229         }else{
59230           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
59231               pTabList, 0, pColumn->a[i].zName);
59232           pParse->nErr++;
59233           goto insert_cleanup;
59234         }
59235       }
59236     }
59237   }
59238
59239   /* If there is no IDLIST term but the table has an integer primary
59240   ** key, the set the keyColumn variable to the primary key column index
59241   ** in the original table definition.
59242   */
59243   if( pColumn==0 && nColumn>0 ){
59244     keyColumn = pTab->iPKey;
59245   }
59246
59247   /* Open the temp table for FOR EACH ROW triggers
59248   */
59249   if( triggers_exist ){
59250     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
59251     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
59252   }
59253     
59254   /* Initialize the count of rows to be inserted
59255   */
59256   if( db->flags & SQLITE_CountRows ){
59257     regRowCount = ++pParse->nMem;
59258     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
59259   }
59260
59261   /* If this is not a view, open the table and and all indices */
59262   if( !isView ){
59263     int nIdx;
59264     int i;
59265
59266     baseCur = pParse->nTab;
59267     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
59268     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
59269     if( aRegIdx==0 ){
59270       goto insert_cleanup;
59271     }
59272     for(i=0; i<nIdx; i++){
59273       aRegIdx[i] = ++pParse->nMem;
59274     }
59275   }
59276
59277   /* If the data source is a temporary table, then we have to create
59278   ** a loop because there might be multiple rows of data.  If the data
59279   ** source is a subroutine call from the SELECT statement, then we need
59280   ** to launch the SELECT statement processing.
59281   */
59282   if( useTempTable ){
59283     iBreak = sqlite3VdbeMakeLabel(v);
59284     sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak);
59285     iCont = sqlite3VdbeCurrentAddr(v);
59286   }else if( pSelect ){
59287     sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop);
59288     sqlite3VdbeResolveLabel(v, iInsertBlock);
59289   }
59290
59291   /* Allocate registers for holding the rowid of the new row,
59292   ** the content of the new row, and the assemblied row record.
59293   */
59294   regRecord = ++pParse->nMem;
59295   regRowid = regIns = pParse->nMem+1;
59296   pParse->nMem += pTab->nCol + 1;
59297   if( IsVirtual(pTab) ){
59298     regRowid++;
59299     pParse->nMem++;
59300   }
59301   regData = regRowid+1;
59302
59303   /* Run the BEFORE and INSTEAD OF triggers, if there are any
59304   */
59305   endOfLoop = sqlite3VdbeMakeLabel(v);
59306   if( triggers_exist & TRIGGER_BEFORE ){
59307     int regRowid;
59308     int regCols;
59309     int regRec;
59310
59311     /* build the NEW.* reference row.  Note that if there is an INTEGER
59312     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
59313     ** translated into a unique ID for the row.  But on a BEFORE trigger,
59314     ** we do not know what the unique ID will be (because the insert has
59315     ** not happened yet) so we substitute a rowid of -1
59316     */
59317     regRowid = sqlite3GetTempReg(pParse);
59318     if( keyColumn<0 ){
59319       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
59320     }else if( useTempTable ){
59321       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
59322     }else{
59323       int j1;
59324       assert( pSelect==0 );  /* Otherwise useTempTable is true */
59325       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
59326       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
59327       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
59328       sqlite3VdbeJumpHere(v, j1);
59329       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
59330     }
59331
59332     /* Cannot have triggers on a virtual table. If it were possible,
59333     ** this block would have to account for hidden column.
59334     */
59335     assert(!IsVirtual(pTab));
59336
59337     /* Create the new column data
59338     */
59339     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
59340     for(i=0; i<pTab->nCol; i++){
59341       if( pColumn==0 ){
59342         j = i;
59343       }else{
59344         for(j=0; j<pColumn->nId; j++){
59345           if( pColumn->a[j].idx==i ) break;
59346         }
59347       }
59348       if( pColumn && j>=pColumn->nId ){
59349         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
59350       }else if( useTempTable ){
59351         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 
59352       }else{
59353         assert( pSelect==0 ); /* Otherwise useTempTable is true */
59354         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
59355       }
59356     }
59357     regRec = sqlite3GetTempReg(pParse);
59358     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
59359
59360     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
59361     ** do not attempt any conversions before assembling the record.
59362     ** If this is a real table, attempt conversions as required by the
59363     ** table column affinities.
59364     */
59365     if( !isView ){
59366       sqlite3TableAffinityStr(v, pTab);
59367     }
59368     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
59369     sqlite3ReleaseTempReg(pParse, regRec);
59370     sqlite3ReleaseTempReg(pParse, regRowid);
59371     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
59372
59373     /* Fire BEFORE or INSTEAD OF triggers */
59374     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
59375         newIdx, -1, onError, endOfLoop, 0, 0) ){
59376       goto insert_cleanup;
59377     }
59378   }
59379
59380   /* Push the record number for the new entry onto the stack.  The
59381   ** record number is a randomly generate integer created by NewRowid
59382   ** except when the table has an INTEGER PRIMARY KEY column, in which
59383   ** case the record number is the same as that column. 
59384   */
59385   if( !isView ){
59386     if( IsVirtual(pTab) ){
59387       /* The row that the VUpdate opcode will delete: none */
59388       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
59389     }
59390     if( keyColumn>=0 ){
59391       if( useTempTable ){
59392         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
59393       }else if( pSelect ){
59394         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
59395       }else{
59396         VdbeOp *pOp;
59397         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
59398         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
59399         if( pOp && pOp->opcode==OP_Null ){
59400           appendFlag = 1;
59401           pOp->opcode = OP_NewRowid;
59402           pOp->p1 = baseCur;
59403           pOp->p2 = regRowid;
59404           pOp->p3 = regAutoinc;
59405         }
59406       }
59407       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
59408       ** to generate a unique primary key value.
59409       */
59410       if( !appendFlag ){
59411         int j1;
59412         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
59413         sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
59414         sqlite3VdbeJumpHere(v, j1);
59415         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
59416       }
59417     }else if( IsVirtual(pTab) ){
59418       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
59419     }else{
59420       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
59421       appendFlag = 1;
59422     }
59423     autoIncStep(pParse, regAutoinc, regRowid);
59424
59425     /* Push onto the stack, data for all columns of the new entry, beginning
59426     ** with the first column.
59427     */
59428     nHidden = 0;
59429     for(i=0; i<pTab->nCol; i++){
59430       int iRegStore = regRowid+1+i;
59431       if( i==pTab->iPKey ){
59432         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
59433         ** Whenever this column is read, the record number will be substituted
59434         ** in its place.  So will fill this column with a NULL to avoid
59435         ** taking up data space with information that will never be used. */
59436         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
59437         continue;
59438       }
59439       if( pColumn==0 ){
59440         if( IsHiddenColumn(&pTab->aCol[i]) ){
59441           assert( IsVirtual(pTab) );
59442           j = -1;
59443           nHidden++;
59444         }else{
59445           j = i - nHidden;
59446         }
59447       }else{
59448         for(j=0; j<pColumn->nId; j++){
59449           if( pColumn->a[j].idx==i ) break;
59450         }
59451       }
59452       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
59453         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
59454       }else if( useTempTable ){
59455         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
59456       }else if( pSelect ){
59457         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
59458       }else{
59459         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
59460       }
59461     }
59462
59463     /* Generate code to check constraints and generate index keys and
59464     ** do the insertion.
59465     */
59466 #ifndef SQLITE_OMIT_VIRTUALTABLE
59467     if( IsVirtual(pTab) ){
59468       sqlite3VtabMakeWritable(pParse, pTab);
59469       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
59470                      (const char*)pTab->pVtab, P4_VTAB);
59471     }else
59472 #endif
59473     {
59474       sqlite3GenerateConstraintChecks(
59475           pParse,
59476           pTab,
59477           baseCur,
59478           regIns,
59479           aRegIdx,
59480           keyColumn>=0,
59481           0,
59482           onError,
59483           endOfLoop
59484       );
59485       sqlite3CompleteInsertion(
59486           pParse,
59487           pTab,
59488           baseCur,
59489           regIns,
59490           aRegIdx,
59491           0,
59492           0,
59493           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
59494           appendFlag
59495        );
59496     }
59497   }
59498
59499   /* Update the count of rows that are inserted
59500   */
59501   if( (db->flags & SQLITE_CountRows)!=0 ){
59502     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
59503   }
59504
59505   if( triggers_exist ){
59506     /* Code AFTER triggers */
59507     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
59508           newIdx, -1, onError, endOfLoop, 0, 0) ){
59509       goto insert_cleanup;
59510     }
59511   }
59512
59513   /* The bottom of the loop, if the data source is a SELECT statement
59514   */
59515   sqlite3VdbeResolveLabel(v, endOfLoop);
59516   if( useTempTable ){
59517     sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont);
59518     sqlite3VdbeResolveLabel(v, iBreak);
59519     sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0);
59520   }else if( pSelect ){
59521     sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
59522     sqlite3VdbeResolveLabel(v, iCleanup);
59523   }
59524
59525   if( !IsVirtual(pTab) && !isView ){
59526     /* Close all tables opened */
59527     sqlite3VdbeAddOp2(v, OP_Close, baseCur, 0);
59528     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
59529       sqlite3VdbeAddOp2(v, OP_Close, idx+baseCur, 0);
59530     }
59531   }
59532
59533   /* Update the sqlite_sequence table by storing the content of the
59534   ** counter value in memory regAutoinc back into the sqlite_sequence
59535   ** table.
59536   */
59537   autoIncEnd(pParse, iDb, pTab, regAutoinc);
59538
59539   /*
59540   ** Return the number of rows inserted. If this routine is 
59541   ** generating code because of a call to sqlite3NestedParse(), do not
59542   ** invoke the callback function.
59543   */
59544   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
59545     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
59546     sqlite3VdbeSetNumCols(v, 1);
59547     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
59548   }
59549
59550 insert_cleanup:
59551   sqlite3SrcListDelete(pTabList);
59552   sqlite3ExprListDelete(pList);
59553   sqlite3SelectDelete(pSelect);
59554   sqlite3IdListDelete(pColumn);
59555   sqlite3_free(aRegIdx);
59556 }
59557
59558 /*
59559 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
59560 **
59561 ** The input is a range of consecutive registers as follows:
59562 **
59563 **    1.  The rowid of the row to be updated before the update.  This
59564 **        value is omitted unless we are doing an UPDATE that involves a
59565 **        change to the record number or writing to a virtual table.
59566 **
59567 **    2.  The rowid of the row after the update.
59568 **
59569 **    3.  The data in the first column of the entry after the update.
59570 **
59571 **    i.  Data from middle columns...
59572 **
59573 **    N.  The data in the last column of the entry after the update.
59574 **
59575 ** The regRowid parameter is the index of the register containing (2).
59576 **
59577 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
59578 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
59579 ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
59580 ** the update or insert statement.  If rowidChng is false, it means that
59581 ** the rowid is computed automatically in an insert or that the rowid value
59582 ** is not modified by the update.
59583 **
59584 ** The code generated by this routine store new index entries into
59585 ** registers identified by aRegIdx[].  No index entry is created for
59586 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
59587 ** the same as the order of indices on the linked list of indices
59588 ** attached to the table.
59589 **
59590 ** This routine also generates code to check constraints.  NOT NULL,
59591 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
59592 ** then the appropriate action is performed.  There are five possible
59593 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
59594 **
59595 **  Constraint type  Action       What Happens
59596 **  ---------------  ----------   ----------------------------------------
59597 **  any              ROLLBACK     The current transaction is rolled back and
59598 **                                sqlite3_exec() returns immediately with a
59599 **                                return code of SQLITE_CONSTRAINT.
59600 **
59601 **  any              ABORT        Back out changes from the current command
59602 **                                only (do not do a complete rollback) then
59603 **                                cause sqlite3_exec() to return immediately
59604 **                                with SQLITE_CONSTRAINT.
59605 **
59606 **  any              FAIL         Sqlite_exec() returns immediately with a
59607 **                                return code of SQLITE_CONSTRAINT.  The
59608 **                                transaction is not rolled back and any
59609 **                                prior changes are retained.
59610 **
59611 **  any              IGNORE       The record number and data is popped from
59612 **                                the stack and there is an immediate jump
59613 **                                to label ignoreDest.
59614 **
59615 **  NOT NULL         REPLACE      The NULL value is replace by the default
59616 **                                value for that column.  If the default value
59617 **                                is NULL, the action is the same as ABORT.
59618 **
59619 **  UNIQUE           REPLACE      The other row that conflicts with the row
59620 **                                being inserted is removed.
59621 **
59622 **  CHECK            REPLACE      Illegal.  The results in an exception.
59623 **
59624 ** Which action to take is determined by the overrideError parameter.
59625 ** Or if overrideError==OE_Default, then the pParse->onError parameter
59626 ** is used.  Or if pParse->onError==OE_Default then the onError value
59627 ** for the constraint is used.
59628 **
59629 ** The calling routine must open a read/write cursor for pTab with
59630 ** cursor number "baseCur".  All indices of pTab must also have open
59631 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
59632 ** Except, if there is no possibility of a REPLACE action then
59633 ** cursors do not need to be open for indices where aRegIdx[i]==0.
59634 */
59635 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
59636   Parse *pParse,      /* The parser context */
59637   Table *pTab,        /* the table into which we are inserting */
59638   int baseCur,        /* Index of a read/write cursor pointing at pTab */
59639   int regRowid,       /* Index of the range of input registers */
59640   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
59641   int rowidChng,      /* True if the rowid might collide with existing entry */
59642   int isUpdate,       /* True for UPDATE, False for INSERT */
59643   int overrideError,  /* Override onError to this if not OE_Default */
59644   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
59645 ){
59646   int i;
59647   Vdbe *v;
59648   int nCol;
59649   int onError;
59650   int j1, j2, j3;     /* Addresses of jump instructions */
59651   int regData;        /* Register containing first data column */
59652   int iCur;
59653   Index *pIdx;
59654   int seenReplace = 0;
59655   int hasTwoRowids = (isUpdate && rowidChng);
59656
59657   v = sqlite3GetVdbe(pParse);
59658   assert( v!=0 );
59659   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
59660   nCol = pTab->nCol;
59661   regData = regRowid + 1;
59662
59663
59664   /* Test all NOT NULL constraints.
59665   */
59666   for(i=0; i<nCol; i++){
59667     if( i==pTab->iPKey ){
59668       continue;
59669     }
59670     onError = pTab->aCol[i].notNull;
59671     if( onError==OE_None ) continue;
59672     if( overrideError!=OE_Default ){
59673       onError = overrideError;
59674     }else if( onError==OE_Default ){
59675       onError = OE_Abort;
59676     }
59677     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
59678       onError = OE_Abort;
59679     }
59680     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
59681     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
59682         || onError==OE_Ignore || onError==OE_Replace );
59683     switch( onError ){
59684       case OE_Rollback:
59685       case OE_Abort:
59686       case OE_Fail: {
59687         char *zMsg = 0;
59688         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
59689         sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
59690                         " may not be NULL", (char*)0);
59691         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
59692         break;
59693       }
59694       case OE_Ignore: {
59695         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
59696         break;
59697       }
59698       case OE_Replace: {
59699         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
59700         break;
59701       }
59702     }
59703     sqlite3VdbeJumpHere(v, j1);
59704   }
59705
59706   /* Test all CHECK constraints
59707   */
59708 #ifndef SQLITE_OMIT_CHECK
59709   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
59710     int allOk = sqlite3VdbeMakeLabel(v);
59711     pParse->ckBase = regData;
59712     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
59713     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
59714     if( onError==OE_Ignore ){
59715       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
59716     }else{
59717       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
59718     }
59719     sqlite3VdbeResolveLabel(v, allOk);
59720   }
59721 #endif /* !defined(SQLITE_OMIT_CHECK) */
59722
59723   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
59724   ** of the new record does not previously exist.  Except, if this
59725   ** is an UPDATE and the primary key is not changing, that is OK.
59726   */
59727   if( rowidChng ){
59728     onError = pTab->keyConf;
59729     if( overrideError!=OE_Default ){
59730       onError = overrideError;
59731     }else if( onError==OE_Default ){
59732       onError = OE_Abort;
59733     }
59734     
59735     if( onError!=OE_Replace || pTab->pIndex ){
59736       if( isUpdate ){
59737         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
59738       }
59739       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
59740       switch( onError ){
59741         default: {
59742           onError = OE_Abort;
59743           /* Fall thru into the next case */
59744         }
59745         case OE_Rollback:
59746         case OE_Abort:
59747         case OE_Fail: {
59748           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
59749                            "PRIMARY KEY must be unique", P4_STATIC);
59750           break;
59751         }
59752         case OE_Replace: {
59753           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
59754           seenReplace = 1;
59755           break;
59756         }
59757         case OE_Ignore: {
59758           assert( seenReplace==0 );
59759           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
59760           break;
59761         }
59762       }
59763       sqlite3VdbeJumpHere(v, j3);
59764       if( isUpdate ){
59765         sqlite3VdbeJumpHere(v, j2);
59766       }
59767     }
59768   }
59769
59770   /* Test all UNIQUE constraints by creating entries for each UNIQUE
59771   ** index and making sure that duplicate entries do not already exist.
59772   ** Add the new records to the indices as we go.
59773   */
59774   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
59775     int regIdx;
59776     int regR;
59777
59778     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
59779
59780     /* Create a key for accessing the index entry */
59781     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
59782     for(i=0; i<pIdx->nColumn; i++){
59783       int idx = pIdx->aiColumn[i];
59784       if( idx==pTab->iPKey ){
59785         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
59786       }else{
59787         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
59788       }
59789     }
59790     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
59791     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
59792     sqlite3IndexAffinityStr(v, pIdx);
59793     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
59794     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
59795
59796     /* Find out what action to take in case there is an indexing conflict */
59797     onError = pIdx->onError;
59798     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
59799     if( overrideError!=OE_Default ){
59800       onError = overrideError;
59801     }else if( onError==OE_Default ){
59802       onError = OE_Abort;
59803     }
59804     if( seenReplace ){
59805       if( onError==OE_Ignore ) onError = OE_Replace;
59806       else if( onError==OE_Fail ) onError = OE_Abort;
59807     }
59808     
59809
59810     /* Check to see if the new index entry will be unique */
59811     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
59812     regR = sqlite3GetTempReg(pParse);
59813     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
59814     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
59815                            regR, (char*)aRegIdx[iCur],
59816                            P4_INT32);
59817
59818     /* Generate code that executes if the new index entry is not unique */
59819     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
59820         || onError==OE_Ignore || onError==OE_Replace );
59821     switch( onError ){
59822       case OE_Rollback:
59823       case OE_Abort:
59824       case OE_Fail: {
59825         int j, n1, n2;
59826         char zErrMsg[200];
59827         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
59828                          pIdx->nColumn>1 ? "columns " : "column ");
59829         n1 = strlen(zErrMsg);
59830         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
59831           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
59832           n2 = strlen(zCol);
59833           if( j>0 ){
59834             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
59835             n1 += 2;
59836           }
59837           if( n1+n2>sizeof(zErrMsg)-30 ){
59838             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
59839             n1 += 3;
59840             break;
59841           }else{
59842             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
59843             n1 += n2;
59844           }
59845         }
59846         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 
59847             pIdx->nColumn>1 ? " are not unique" : " is not unique");
59848         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
59849         break;
59850       }
59851       case OE_Ignore: {
59852         assert( seenReplace==0 );
59853         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
59854         break;
59855       }
59856       case OE_Replace: {
59857         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
59858         seenReplace = 1;
59859         break;
59860       }
59861     }
59862     sqlite3VdbeJumpHere(v, j2);
59863     sqlite3VdbeJumpHere(v, j3);
59864     sqlite3ReleaseTempReg(pParse, regR);
59865   }
59866 }
59867
59868 /*
59869 ** This routine generates code to finish the INSERT or UPDATE operation
59870 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
59871 ** A consecutive range of registers starting at regRowid contains the
59872 ** rowid and the content to be inserted.
59873 **
59874 ** The arguments to this routine should be the same as the first six
59875 ** arguments to sqlite3GenerateConstraintChecks.
59876 */
59877 SQLITE_PRIVATE void sqlite3CompleteInsertion(
59878   Parse *pParse,      /* The parser context */
59879   Table *pTab,        /* the table into which we are inserting */
59880   int baseCur,        /* Index of a read/write cursor pointing at pTab */
59881   int regRowid,       /* Range of content */
59882   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
59883   int rowidChng,      /* True if the record number will change */
59884   int isUpdate,       /* True for UPDATE, False for INSERT */
59885   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
59886   int appendBias      /* True if this is likely to be an append */
59887 ){
59888   int i;
59889   Vdbe *v;
59890   int nIdx;
59891   Index *pIdx;
59892   int pik_flags;
59893   int regData;
59894   int regRec;
59895
59896   v = sqlite3GetVdbe(pParse);
59897   assert( v!=0 );
59898   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
59899   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
59900   for(i=nIdx-1; i>=0; i--){
59901     if( aRegIdx[i]==0 ) continue;
59902     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
59903   }
59904   regData = regRowid + 1;
59905   regRec = sqlite3GetTempReg(pParse);
59906   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
59907   sqlite3TableAffinityStr(v, pTab);
59908   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
59909 #ifndef SQLITE_OMIT_TRIGGER
59910   if( newIdx>=0 ){
59911     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
59912   }
59913 #endif
59914   if( pParse->nested ){
59915     pik_flags = 0;
59916   }else{
59917     pik_flags = OPFLAG_NCHANGE;
59918     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
59919   }
59920   if( appendBias ){
59921     pik_flags |= OPFLAG_APPEND;
59922   }
59923   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
59924   if( !pParse->nested ){
59925     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
59926   }
59927   sqlite3VdbeChangeP5(v, pik_flags);
59928 }
59929
59930 /*
59931 ** Generate code that will open cursors for a table and for all
59932 ** indices of that table.  The "baseCur" parameter is the cursor number used
59933 ** for the table.  Indices are opened on subsequent cursors.
59934 **
59935 ** Return the number of indices on the table.
59936 */
59937 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
59938   Parse *pParse,   /* Parsing context */
59939   Table *pTab,     /* Table to be opened */
59940   int baseCur,        /* Cursor number assigned to the table */
59941   int op           /* OP_OpenRead or OP_OpenWrite */
59942 ){
59943   int i;
59944   int iDb;
59945   Index *pIdx;
59946   Vdbe *v;
59947
59948   if( IsVirtual(pTab) ) return 0;
59949   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
59950   v = sqlite3GetVdbe(pParse);
59951   assert( v!=0 );
59952   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
59953   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
59954     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
59955     assert( pIdx->pSchema==pTab->pSchema );
59956     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
59957                       (char*)pKey, P4_KEYINFO_HANDOFF);
59958     VdbeComment((v, "%s", pIdx->zName));
59959   }
59960   if( pParse->nTab<=baseCur+i ){
59961     pParse->nTab = baseCur+i;
59962   }
59963   return i-1;
59964 }
59965
59966
59967 #ifdef SQLITE_TEST
59968 /*
59969 ** The following global variable is incremented whenever the
59970 ** transfer optimization is used.  This is used for testing
59971 ** purposes only - to make sure the transfer optimization really
59972 ** is happening when it is suppose to.
59973 */
59974 SQLITE_API int sqlite3_xferopt_count;
59975 #endif /* SQLITE_TEST */
59976
59977
59978 #ifndef SQLITE_OMIT_XFER_OPT
59979 /*
59980 ** Check to collation names to see if they are compatible.
59981 */
59982 static int xferCompatibleCollation(const char *z1, const char *z2){
59983   if( z1==0 ){
59984     return z2==0;
59985   }
59986   if( z2==0 ){
59987     return 0;
59988   }
59989   return sqlite3StrICmp(z1, z2)==0;
59990 }
59991
59992
59993 /*
59994 ** Check to see if index pSrc is compatible as a source of data
59995 ** for index pDest in an insert transfer optimization.  The rules
59996 ** for a compatible index:
59997 **
59998 **    *   The index is over the same set of columns
59999 **    *   The same DESC and ASC markings occurs on all columns
60000 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
60001 **    *   The same collating sequence on each column
60002 */
60003 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
60004   int i;
60005   assert( pDest && pSrc );
60006   assert( pDest->pTable!=pSrc->pTable );
60007   if( pDest->nColumn!=pSrc->nColumn ){
60008     return 0;   /* Different number of columns */
60009   }
60010   if( pDest->onError!=pSrc->onError ){
60011     return 0;   /* Different conflict resolution strategies */
60012   }
60013   for(i=0; i<pSrc->nColumn; i++){
60014     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
60015       return 0;   /* Different columns indexed */
60016     }
60017     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
60018       return 0;   /* Different sort orders */
60019     }
60020     if( pSrc->azColl[i]!=pDest->azColl[i] ){
60021       return 0;   /* Different collating sequences */
60022     }
60023   }
60024
60025   /* If no test above fails then the indices must be compatible */
60026   return 1;
60027 }
60028
60029 /*
60030 ** Attempt the transfer optimization on INSERTs of the form
60031 **
60032 **     INSERT INTO tab1 SELECT * FROM tab2;
60033 **
60034 ** This optimization is only attempted if
60035 **
60036 **    (1)  tab1 and tab2 have identical schemas including all the
60037 **         same indices and constraints
60038 **
60039 **    (2)  tab1 and tab2 are different tables
60040 **
60041 **    (3)  There must be no triggers on tab1
60042 **
60043 **    (4)  The result set of the SELECT statement is "*"
60044 **
60045 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
60046 **         or LIMIT clause.
60047 **
60048 **    (6)  The SELECT statement is a simple (not a compound) select that
60049 **         contains only tab2 in its FROM clause
60050 **
60051 ** This method for implementing the INSERT transfers raw records from
60052 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
60053 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
60054 ** the resulting tab1 has much less fragmentation.
60055 **
60056 ** This routine returns TRUE if the optimization is attempted.  If any
60057 ** of the conditions above fail so that the optimization should not
60058 ** be attempted, then this routine returns FALSE.
60059 */
60060 static int xferOptimization(
60061   Parse *pParse,        /* Parser context */
60062   Table *pDest,         /* The table we are inserting into */
60063   Select *pSelect,      /* A SELECT statement to use as the data source */
60064   int onError,          /* How to handle constraint errors */
60065   int iDbDest           /* The database of pDest */
60066 ){
60067   ExprList *pEList;                /* The result set of the SELECT */
60068   Table *pSrc;                     /* The table in the FROM clause of SELECT */
60069   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
60070   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
60071   int i;                           /* Loop counter */
60072   int iDbSrc;                      /* The database of pSrc */
60073   int iSrc, iDest;                 /* Cursors from source and destination */
60074   int addr1, addr2;                /* Loop addresses */
60075   int emptyDestTest;               /* Address of test for empty pDest */
60076   int emptySrcTest;                /* Address of test for empty pSrc */
60077   Vdbe *v;                         /* The VDBE we are building */
60078   KeyInfo *pKey;                   /* Key information for an index */
60079   int regAutoinc;                  /* Memory register used by AUTOINC */
60080   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
60081   int regData, regRowid;           /* Registers holding data and rowid */
60082
60083   if( pSelect==0 ){
60084     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
60085   }
60086   if( pDest->pTrigger ){
60087     return 0;   /* tab1 must not have triggers */
60088   }
60089 #ifndef SQLITE_OMIT_VIRTUALTABLE
60090   if( pDest->isVirtual ){
60091     return 0;   /* tab1 must not be a virtual table */
60092   }
60093 #endif
60094   if( onError==OE_Default ){
60095     onError = OE_Abort;
60096   }
60097   if( onError!=OE_Abort && onError!=OE_Rollback ){
60098     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
60099   }
60100   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
60101   if( pSelect->pSrc->nSrc!=1 ){
60102     return 0;   /* FROM clause must have exactly one term */
60103   }
60104   if( pSelect->pSrc->a[0].pSelect ){
60105     return 0;   /* FROM clause cannot contain a subquery */
60106   }
60107   if( pSelect->pWhere ){
60108     return 0;   /* SELECT may not have a WHERE clause */
60109   }
60110   if( pSelect->pOrderBy ){
60111     return 0;   /* SELECT may not have an ORDER BY clause */
60112   }
60113   /* Do not need to test for a HAVING clause.  If HAVING is present but
60114   ** there is no ORDER BY, we will get an error. */
60115   if( pSelect->pGroupBy ){
60116     return 0;   /* SELECT may not have a GROUP BY clause */
60117   }
60118   if( pSelect->pLimit ){
60119     return 0;   /* SELECT may not have a LIMIT clause */
60120   }
60121   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
60122   if( pSelect->pPrior ){
60123     return 0;   /* SELECT may not be a compound query */
60124   }
60125   if( pSelect->isDistinct ){
60126     return 0;   /* SELECT may not be DISTINCT */
60127   }
60128   pEList = pSelect->pEList;
60129   assert( pEList!=0 );
60130   if( pEList->nExpr!=1 ){
60131     return 0;   /* The result set must have exactly one column */
60132   }
60133   assert( pEList->a[0].pExpr );
60134   if( pEList->a[0].pExpr->op!=TK_ALL ){
60135     return 0;   /* The result set must be the special operator "*" */
60136   }
60137
60138   /* At this point we have established that the statement is of the
60139   ** correct syntactic form to participate in this optimization.  Now
60140   ** we have to check the semantics.
60141   */
60142   pItem = pSelect->pSrc->a;
60143   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
60144   if( pSrc==0 ){
60145     return 0;   /* FROM clause does not contain a real table */
60146   }
60147   if( pSrc==pDest ){
60148     return 0;   /* tab1 and tab2 may not be the same table */
60149   }
60150 #ifndef SQLITE_OMIT_VIRTUALTABLE
60151   if( pSrc->isVirtual ){
60152     return 0;   /* tab2 must not be a virtual table */
60153   }
60154 #endif
60155   if( pSrc->pSelect ){
60156     return 0;   /* tab2 may not be a view */
60157   }
60158   if( pDest->nCol!=pSrc->nCol ){
60159     return 0;   /* Number of columns must be the same in tab1 and tab2 */
60160   }
60161   if( pDest->iPKey!=pSrc->iPKey ){
60162     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
60163   }
60164   for(i=0; i<pDest->nCol; i++){
60165     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
60166       return 0;    /* Affinity must be the same on all columns */
60167     }
60168     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
60169       return 0;    /* Collating sequence must be the same on all columns */
60170     }
60171     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
60172       return 0;    /* tab2 must be NOT NULL if tab1 is */
60173     }
60174   }
60175   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
60176     if( pDestIdx->onError!=OE_None ){
60177       destHasUniqueIdx = 1;
60178     }
60179     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
60180       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
60181     }
60182     if( pSrcIdx==0 ){
60183       return 0;    /* pDestIdx has no corresponding index in pSrc */
60184     }
60185   }
60186 #ifndef SQLITE_OMIT_CHECK
60187   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
60188     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
60189   }
60190 #endif
60191
60192   /* If we get this far, it means either:
60193   **
60194   **    *   We can always do the transfer if the table contains an
60195   **        an integer primary key
60196   **
60197   **    *   We can conditionally do the transfer if the destination
60198   **        table is empty.
60199   */
60200 #ifdef SQLITE_TEST
60201   sqlite3_xferopt_count++;
60202 #endif
60203   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
60204   v = sqlite3GetVdbe(pParse);
60205   sqlite3CodeVerifySchema(pParse, iDbSrc);
60206   iSrc = pParse->nTab++;
60207   iDest = pParse->nTab++;
60208   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
60209   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
60210   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
60211     /* If tables do not have an INTEGER PRIMARY KEY and there
60212     ** are indices to be copied and the destination is not empty,
60213     ** we have to disallow the transfer optimization because the
60214     ** the rowids might change which will mess up indexing.
60215     **
60216     ** Or if the destination has a UNIQUE index and is not empty,
60217     ** we also disallow the transfer optimization because we cannot
60218     ** insure that all entries in the union of DEST and SRC will be
60219     ** unique.
60220     */
60221     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
60222     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
60223     sqlite3VdbeJumpHere(v, addr1);
60224   }else{
60225     emptyDestTest = 0;
60226   }
60227   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
60228   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
60229   regData = sqlite3GetTempReg(pParse);
60230   regRowid = sqlite3GetTempReg(pParse);
60231   if( pDest->iPKey>=0 ){
60232     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
60233     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
60234     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
60235                       "PRIMARY KEY must be unique", P4_STATIC);
60236     sqlite3VdbeJumpHere(v, addr2);
60237     autoIncStep(pParse, regAutoinc, regRowid);
60238   }else if( pDest->pIndex==0 ){
60239     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
60240   }else{
60241     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
60242     assert( pDest->autoInc==0 );
60243   }
60244   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
60245   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
60246   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
60247   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
60248   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
60249   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
60250   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
60251     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
60252       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
60253     }
60254     assert( pSrcIdx );
60255     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
60256     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
60257     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
60258     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
60259                       (char*)pKey, P4_KEYINFO_HANDOFF);
60260     VdbeComment((v, "%s", pSrcIdx->zName));
60261     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
60262     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
60263                       (char*)pKey, P4_KEYINFO_HANDOFF);
60264     VdbeComment((v, "%s", pDestIdx->zName));
60265     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
60266     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
60267     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
60268     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
60269     sqlite3VdbeJumpHere(v, addr1);
60270   }
60271   sqlite3VdbeJumpHere(v, emptySrcTest);
60272   sqlite3ReleaseTempReg(pParse, regRowid);
60273   sqlite3ReleaseTempReg(pParse, regData);
60274   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
60275   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
60276   if( emptyDestTest ){
60277     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
60278     sqlite3VdbeJumpHere(v, emptyDestTest);
60279     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
60280     return 0;
60281   }else{
60282     return 1;
60283   }
60284 }
60285 #endif /* SQLITE_OMIT_XFER_OPT */
60286
60287 /* Make sure "isView" gets undefined in case this file becomes part of
60288 ** the amalgamation - so that subsequent files do not see isView as a
60289 ** macro. */
60290 #undef isView
60291
60292 /************** End of insert.c **********************************************/
60293 /************** Begin file legacy.c ******************************************/
60294 /*
60295 ** 2001 September 15
60296 **
60297 ** The author disclaims copyright to this source code.  In place of
60298 ** a legal notice, here is a blessing:
60299 **
60300 **    May you do good and not evil.
60301 **    May you find forgiveness for yourself and forgive others.
60302 **    May you share freely, never taking more than you give.
60303 **
60304 *************************************************************************
60305 ** Main file for the SQLite library.  The routines in this file
60306 ** implement the programmer interface to the library.  Routines in
60307 ** other files are for internal use by SQLite and should not be
60308 ** accessed by users of the library.
60309 **
60310 ** $Id: legacy.c,v 1.24 2008/03/21 18:01:14 drh Exp $
60311 */
60312
60313
60314 /*
60315 ** Execute SQL code.  Return one of the SQLITE_ success/failure
60316 ** codes.  Also write an error message into memory obtained from
60317 ** malloc() and make *pzErrMsg point to that message.
60318 **
60319 ** If the SQL is a query, then for each row in the query result
60320 ** the xCallback() function is called.  pArg becomes the first
60321 ** argument to xCallback().  If xCallback=NULL then no callback
60322 ** is invoked, even for queries.
60323 */
60324 SQLITE_API int sqlite3_exec(
60325   sqlite3 *db,                /* The database on which the SQL executes */
60326   const char *zSql,           /* The SQL to be executed */
60327   sqlite3_callback xCallback, /* Invoke this callback routine */
60328   void *pArg,                 /* First argument to xCallback() */
60329   char **pzErrMsg             /* Write error messages here */
60330 ){
60331   int rc = SQLITE_OK;
60332   const char *zLeftover;
60333   sqlite3_stmt *pStmt = 0;
60334   char **azCols = 0;
60335
60336   int nRetry = 0;
60337   int nCallback;
60338
60339   if( zSql==0 ) return SQLITE_OK;
60340
60341   sqlite3_mutex_enter(db->mutex);
60342   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
60343     int nCol;
60344     char **azVals = 0;
60345
60346     pStmt = 0;
60347     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
60348     assert( rc==SQLITE_OK || pStmt==0 );
60349     if( rc!=SQLITE_OK ){
60350       continue;
60351     }
60352     if( !pStmt ){
60353       /* this happens for a comment or white-space */
60354       zSql = zLeftover;
60355       continue;
60356     }
60357
60358     nCallback = 0;
60359     nCol = sqlite3_column_count(pStmt);
60360
60361     while( 1 ){
60362       int i;
60363       rc = sqlite3_step(pStmt);
60364
60365       /* Invoke the callback function if required */
60366       if( xCallback && (SQLITE_ROW==rc || 
60367           (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
60368         if( 0==nCallback ){
60369           if( azCols==0 ){
60370             azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
60371             if( azCols==0 ){
60372               goto exec_out;
60373             }
60374           }
60375           for(i=0; i<nCol; i++){
60376             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
60377             if( !azCols[i] ){
60378               db->mallocFailed = 1;
60379               goto exec_out;
60380             }
60381           }
60382           nCallback++;
60383         }
60384         if( rc==SQLITE_ROW ){
60385           azVals = &azCols[nCol];
60386           for(i=0; i<nCol; i++){
60387             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
60388             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
60389               db->mallocFailed = 1;
60390               goto exec_out;
60391             }
60392           }
60393         }
60394         if( xCallback(pArg, nCol, azVals, azCols) ){
60395           rc = SQLITE_ABORT;
60396           goto exec_out;
60397         }
60398       }
60399
60400       if( rc!=SQLITE_ROW ){
60401         rc = sqlite3_finalize(pStmt);
60402         pStmt = 0;
60403         if( rc!=SQLITE_SCHEMA ){
60404           nRetry = 0;
60405           zSql = zLeftover;
60406           while( isspace((unsigned char)zSql[0]) ) zSql++;
60407         }
60408         break;
60409       }
60410     }
60411
60412     sqlite3_free(azCols);
60413     azCols = 0;
60414   }
60415
60416 exec_out:
60417   if( pStmt ) sqlite3_finalize(pStmt);
60418   if( azCols ) sqlite3_free(azCols);
60419
60420   rc = sqlite3ApiExit(db, rc);
60421   if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
60422     int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
60423     *pzErrMsg = sqlite3_malloc(nErrMsg);
60424     if( *pzErrMsg ){
60425       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
60426     }
60427   }else if( pzErrMsg ){
60428     *pzErrMsg = 0;
60429   }
60430
60431   assert( (rc&db->errMask)==rc );
60432   sqlite3_mutex_leave(db->mutex);
60433   return rc;
60434 }
60435
60436 /************** End of legacy.c **********************************************/
60437 /************** Begin file loadext.c *****************************************/
60438 /*
60439 ** 2006 June 7
60440 **
60441 ** The author disclaims copyright to this source code.  In place of
60442 ** a legal notice, here is a blessing:
60443 **
60444 **    May you do good and not evil.
60445 **    May you find forgiveness for yourself and forgive others.
60446 **    May you share freely, never taking more than you give.
60447 **
60448 *************************************************************************
60449 ** This file contains code used to dynamically load extensions into
60450 ** the SQLite library.
60451 */
60452
60453 #ifndef SQLITE_CORE
60454   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
60455 #endif
60456 /************** Include sqlite3ext.h in the middle of loadext.c **************/
60457 /************** Begin file sqlite3ext.h **************************************/
60458 /*
60459 ** 2006 June 7
60460 **
60461 ** The author disclaims copyright to this source code.  In place of
60462 ** a legal notice, here is a blessing:
60463 **
60464 **    May you do good and not evil.
60465 **    May you find forgiveness for yourself and forgive others.
60466 **    May you share freely, never taking more than you give.
60467 **
60468 *************************************************************************
60469 ** This header file defines the SQLite interface for use by
60470 ** shared libraries that want to be imported as extensions into
60471 ** an SQLite instance.  Shared libraries that intend to be loaded
60472 ** as extensions by SQLite should #include this file instead of 
60473 ** sqlite3.h.
60474 **
60475 ** @(#) $Id: sqlite3ext.h,v 1.21 2008/03/19 21:45:51 drh Exp $
60476 */
60477 #ifndef _SQLITE3EXT_H_
60478 #define _SQLITE3EXT_H_
60479
60480 typedef struct sqlite3_api_routines sqlite3_api_routines;
60481
60482 /*
60483 ** The following structure holds pointers to all of the SQLite API
60484 ** routines.
60485 **
60486 ** WARNING:  In order to maintain backwards compatibility, add new
60487 ** interfaces to the end of this structure only.  If you insert new
60488 ** interfaces in the middle of this structure, then older different
60489 ** versions of SQLite will not be able to load each others' shared
60490 ** libraries!
60491 */
60492 struct sqlite3_api_routines {
60493   void * (*aggregate_context)(sqlite3_context*,int nBytes);
60494   int  (*aggregate_count)(sqlite3_context*);
60495   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
60496   int  (*bind_double)(sqlite3_stmt*,int,double);
60497   int  (*bind_int)(sqlite3_stmt*,int,int);
60498   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
60499   int  (*bind_null)(sqlite3_stmt*,int);
60500   int  (*bind_parameter_count)(sqlite3_stmt*);
60501   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
60502   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
60503   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
60504   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
60505   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
60506   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
60507   int  (*busy_timeout)(sqlite3*,int ms);
60508   int  (*changes)(sqlite3*);
60509   int  (*close)(sqlite3*);
60510   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
60511   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
60512   const void * (*column_blob)(sqlite3_stmt*,int iCol);
60513   int  (*column_bytes)(sqlite3_stmt*,int iCol);
60514   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
60515   int  (*column_count)(sqlite3_stmt*pStmt);
60516   const char * (*column_database_name)(sqlite3_stmt*,int);
60517   const void * (*column_database_name16)(sqlite3_stmt*,int);
60518   const char * (*column_decltype)(sqlite3_stmt*,int i);
60519   const void * (*column_decltype16)(sqlite3_stmt*,int);
60520   double  (*column_double)(sqlite3_stmt*,int iCol);
60521   int  (*column_int)(sqlite3_stmt*,int iCol);
60522   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
60523   const char * (*column_name)(sqlite3_stmt*,int);
60524   const void * (*column_name16)(sqlite3_stmt*,int);
60525   const char * (*column_origin_name)(sqlite3_stmt*,int);
60526   const void * (*column_origin_name16)(sqlite3_stmt*,int);
60527   const char * (*column_table_name)(sqlite3_stmt*,int);
60528   const void * (*column_table_name16)(sqlite3_stmt*,int);
60529   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
60530   const void * (*column_text16)(sqlite3_stmt*,int iCol);
60531   int  (*column_type)(sqlite3_stmt*,int iCol);
60532   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
60533   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
60534   int  (*complete)(const char*sql);
60535   int  (*complete16)(const void*sql);
60536   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
60537   int  (*create_collation16)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
60538   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*));
60539   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*));
60540   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
60541   int  (*data_count)(sqlite3_stmt*pStmt);
60542   sqlite3 * (*db_handle)(sqlite3_stmt*);
60543   int (*declare_vtab)(sqlite3*,const char*);
60544   int  (*enable_shared_cache)(int);
60545   int  (*errcode)(sqlite3*db);
60546   const char * (*errmsg)(sqlite3*);
60547   const void * (*errmsg16)(sqlite3*);
60548   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
60549   int  (*expired)(sqlite3_stmt*);
60550   int  (*finalize)(sqlite3_stmt*pStmt);
60551   void  (*free)(void*);
60552   void  (*free_table)(char**result);
60553   int  (*get_autocommit)(sqlite3*);
60554   void * (*get_auxdata)(sqlite3_context*,int);
60555   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
60556   int  (*global_recover)(void);
60557   void  (*interruptx)(sqlite3*);
60558   sqlite_int64  (*last_insert_rowid)(sqlite3*);
60559   const char * (*libversion)(void);
60560   int  (*libversion_number)(void);
60561   void *(*malloc)(int);
60562   char * (*mprintf)(const char*,...);
60563   int  (*open)(const char*,sqlite3**);
60564   int  (*open16)(const void*,sqlite3**);
60565   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
60566   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
60567   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
60568   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
60569   void *(*realloc)(void*,int);
60570   int  (*reset)(sqlite3_stmt*pStmt);
60571   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
60572   void  (*result_double)(sqlite3_context*,double);
60573   void  (*result_error)(sqlite3_context*,const char*,int);
60574   void  (*result_error16)(sqlite3_context*,const void*,int);
60575   void  (*result_int)(sqlite3_context*,int);
60576   void  (*result_int64)(sqlite3_context*,sqlite_int64);
60577   void  (*result_null)(sqlite3_context*);
60578   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
60579   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
60580   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
60581   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
60582   void  (*result_value)(sqlite3_context*,sqlite3_value*);
60583   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
60584   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
60585   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
60586   char * (*snprintf)(int,char*,const char*,...);
60587   int  (*step)(sqlite3_stmt*);
60588   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
60589   void  (*thread_cleanup)(void);
60590   int  (*total_changes)(sqlite3*);
60591   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
60592   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
60593   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
60594   void * (*user_data)(sqlite3_context*);
60595   const void * (*value_blob)(sqlite3_value*);
60596   int  (*value_bytes)(sqlite3_value*);
60597   int  (*value_bytes16)(sqlite3_value*);
60598   double  (*value_double)(sqlite3_value*);
60599   int  (*value_int)(sqlite3_value*);
60600   sqlite_int64  (*value_int64)(sqlite3_value*);
60601   int  (*value_numeric_type)(sqlite3_value*);
60602   const unsigned char * (*value_text)(sqlite3_value*);
60603   const void * (*value_text16)(sqlite3_value*);
60604   const void * (*value_text16be)(sqlite3_value*);
60605   const void * (*value_text16le)(sqlite3_value*);
60606   int  (*value_type)(sqlite3_value*);
60607   char *(*vmprintf)(const char*,va_list);
60608   /* Added ??? */
60609   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
60610   /* Added by 3.3.13 */
60611   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
60612   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
60613   int (*clear_bindings)(sqlite3_stmt*);
60614   /* Added by 3.4.1 */
60615   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
60616   /* Added by 3.5.0 */
60617   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
60618   int (*blob_bytes)(sqlite3_blob*);
60619   int (*blob_close)(sqlite3_blob*);
60620   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
60621   int (*blob_read)(sqlite3_blob*,void*,int,int);
60622   int (*blob_write)(sqlite3_blob*,const void*,int,int);
60623   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
60624   int (*file_control)(sqlite3*,const char*,int,void*);
60625   sqlite3_int64 (*memory_highwater)(int);
60626   sqlite3_int64 (*memory_used)(void);
60627   sqlite3_mutex *(*mutex_alloc)(int);
60628   void (*mutex_enter)(sqlite3_mutex*);
60629   void (*mutex_free)(sqlite3_mutex*);
60630   void (*mutex_leave)(sqlite3_mutex*);
60631   int (*mutex_try)(sqlite3_mutex*);
60632   int (*open_v2)(const char*,sqlite3**,int,const char*);
60633   int (*release_memory)(int);
60634   void (*result_error_nomem)(sqlite3_context*);
60635   void (*result_error_toobig)(sqlite3_context*);
60636   int (*sleep)(int);
60637   void (*soft_heap_limit)(int);
60638   sqlite3_vfs *(*vfs_find)(const char*);
60639   int (*vfs_register)(sqlite3_vfs*,int);
60640   int (*vfs_unregister)(sqlite3_vfs*);
60641   int (*xthreadsafe)(void);
60642   void (*result_zeroblob)(sqlite3_context*,int);
60643   void (*result_error_code)(sqlite3_context*,int);
60644   int (*test_control)(int, ...);
60645   void (*randomness)(int,void*);
60646   sqlite3 *(*context_db_handle)(sqlite3_context*);
60647 };
60648
60649 /*
60650 ** The following macros redefine the API routines so that they are
60651 ** redirected throught the global sqlite3_api structure.
60652 **
60653 ** This header file is also used by the loadext.c source file
60654 ** (part of the main SQLite library - not an extension) so that
60655 ** it can get access to the sqlite3_api_routines structure
60656 ** definition.  But the main library does not want to redefine
60657 ** the API.  So the redefinition macros are only valid if the
60658 ** SQLITE_CORE macros is undefined.
60659 */
60660 #ifndef SQLITE_CORE
60661 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
60662 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
60663 #define sqlite3_bind_blob              sqlite3_api->bind_blob
60664 #define sqlite3_bind_double            sqlite3_api->bind_double
60665 #define sqlite3_bind_int               sqlite3_api->bind_int
60666 #define sqlite3_bind_int64             sqlite3_api->bind_int64
60667 #define sqlite3_bind_null              sqlite3_api->bind_null
60668 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
60669 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
60670 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
60671 #define sqlite3_bind_text              sqlite3_api->bind_text
60672 #define sqlite3_bind_text16            sqlite3_api->bind_text16
60673 #define sqlite3_bind_value             sqlite3_api->bind_value
60674 #define sqlite3_busy_handler           sqlite3_api->busy_handler
60675 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
60676 #define sqlite3_changes                sqlite3_api->changes
60677 #define sqlite3_close                  sqlite3_api->close
60678 #define sqlite3_collation_needed       sqlite3_api->collation_needed
60679 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
60680 #define sqlite3_column_blob            sqlite3_api->column_blob
60681 #define sqlite3_column_bytes           sqlite3_api->column_bytes
60682 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
60683 #define sqlite3_column_count           sqlite3_api->column_count
60684 #define sqlite3_column_database_name   sqlite3_api->column_database_name
60685 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
60686 #define sqlite3_column_decltype        sqlite3_api->column_decltype
60687 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
60688 #define sqlite3_column_double          sqlite3_api->column_double
60689 #define sqlite3_column_int             sqlite3_api->column_int
60690 #define sqlite3_column_int64           sqlite3_api->column_int64
60691 #define sqlite3_column_name            sqlite3_api->column_name
60692 #define sqlite3_column_name16          sqlite3_api->column_name16
60693 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
60694 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
60695 #define sqlite3_column_table_name      sqlite3_api->column_table_name
60696 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
60697 #define sqlite3_column_text            sqlite3_api->column_text
60698 #define sqlite3_column_text16          sqlite3_api->column_text16
60699 #define sqlite3_column_type            sqlite3_api->column_type
60700 #define sqlite3_column_value           sqlite3_api->column_value
60701 #define sqlite3_commit_hook            sqlite3_api->commit_hook
60702 #define sqlite3_complete               sqlite3_api->complete
60703 #define sqlite3_complete16             sqlite3_api->complete16
60704 #define sqlite3_create_collation       sqlite3_api->create_collation
60705 #define sqlite3_create_collation16     sqlite3_api->create_collation16
60706 #define sqlite3_create_function        sqlite3_api->create_function
60707 #define sqlite3_create_function16      sqlite3_api->create_function16
60708 #define sqlite3_create_module          sqlite3_api->create_module
60709 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
60710 #define sqlite3_data_count             sqlite3_api->data_count
60711 #define sqlite3_db_handle              sqlite3_api->db_handle
60712 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
60713 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
60714 #define sqlite3_errcode                sqlite3_api->errcode
60715 #define sqlite3_errmsg                 sqlite3_api->errmsg
60716 #define sqlite3_errmsg16               sqlite3_api->errmsg16
60717 #define sqlite3_exec                   sqlite3_api->exec
60718 #define sqlite3_expired                sqlite3_api->expired
60719 #define sqlite3_finalize               sqlite3_api->finalize
60720 #define sqlite3_free                   sqlite3_api->free
60721 #define sqlite3_free_table             sqlite3_api->free_table
60722 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
60723 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
60724 #define sqlite3_get_table              sqlite3_api->get_table
60725 #define sqlite3_global_recover         sqlite3_api->global_recover
60726 #define sqlite3_interrupt              sqlite3_api->interruptx
60727 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
60728 #define sqlite3_libversion             sqlite3_api->libversion
60729 #define sqlite3_libversion_number      sqlite3_api->libversion_number
60730 #define sqlite3_malloc                 sqlite3_api->malloc
60731 #define sqlite3_mprintf                sqlite3_api->mprintf
60732 #define sqlite3_open                   sqlite3_api->open
60733 #define sqlite3_open16                 sqlite3_api->open16
60734 #define sqlite3_prepare                sqlite3_api->prepare
60735 #define sqlite3_prepare16              sqlite3_api->prepare16
60736 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
60737 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
60738 #define sqlite3_profile                sqlite3_api->profile
60739 #define sqlite3_progress_handler       sqlite3_api->progress_handler
60740 #define sqlite3_realloc                sqlite3_api->realloc
60741 #define sqlite3_reset                  sqlite3_api->reset
60742 #define sqlite3_result_blob            sqlite3_api->result_blob
60743 #define sqlite3_result_double          sqlite3_api->result_double
60744 #define sqlite3_result_error           sqlite3_api->result_error
60745 #define sqlite3_result_error16         sqlite3_api->result_error16
60746 #define sqlite3_result_int             sqlite3_api->result_int
60747 #define sqlite3_result_int64           sqlite3_api->result_int64
60748 #define sqlite3_result_null            sqlite3_api->result_null
60749 #define sqlite3_result_text            sqlite3_api->result_text
60750 #define sqlite3_result_text16          sqlite3_api->result_text16
60751 #define sqlite3_result_text16be        sqlite3_api->result_text16be
60752 #define sqlite3_result_text16le        sqlite3_api->result_text16le
60753 #define sqlite3_result_value           sqlite3_api->result_value
60754 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
60755 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
60756 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
60757 #define sqlite3_snprintf               sqlite3_api->snprintf
60758 #define sqlite3_step                   sqlite3_api->step
60759 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
60760 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
60761 #define sqlite3_total_changes          sqlite3_api->total_changes
60762 #define sqlite3_trace                  sqlite3_api->trace
60763 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
60764 #define sqlite3_update_hook            sqlite3_api->update_hook
60765 #define sqlite3_user_data              sqlite3_api->user_data
60766 #define sqlite3_value_blob             sqlite3_api->value_blob
60767 #define sqlite3_value_bytes            sqlite3_api->value_bytes
60768 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
60769 #define sqlite3_value_double           sqlite3_api->value_double
60770 #define sqlite3_value_int              sqlite3_api->value_int
60771 #define sqlite3_value_int64            sqlite3_api->value_int64
60772 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
60773 #define sqlite3_value_text             sqlite3_api->value_text
60774 #define sqlite3_value_text16           sqlite3_api->value_text16
60775 #define sqlite3_value_text16be         sqlite3_api->value_text16be
60776 #define sqlite3_value_text16le         sqlite3_api->value_text16le
60777 #define sqlite3_value_type             sqlite3_api->value_type
60778 #define sqlite3_vmprintf               sqlite3_api->vmprintf
60779 #define sqlite3_overload_function      sqlite3_api->overload_function
60780 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
60781 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
60782 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
60783 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
60784 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
60785 #define sqlite3_blob_close             sqlite3_api->blob_close
60786 #define sqlite3_blob_open              sqlite3_api->blob_open
60787 #define sqlite3_blob_read              sqlite3_api->blob_read
60788 #define sqlite3_blob_write             sqlite3_api->blob_write
60789 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
60790 #define sqlite3_file_control           sqlite3_api->file_control
60791 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
60792 #define sqlite3_memory_used            sqlite3_api->memory_used
60793 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
60794 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
60795 #define sqlite3_mutex_free             sqlite3_api->mutex_free
60796 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
60797 #define sqlite3_mutex_try              sqlite3_api->mutex_try
60798 #define sqlite3_open_v2                sqlite3_api->open_v2
60799 #define sqlite3_release_memory         sqlite3_api->release_memory
60800 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
60801 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
60802 #define sqlite3_sleep                  sqlite3_api->sleep
60803 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
60804 #define sqlite3_vfs_find               sqlite3_api->vfs_find
60805 #define sqlite3_vfs_register           sqlite3_api->vfs_register
60806 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
60807 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
60808 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
60809 #define sqlite3_result_error_code      sqlite3_api->result_error_code
60810 #define sqlite3_test_control           sqlite3_api->test_control
60811 #define sqlite3_randomness             sqlite3_api->randomness
60812 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
60813 #endif /* SQLITE_CORE */
60814
60815 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api;
60816 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
60817
60818 #endif /* _SQLITE3EXT_H_ */
60819
60820 /************** End of sqlite3ext.h ******************************************/
60821 /************** Continuing where we left off in loadext.c ********************/
60822
60823 #ifndef SQLITE_OMIT_LOAD_EXTENSION
60824
60825 /*
60826 ** Some API routines are omitted when various features are
60827 ** excluded from a build of SQLite.  Substitute a NULL pointer
60828 ** for any missing APIs.
60829 */
60830 #ifndef SQLITE_ENABLE_COLUMN_METADATA
60831 # define sqlite3_column_database_name   0
60832 # define sqlite3_column_database_name16 0
60833 # define sqlite3_column_table_name      0
60834 # define sqlite3_column_table_name16    0
60835 # define sqlite3_column_origin_name     0
60836 # define sqlite3_column_origin_name16   0
60837 # define sqlite3_table_column_metadata  0
60838 #endif
60839
60840 #ifdef SQLITE_OMIT_AUTHORIZATION
60841 # define sqlite3_set_authorizer         0
60842 #endif
60843
60844 #ifdef SQLITE_OMIT_UTF16
60845 # define sqlite3_bind_text16            0
60846 # define sqlite3_collation_needed16     0
60847 # define sqlite3_column_decltype16      0
60848 # define sqlite3_column_name16          0
60849 # define sqlite3_column_text16          0
60850 # define sqlite3_complete16             0
60851 # define sqlite3_create_collation16     0
60852 # define sqlite3_create_function16      0
60853 # define sqlite3_errmsg16               0
60854 # define sqlite3_open16                 0
60855 # define sqlite3_prepare16              0
60856 # define sqlite3_prepare16_v2           0
60857 # define sqlite3_result_error16         0
60858 # define sqlite3_result_text16          0
60859 # define sqlite3_result_text16be        0
60860 # define sqlite3_result_text16le        0
60861 # define sqlite3_value_text16           0
60862 # define sqlite3_value_text16be         0
60863 # define sqlite3_value_text16le         0
60864 # define sqlite3_column_database_name16 0
60865 # define sqlite3_column_table_name16    0
60866 # define sqlite3_column_origin_name16   0
60867 #endif
60868
60869 #ifdef SQLITE_OMIT_COMPLETE
60870 # define sqlite3_complete 0
60871 # define sqlite3_complete16 0
60872 #endif
60873
60874 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
60875 # define sqlite3_progress_handler 0
60876 #endif
60877
60878 #ifdef SQLITE_OMIT_VIRTUALTABLE
60879 # define sqlite3_create_module 0
60880 # define sqlite3_create_module_v2 0
60881 # define sqlite3_declare_vtab 0
60882 #endif
60883
60884 #ifdef SQLITE_OMIT_SHARED_CACHE
60885 # define sqlite3_enable_shared_cache 0
60886 #endif
60887
60888 #ifdef SQLITE_OMIT_TRACE
60889 # define sqlite3_profile       0
60890 # define sqlite3_trace         0
60891 #endif
60892
60893 #ifdef SQLITE_OMIT_GET_TABLE
60894 # define sqlite3_free_table    0
60895 # define sqlite3_get_table     0
60896 #endif
60897
60898 #ifdef SQLITE_OMIT_INCRBLOB
60899 #define sqlite3_bind_zeroblob  0
60900 #define sqlite3_blob_bytes     0
60901 #define sqlite3_blob_close     0
60902 #define sqlite3_blob_open      0
60903 #define sqlite3_blob_read      0
60904 #define sqlite3_blob_write     0
60905 #endif
60906
60907 /*
60908 ** The following structure contains pointers to all SQLite API routines.
60909 ** A pointer to this structure is passed into extensions when they are
60910 ** loaded so that the extension can make calls back into the SQLite
60911 ** library.
60912 **
60913 ** When adding new APIs, add them to the bottom of this structure
60914 ** in order to preserve backwards compatibility.
60915 **
60916 ** Extensions that use newer APIs should first call the
60917 ** sqlite3_libversion_number() to make sure that the API they
60918 ** intend to use is supported by the library.  Extensions should
60919 ** also check to make sure that the pointer to the function is
60920 ** not NULL before calling it.
60921 */
60922 static const sqlite3_api_routines sqlite3Apis = {
60923   sqlite3_aggregate_context,
60924   sqlite3_aggregate_count,
60925   sqlite3_bind_blob,
60926   sqlite3_bind_double,
60927   sqlite3_bind_int,
60928   sqlite3_bind_int64,
60929   sqlite3_bind_null,
60930   sqlite3_bind_parameter_count,
60931   sqlite3_bind_parameter_index,
60932   sqlite3_bind_parameter_name,
60933   sqlite3_bind_text,
60934   sqlite3_bind_text16,
60935   sqlite3_bind_value,
60936   sqlite3_busy_handler,
60937   sqlite3_busy_timeout,
60938   sqlite3_changes,
60939   sqlite3_close,
60940   sqlite3_collation_needed,
60941   sqlite3_collation_needed16,
60942   sqlite3_column_blob,
60943   sqlite3_column_bytes,
60944   sqlite3_column_bytes16,
60945   sqlite3_column_count,
60946   sqlite3_column_database_name,
60947   sqlite3_column_database_name16,
60948   sqlite3_column_decltype,
60949   sqlite3_column_decltype16,
60950   sqlite3_column_double,
60951   sqlite3_column_int,
60952   sqlite3_column_int64,
60953   sqlite3_column_name,
60954   sqlite3_column_name16,
60955   sqlite3_column_origin_name,
60956   sqlite3_column_origin_name16,
60957   sqlite3_column_table_name,
60958   sqlite3_column_table_name16,
60959   sqlite3_column_text,
60960   sqlite3_column_text16,
60961   sqlite3_column_type,
60962   sqlite3_column_value,
60963   sqlite3_commit_hook,
60964   sqlite3_complete,
60965   sqlite3_complete16,
60966   sqlite3_create_collation,
60967   sqlite3_create_collation16,
60968   sqlite3_create_function,
60969   sqlite3_create_function16,
60970   sqlite3_create_module,
60971   sqlite3_data_count,
60972   sqlite3_db_handle,
60973   sqlite3_declare_vtab,
60974   sqlite3_enable_shared_cache,
60975   sqlite3_errcode,
60976   sqlite3_errmsg,
60977   sqlite3_errmsg16,
60978   sqlite3_exec,
60979   sqlite3_expired,
60980   sqlite3_finalize,
60981   sqlite3_free,
60982   sqlite3_free_table,
60983   sqlite3_get_autocommit,
60984   sqlite3_get_auxdata,
60985   sqlite3_get_table,
60986   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
60987   sqlite3_interrupt,
60988   sqlite3_last_insert_rowid,
60989   sqlite3_libversion,
60990   sqlite3_libversion_number,
60991   sqlite3_malloc,
60992   sqlite3_mprintf,
60993   sqlite3_open,
60994   sqlite3_open16,
60995   sqlite3_prepare,
60996   sqlite3_prepare16,
60997   sqlite3_profile,
60998   sqlite3_progress_handler,
60999   sqlite3_realloc,
61000   sqlite3_reset,
61001   sqlite3_result_blob,
61002   sqlite3_result_double,
61003   sqlite3_result_error,
61004   sqlite3_result_error16,
61005   sqlite3_result_int,
61006   sqlite3_result_int64,
61007   sqlite3_result_null,
61008   sqlite3_result_text,
61009   sqlite3_result_text16,
61010   sqlite3_result_text16be,
61011   sqlite3_result_text16le,
61012   sqlite3_result_value,
61013   sqlite3_rollback_hook,
61014   sqlite3_set_authorizer,
61015   sqlite3_set_auxdata,
61016   sqlite3_snprintf,
61017   sqlite3_step,
61018   sqlite3_table_column_metadata,
61019   sqlite3_thread_cleanup,
61020   sqlite3_total_changes,
61021   sqlite3_trace,
61022   sqlite3_transfer_bindings,
61023   sqlite3_update_hook,
61024   sqlite3_user_data,
61025   sqlite3_value_blob,
61026   sqlite3_value_bytes,
61027   sqlite3_value_bytes16,
61028   sqlite3_value_double,
61029   sqlite3_value_int,
61030   sqlite3_value_int64,
61031   sqlite3_value_numeric_type,
61032   sqlite3_value_text,
61033   sqlite3_value_text16,
61034   sqlite3_value_text16be,
61035   sqlite3_value_text16le,
61036   sqlite3_value_type,
61037   sqlite3_vmprintf,
61038   /*
61039   ** The original API set ends here.  All extensions can call any
61040   ** of the APIs above provided that the pointer is not NULL.  But
61041   ** before calling APIs that follow, extension should check the
61042   ** sqlite3_libversion_number() to make sure they are dealing with
61043   ** a library that is new enough to support that API.
61044   *************************************************************************
61045   */
61046   sqlite3_overload_function,
61047
61048   /*
61049   ** Added after 3.3.13
61050   */
61051   sqlite3_prepare_v2,
61052   sqlite3_prepare16_v2,
61053   sqlite3_clear_bindings,
61054
61055   /*
61056   ** Added for 3.4.1
61057   */
61058   sqlite3_create_module_v2,
61059
61060   /*
61061   ** Added for 3.5.0
61062   */
61063   sqlite3_bind_zeroblob,
61064   sqlite3_blob_bytes,
61065   sqlite3_blob_close,
61066   sqlite3_blob_open,
61067   sqlite3_blob_read,
61068   sqlite3_blob_write,
61069   sqlite3_create_collation_v2,
61070   sqlite3_file_control,
61071   sqlite3_memory_highwater,
61072   sqlite3_memory_used,
61073 #ifdef SQLITE_MUTEX_NOOP
61074   0, 
61075   0, 
61076   0,
61077   0,
61078   0,
61079 #else
61080   sqlite3_mutex_alloc,
61081   sqlite3_mutex_enter,
61082   sqlite3_mutex_free,
61083   sqlite3_mutex_leave,
61084   sqlite3_mutex_try,
61085 #endif
61086   sqlite3_open_v2,
61087   sqlite3_release_memory,
61088   sqlite3_result_error_nomem,
61089   sqlite3_result_error_toobig,
61090   sqlite3_sleep,
61091   sqlite3_soft_heap_limit,
61092   sqlite3_vfs_find,
61093   sqlite3_vfs_register,
61094   sqlite3_vfs_unregister,
61095
61096   /*
61097   ** Added for 3.5.8
61098   */
61099   sqlite3_threadsafe,
61100   sqlite3_result_zeroblob,
61101   sqlite3_result_error_code,
61102   sqlite3_test_control,
61103   sqlite3_randomness,
61104   sqlite3_context_db_handle,
61105 };
61106
61107 /*
61108 ** Attempt to load an SQLite extension library contained in the file
61109 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
61110 ** default entry point name (sqlite3_extension_init) is used.  Use
61111 ** of the default name is recommended.
61112 **
61113 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
61114 **
61115 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
61116 ** error message text.  The calling function should free this memory
61117 ** by calling sqlite3_free().
61118 */
61119 static int sqlite3LoadExtension(
61120   sqlite3 *db,          /* Load the extension into this database connection */
61121   const char *zFile,    /* Name of the shared library containing extension */
61122   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
61123   char **pzErrMsg       /* Put error message here if not 0 */
61124 ){
61125   sqlite3_vfs *pVfs = db->pVfs;
61126   void *handle;
61127   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
61128   char *zErrmsg = 0;
61129   void **aHandle;
61130
61131   /* Ticket #1863.  To avoid a creating security problems for older
61132   ** applications that relink against newer versions of SQLite, the
61133   ** ability to run load_extension is turned off by default.  One
61134   ** must call sqlite3_enable_load_extension() to turn on extension
61135   ** loading.  Otherwise you get the following error.
61136   */
61137   if( (db->flags & SQLITE_LoadExtension)==0 ){
61138     if( pzErrMsg ){
61139       *pzErrMsg = sqlite3_mprintf("not authorized");
61140     }
61141     return SQLITE_ERROR;
61142   }
61143
61144   if( zProc==0 ){
61145     zProc = "sqlite3_extension_init";
61146   }
61147
61148   handle = sqlite3OsDlOpen(pVfs, zFile);
61149   if( handle==0 ){
61150     if( pzErrMsg ){
61151       char zErr[256];
61152       zErr[sizeof(zErr)-1] = '\0';
61153       sqlite3_snprintf(sizeof(zErr)-1, zErr, 
61154           "unable to open shared library [%s]", zFile);
61155       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
61156       *pzErrMsg = sqlite3DbStrDup(db, zErr);
61157     }
61158     return SQLITE_ERROR;
61159   }
61160   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
61161                    sqlite3OsDlSym(pVfs, handle, zProc);
61162   if( xInit==0 ){
61163     if( pzErrMsg ){
61164       char zErr[256];
61165       zErr[sizeof(zErr)-1] = '\0';
61166       sqlite3_snprintf(sizeof(zErr)-1, zErr,
61167           "no entry point [%s] in shared library [%s]", zProc,zFile);
61168       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
61169       *pzErrMsg = sqlite3DbStrDup(db, zErr);
61170       sqlite3OsDlClose(pVfs, handle);
61171     }
61172     return SQLITE_ERROR;
61173   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
61174     if( pzErrMsg ){
61175       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
61176     }
61177     sqlite3_free(zErrmsg);
61178     sqlite3OsDlClose(pVfs, handle);
61179     return SQLITE_ERROR;
61180   }
61181
61182   /* Append the new shared library handle to the db->aExtension array. */
61183   db->nExtension++;
61184   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db->nExtension);
61185   if( aHandle==0 ){
61186     return SQLITE_NOMEM;
61187   }
61188   if( db->nExtension>0 ){
61189     memcpy(aHandle, db->aExtension, sizeof(handle)*(db->nExtension-1));
61190   }
61191   sqlite3_free(db->aExtension);
61192   db->aExtension = aHandle;
61193
61194   db->aExtension[db->nExtension-1] = handle;
61195   return SQLITE_OK;
61196 }
61197 SQLITE_API int sqlite3_load_extension(
61198   sqlite3 *db,          /* Load the extension into this database connection */
61199   const char *zFile,    /* Name of the shared library containing extension */
61200   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
61201   char **pzErrMsg       /* Put error message here if not 0 */
61202 ){
61203   int rc;
61204   sqlite3_mutex_enter(db->mutex);
61205   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
61206   sqlite3_mutex_leave(db->mutex);
61207   return rc;
61208 }
61209
61210 /*
61211 ** Call this routine when the database connection is closing in order
61212 ** to clean up loaded extensions
61213 */
61214 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
61215   int i;
61216   assert( sqlite3_mutex_held(db->mutex) );
61217   for(i=0; i<db->nExtension; i++){
61218     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
61219   }
61220   sqlite3_free(db->aExtension);
61221 }
61222
61223 /*
61224 ** Enable or disable extension loading.  Extension loading is disabled by
61225 ** default so as not to open security holes in older applications.
61226 */
61227 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
61228   sqlite3_mutex_enter(db->mutex);
61229   if( onoff ){
61230     db->flags |= SQLITE_LoadExtension;
61231   }else{
61232     db->flags &= ~SQLITE_LoadExtension;
61233   }
61234   sqlite3_mutex_leave(db->mutex);
61235   return SQLITE_OK;
61236 }
61237
61238 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
61239
61240 /*
61241 ** The auto-extension code added regardless of whether or not extension
61242 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
61243 ** code if regular extension loading is not available.  This is that
61244 ** dummy pointer.
61245 */
61246 #ifdef SQLITE_OMIT_LOAD_EXTENSION
61247 static const sqlite3_api_routines sqlite3Apis = { 0 };
61248 #endif
61249
61250
61251 /*
61252 ** The following object holds the list of automatically loaded
61253 ** extensions.
61254 **
61255 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
61256 ** mutex must be held while accessing this list.
61257 */
61258 static struct {
61259   int nExt;        /* Number of entries in aExt[] */          
61260   void **aExt;     /* Pointers to the extension init functions */
61261 } autoext = { 0, 0 };
61262
61263
61264 /*
61265 ** Register a statically linked extension that is automatically
61266 ** loaded by every new database connection.
61267 */
61268 SQLITE_API int sqlite3_auto_extension(void *xInit){
61269   int i;
61270   int rc = SQLITE_OK;
61271 #ifndef SQLITE_MUTEX_NOOP
61272   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
61273 #endif
61274   sqlite3_mutex_enter(mutex);
61275   for(i=0; i<autoext.nExt; i++){
61276     if( autoext.aExt[i]==xInit ) break;
61277   }
61278   if( i==autoext.nExt ){
61279     int nByte = (autoext.nExt+1)*sizeof(autoext.aExt[0]);
61280     void **aNew;
61281     aNew = sqlite3_realloc(autoext.aExt, nByte);
61282     if( aNew==0 ){
61283       rc = SQLITE_NOMEM;
61284     }else{
61285       autoext.aExt = aNew;
61286       autoext.aExt[autoext.nExt] = xInit;
61287       autoext.nExt++;
61288     }
61289   }
61290   sqlite3_mutex_leave(mutex);
61291   assert( (rc&0xff)==rc );
61292   return rc;
61293 }
61294
61295 /*
61296 ** Reset the automatic extension loading mechanism.
61297 */
61298 SQLITE_API void sqlite3_reset_auto_extension(void){
61299 #ifndef SQLITE_MUTEX_NOOP
61300   sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
61301 #endif
61302   sqlite3_mutex_enter(mutex);
61303   sqlite3_free(autoext.aExt);
61304   autoext.aExt = 0;
61305   autoext.nExt = 0;
61306   sqlite3_mutex_leave(mutex);
61307 }
61308
61309 /*
61310 ** Load all automatic extensions.
61311 */
61312 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
61313   int i;
61314   int go = 1;
61315   int rc = SQLITE_OK;
61316   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
61317
61318   if( autoext.nExt==0 ){
61319     /* Common case: early out without every having to acquire a mutex */
61320     return SQLITE_OK;
61321   }
61322   for(i=0; go; i++){
61323     char *zErrmsg = 0;
61324 #ifndef SQLITE_MUTEX_NOOP
61325     sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
61326 #endif
61327     sqlite3_mutex_enter(mutex);
61328     if( i>=autoext.nExt ){
61329       xInit = 0;
61330       go = 0;
61331     }else{
61332       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
61333               autoext.aExt[i];
61334     }
61335     sqlite3_mutex_leave(mutex);
61336     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
61337       sqlite3Error(db, SQLITE_ERROR,
61338             "automatic extension loading failed: %s", zErrmsg);
61339       go = 0;
61340       rc = SQLITE_ERROR;
61341       sqlite3_free(zErrmsg);
61342     }
61343   }
61344   return rc;
61345 }
61346
61347 /************** End of loadext.c *********************************************/
61348 /************** Begin file pragma.c ******************************************/
61349 /*
61350 ** 2003 April 6
61351 **
61352 ** The author disclaims copyright to this source code.  In place of
61353 ** a legal notice, here is a blessing:
61354 **
61355 **    May you do good and not evil.
61356 **    May you find forgiveness for yourself and forgive others.
61357 **    May you share freely, never taking more than you give.
61358 **
61359 *************************************************************************
61360 ** This file contains code used to implement the PRAGMA command.
61361 **
61362 ** $Id: pragma.c,v 1.176 2008/04/17 20:59:38 drh Exp $
61363 */
61364
61365 /* Ignore this whole file if pragmas are disabled
61366 */
61367 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
61368
61369 /*
61370 ** Interpret the given string as a safety level.  Return 0 for OFF,
61371 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
61372 ** unrecognized string argument.
61373 **
61374 ** Note that the values returned are one less that the values that
61375 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
61376 ** to support legacy SQL code.  The safety level used to be boolean
61377 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
61378 */
61379 static int getSafetyLevel(const char *z){
61380                              /* 123456789 123456789 */
61381   static const char zText[] = "onoffalseyestruefull";
61382   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
61383   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
61384   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
61385   int i, n;
61386   if( isdigit(*z) ){
61387     return atoi(z);
61388   }
61389   n = strlen(z);
61390   for(i=0; i<sizeof(iLength); i++){
61391     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
61392       return iValue[i];
61393     }
61394   }
61395   return 1;
61396 }
61397
61398 /*
61399 ** Interpret the given string as a boolean value.
61400 */
61401 static int getBoolean(const char *z){
61402   return getSafetyLevel(z)&1;
61403 }
61404
61405 /*
61406 ** Interpret the given string as a locking mode value.
61407 */
61408 static int getLockingMode(const char *z){
61409   if( z ){
61410     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
61411     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
61412   }
61413   return PAGER_LOCKINGMODE_QUERY;
61414 }
61415
61416 #ifndef SQLITE_OMIT_AUTOVACUUM
61417 /*
61418 ** Interpret the given string as an auto-vacuum mode value.
61419 **
61420 ** The following strings, "none", "full" and "incremental" are 
61421 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
61422 */
61423 static int getAutoVacuum(const char *z){
61424   int i;
61425   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
61426   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
61427   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
61428   i = atoi(z);
61429   return ((i>=0&&i<=2)?i:0);
61430 }
61431 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
61432
61433 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
61434 /*
61435 ** Interpret the given string as a temp db location. Return 1 for file
61436 ** backed temporary databases, 2 for the Red-Black tree in memory database
61437 ** and 0 to use the compile-time default.
61438 */
61439 static int getTempStore(const char *z){
61440   if( z[0]>='0' && z[0]<='2' ){
61441     return z[0] - '0';
61442   }else if( sqlite3StrICmp(z, "file")==0 ){
61443     return 1;
61444   }else if( sqlite3StrICmp(z, "memory")==0 ){
61445     return 2;
61446   }else{
61447     return 0;
61448   }
61449 }
61450 #endif /* SQLITE_PAGER_PRAGMAS */
61451
61452 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
61453 /*
61454 ** Invalidate temp storage, either when the temp storage is changed
61455 ** from default, or when 'file' and the temp_store_directory has changed
61456 */
61457 static int invalidateTempStorage(Parse *pParse){
61458   sqlite3 *db = pParse->db;
61459   if( db->aDb[1].pBt!=0 ){
61460     if( !db->autoCommit ){
61461       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
61462         "from within a transaction");
61463       return SQLITE_ERROR;
61464     }
61465     sqlite3BtreeClose(db->aDb[1].pBt);
61466     db->aDb[1].pBt = 0;
61467     sqlite3ResetInternalSchema(db, 0);
61468   }
61469   return SQLITE_OK;
61470 }
61471 #endif /* SQLITE_PAGER_PRAGMAS */
61472
61473 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
61474 /*
61475 ** If the TEMP database is open, close it and mark the database schema
61476 ** as needing reloading.  This must be done when using the TEMP_STORE
61477 ** or DEFAULT_TEMP_STORE pragmas.
61478 */
61479 static int changeTempStorage(Parse *pParse, const char *zStorageType){
61480   int ts = getTempStore(zStorageType);
61481   sqlite3 *db = pParse->db;
61482   if( db->temp_store==ts ) return SQLITE_OK;
61483   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
61484     return SQLITE_ERROR;
61485   }
61486   db->temp_store = ts;
61487   return SQLITE_OK;
61488 }
61489 #endif /* SQLITE_PAGER_PRAGMAS */
61490
61491 /*
61492 ** Generate code to return a single integer value.
61493 */
61494 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
61495   Vdbe *v = sqlite3GetVdbe(pParse);
61496   int mem = ++pParse->nMem;
61497   sqlite3VdbeAddOp2(v, OP_Integer, value, mem);
61498   if( pParse->explain==0 ){
61499     sqlite3VdbeSetNumCols(v, 1);
61500     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P4_STATIC);
61501   }
61502   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
61503 }
61504
61505 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
61506 /*
61507 ** Check to see if zRight and zLeft refer to a pragma that queries
61508 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
61509 ** Also, implement the pragma.
61510 */
61511 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
61512   static const struct sPragmaType {
61513     const char *zName;  /* Name of the pragma */
61514     int mask;           /* Mask for the db->flags value */
61515   } aPragma[] = {
61516     { "full_column_names",        SQLITE_FullColNames  },
61517     { "short_column_names",       SQLITE_ShortColNames },
61518     { "count_changes",            SQLITE_CountRows     },
61519     { "empty_result_callbacks",   SQLITE_NullCallback  },
61520     { "legacy_file_format",       SQLITE_LegacyFileFmt },
61521     { "fullfsync",                SQLITE_FullFSync     },
61522 #ifdef SQLITE_DEBUG
61523     { "sql_trace",                SQLITE_SqlTrace      },
61524     { "vdbe_listing",             SQLITE_VdbeListing   },
61525     { "vdbe_trace",               SQLITE_VdbeTrace     },
61526 #endif
61527 #ifndef SQLITE_OMIT_CHECK
61528     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
61529 #endif
61530     /* The following is VERY experimental */
61531     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
61532     { "omit_readlock",            SQLITE_NoReadlock    },
61533
61534     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
61535     ** flag if there are any active statements. */
61536     { "read_uncommitted",         SQLITE_ReadUncommitted },
61537   };
61538   int i;
61539   const struct sPragmaType *p;
61540   for(i=0, p=aPragma; i<sizeof(aPragma)/sizeof(aPragma[0]); i++, p++){
61541     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
61542       sqlite3 *db = pParse->db;
61543       Vdbe *v;
61544       v = sqlite3GetVdbe(pParse);
61545       if( v ){
61546         if( zRight==0 ){
61547           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
61548         }else{
61549           if( getBoolean(zRight) ){
61550             db->flags |= p->mask;
61551           }else{
61552             db->flags &= ~p->mask;
61553           }
61554
61555           /* Many of the flag-pragmas modify the code generated by the SQL 
61556           ** compiler (eg. count_changes). So add an opcode to expire all
61557           ** compiled SQL statements after modifying a pragma value.
61558           */
61559           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
61560         }
61561       }
61562
61563       return 1;
61564     }
61565   }
61566   return 0;
61567 }
61568 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
61569
61570 /*
61571 ** Process a pragma statement.  
61572 **
61573 ** Pragmas are of this form:
61574 **
61575 **      PRAGMA [database.]id [= value]
61576 **
61577 ** The identifier might also be a string.  The value is a string, and
61578 ** identifier, or a number.  If minusFlag is true, then the value is
61579 ** a number that was preceded by a minus sign.
61580 **
61581 ** If the left side is "database.id" then pId1 is the database name
61582 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
61583 ** id and pId2 is any empty string.
61584 */
61585 SQLITE_PRIVATE void sqlite3Pragma(
61586   Parse *pParse, 
61587   Token *pId1,        /* First part of [database.]id field */
61588   Token *pId2,        /* Second part of [database.]id field, or NULL */
61589   Token *pValue,      /* Token for <value>, or NULL */
61590   int minusFlag       /* True if a '-' sign preceded <value> */
61591 ){
61592   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
61593   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
61594   const char *zDb = 0;   /* The database name */
61595   Token *pId;            /* Pointer to <id> token */
61596   int iDb;               /* Database index for <database> */
61597   sqlite3 *db = pParse->db;
61598   Db *pDb;
61599   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
61600   if( v==0 ) return;
61601   pParse->nMem = 2;
61602
61603   /* Interpret the [database.] part of the pragma statement. iDb is the
61604   ** index of the database this pragma is being applied to in db.aDb[]. */
61605   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
61606   if( iDb<0 ) return;
61607   pDb = &db->aDb[iDb];
61608
61609   /* If the temp database has been explicitly named as part of the 
61610   ** pragma, make sure it is open. 
61611   */
61612   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
61613     return;
61614   }
61615
61616   zLeft = sqlite3NameFromToken(db, pId);
61617   if( !zLeft ) return;
61618   if( minusFlag ){
61619     zRight = sqlite3MPrintf(db, "-%T", pValue);
61620   }else{
61621     zRight = sqlite3NameFromToken(db, pValue);
61622   }
61623
61624   zDb = ((iDb>0)?pDb->zName:0);
61625   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
61626     goto pragma_out;
61627   }
61628  
61629 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
61630   /*
61631   **  PRAGMA [database.]default_cache_size
61632   **  PRAGMA [database.]default_cache_size=N
61633   **
61634   ** The first form reports the current persistent setting for the
61635   ** page cache size.  The value returned is the maximum number of
61636   ** pages in the page cache.  The second form sets both the current
61637   ** page cache size value and the persistent page cache size value
61638   ** stored in the database file.
61639   **
61640   ** The default cache size is stored in meta-value 2 of page 1 of the
61641   ** database file.  The cache size is actually the absolute value of
61642   ** this memory location.  The sign of meta-value 2 determines the
61643   ** synchronous setting.  A negative value means synchronous is off
61644   ** and a positive value means synchronous is on.
61645   */
61646   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
61647     static const VdbeOpList getCacheSize[] = {
61648       { OP_ReadCookie,  0, 1,        2},  /* 0 */
61649       { OP_IfPos,       1, 6,        0},
61650       { OP_Integer,     0, 2,        0},
61651       { OP_Subtract,    1, 2,        1},
61652       { OP_IfPos,       1, 6,        0},
61653       { OP_Integer,     0, 1,        0},  /* 5 */
61654       { OP_ResultRow,   1, 1,        0},
61655     };
61656     int addr;
61657     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
61658     sqlite3VdbeUsesBtree(v, iDb);
61659     if( !zRight ){
61660       sqlite3VdbeSetNumCols(v, 1);
61661       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P4_STATIC);
61662       pParse->nMem += 2;
61663       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
61664       sqlite3VdbeChangeP1(v, addr, iDb);
61665       sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
61666     }else{
61667       int size = atoi(zRight);
61668       if( size<0 ) size = -size;
61669       sqlite3BeginWriteOperation(pParse, 0, iDb);
61670       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
61671       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
61672       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
61673       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
61674       sqlite3VdbeJumpHere(v, addr);
61675       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
61676       pDb->pSchema->cache_size = size;
61677       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
61678     }
61679   }else
61680
61681   /*
61682   **  PRAGMA [database.]page_size
61683   **  PRAGMA [database.]page_size=N
61684   **
61685   ** The first form reports the current setting for the
61686   ** database page size in bytes.  The second form sets the
61687   ** database page size value.  The value can only be set if
61688   ** the database has not yet been created.
61689   */
61690   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
61691     Btree *pBt = pDb->pBt;
61692     if( !zRight ){
61693       int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
61694       returnSingleInt(pParse, "page_size", size);
61695     }else{
61696       /* Malloc may fail when setting the page-size, as there is an internal
61697       ** buffer that the pager module resizes using sqlite3_realloc().
61698       */
61699       db->nextPagesize = atoi(zRight);
61700       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1) ){
61701         db->mallocFailed = 1;
61702       }
61703     }
61704   }else
61705
61706   /*
61707   **  PRAGMA [database.]max_page_count
61708   **  PRAGMA [database.]max_page_count=N
61709   **
61710   ** The first form reports the current setting for the
61711   ** maximum number of pages in the database file.  The 
61712   ** second form attempts to change this setting.  Both
61713   ** forms return the current setting.
61714   */
61715   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
61716     Btree *pBt = pDb->pBt;
61717     int newMax = 0;
61718     if( zRight ){
61719       newMax = atoi(zRight);
61720     }
61721     if( pBt ){
61722       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
61723     }
61724     returnSingleInt(pParse, "max_page_count", newMax);
61725   }else
61726
61727   /*
61728   **  PRAGMA [database.]locking_mode
61729   **  PRAGMA [database.]locking_mode = (normal|exclusive)
61730   */
61731   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
61732     const char *zRet = "normal";
61733     int eMode = getLockingMode(zRight);
61734
61735     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
61736       /* Simple "PRAGMA locking_mode;" statement. This is a query for
61737       ** the current default locking mode (which may be different to
61738       ** the locking-mode of the main database).
61739       */
61740       eMode = db->dfltLockMode;
61741     }else{
61742       Pager *pPager;
61743       if( pId2->n==0 ){
61744         /* This indicates that no database name was specified as part
61745         ** of the PRAGMA command. In this case the locking-mode must be
61746         ** set on all attached databases, as well as the main db file.
61747         **
61748         ** Also, the sqlite3.dfltLockMode variable is set so that
61749         ** any subsequently attached databases also use the specified
61750         ** locking mode.
61751         */
61752         int ii;
61753         assert(pDb==&db->aDb[0]);
61754         for(ii=2; ii<db->nDb; ii++){
61755           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
61756           sqlite3PagerLockingMode(pPager, eMode);
61757         }
61758         db->dfltLockMode = eMode;
61759       }
61760       pPager = sqlite3BtreePager(pDb->pBt);
61761       eMode = sqlite3PagerLockingMode(pPager, eMode);
61762     }
61763
61764     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
61765     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
61766       zRet = "exclusive";
61767     }
61768     sqlite3VdbeSetNumCols(v, 1);
61769     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P4_STATIC);
61770     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
61771     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
61772   }else
61773
61774   /*
61775   **  PRAGMA [database.]journal_mode
61776   **  PRAGMA [database.]journal_mode = (delete|persist|off)
61777   */
61778   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
61779     int eMode;
61780     static const char *azModeName[] = {"delete", "persist", "off"};
61781
61782     if( zRight==0 ){
61783       eMode = PAGER_JOURNALMODE_QUERY;
61784     }else{
61785       int n = strlen(zRight);
61786       eMode = 2;
61787       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
61788         eMode--;
61789       }
61790     }
61791     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
61792       /* Simple "PRAGMA persistent_journal;" statement. This is a query for
61793       ** the current default journal mode (which may be different to
61794       ** the journal-mode of the main database).
61795       */
61796       eMode = db->dfltJournalMode;
61797     }else{
61798       Pager *pPager;
61799       if( pId2->n==0 ){
61800         /* This indicates that no database name was specified as part
61801         ** of the PRAGMA command. In this case the journal-mode must be
61802         ** set on all attached databases, as well as the main db file.
61803         **
61804         ** Also, the sqlite3.dfltJournalMode variable is set so that
61805         ** any subsequently attached databases also use the specified
61806         ** journal mode.
61807         */
61808         int ii;
61809         assert(pDb==&db->aDb[0]);
61810         for(ii=1; ii<db->nDb; ii++){
61811           if( db->aDb[ii].pBt ){
61812             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
61813             sqlite3PagerJournalMode(pPager, eMode);
61814           }
61815         }
61816         db->dfltJournalMode = eMode;
61817       }
61818       pPager = sqlite3BtreePager(pDb->pBt);
61819       eMode = sqlite3PagerJournalMode(pPager, eMode);
61820     }
61821     assert( eMode==PAGER_JOURNALMODE_DELETE
61822               || eMode==PAGER_JOURNALMODE_PERSIST
61823               || eMode==PAGER_JOURNALMODE_OFF );
61824     sqlite3VdbeSetNumCols(v, 1);
61825     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", P4_STATIC);
61826     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
61827            azModeName[eMode], P4_STATIC);
61828     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
61829   }else
61830 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
61831
61832   /*
61833   **  PRAGMA [database.]auto_vacuum
61834   **  PRAGMA [database.]auto_vacuum=N
61835   **
61836   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
61837   */
61838 #ifndef SQLITE_OMIT_AUTOVACUUM
61839   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
61840     Btree *pBt = pDb->pBt;
61841     if( sqlite3ReadSchema(pParse) ){
61842       goto pragma_out;
61843     }
61844     if( !zRight ){
61845       int auto_vacuum = 
61846           pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
61847       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
61848     }else{
61849       int eAuto = getAutoVacuum(zRight);
61850       db->nextAutovac = eAuto;
61851       if( eAuto>=0 ){
61852         /* Call SetAutoVacuum() to set initialize the internal auto and
61853         ** incr-vacuum flags. This is required in case this connection
61854         ** creates the database file. It is important that it is created
61855         ** as an auto-vacuum capable db.
61856         */
61857         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
61858         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
61859           /* When setting the auto_vacuum mode to either "full" or 
61860           ** "incremental", write the value of meta[6] in the database
61861           ** file. Before writing to meta[6], check that meta[3] indicates
61862           ** that this really is an auto-vacuum capable database.
61863           */
61864           static const VdbeOpList setMeta6[] = {
61865             { OP_Transaction,    0,               1,        0},    /* 0 */
61866             { OP_ReadCookie,     0,               1,        3},    /* 1 */
61867             { OP_If,             1,               0,        0},    /* 2 */
61868             { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
61869             { OP_Integer,        0,               1,        0},    /* 4 */
61870             { OP_SetCookie,      0,               6,        1},    /* 5 */
61871           };
61872           int iAddr;
61873           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
61874           sqlite3VdbeChangeP1(v, iAddr, iDb);
61875           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
61876           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
61877           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
61878           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
61879           sqlite3VdbeUsesBtree(v, iDb);
61880         }
61881       }
61882     }
61883   }else
61884 #endif
61885
61886   /*
61887   **  PRAGMA [database.]incremental_vacuum(N)
61888   **
61889   ** Do N steps of incremental vacuuming on a database.
61890   */
61891 #ifndef SQLITE_OMIT_AUTOVACUUM
61892   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
61893     int iLimit, addr;
61894     if( sqlite3ReadSchema(pParse) ){
61895       goto pragma_out;
61896     }
61897     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
61898       iLimit = 0x7fffffff;
61899     }
61900     sqlite3BeginWriteOperation(pParse, 0, iDb);
61901     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
61902     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
61903     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
61904     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
61905     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
61906     sqlite3VdbeJumpHere(v, addr);
61907   }else
61908 #endif
61909
61910 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
61911   /*
61912   **  PRAGMA [database.]cache_size
61913   **  PRAGMA [database.]cache_size=N
61914   **
61915   ** The first form reports the current local setting for the
61916   ** page cache size.  The local setting can be different from
61917   ** the persistent cache size value that is stored in the database
61918   ** file itself.  The value returned is the maximum number of
61919   ** pages in the page cache.  The second form sets the local
61920   ** page cache size value.  It does not change the persistent
61921   ** cache size stored on the disk so the cache size will revert
61922   ** to its default value when the database is closed and reopened.
61923   ** N should be a positive integer.
61924   */
61925   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
61926     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
61927     if( !zRight ){
61928       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
61929     }else{
61930       int size = atoi(zRight);
61931       if( size<0 ) size = -size;
61932       pDb->pSchema->cache_size = size;
61933       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
61934     }
61935   }else
61936
61937   /*
61938   **   PRAGMA temp_store
61939   **   PRAGMA temp_store = "default"|"memory"|"file"
61940   **
61941   ** Return or set the local value of the temp_store flag.  Changing
61942   ** the local value does not make changes to the disk file and the default
61943   ** value will be restored the next time the database is opened.
61944   **
61945   ** Note that it is possible for the library compile-time options to
61946   ** override this setting
61947   */
61948   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
61949     if( !zRight ){
61950       returnSingleInt(pParse, "temp_store", db->temp_store);
61951     }else{
61952       changeTempStorage(pParse, zRight);
61953     }
61954   }else
61955
61956   /*
61957   **   PRAGMA temp_store_directory
61958   **   PRAGMA temp_store_directory = ""|"directory_name"
61959   **
61960   ** Return or set the local value of the temp_store_directory flag.  Changing
61961   ** the value sets a specific directory to be used for temporary files.
61962   ** Setting to a null string reverts to the default temporary directory search.
61963   ** If temporary directory is changed, then invalidateTempStorage.
61964   **
61965   */
61966   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
61967     if( !zRight ){
61968       if( sqlite3_temp_directory ){
61969         sqlite3VdbeSetNumCols(v, 1);
61970         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
61971             "temp_store_directory", P4_STATIC);
61972         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
61973         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
61974       }
61975     }else{
61976       if( zRight[0] 
61977        && sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE)==0 
61978       ){
61979         sqlite3ErrorMsg(pParse, "not a writable directory");
61980         goto pragma_out;
61981       }
61982       if( TEMP_STORE==0
61983        || (TEMP_STORE==1 && db->temp_store<=1)
61984        || (TEMP_STORE==2 && db->temp_store==1)
61985       ){
61986         invalidateTempStorage(pParse);
61987       }
61988       sqlite3_free(sqlite3_temp_directory);
61989       if( zRight[0] ){
61990         sqlite3_temp_directory = zRight;
61991         zRight = 0;
61992       }else{
61993         sqlite3_temp_directory = 0;
61994       }
61995     }
61996   }else
61997
61998   /*
61999   **   PRAGMA [database.]synchronous
62000   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
62001   **
62002   ** Return or set the local value of the synchronous flag.  Changing
62003   ** the local value does not make changes to the disk file and the
62004   ** default value will be restored the next time the database is
62005   ** opened.
62006   */
62007   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
62008     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
62009     if( !zRight ){
62010       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
62011     }else{
62012       if( !db->autoCommit ){
62013         sqlite3ErrorMsg(pParse, 
62014             "Safety level may not be changed inside a transaction");
62015       }else{
62016         pDb->safety_level = getSafetyLevel(zRight)+1;
62017       }
62018     }
62019   }else
62020 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
62021
62022 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
62023   if( flagPragma(pParse, zLeft, zRight) ){
62024     /* The flagPragma() subroutine also generates any necessary code
62025     ** there is nothing more to do here */
62026   }else
62027 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
62028
62029 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
62030   /*
62031   **   PRAGMA table_info(<table>)
62032   **
62033   ** Return a single row for each column of the named table. The columns of
62034   ** the returned data set are:
62035   **
62036   ** cid:        Column id (numbered from left to right, starting at 0)
62037   ** name:       Column name
62038   ** type:       Column declaration type.
62039   ** notnull:    True if 'NOT NULL' is part of column declaration
62040   ** dflt_value: The default value for the column, if any.
62041   */
62042   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
62043     Table *pTab;
62044     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
62045     pTab = sqlite3FindTable(db, zRight, zDb);
62046     if( pTab ){
62047       int i;
62048       int nHidden = 0;
62049       Column *pCol;
62050       sqlite3VdbeSetNumCols(v, 6);
62051       pParse->nMem = 6;
62052       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P4_STATIC);
62053       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
62054       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P4_STATIC);
62055       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P4_STATIC);
62056       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P4_STATIC);
62057       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P4_STATIC);
62058       sqlite3ViewGetColumnNames(pParse, pTab);
62059       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
62060         const Token *pDflt;
62061         if( IsHiddenColumn(pCol) ){
62062           nHidden++;
62063           continue;
62064         }
62065         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
62066         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
62067         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
62068            pCol->zType ? pCol->zType : "", 0);
62069         sqlite3VdbeAddOp2(v, OP_Integer, pCol->notNull, 4);
62070         if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
62071           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n);
62072         }else{
62073           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
62074         }
62075         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
62076         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
62077       }
62078     }
62079   }else
62080
62081   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
62082     Index *pIdx;
62083     Table *pTab;
62084     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
62085     pIdx = sqlite3FindIndex(db, zRight, zDb);
62086     if( pIdx ){
62087       int i;
62088       pTab = pIdx->pTable;
62089       sqlite3VdbeSetNumCols(v, 3);
62090       pParse->nMem = 3;
62091       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P4_STATIC);
62092       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P4_STATIC);
62093       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P4_STATIC);
62094       for(i=0; i<pIdx->nColumn; i++){
62095         int cnum = pIdx->aiColumn[i];
62096         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
62097         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
62098         assert( pTab->nCol>cnum );
62099         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
62100         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
62101       }
62102     }
62103   }else
62104
62105   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
62106     Index *pIdx;
62107     Table *pTab;
62108     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
62109     pTab = sqlite3FindTable(db, zRight, zDb);
62110     if( pTab ){
62111       v = sqlite3GetVdbe(pParse);
62112       pIdx = pTab->pIndex;
62113       if( pIdx ){
62114         int i = 0; 
62115         sqlite3VdbeSetNumCols(v, 3);
62116         pParse->nMem = 3;
62117         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
62118         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
62119         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P4_STATIC);
62120         while(pIdx){
62121           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
62122           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
62123           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
62124           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
62125           ++i;
62126           pIdx = pIdx->pNext;
62127         }
62128       }
62129     }
62130   }else
62131
62132   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
62133     int i;
62134     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
62135     sqlite3VdbeSetNumCols(v, 3);
62136     pParse->nMem = 3;
62137     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
62138     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
62139     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P4_STATIC);
62140     for(i=0; i<db->nDb; i++){
62141       if( db->aDb[i].pBt==0 ) continue;
62142       assert( db->aDb[i].zName!=0 );
62143       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
62144       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
62145       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
62146            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
62147       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
62148     }
62149   }else
62150
62151   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
62152     int i = 0;
62153     HashElem *p;
62154     sqlite3VdbeSetNumCols(v, 2);
62155     pParse->nMem = 2;
62156     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
62157     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
62158     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
62159       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
62160       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
62161       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
62162       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
62163     }
62164   }else
62165 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
62166
62167 #ifndef SQLITE_OMIT_FOREIGN_KEY
62168   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
62169     FKey *pFK;
62170     Table *pTab;
62171     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
62172     pTab = sqlite3FindTable(db, zRight, zDb);
62173     if( pTab ){
62174       v = sqlite3GetVdbe(pParse);
62175       pFK = pTab->pFKey;
62176       if( pFK ){
62177         int i = 0; 
62178         sqlite3VdbeSetNumCols(v, 5);
62179         pParse->nMem = 5;
62180         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P4_STATIC);
62181         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P4_STATIC);
62182         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P4_STATIC);
62183         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P4_STATIC);
62184         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P4_STATIC);
62185         while(pFK){
62186           int j;
62187           for(j=0; j<pFK->nCol; j++){
62188             char *zCol = pFK->aCol[j].zCol;
62189             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
62190             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
62191             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
62192             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
62193                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
62194             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
62195             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
62196           }
62197           ++i;
62198           pFK = pFK->pNextFrom;
62199         }
62200       }
62201     }
62202   }else
62203 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
62204
62205 #ifndef NDEBUG
62206   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
62207     if( zRight ){
62208       if( getBoolean(zRight) ){
62209         sqlite3ParserTrace(stderr, "parser: ");
62210       }else{
62211         sqlite3ParserTrace(0, 0);
62212       }
62213     }
62214   }else
62215 #endif
62216
62217   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
62218   ** used will be case sensitive or not depending on the RHS.
62219   */
62220   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
62221     if( zRight ){
62222       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
62223     }
62224   }else
62225
62226 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
62227 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
62228 #endif
62229
62230 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
62231   /* Pragma "quick_check" is an experimental reduced version of 
62232   ** integrity_check designed to detect most database corruption
62233   ** without most of the overhead of a full integrity-check.
62234   */
62235   if( sqlite3StrICmp(zLeft, "integrity_check")==0
62236    || sqlite3StrICmp(zLeft, "quick_check")==0 
62237   ){
62238     int i, j, addr, mxErr;
62239
62240     /* Code that appears at the end of the integrity check.  If no error
62241     ** messages have been generated, output OK.  Otherwise output the
62242     ** error message
62243     */
62244     static const VdbeOpList endCode[] = {
62245       { OP_AddImm,      1, 0,        0},    /* 0 */
62246       { OP_IfNeg,       1, 0,        0},    /* 1 */
62247       { OP_String8,     0, 3,        0},    /* 2 */
62248       { OP_ResultRow,   3, 1,        0},
62249     };
62250
62251     int isQuick = (zLeft[0]=='q');
62252
62253     /* Initialize the VDBE program */
62254     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
62255     pParse->nMem = 6;
62256     sqlite3VdbeSetNumCols(v, 1);
62257     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P4_STATIC);
62258
62259     /* Set the maximum error count */
62260     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
62261     if( zRight ){
62262       mxErr = atoi(zRight);
62263       if( mxErr<=0 ){
62264         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
62265       }
62266     }
62267     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
62268
62269     /* Do an integrity check on each database file */
62270     for(i=0; i<db->nDb; i++){
62271       HashElem *x;
62272       Hash *pTbls;
62273       int cnt = 0;
62274
62275       if( OMIT_TEMPDB && i==1 ) continue;
62276
62277       sqlite3CodeVerifySchema(pParse, i);
62278       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
62279       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
62280       sqlite3VdbeJumpHere(v, addr);
62281
62282       /* Do an integrity check of the B-Tree
62283       **
62284       ** Begin by filling registers 2, 3, ... with the root pages numbers
62285       ** for all tables and indices in the database.
62286       */
62287       pTbls = &db->aDb[i].pSchema->tblHash;
62288       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
62289         Table *pTab = sqliteHashData(x);
62290         Index *pIdx;
62291         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
62292         cnt++;
62293         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
62294           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
62295           cnt++;
62296         }
62297       }
62298       if( cnt==0 ) continue;
62299
62300       /* Make sure sufficient number of registers have been allocated */
62301       if( pParse->nMem < cnt+4 ){
62302         pParse->nMem = cnt+4;
62303       }
62304
62305       /* Do the b-tree integrity checks */
62306       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
62307       sqlite3VdbeChangeP5(v, i);
62308       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
62309       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
62310          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
62311          P4_DYNAMIC);
62312       sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
62313       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
62314       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
62315       sqlite3VdbeJumpHere(v, addr);
62316
62317       /* Make sure all the indices are constructed correctly.
62318       */
62319       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
62320         Table *pTab = sqliteHashData(x);
62321         Index *pIdx;
62322         int loopTop;
62323
62324         if( pTab->pIndex==0 ) continue;
62325         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
62326         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
62327         sqlite3VdbeJumpHere(v, addr);
62328         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
62329         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
62330         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
62331         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
62332         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
62333           int jmp2;
62334           static const VdbeOpList idxErr[] = {
62335             { OP_AddImm,      1, -1,  0},
62336             { OP_String8,     0,  3,  0},    /* 1 */
62337             { OP_Rowid,       1,  4,  0},
62338             { OP_String8,     0,  5,  0},    /* 3 */
62339             { OP_String8,     0,  6,  0},    /* 4 */
62340             { OP_Concat,      4,  3,  3},
62341             { OP_Concat,      5,  3,  3},
62342             { OP_Concat,      6,  3,  3},
62343             { OP_ResultRow,   3,  1,  0},
62344             { OP_IfPos,       1,  0,  0},    /* 9 */
62345             { OP_Halt,        0,  0,  0},
62346           };
62347           sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
62348           jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
62349           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
62350           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
62351           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
62352           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
62353           sqlite3VdbeJumpHere(v, addr+9);
62354           sqlite3VdbeJumpHere(v, jmp2);
62355         }
62356         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
62357         sqlite3VdbeJumpHere(v, loopTop);
62358         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
62359           static const VdbeOpList cntIdx[] = {
62360              { OP_Integer,      0,  3,  0},
62361              { OP_Rewind,       0,  0,  0},  /* 1 */
62362              { OP_AddImm,       3,  1,  0},
62363              { OP_Next,         0,  0,  0},  /* 3 */
62364              { OP_Eq,           2,  0,  3},  /* 4 */
62365              { OP_AddImm,       1, -1,  0},
62366              { OP_String8,      0,  2,  0},  /* 6 */
62367              { OP_String8,      0,  3,  0},  /* 7 */
62368              { OP_Concat,       3,  2,  2},
62369              { OP_ResultRow,    2,  1,  0},
62370           };
62371           if( pIdx->tnum==0 ) continue;
62372           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
62373           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
62374           sqlite3VdbeJumpHere(v, addr);
62375           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
62376           sqlite3VdbeChangeP1(v, addr+1, j+2);
62377           sqlite3VdbeChangeP2(v, addr+1, addr+4);
62378           sqlite3VdbeChangeP1(v, addr+3, j+2);
62379           sqlite3VdbeChangeP2(v, addr+3, addr+2);
62380           sqlite3VdbeJumpHere(v, addr+4);
62381           sqlite3VdbeChangeP4(v, addr+6, 
62382                      "wrong # of entries in index ", P4_STATIC);
62383           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
62384         }
62385       } 
62386     }
62387     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
62388     sqlite3VdbeChangeP2(v, addr, -mxErr);
62389     sqlite3VdbeJumpHere(v, addr+1);
62390     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
62391   }else
62392 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
62393
62394 #ifndef SQLITE_OMIT_UTF16
62395   /*
62396   **   PRAGMA encoding
62397   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
62398   **
62399   ** In its first form, this pragma returns the encoding of the main
62400   ** database. If the database is not initialized, it is initialized now.
62401   **
62402   ** The second form of this pragma is a no-op if the main database file
62403   ** has not already been initialized. In this case it sets the default
62404   ** encoding that will be used for the main database file if a new file
62405   ** is created. If an existing main database file is opened, then the
62406   ** default text encoding for the existing database is used.
62407   ** 
62408   ** In all cases new databases created using the ATTACH command are
62409   ** created to use the same default text encoding as the main database. If
62410   ** the main database has not been initialized and/or created when ATTACH
62411   ** is executed, this is done before the ATTACH operation.
62412   **
62413   ** In the second form this pragma sets the text encoding to be used in
62414   ** new database files created using this database handle. It is only
62415   ** useful if invoked immediately after the main database i
62416   */
62417   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
62418     static const struct EncName {
62419       char *zName;
62420       u8 enc;
62421     } encnames[] = {
62422       { "UTF-8",    SQLITE_UTF8        },
62423       { "UTF8",     SQLITE_UTF8        },
62424       { "UTF-16le", SQLITE_UTF16LE     },
62425       { "UTF16le",  SQLITE_UTF16LE     },
62426       { "UTF-16be", SQLITE_UTF16BE     },
62427       { "UTF16be",  SQLITE_UTF16BE     },
62428       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
62429       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
62430       { 0, 0 }
62431     };
62432     const struct EncName *pEnc;
62433     if( !zRight ){    /* "PRAGMA encoding" */
62434       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
62435       sqlite3VdbeSetNumCols(v, 1);
62436       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P4_STATIC);
62437       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
62438       for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
62439         if( pEnc->enc==ENC(pParse->db) ){
62440           sqlite3VdbeChangeP4(v, -1, pEnc->zName, P4_STATIC);
62441           break;
62442         }
62443       }
62444       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
62445     }else{                        /* "PRAGMA encoding = XXX" */
62446       /* Only change the value of sqlite.enc if the database handle is not
62447       ** initialized. If the main database exists, the new sqlite.enc value
62448       ** will be overwritten when the schema is next loaded. If it does not
62449       ** already exists, it will be created to use the new encoding value.
62450       */
62451       if( 
62452         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
62453         DbHasProperty(db, 0, DB_Empty) 
62454       ){
62455         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
62456           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
62457             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
62458             break;
62459           }
62460         }
62461         if( !pEnc->zName ){
62462           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
62463         }
62464       }
62465     }
62466   }else
62467 #endif /* SQLITE_OMIT_UTF16 */
62468
62469 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
62470   /*
62471   **   PRAGMA [database.]schema_version
62472   **   PRAGMA [database.]schema_version = <integer>
62473   **
62474   **   PRAGMA [database.]user_version
62475   **   PRAGMA [database.]user_version = <integer>
62476   **
62477   ** The pragma's schema_version and user_version are used to set or get
62478   ** the value of the schema-version and user-version, respectively. Both
62479   ** the schema-version and the user-version are 32-bit signed integers
62480   ** stored in the database header.
62481   **
62482   ** The schema-cookie is usually only manipulated internally by SQLite. It
62483   ** is incremented by SQLite whenever the database schema is modified (by
62484   ** creating or dropping a table or index). The schema version is used by
62485   ** SQLite each time a query is executed to ensure that the internal cache
62486   ** of the schema used when compiling the SQL query matches the schema of
62487   ** the database against which the compiled query is actually executed.
62488   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
62489   ** the schema-version is potentially dangerous and may lead to program
62490   ** crashes or database corruption. Use with caution!
62491   **
62492   ** The user-version is not used internally by SQLite. It may be used by
62493   ** applications for any purpose.
62494   */
62495   if( sqlite3StrICmp(zLeft, "schema_version")==0 
62496    || sqlite3StrICmp(zLeft, "user_version")==0 
62497    || sqlite3StrICmp(zLeft, "freelist_count")==0 
62498   ){
62499
62500     int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
62501     sqlite3VdbeUsesBtree(v, iDb);
62502     switch( zLeft[0] ){
62503       case 's': case 'S':
62504         iCookie = 0;
62505         break;
62506       case 'f': case 'F':
62507         iCookie = 1;
62508         iDb = (-1*(iDb+1));
62509         assert(iDb<=0);
62510         break;
62511       default:
62512         iCookie = 5;
62513         break;
62514     }
62515
62516     if( zRight && iDb>=0 ){
62517       /* Write the specified cookie value */
62518       static const VdbeOpList setCookie[] = {
62519         { OP_Transaction,    0,  1,  0},    /* 0 */
62520         { OP_Integer,        0,  1,  0},    /* 1 */
62521         { OP_SetCookie,      0,  0,  1},    /* 2 */
62522       };
62523       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
62524       sqlite3VdbeChangeP1(v, addr, iDb);
62525       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
62526       sqlite3VdbeChangeP1(v, addr+2, iDb);
62527       sqlite3VdbeChangeP2(v, addr+2, iCookie);
62528     }else{
62529       /* Read the specified cookie value */
62530       static const VdbeOpList readCookie[] = {
62531         { OP_ReadCookie,      0,  1,  0},    /* 0 */
62532         { OP_ResultRow,       1,  1,  0}
62533       };
62534       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
62535       sqlite3VdbeChangeP1(v, addr, iDb);
62536       sqlite3VdbeChangeP3(v, addr, iCookie);
62537       sqlite3VdbeSetNumCols(v, 1);
62538       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P4_TRANSIENT);
62539     }
62540   }else
62541 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
62542
62543 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
62544   /*
62545   ** Report the current state of file logs for all databases
62546   */
62547   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
62548     static const char *const azLockName[] = {
62549       "unlocked", "shared", "reserved", "pending", "exclusive"
62550     };
62551     int i;
62552     Vdbe *v = sqlite3GetVdbe(pParse);
62553     sqlite3VdbeSetNumCols(v, 2);
62554     pParse->nMem = 2;
62555     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P4_STATIC);
62556     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P4_STATIC);
62557     for(i=0; i<db->nDb; i++){
62558       Btree *pBt;
62559       Pager *pPager;
62560       const char *zState = "unknown";
62561       int j;
62562       if( db->aDb[i].zName==0 ) continue;
62563       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
62564       pBt = db->aDb[i].pBt;
62565       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
62566         zState = "closed";
62567       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
62568                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
62569          zState = azLockName[j];
62570       }
62571       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
62572       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
62573     }
62574   }else
62575 #endif
62576
62577 #ifdef SQLITE_SSE
62578   /*
62579   ** Check to see if the sqlite_statements table exists.  Create it
62580   ** if it does not.
62581   */
62582   if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
62583     extern int sqlite3CreateStatementsTable(Parse*);
62584     sqlite3CreateStatementsTable(pParse);
62585   }else
62586 #endif
62587
62588 #if SQLITE_HAS_CODEC
62589   if( sqlite3StrICmp(zLeft, "key")==0 ){
62590     sqlite3_key(db, zRight, strlen(zRight));
62591   }else
62592 #endif
62593 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
62594   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
62595 #if SQLITE_HAS_CODEC
62596     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
62597       extern void sqlite3_activate_see(const char*);
62598       sqlite3_activate_see(&zRight[4]);
62599     }
62600 #endif
62601 #ifdef SQLITE_ENABLE_CEROD
62602     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
62603       extern void sqlite3_activate_cerod(const char*);
62604       sqlite3_activate_cerod(&zRight[6]);
62605     }
62606 #endif
62607   }
62608 #endif
62609
62610   {}
62611
62612   if( v ){
62613     /* Code an OP_Expire at the end of each PRAGMA program to cause
62614     ** the VDBE implementing the pragma to expire. Most (all?) pragmas
62615     ** are only valid for a single execution.
62616     */
62617     sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
62618
62619     /*
62620     ** Reset the safety level, in case the fullfsync flag or synchronous
62621     ** setting changed.
62622     */
62623 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
62624     if( db->autoCommit ){
62625       sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
62626                  (db->flags&SQLITE_FullFSync)!=0);
62627     }
62628 #endif
62629   }
62630 pragma_out:
62631   sqlite3_free(zLeft);
62632   sqlite3_free(zRight);
62633 }
62634
62635 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
62636
62637 /************** End of pragma.c **********************************************/
62638 /************** Begin file prepare.c *****************************************/
62639 /*
62640 ** 2005 May 25
62641 **
62642 ** The author disclaims copyright to this source code.  In place of
62643 ** a legal notice, here is a blessing:
62644 **
62645 **    May you do good and not evil.
62646 **    May you find forgiveness for yourself and forgive others.
62647 **    May you share freely, never taking more than you give.
62648 **
62649 *************************************************************************
62650 ** This file contains the implementation of the sqlite3_prepare()
62651 ** interface, and routines that contribute to loading the database schema
62652 ** from disk.
62653 **
62654 ** $Id: prepare.c,v 1.83 2008/04/03 14:36:26 danielk1977 Exp $
62655 */
62656
62657 /*
62658 ** Fill the InitData structure with an error message that indicates
62659 ** that the database is corrupt.
62660 */
62661 static void corruptSchema(
62662   InitData *pData,     /* Initialization context */
62663   const char *zObj,    /* Object being parsed at the point of error */
62664   const char *zExtra   /* Error information */
62665 ){
62666   if( !pData->db->mallocFailed ){
62667     if( zObj==0 ) zObj = "?";
62668     sqlite3SetString(pData->pzErrMsg, "malformed database schema (",  zObj, ")",
62669        zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
62670   }
62671   pData->rc = SQLITE_CORRUPT;
62672 }
62673
62674 /*
62675 ** This is the callback routine for the code that initializes the
62676 ** database.  See sqlite3Init() below for additional information.
62677 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
62678 **
62679 ** Each callback contains the following information:
62680 **
62681 **     argv[0] = name of thing being created
62682 **     argv[1] = root page number for table or index. 0 for trigger or view.
62683 **     argv[2] = SQL text for the CREATE statement.
62684 **
62685 */
62686 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
62687   InitData *pData = (InitData*)pInit;
62688   sqlite3 *db = pData->db;
62689   int iDb = pData->iDb;
62690
62691   assert( sqlite3_mutex_held(db->mutex) );
62692   pData->rc = SQLITE_OK;
62693   DbClearProperty(db, iDb, DB_Empty);
62694   if( db->mallocFailed ){
62695     corruptSchema(pData, argv[0], 0);
62696     return SQLITE_NOMEM;
62697   }
62698
62699   assert( argc==3 );
62700   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
62701   if( argv[1]==0 ){
62702     corruptSchema(pData, argv[0], 0);
62703     return 1;
62704   }
62705   assert( iDb>=0 && iDb<db->nDb );
62706   if( argv[2] && argv[2][0] ){
62707     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
62708     ** But because db->init.busy is set to 1, no VDBE code is generated
62709     ** or executed.  All the parser does is build the internal data
62710     ** structures that describe the table, index, or view.
62711     */
62712     char *zErr;
62713     int rc;
62714     assert( db->init.busy );
62715     db->init.iDb = iDb;
62716     db->init.newTnum = atoi(argv[1]);
62717     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
62718     db->init.iDb = 0;
62719     assert( rc!=SQLITE_OK || zErr==0 );
62720     if( SQLITE_OK!=rc ){
62721       pData->rc = rc;
62722       if( rc==SQLITE_NOMEM ){
62723         db->mallocFailed = 1;
62724       }else if( rc!=SQLITE_INTERRUPT ){
62725         corruptSchema(pData, argv[0], zErr);
62726       }
62727       sqlite3_free(zErr);
62728       return 1;
62729     }
62730   }else if( argv[0]==0 ){
62731     corruptSchema(pData, 0, 0);
62732   }else{
62733     /* If the SQL column is blank it means this is an index that
62734     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
62735     ** constraint for a CREATE TABLE.  The index should have already
62736     ** been created when we processed the CREATE TABLE.  All we have
62737     ** to do here is record the root page number for that index.
62738     */
62739     Index *pIndex;
62740     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
62741     if( pIndex==0 || pIndex->tnum!=0 ){
62742       /* This can occur if there exists an index on a TEMP table which
62743       ** has the same name as another index on a permanent index.  Since
62744       ** the permanent table is hidden by the TEMP table, we can also
62745       ** safely ignore the index on the permanent table.
62746       */
62747       /* Do Nothing */;
62748     }else{
62749       pIndex->tnum = atoi(argv[1]);
62750     }
62751   }
62752   return 0;
62753 }
62754
62755 /*
62756 ** Attempt to read the database schema and initialize internal
62757 ** data structures for a single database file.  The index of the
62758 ** database file is given by iDb.  iDb==0 is used for the main
62759 ** database.  iDb==1 should never be used.  iDb>=2 is used for
62760 ** auxiliary databases.  Return one of the SQLITE_ error codes to
62761 ** indicate success or failure.
62762 */
62763 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
62764   int rc;
62765   BtCursor *curMain;
62766   int size;
62767   Table *pTab;
62768   Db *pDb;
62769   char const *azArg[4];
62770   int meta[10];
62771   InitData initData;
62772   char const *zMasterSchema;
62773   char const *zMasterName = SCHEMA_TABLE(iDb);
62774
62775   /*
62776   ** The master database table has a structure like this
62777   */
62778   static const char master_schema[] = 
62779      "CREATE TABLE sqlite_master(\n"
62780      "  type text,\n"
62781      "  name text,\n"
62782      "  tbl_name text,\n"
62783      "  rootpage integer,\n"
62784      "  sql text\n"
62785      ")"
62786   ;
62787 #ifndef SQLITE_OMIT_TEMPDB
62788   static const char temp_master_schema[] = 
62789      "CREATE TEMP TABLE sqlite_temp_master(\n"
62790      "  type text,\n"
62791      "  name text,\n"
62792      "  tbl_name text,\n"
62793      "  rootpage integer,\n"
62794      "  sql text\n"
62795      ")"
62796   ;
62797 #else
62798   #define temp_master_schema 0
62799 #endif
62800
62801   assert( iDb>=0 && iDb<db->nDb );
62802   assert( db->aDb[iDb].pSchema );
62803   assert( sqlite3_mutex_held(db->mutex) );
62804   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
62805
62806   /* zMasterSchema and zInitScript are set to point at the master schema
62807   ** and initialisation script appropriate for the database being
62808   ** initialised. zMasterName is the name of the master table.
62809   */
62810   if( !OMIT_TEMPDB && iDb==1 ){
62811     zMasterSchema = temp_master_schema;
62812   }else{
62813     zMasterSchema = master_schema;
62814   }
62815   zMasterName = SCHEMA_TABLE(iDb);
62816
62817   /* Construct the schema tables.  */
62818   azArg[0] = zMasterName;
62819   azArg[1] = "1";
62820   azArg[2] = zMasterSchema;
62821   azArg[3] = 0;
62822   initData.db = db;
62823   initData.iDb = iDb;
62824   initData.pzErrMsg = pzErrMsg;
62825   (void)sqlite3SafetyOff(db);
62826   rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
62827   (void)sqlite3SafetyOn(db);
62828   if( rc ){
62829     rc = initData.rc;
62830     goto error_out;
62831   }
62832   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
62833   if( pTab ){
62834     pTab->readOnly = 1;
62835   }
62836
62837   /* Create a cursor to hold the database open
62838   */
62839   pDb = &db->aDb[iDb];
62840   if( pDb->pBt==0 ){
62841     if( !OMIT_TEMPDB && iDb==1 ){
62842       DbSetProperty(db, 1, DB_SchemaLoaded);
62843     }
62844     return SQLITE_OK;
62845   }
62846   curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
62847   if( !curMain ){
62848     rc = SQLITE_NOMEM;
62849     goto error_out;
62850   }
62851   sqlite3BtreeEnter(pDb->pBt);
62852   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
62853   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
62854     sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
62855     goto leave_error_out;
62856   }
62857
62858   /* Get the database meta information.
62859   **
62860   ** Meta values are as follows:
62861   **    meta[0]   Schema cookie.  Changes with each schema change.
62862   **    meta[1]   File format of schema layer.
62863   **    meta[2]   Size of the page cache.
62864   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
62865   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
62866   **    meta[5]   The user cookie. Used by the application.
62867   **    meta[6]   Incremental-vacuum flag.
62868   **    meta[7]
62869   **    meta[8]
62870   **    meta[9]
62871   **
62872   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
62873   ** the possible values of meta[4].
62874   */
62875   if( rc==SQLITE_OK ){
62876     int i;
62877     for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){
62878       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
62879     }
62880     if( rc ){
62881       sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
62882       goto leave_error_out;
62883     }
62884   }else{
62885     memset(meta, 0, sizeof(meta));
62886   }
62887   pDb->pSchema->schema_cookie = meta[0];
62888
62889   /* If opening a non-empty database, check the text encoding. For the
62890   ** main database, set sqlite3.enc to the encoding of the main database.
62891   ** For an attached db, it is an error if the encoding is not the same
62892   ** as sqlite3.enc.
62893   */
62894   if( meta[4] ){  /* text encoding */
62895     if( iDb==0 ){
62896       /* If opening the main database, set ENC(db). */
62897       ENC(db) = (u8)meta[4];
62898       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
62899     }else{
62900       /* If opening an attached database, the encoding much match ENC(db) */
62901       if( meta[4]!=ENC(db) ){
62902         sqlite3SetString(pzErrMsg, "attached databases must use the same"
62903             " text encoding as main database", (char*)0);
62904         rc = SQLITE_ERROR;
62905         goto leave_error_out;
62906       }
62907     }
62908   }else{
62909     DbSetProperty(db, iDb, DB_Empty);
62910   }
62911   pDb->pSchema->enc = ENC(db);
62912
62913   size = meta[2];
62914   if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
62915   if( size<0 ) size = -size;
62916   pDb->pSchema->cache_size = size;
62917   sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
62918
62919   /*
62920   ** file_format==1    Version 3.0.0.
62921   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
62922   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
62923   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
62924   */
62925   pDb->pSchema->file_format = meta[1];
62926   if( pDb->pSchema->file_format==0 ){
62927     pDb->pSchema->file_format = 1;
62928   }
62929   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
62930     sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);
62931     rc = SQLITE_ERROR;
62932     goto leave_error_out;
62933   }
62934
62935   /* Ticket #2804:  When we open a database in the newer file format,
62936   ** clear the legacy_file_format pragma flag so that a VACUUM will
62937   ** not downgrade the database and thus invalidate any descending
62938   ** indices that the user might have created.
62939   */
62940   if( iDb==0 && meta[1]>=4 ){
62941     db->flags &= ~SQLITE_LegacyFileFmt;
62942   }
62943
62944   /* Read the schema information out of the schema tables
62945   */
62946   assert( db->init.busy );
62947   if( rc==SQLITE_EMPTY ){
62948     /* For an empty database, there is nothing to read */
62949     rc = SQLITE_OK;
62950   }else{
62951     char *zSql;
62952     zSql = sqlite3MPrintf(db, 
62953         "SELECT name, rootpage, sql FROM '%q'.%s",
62954         db->aDb[iDb].zName, zMasterName);
62955     (void)sqlite3SafetyOff(db);
62956 #ifndef SQLITE_OMIT_AUTHORIZATION
62957     {
62958       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
62959       xAuth = db->xAuth;
62960       db->xAuth = 0;
62961 #endif
62962       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
62963 #ifndef SQLITE_OMIT_AUTHORIZATION
62964       db->xAuth = xAuth;
62965     }
62966 #endif
62967     if( rc==SQLITE_ABORT ) rc = initData.rc;
62968     (void)sqlite3SafetyOn(db);
62969     sqlite3_free(zSql);
62970 #ifndef SQLITE_OMIT_ANALYZE
62971     if( rc==SQLITE_OK ){
62972       sqlite3AnalysisLoad(db, iDb);
62973     }
62974 #endif
62975   }
62976   if( db->mallocFailed ){
62977     /* sqlite3SetString(pzErrMsg, "out of memory", (char*)0); */
62978     rc = SQLITE_NOMEM;
62979     sqlite3ResetInternalSchema(db, 0);
62980   }
62981   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
62982     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
62983     ** the schema loaded, even if errors occured. In this situation the 
62984     ** current sqlite3_prepare() operation will fail, but the following one
62985     ** will attempt to compile the supplied statement against whatever subset
62986     ** of the schema was loaded before the error occured. The primary
62987     ** purpose of this is to allow access to the sqlite_master table
62988     ** even when its contents have been corrupted.
62989     */
62990     DbSetProperty(db, iDb, DB_SchemaLoaded);
62991     rc = SQLITE_OK;
62992   }
62993
62994   /* Jump here for an error that occurs after successfully allocating
62995   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
62996   ** before that point, jump to error_out.
62997   */
62998 leave_error_out:
62999   sqlite3BtreeCloseCursor(curMain);
63000   sqlite3_free(curMain);
63001   sqlite3BtreeLeave(pDb->pBt);
63002
63003 error_out:
63004   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
63005     db->mallocFailed = 1;
63006   }
63007   return rc;
63008 }
63009
63010 /*
63011 ** Initialize all database files - the main database file, the file
63012 ** used to store temporary tables, and any additional database files
63013 ** created using ATTACH statements.  Return a success code.  If an
63014 ** error occurs, write an error message into *pzErrMsg.
63015 **
63016 ** After a database is initialized, the DB_SchemaLoaded bit is set
63017 ** bit is set in the flags field of the Db structure. If the database
63018 ** file was of zero-length, then the DB_Empty flag is also set.
63019 */
63020 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
63021   int i, rc;
63022   int commit_internal = !(db->flags&SQLITE_InternChanges);
63023   
63024   assert( sqlite3_mutex_held(db->mutex) );
63025   if( db->init.busy ) return SQLITE_OK;
63026   rc = SQLITE_OK;
63027   db->init.busy = 1;
63028   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63029     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
63030     rc = sqlite3InitOne(db, i, pzErrMsg);
63031     if( rc ){
63032       sqlite3ResetInternalSchema(db, i);
63033     }
63034   }
63035
63036   /* Once all the other databases have been initialised, load the schema
63037   ** for the TEMP database. This is loaded last, as the TEMP database
63038   ** schema may contain references to objects in other databases.
63039   */
63040 #ifndef SQLITE_OMIT_TEMPDB
63041   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
63042     rc = sqlite3InitOne(db, 1, pzErrMsg);
63043     if( rc ){
63044       sqlite3ResetInternalSchema(db, 1);
63045     }
63046   }
63047 #endif
63048
63049   db->init.busy = 0;
63050   if( rc==SQLITE_OK && commit_internal ){
63051     sqlite3CommitInternalChanges(db);
63052   }
63053
63054   return rc; 
63055 }
63056
63057 /*
63058 ** This routine is a no-op if the database schema is already initialised.
63059 ** Otherwise, the schema is loaded. An error code is returned.
63060 */
63061 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
63062   int rc = SQLITE_OK;
63063   sqlite3 *db = pParse->db;
63064   assert( sqlite3_mutex_held(db->mutex) );
63065   if( !db->init.busy ){
63066     rc = sqlite3Init(db, &pParse->zErrMsg);
63067   }
63068   if( rc!=SQLITE_OK ){
63069     pParse->rc = rc;
63070     pParse->nErr++;
63071   }
63072   return rc;
63073 }
63074
63075
63076 /*
63077 ** Check schema cookies in all databases.  If any cookie is out
63078 ** of date, return 0.  If all schema cookies are current, return 1.
63079 */
63080 static int schemaIsValid(sqlite3 *db){
63081   int iDb;
63082   int rc;
63083   BtCursor *curTemp;
63084   int cookie;
63085   int allOk = 1;
63086
63087   curTemp = (BtCursor *)sqlite3_malloc(sqlite3BtreeCursorSize());
63088   if( curTemp ){
63089     assert( sqlite3_mutex_held(db->mutex) );
63090     for(iDb=0; allOk && iDb<db->nDb; iDb++){
63091       Btree *pBt;
63092       pBt = db->aDb[iDb].pBt;
63093       if( pBt==0 ) continue;
63094       memset(curTemp, 0, sqlite3BtreeCursorSize());
63095       rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
63096       if( rc==SQLITE_OK ){
63097         rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
63098         if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
63099           allOk = 0;
63100         }
63101         sqlite3BtreeCloseCursor(curTemp);
63102       }
63103       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
63104         db->mallocFailed = 1;
63105       }
63106     }
63107     sqlite3_free(curTemp);
63108   }else{
63109     allOk = 0;
63110     db->mallocFailed = 1;
63111   }
63112
63113   return allOk;
63114 }
63115
63116 /*
63117 ** Convert a schema pointer into the iDb index that indicates
63118 ** which database file in db->aDb[] the schema refers to.
63119 **
63120 ** If the same database is attached more than once, the first
63121 ** attached database is returned.
63122 */
63123 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
63124   int i = -1000000;
63125
63126   /* If pSchema is NULL, then return -1000000. This happens when code in 
63127   ** expr.c is trying to resolve a reference to a transient table (i.e. one
63128   ** created by a sub-select). In this case the return value of this 
63129   ** function should never be used.
63130   **
63131   ** We return -1000000 instead of the more usual -1 simply because using
63132   ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much 
63133   ** more likely to cause a segfault than -1 (of course there are assert()
63134   ** statements too, but it never hurts to play the odds).
63135   */
63136   assert( sqlite3_mutex_held(db->mutex) );
63137   if( pSchema ){
63138     for(i=0; i<db->nDb; i++){
63139       if( db->aDb[i].pSchema==pSchema ){
63140         break;
63141       }
63142     }
63143     assert( i>=0 &&i>=0 &&  i<db->nDb );
63144   }
63145   return i;
63146 }
63147
63148 /*
63149 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
63150 */
63151 static int sqlite3Prepare(
63152   sqlite3 *db,              /* Database handle. */
63153   const char *zSql,         /* UTF-8 encoded SQL statement. */
63154   int nBytes,               /* Length of zSql in bytes. */
63155   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
63156   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
63157   const char **pzTail       /* OUT: End of parsed string */
63158 ){
63159   Parse sParse;
63160   char *zErrMsg = 0;
63161   int rc = SQLITE_OK;
63162   int i;
63163
63164   assert( ppStmt );
63165   *ppStmt = 0;
63166   if( sqlite3SafetyOn(db) ){
63167     return SQLITE_MISUSE;
63168   }
63169   assert( !db->mallocFailed );
63170   assert( sqlite3_mutex_held(db->mutex) );
63171
63172   /* If any attached database schemas are locked, do not proceed with
63173   ** compilation. Instead return SQLITE_LOCKED immediately.
63174   */
63175   for(i=0; i<db->nDb; i++) {
63176     Btree *pBt = db->aDb[i].pBt;
63177     if( pBt ){
63178       int rc;
63179       rc = sqlite3BtreeSchemaLocked(pBt);
63180       if( rc ){
63181         const char *zDb = db->aDb[i].zName;
63182         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
63183         (void)sqlite3SafetyOff(db);
63184         return SQLITE_LOCKED;
63185       }
63186     }
63187   }
63188   
63189   memset(&sParse, 0, sizeof(sParse));
63190   sParse.db = db;
63191   if( nBytes>=0 && zSql[nBytes-1]!=0 ){
63192     char *zSqlCopy;
63193     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
63194     if( nBytes>mxLen ){
63195       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
63196       (void)sqlite3SafetyOff(db);
63197       return SQLITE_TOOBIG;
63198     }
63199     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
63200     if( zSqlCopy ){
63201       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
63202       sqlite3_free(zSqlCopy);
63203       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
63204     }else{
63205       sParse.zTail = &zSql[nBytes];
63206     }
63207   }else{
63208     sqlite3RunParser(&sParse, zSql, &zErrMsg);
63209   }
63210
63211   if( db->mallocFailed ){
63212     sParse.rc = SQLITE_NOMEM;
63213   }
63214   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
63215   if( sParse.checkSchema && !schemaIsValid(db) ){
63216     sParse.rc = SQLITE_SCHEMA;
63217   }
63218   if( sParse.rc==SQLITE_SCHEMA ){
63219     sqlite3ResetInternalSchema(db, 0);
63220   }
63221   if( db->mallocFailed ){
63222     sParse.rc = SQLITE_NOMEM;
63223   }
63224   if( pzTail ){
63225     *pzTail = sParse.zTail;
63226   }
63227   rc = sParse.rc;
63228
63229 #ifndef SQLITE_OMIT_EXPLAIN
63230   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
63231     if( sParse.explain==2 ){
63232       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
63233       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P4_STATIC);
63234       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P4_STATIC);
63235       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P4_STATIC);
63236     }else{
63237       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
63238       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P4_STATIC);
63239       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P4_STATIC);
63240       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P4_STATIC);
63241       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P4_STATIC);
63242       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P4_STATIC);
63243       sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", P4_STATIC);
63244       sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", P4_STATIC);
63245       sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment",P4_STATIC);
63246     }
63247   }
63248 #endif
63249
63250   if( sqlite3SafetyOff(db) ){
63251     rc = SQLITE_MISUSE;
63252   }
63253
63254   if( saveSqlFlag ){
63255     sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
63256   }
63257   if( rc!=SQLITE_OK || db->mallocFailed ){
63258     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
63259     assert(!(*ppStmt));
63260   }else{
63261     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
63262   }
63263
63264   if( zErrMsg ){
63265     sqlite3Error(db, rc, "%s", zErrMsg);
63266     sqlite3_free(zErrMsg);
63267   }else{
63268     sqlite3Error(db, rc, 0);
63269   }
63270
63271   rc = sqlite3ApiExit(db, rc);
63272   assert( (rc&db->errMask)==rc );
63273   return rc;
63274 }
63275 static int sqlite3LockAndPrepare(
63276   sqlite3 *db,              /* Database handle. */
63277   const char *zSql,         /* UTF-8 encoded SQL statement. */
63278   int nBytes,               /* Length of zSql in bytes. */
63279   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
63280   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
63281   const char **pzTail       /* OUT: End of parsed string */
63282 ){
63283   int rc;
63284   if( !sqlite3SafetyCheckOk(db) ){
63285     return SQLITE_MISUSE;
63286   }
63287   sqlite3_mutex_enter(db->mutex);
63288   sqlite3BtreeEnterAll(db);
63289   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
63290   sqlite3BtreeLeaveAll(db);
63291   sqlite3_mutex_leave(db->mutex);
63292   return rc;
63293 }
63294
63295 /*
63296 ** Rerun the compilation of a statement after a schema change.
63297 ** Return true if the statement was recompiled successfully.
63298 ** Return false if there is an error of some kind.
63299 */
63300 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
63301   int rc;
63302   sqlite3_stmt *pNew;
63303   const char *zSql;
63304   sqlite3 *db;
63305
63306   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
63307   zSql = sqlite3_sql((sqlite3_stmt *)p);
63308   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
63309   db = sqlite3VdbeDb(p);
63310   assert( sqlite3_mutex_held(db->mutex) );
63311   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
63312   if( rc ){
63313     if( rc==SQLITE_NOMEM ){
63314       db->mallocFailed = 1;
63315     }
63316     assert( pNew==0 );
63317     return 0;
63318   }else{
63319     assert( pNew!=0 );
63320   }
63321   sqlite3VdbeSwap((Vdbe*)pNew, p);
63322   sqlite3_transfer_bindings(pNew, (sqlite3_stmt*)p);
63323   sqlite3VdbeResetStepResult((Vdbe*)pNew);
63324   sqlite3VdbeFinalize((Vdbe*)pNew);
63325   return 1;
63326 }
63327
63328
63329 /*
63330 ** Two versions of the official API.  Legacy and new use.  In the legacy
63331 ** version, the original SQL text is not saved in the prepared statement
63332 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
63333 ** sqlite3_step().  In the new version, the original SQL text is retained
63334 ** and the statement is automatically recompiled if an schema change
63335 ** occurs.
63336 */
63337 SQLITE_API int sqlite3_prepare(
63338   sqlite3 *db,              /* Database handle. */
63339   const char *zSql,         /* UTF-8 encoded SQL statement. */
63340   int nBytes,               /* Length of zSql in bytes. */
63341   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
63342   const char **pzTail       /* OUT: End of parsed string */
63343 ){
63344   int rc;
63345   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
63346   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
63347   return rc;
63348 }
63349 SQLITE_API int sqlite3_prepare_v2(
63350   sqlite3 *db,              /* Database handle. */
63351   const char *zSql,         /* UTF-8 encoded SQL statement. */
63352   int nBytes,               /* Length of zSql in bytes. */
63353   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
63354   const char **pzTail       /* OUT: End of parsed string */
63355 ){
63356   int rc;
63357   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
63358   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
63359   return rc;
63360 }
63361
63362
63363 #ifndef SQLITE_OMIT_UTF16
63364 /*
63365 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
63366 */
63367 static int sqlite3Prepare16(
63368   sqlite3 *db,              /* Database handle. */ 
63369   const void *zSql,         /* UTF-8 encoded SQL statement. */
63370   int nBytes,               /* Length of zSql in bytes. */
63371   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
63372   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
63373   const void **pzTail       /* OUT: End of parsed string */
63374 ){
63375   /* This function currently works by first transforming the UTF-16
63376   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
63377   ** tricky bit is figuring out the pointer to return in *pzTail.
63378   */
63379   char *zSql8;
63380   const char *zTail8 = 0;
63381   int rc = SQLITE_OK;
63382
63383   if( !sqlite3SafetyCheckOk(db) ){
63384     return SQLITE_MISUSE;
63385   }
63386   sqlite3_mutex_enter(db->mutex);
63387   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
63388   if( zSql8 ){
63389     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
63390   }
63391
63392   if( zTail8 && pzTail ){
63393     /* If sqlite3_prepare returns a tail pointer, we calculate the
63394     ** equivalent pointer into the UTF-16 string by counting the unicode
63395     ** characters between zSql8 and zTail8, and then returning a pointer
63396     ** the same number of characters into the UTF-16 string.
63397     */
63398     int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
63399     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
63400   }
63401   sqlite3_free(zSql8); 
63402   rc = sqlite3ApiExit(db, rc);
63403   sqlite3_mutex_leave(db->mutex);
63404   return rc;
63405 }
63406
63407 /*
63408 ** Two versions of the official API.  Legacy and new use.  In the legacy
63409 ** version, the original SQL text is not saved in the prepared statement
63410 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
63411 ** sqlite3_step().  In the new version, the original SQL text is retained
63412 ** and the statement is automatically recompiled if an schema change
63413 ** occurs.
63414 */
63415 SQLITE_API int sqlite3_prepare16(
63416   sqlite3 *db,              /* Database handle. */ 
63417   const void *zSql,         /* UTF-8 encoded SQL statement. */
63418   int nBytes,               /* Length of zSql in bytes. */
63419   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
63420   const void **pzTail       /* OUT: End of parsed string */
63421 ){
63422   int rc;
63423   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
63424   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
63425   return rc;
63426 }
63427 SQLITE_API int sqlite3_prepare16_v2(
63428   sqlite3 *db,              /* Database handle. */ 
63429   const void *zSql,         /* UTF-8 encoded SQL statement. */
63430   int nBytes,               /* Length of zSql in bytes. */
63431   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
63432   const void **pzTail       /* OUT: End of parsed string */
63433 ){
63434   int rc;
63435   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
63436   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
63437   return rc;
63438 }
63439
63440 #endif /* SQLITE_OMIT_UTF16 */
63441
63442 /************** End of prepare.c *********************************************/
63443 /************** Begin file select.c ******************************************/
63444 /*
63445 ** 2001 September 15
63446 **
63447 ** The author disclaims copyright to this source code.  In place of
63448 ** a legal notice, here is a blessing:
63449 **
63450 **    May you do good and not evil.
63451 **    May you find forgiveness for yourself and forgive others.
63452 **    May you share freely, never taking more than you give.
63453 **
63454 *************************************************************************
63455 ** This file contains C code routines that are called by the parser
63456 ** to handle SELECT statements in SQLite.
63457 **
63458 ** $Id: select.c,v 1.429 2008/05/01 17:03:49 drh Exp $
63459 */
63460
63461
63462 /*
63463 ** Delete all the content of a Select structure but do not deallocate
63464 ** the select structure itself.
63465 */
63466 static void clearSelect(Select *p){
63467   sqlite3ExprListDelete(p->pEList);
63468   sqlite3SrcListDelete(p->pSrc);
63469   sqlite3ExprDelete(p->pWhere);
63470   sqlite3ExprListDelete(p->pGroupBy);
63471   sqlite3ExprDelete(p->pHaving);
63472   sqlite3ExprListDelete(p->pOrderBy);
63473   sqlite3SelectDelete(p->pPrior);
63474   sqlite3ExprDelete(p->pLimit);
63475   sqlite3ExprDelete(p->pOffset);
63476 }
63477
63478 /*
63479 ** Initialize a SelectDest structure.
63480 */
63481 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
63482   pDest->eDest = eDest;
63483   pDest->iParm = iParm;
63484   pDest->affinity = 0;
63485   pDest->iMem = 0;
63486   pDest->nMem = 0;
63487 }
63488
63489
63490 /*
63491 ** Allocate a new Select structure and return a pointer to that
63492 ** structure.
63493 */
63494 SQLITE_PRIVATE Select *sqlite3SelectNew(
63495   Parse *pParse,        /* Parsing context */
63496   ExprList *pEList,     /* which columns to include in the result */
63497   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
63498   Expr *pWhere,         /* the WHERE clause */
63499   ExprList *pGroupBy,   /* the GROUP BY clause */
63500   Expr *pHaving,        /* the HAVING clause */
63501   ExprList *pOrderBy,   /* the ORDER BY clause */
63502   int isDistinct,       /* true if the DISTINCT keyword is present */
63503   Expr *pLimit,         /* LIMIT value.  NULL means not used */
63504   Expr *pOffset         /* OFFSET value.  NULL means no offset */
63505 ){
63506   Select *pNew;
63507   Select standin;
63508   sqlite3 *db = pParse->db;
63509   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
63510   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
63511   if( pNew==0 ){
63512     pNew = &standin;
63513     memset(pNew, 0, sizeof(*pNew));
63514   }
63515   if( pEList==0 ){
63516     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
63517   }
63518   pNew->pEList = pEList;
63519   pNew->pSrc = pSrc;
63520   pNew->pWhere = pWhere;
63521   pNew->pGroupBy = pGroupBy;
63522   pNew->pHaving = pHaving;
63523   pNew->pOrderBy = pOrderBy;
63524   pNew->isDistinct = isDistinct;
63525   pNew->op = TK_SELECT;
63526   assert( pOffset==0 || pLimit!=0 );
63527   pNew->pLimit = pLimit;
63528   pNew->pOffset = pOffset;
63529   pNew->iLimit = -1;
63530   pNew->iOffset = -1;
63531   pNew->addrOpenEphm[0] = -1;
63532   pNew->addrOpenEphm[1] = -1;
63533   pNew->addrOpenEphm[2] = -1;
63534   if( pNew==&standin) {
63535     clearSelect(pNew);
63536     pNew = 0;
63537   }
63538   return pNew;
63539 }
63540
63541 /*
63542 ** Delete the given Select structure and all of its substructures.
63543 */
63544 SQLITE_PRIVATE void sqlite3SelectDelete(Select *p){
63545   if( p ){
63546     clearSelect(p);
63547     sqlite3_free(p);
63548   }
63549 }
63550
63551 /*
63552 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
63553 ** type of join.  Return an integer constant that expresses that type
63554 ** in terms of the following bit values:
63555 **
63556 **     JT_INNER
63557 **     JT_CROSS
63558 **     JT_OUTER
63559 **     JT_NATURAL
63560 **     JT_LEFT
63561 **     JT_RIGHT
63562 **
63563 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
63564 **
63565 ** If an illegal or unsupported join type is seen, then still return
63566 ** a join type, but put an error in the pParse structure.
63567 */
63568 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
63569   int jointype = 0;
63570   Token *apAll[3];
63571   Token *p;
63572   static const struct {
63573     const char zKeyword[8];
63574     u8 nChar;
63575     u8 code;
63576   } keywords[] = {
63577     { "natural", 7, JT_NATURAL },
63578     { "left",    4, JT_LEFT|JT_OUTER },
63579     { "right",   5, JT_RIGHT|JT_OUTER },
63580     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
63581     { "outer",   5, JT_OUTER },
63582     { "inner",   5, JT_INNER },
63583     { "cross",   5, JT_INNER|JT_CROSS },
63584   };
63585   int i, j;
63586   apAll[0] = pA;
63587   apAll[1] = pB;
63588   apAll[2] = pC;
63589   for(i=0; i<3 && apAll[i]; i++){
63590     p = apAll[i];
63591     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
63592       if( p->n==keywords[j].nChar 
63593           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
63594         jointype |= keywords[j].code;
63595         break;
63596       }
63597     }
63598     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
63599       jointype |= JT_ERROR;
63600       break;
63601     }
63602   }
63603   if(
63604      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
63605      (jointype & JT_ERROR)!=0
63606   ){
63607     const char *zSp1 = " ";
63608     const char *zSp2 = " ";
63609     if( pB==0 ){ zSp1++; }
63610     if( pC==0 ){ zSp2++; }
63611     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
63612        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
63613     jointype = JT_INNER;
63614   }else if( jointype & JT_RIGHT ){
63615     sqlite3ErrorMsg(pParse, 
63616       "RIGHT and FULL OUTER JOINs are not currently supported");
63617     jointype = JT_INNER;
63618   }
63619   return jointype;
63620 }
63621
63622 /*
63623 ** Return the index of a column in a table.  Return -1 if the column
63624 ** is not contained in the table.
63625 */
63626 static int columnIndex(Table *pTab, const char *zCol){
63627   int i;
63628   for(i=0; i<pTab->nCol; i++){
63629     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
63630   }
63631   return -1;
63632 }
63633
63634 /*
63635 ** Set the value of a token to a '\000'-terminated string.
63636 */
63637 static void setToken(Token *p, const char *z){
63638   p->z = (u8*)z;
63639   p->n = z ? strlen(z) : 0;
63640   p->dyn = 0;
63641 }
63642
63643 /*
63644 ** Set the token to the double-quoted and escaped version of the string pointed
63645 ** to by z. For example;
63646 **
63647 **    {a"bc}  ->  {"a""bc"}
63648 */
63649 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
63650
63651   /* Check if the string contains any " characters. If it does, then
63652   ** this function will malloc space to create a quoted version of
63653   ** the string in. Otherwise, save a call to sqlite3MPrintf() by
63654   ** just copying the pointer to the string.
63655   */
63656   const char *z2 = z;
63657   while( *z2 ){
63658     if( *z2=='"' ) break;
63659     z2++;
63660   }
63661
63662   if( *z2 ){
63663     /* String contains " characters - copy and quote the string. */
63664     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
63665     if( p->z ){
63666       p->n = strlen((char *)p->z);
63667       p->dyn = 1;
63668     }
63669   }else{
63670     /* String contains no " characters - copy the pointer. */
63671     p->z = (u8*)z;
63672     p->n = (z2 - z);
63673     p->dyn = 0;
63674   }
63675 }
63676
63677 /*
63678 ** Create an expression node for an identifier with the name of zName
63679 */
63680 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
63681   Token dummy;
63682   setToken(&dummy, zName);
63683   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
63684 }
63685
63686 /*
63687 ** Add a term to the WHERE expression in *ppExpr that requires the
63688 ** zCol column to be equal in the two tables pTab1 and pTab2.
63689 */
63690 static void addWhereTerm(
63691   Parse *pParse,           /* Parsing context */
63692   const char *zCol,        /* Name of the column */
63693   const Table *pTab1,      /* First table */
63694   const char *zAlias1,     /* Alias for first table.  May be NULL */
63695   const Table *pTab2,      /* Second table */
63696   const char *zAlias2,     /* Alias for second table.  May be NULL */
63697   int iRightJoinTable,     /* VDBE cursor for the right table */
63698   Expr **ppExpr,           /* Add the equality term to this expression */
63699   int isOuterJoin          /* True if dealing with an OUTER join */
63700 ){
63701   Expr *pE1a, *pE1b, *pE1c;
63702   Expr *pE2a, *pE2b, *pE2c;
63703   Expr *pE;
63704
63705   pE1a = sqlite3CreateIdExpr(pParse, zCol);
63706   pE2a = sqlite3CreateIdExpr(pParse, zCol);
63707   if( zAlias1==0 ){
63708     zAlias1 = pTab1->zName;
63709   }
63710   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
63711   if( zAlias2==0 ){
63712     zAlias2 = pTab2->zName;
63713   }
63714   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
63715   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
63716   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
63717   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
63718   if( pE && isOuterJoin ){
63719     ExprSetProperty(pE, EP_FromJoin);
63720     pE->iRightJoinTable = iRightJoinTable;
63721   }
63722   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
63723 }
63724
63725 /*
63726 ** Set the EP_FromJoin property on all terms of the given expression.
63727 ** And set the Expr.iRightJoinTable to iTable for every term in the
63728 ** expression.
63729 **
63730 ** The EP_FromJoin property is used on terms of an expression to tell
63731 ** the LEFT OUTER JOIN processing logic that this term is part of the
63732 ** join restriction specified in the ON or USING clause and not a part
63733 ** of the more general WHERE clause.  These terms are moved over to the
63734 ** WHERE clause during join processing but we need to remember that they
63735 ** originated in the ON or USING clause.
63736 **
63737 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
63738 ** expression depends on table iRightJoinTable even if that table is not
63739 ** explicitly mentioned in the expression.  That information is needed
63740 ** for cases like this:
63741 **
63742 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
63743 **
63744 ** The where clause needs to defer the handling of the t1.x=5
63745 ** term until after the t2 loop of the join.  In that way, a
63746 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
63747 ** defer the handling of t1.x=5, it will be processed immediately
63748 ** after the t1 loop and rows with t1.x!=5 will never appear in
63749 ** the output, which is incorrect.
63750 */
63751 static void setJoinExpr(Expr *p, int iTable){
63752   while( p ){
63753     ExprSetProperty(p, EP_FromJoin);
63754     p->iRightJoinTable = iTable;
63755     setJoinExpr(p->pLeft, iTable);
63756     p = p->pRight;
63757   } 
63758 }
63759
63760 /*
63761 ** This routine processes the join information for a SELECT statement.
63762 ** ON and USING clauses are converted into extra terms of the WHERE clause.
63763 ** NATURAL joins also create extra WHERE clause terms.
63764 **
63765 ** The terms of a FROM clause are contained in the Select.pSrc structure.
63766 ** The left most table is the first entry in Select.pSrc.  The right-most
63767 ** table is the last entry.  The join operator is held in the entry to
63768 ** the left.  Thus entry 0 contains the join operator for the join between
63769 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
63770 ** also attached to the left entry.
63771 **
63772 ** This routine returns the number of errors encountered.
63773 */
63774 static int sqliteProcessJoin(Parse *pParse, Select *p){
63775   SrcList *pSrc;                  /* All tables in the FROM clause */
63776   int i, j;                       /* Loop counters */
63777   struct SrcList_item *pLeft;     /* Left table being joined */
63778   struct SrcList_item *pRight;    /* Right table being joined */
63779
63780   pSrc = p->pSrc;
63781   pLeft = &pSrc->a[0];
63782   pRight = &pLeft[1];
63783   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
63784     Table *pLeftTab = pLeft->pTab;
63785     Table *pRightTab = pRight->pTab;
63786     int isOuter;
63787
63788     if( pLeftTab==0 || pRightTab==0 ) continue;
63789     isOuter = (pRight->jointype & JT_OUTER)!=0;
63790
63791     /* When the NATURAL keyword is present, add WHERE clause terms for
63792     ** every column that the two tables have in common.
63793     */
63794     if( pRight->jointype & JT_NATURAL ){
63795       if( pRight->pOn || pRight->pUsing ){
63796         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
63797            "an ON or USING clause", 0);
63798         return 1;
63799       }
63800       for(j=0; j<pLeftTab->nCol; j++){
63801         char *zName = pLeftTab->aCol[j].zName;
63802         if( columnIndex(pRightTab, zName)>=0 ){
63803           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
63804                               pRightTab, pRight->zAlias,
63805                               pRight->iCursor, &p->pWhere, isOuter);
63806           
63807         }
63808       }
63809     }
63810
63811     /* Disallow both ON and USING clauses in the same join
63812     */
63813     if( pRight->pOn && pRight->pUsing ){
63814       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
63815         "clauses in the same join");
63816       return 1;
63817     }
63818
63819     /* Add the ON clause to the end of the WHERE clause, connected by
63820     ** an AND operator.
63821     */
63822     if( pRight->pOn ){
63823       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
63824       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
63825       pRight->pOn = 0;
63826     }
63827
63828     /* Create extra terms on the WHERE clause for each column named
63829     ** in the USING clause.  Example: If the two tables to be joined are 
63830     ** A and B and the USING clause names X, Y, and Z, then add this
63831     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
63832     ** Report an error if any column mentioned in the USING clause is
63833     ** not contained in both tables to be joined.
63834     */
63835     if( pRight->pUsing ){
63836       IdList *pList = pRight->pUsing;
63837       for(j=0; j<pList->nId; j++){
63838         char *zName = pList->a[j].zName;
63839         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
63840           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
63841             "not present in both tables", zName);
63842           return 1;
63843         }
63844         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
63845                             pRightTab, pRight->zAlias,
63846                             pRight->iCursor, &p->pWhere, isOuter);
63847       }
63848     }
63849   }
63850   return 0;
63851 }
63852
63853 /*
63854 ** Insert code into "v" that will push the record on the top of the
63855 ** stack into the sorter.
63856 */
63857 static void pushOntoSorter(
63858   Parse *pParse,         /* Parser context */
63859   ExprList *pOrderBy,    /* The ORDER BY clause */
63860   Select *pSelect,       /* The whole SELECT statement */
63861   int regData            /* Register holding data to be sorted */
63862 ){
63863   Vdbe *v = pParse->pVdbe;
63864   int nExpr = pOrderBy->nExpr;
63865   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
63866   int regRecord = sqlite3GetTempReg(pParse);
63867   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
63868   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
63869   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1);
63870   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
63871   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
63872   sqlite3ReleaseTempReg(pParse, regRecord);
63873   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
63874   if( pSelect->iLimit>=0 ){
63875     int addr1, addr2;
63876     int iLimit;
63877     if( pSelect->pOffset ){
63878       iLimit = pSelect->iOffset+1;
63879     }else{
63880       iLimit = pSelect->iLimit;
63881     }
63882     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
63883     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
63884     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
63885     sqlite3VdbeJumpHere(v, addr1);
63886     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
63887     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
63888     sqlite3VdbeJumpHere(v, addr2);
63889     pSelect->iLimit = -1;
63890   }
63891 }
63892
63893 /*
63894 ** Add code to implement the OFFSET
63895 */
63896 static void codeOffset(
63897   Vdbe *v,          /* Generate code into this VM */
63898   Select *p,        /* The SELECT statement being coded */
63899   int iContinue     /* Jump here to skip the current record */
63900 ){
63901   if( p->iOffset>=0 && iContinue!=0 ){
63902     int addr;
63903     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
63904     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
63905     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
63906     VdbeComment((v, "skip OFFSET records"));
63907     sqlite3VdbeJumpHere(v, addr);
63908   }
63909 }
63910
63911 /*
63912 ** Add code that will check to make sure the N registers starting at iMem
63913 ** form a distinct entry.  iTab is a sorting index that holds previously
63914 ** seen combinations of the N values.  A new entry is made in iTab
63915 ** if the current N values are new.
63916 **
63917 ** A jump to addrRepeat is made and the N+1 values are popped from the
63918 ** stack if the top N elements are not distinct.
63919 */
63920 static void codeDistinct(
63921   Parse *pParse,     /* Parsing and code generating context */
63922   int iTab,          /* A sorting index used to test for distinctness */
63923   int addrRepeat,    /* Jump to here if not distinct */
63924   int N,             /* Number of elements */
63925   int iMem           /* First element */
63926 ){
63927   Vdbe *v;
63928   int r1;
63929
63930   v = pParse->pVdbe;
63931   r1 = sqlite3GetTempReg(pParse);
63932   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
63933   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
63934   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
63935   sqlite3ReleaseTempReg(pParse, r1);
63936 }
63937
63938 /*
63939 ** Generate an error message when a SELECT is used within a subexpression
63940 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
63941 ** column.  We do this in a subroutine because the error occurs in multiple
63942 ** places.
63943 */
63944 static int checkForMultiColumnSelectError(
63945   Parse *pParse,       /* Parse context. */
63946   SelectDest *pDest,   /* Destination of SELECT results */
63947   int nExpr            /* Number of result columns returned by SELECT */
63948 ){
63949   int eDest = pDest->eDest;
63950   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
63951     sqlite3ErrorMsg(pParse, "only a single result allowed for "
63952        "a SELECT that is part of an expression");
63953     return 1;
63954   }else{
63955     return 0;
63956   }
63957 }
63958
63959 /*
63960 ** This routine generates the code for the inside of the inner loop
63961 ** of a SELECT.
63962 **
63963 ** If srcTab and nColumn are both zero, then the pEList expressions
63964 ** are evaluated in order to get the data for this row.  If nColumn>0
63965 ** then data is pulled from srcTab and pEList is used only to get the
63966 ** datatypes for each column.
63967 */
63968 static void selectInnerLoop(
63969   Parse *pParse,          /* The parser context */
63970   Select *p,              /* The complete select statement being coded */
63971   ExprList *pEList,       /* List of values being extracted */
63972   int srcTab,             /* Pull data from this table */
63973   int nColumn,            /* Number of columns in the source table */
63974   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
63975   int distinct,           /* If >=0, make sure results are distinct */
63976   SelectDest *pDest,      /* How to dispose of the results */
63977   int iContinue,          /* Jump here to continue with next row */
63978   int iBreak,             /* Jump here to break out of the inner loop */
63979   char *aff               /* affinity string if eDest is SRT_Union */
63980 ){
63981   Vdbe *v = pParse->pVdbe;
63982   int i;
63983   int hasDistinct;        /* True if the DISTINCT keyword is present */
63984   int regResult;              /* Start of memory holding result set */
63985   int eDest = pDest->eDest;   /* How to dispose of results */
63986   int iParm = pDest->iParm;   /* First argument to disposal method */
63987   int nResultCol;             /* Number of result columns */
63988
63989   if( v==0 ) return;
63990   assert( pEList!=0 );
63991
63992   /* If there was a LIMIT clause on the SELECT statement, then do the check
63993   ** to see if this row should be output.
63994   */
63995   hasDistinct = distinct>=0 && pEList->nExpr>0;
63996   if( pOrderBy==0 && !hasDistinct ){
63997     codeOffset(v, p, iContinue);
63998   }
63999
64000   /* Pull the requested columns.
64001   */
64002   if( nColumn>0 ){
64003     nResultCol = nColumn;
64004   }else{
64005     nResultCol = pEList->nExpr;
64006   }
64007   if( pDest->iMem==0 ){
64008     pDest->iMem = sqlite3GetTempRange(pParse, nResultCol);
64009     pDest->nMem = nResultCol;
64010   }else if( pDest->nMem!=nResultCol ){
64011     /* This happens when two SELECTs of a compound SELECT have differing
64012     ** numbers of result columns.  The error message will be generated by
64013     ** a higher-level routine. */
64014     return;
64015   }
64016   regResult = pDest->iMem;
64017   if( nColumn>0 ){
64018     for(i=0; i<nColumn; i++){
64019       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
64020     }
64021   }else if( eDest!=SRT_Exists ){
64022     /* If the destination is an EXISTS(...) expression, the actual
64023     ** values returned by the SELECT are not required.
64024     */
64025     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Callback);
64026   }
64027   nColumn = nResultCol;
64028
64029   /* If the DISTINCT keyword was present on the SELECT statement
64030   ** and this row has been seen before, then do not make this row
64031   ** part of the result.
64032   */
64033   if( hasDistinct ){
64034     assert( pEList!=0 );
64035     assert( pEList->nExpr==nColumn );
64036     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
64037     if( pOrderBy==0 ){
64038       codeOffset(v, p, iContinue);
64039     }
64040   }
64041
64042   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
64043     return;
64044   }
64045
64046   switch( eDest ){
64047     /* In this mode, write each query result to the key of the temporary
64048     ** table iParm.
64049     */
64050 #ifndef SQLITE_OMIT_COMPOUND_SELECT
64051     case SRT_Union: {
64052       int r1;
64053       r1 = sqlite3GetTempReg(pParse);
64054       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
64055       if( aff ){
64056         sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC);
64057       }
64058       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
64059       sqlite3ReleaseTempReg(pParse, r1);
64060       break;
64061     }
64062
64063     /* Construct a record from the query result, but instead of
64064     ** saving that record, use it as a key to delete elements from
64065     ** the temporary table iParm.
64066     */
64067     case SRT_Except: {
64068       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
64069       break;
64070     }
64071 #endif
64072
64073     /* Store the result as data using a unique key.
64074     */
64075     case SRT_Table:
64076     case SRT_EphemTab: {
64077       int r1 = sqlite3GetTempReg(pParse);
64078       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
64079       if( pOrderBy ){
64080         pushOntoSorter(pParse, pOrderBy, p, r1);
64081       }else{
64082         int r2 = sqlite3GetTempReg(pParse);
64083         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
64084         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
64085         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
64086         sqlite3ReleaseTempReg(pParse, r2);
64087       }
64088       sqlite3ReleaseTempReg(pParse, r1);
64089       break;
64090     }
64091
64092 #ifndef SQLITE_OMIT_SUBQUERY
64093     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
64094     ** then there should be a single item on the stack.  Write this
64095     ** item into the set table with bogus data.
64096     */
64097     case SRT_Set: {
64098       int addr2;
64099
64100       assert( nColumn==1 );
64101       addr2 = sqlite3VdbeAddOp1(v, OP_IsNull, regResult);
64102       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
64103       if( pOrderBy ){
64104         /* At first glance you would think we could optimize out the
64105         ** ORDER BY in this case since the order of entries in the set
64106         ** does not matter.  But there might be a LIMIT clause, in which
64107         ** case the order does matter */
64108         pushOntoSorter(pParse, pOrderBy, p, regResult);
64109       }else{
64110         int r1 = sqlite3GetTempReg(pParse);
64111         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
64112         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
64113         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
64114         sqlite3ReleaseTempReg(pParse, r1);
64115       }
64116       sqlite3VdbeJumpHere(v, addr2);
64117       break;
64118     }
64119
64120     /* If any row exist in the result set, record that fact and abort.
64121     */
64122     case SRT_Exists: {
64123       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
64124       /* The LIMIT clause will terminate the loop for us */
64125       break;
64126     }
64127
64128     /* If this is a scalar select that is part of an expression, then
64129     ** store the results in the appropriate memory cell and break out
64130     ** of the scan loop.
64131     */
64132     case SRT_Mem: {
64133       assert( nColumn==1 );
64134       if( pOrderBy ){
64135         pushOntoSorter(pParse, pOrderBy, p, regResult);
64136       }else{
64137         sqlite3ExprCodeMove(pParse, regResult, iParm);
64138         /* The LIMIT clause will jump out of the loop for us */
64139       }
64140       break;
64141     }
64142 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
64143
64144     /* Send the data to the callback function or to a subroutine.  In the
64145     ** case of a subroutine, the subroutine itself is responsible for
64146     ** popping the data from the stack.
64147     */
64148     case SRT_Subroutine:
64149     case SRT_Callback: {
64150       if( pOrderBy ){
64151         int r1 = sqlite3GetTempReg(pParse);
64152         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
64153         pushOntoSorter(pParse, pOrderBy, p, r1);
64154         sqlite3ReleaseTempReg(pParse, r1);
64155       }else if( eDest==SRT_Subroutine ){
64156         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
64157       }else{
64158         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
64159         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
64160       }
64161       break;
64162     }
64163
64164 #if !defined(SQLITE_OMIT_TRIGGER)
64165     /* Discard the results.  This is used for SELECT statements inside
64166     ** the body of a TRIGGER.  The purpose of such selects is to call
64167     ** user-defined functions that have side effects.  We do not care
64168     ** about the actual results of the select.
64169     */
64170     default: {
64171       assert( eDest==SRT_Discard );
64172       break;
64173     }
64174 #endif
64175   }
64176
64177   /* Jump to the end of the loop if the LIMIT is reached.
64178   */
64179   if( p->iLimit>=0 && pOrderBy==0 ){
64180     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
64181     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
64182   }
64183 }
64184
64185 /*
64186 ** Given an expression list, generate a KeyInfo structure that records
64187 ** the collating sequence for each expression in that expression list.
64188 **
64189 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
64190 ** KeyInfo structure is appropriate for initializing a virtual index to
64191 ** implement that clause.  If the ExprList is the result set of a SELECT
64192 ** then the KeyInfo structure is appropriate for initializing a virtual
64193 ** index to implement a DISTINCT test.
64194 **
64195 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
64196 ** function is responsible for seeing that this structure is eventually
64197 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
64198 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
64199 */
64200 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
64201   sqlite3 *db = pParse->db;
64202   int nExpr;
64203   KeyInfo *pInfo;
64204   struct ExprList_item *pItem;
64205   int i;
64206
64207   nExpr = pList->nExpr;
64208   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
64209   if( pInfo ){
64210     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
64211     pInfo->nField = nExpr;
64212     pInfo->enc = ENC(db);
64213     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
64214       CollSeq *pColl;
64215       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
64216       if( !pColl ){
64217         pColl = db->pDfltColl;
64218       }
64219       pInfo->aColl[i] = pColl;
64220       pInfo->aSortOrder[i] = pItem->sortOrder;
64221     }
64222   }
64223   return pInfo;
64224 }
64225
64226
64227 /*
64228 ** If the inner loop was generated using a non-null pOrderBy argument,
64229 ** then the results were placed in a sorter.  After the loop is terminated
64230 ** we need to run the sorter and output the results.  The following
64231 ** routine generates the code needed to do that.
64232 */
64233 static void generateSortTail(
64234   Parse *pParse,    /* Parsing context */
64235   Select *p,        /* The SELECT statement */
64236   Vdbe *v,          /* Generate code into this VDBE */
64237   int nColumn,      /* Number of columns of data */
64238   SelectDest *pDest /* Write the sorted results here */
64239 ){
64240   int brk = sqlite3VdbeMakeLabel(v);
64241   int cont = sqlite3VdbeMakeLabel(v);
64242   int addr;
64243   int iTab;
64244   int pseudoTab = 0;
64245   ExprList *pOrderBy = p->pOrderBy;
64246
64247   int eDest = pDest->eDest;
64248   int iParm = pDest->iParm;
64249
64250   int regRow;
64251   int regRowid;
64252
64253   iTab = pOrderBy->iECursor;
64254   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
64255     pseudoTab = pParse->nTab++;
64256     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
64257     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Callback);
64258   }
64259   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
64260   codeOffset(v, p, cont);
64261   regRow = sqlite3GetTempReg(pParse);
64262   regRowid = sqlite3GetTempReg(pParse);
64263   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
64264   switch( eDest ){
64265     case SRT_Table:
64266     case SRT_EphemTab: {
64267       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
64268       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
64269       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
64270       break;
64271     }
64272 #ifndef SQLITE_OMIT_SUBQUERY
64273     case SRT_Set: {
64274       int j1;
64275       assert( nColumn==1 );
64276       j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regRow);
64277       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
64278       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
64279       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
64280       sqlite3VdbeJumpHere(v, j1);
64281       break;
64282     }
64283     case SRT_Mem: {
64284       assert( nColumn==1 );
64285       sqlite3ExprCodeMove(pParse, regRow, iParm);
64286       /* The LIMIT clause will terminate the loop for us */
64287       break;
64288     }
64289 #endif
64290     case SRT_Callback:
64291     case SRT_Subroutine: {
64292       int i;
64293       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
64294       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
64295       for(i=0; i<nColumn; i++){
64296         assert( regRow!=pDest->iMem+i );
64297         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
64298       }
64299       if( eDest==SRT_Callback ){
64300         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
64301         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
64302       }else{
64303         sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm);
64304       }
64305       break;
64306     }
64307     default: {
64308       /* Do nothing */
64309       break;
64310     }
64311   }
64312   sqlite3ReleaseTempReg(pParse, regRow);
64313   sqlite3ReleaseTempReg(pParse, regRowid);
64314
64315   /* Jump to the end of the loop when the LIMIT is reached
64316   */
64317   if( p->iLimit>=0 ){
64318     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
64319     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, brk);
64320   }
64321
64322   /* The bottom of the loop
64323   */
64324   sqlite3VdbeResolveLabel(v, cont);
64325   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
64326   sqlite3VdbeResolveLabel(v, brk);
64327   if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
64328     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
64329   }
64330
64331 }
64332
64333 /*
64334 ** Return a pointer to a string containing the 'declaration type' of the
64335 ** expression pExpr. The string may be treated as static by the caller.
64336 **
64337 ** The declaration type is the exact datatype definition extracted from the
64338 ** original CREATE TABLE statement if the expression is a column. The
64339 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
64340 ** is considered a column can be complex in the presence of subqueries. The
64341 ** result-set expression in all of the following SELECT statements is 
64342 ** considered a column by this function.
64343 **
64344 **   SELECT col FROM tbl;
64345 **   SELECT (SELECT col FROM tbl;
64346 **   SELECT (SELECT col FROM tbl);
64347 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
64348 ** 
64349 ** The declaration type for any expression other than a column is NULL.
64350 */
64351 static const char *columnType(
64352   NameContext *pNC, 
64353   Expr *pExpr,
64354   const char **pzOriginDb,
64355   const char **pzOriginTab,
64356   const char **pzOriginCol
64357 ){
64358   char const *zType = 0;
64359   char const *zOriginDb = 0;
64360   char const *zOriginTab = 0;
64361   char const *zOriginCol = 0;
64362   int j;
64363   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
64364
64365   switch( pExpr->op ){
64366     case TK_AGG_COLUMN:
64367     case TK_COLUMN: {
64368       /* The expression is a column. Locate the table the column is being
64369       ** extracted from in NameContext.pSrcList. This table may be real
64370       ** database table or a subquery.
64371       */
64372       Table *pTab = 0;            /* Table structure column is extracted from */
64373       Select *pS = 0;             /* Select the column is extracted from */
64374       int iCol = pExpr->iColumn;  /* Index of column in pTab */
64375       while( pNC && !pTab ){
64376         SrcList *pTabList = pNC->pSrcList;
64377         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
64378         if( j<pTabList->nSrc ){
64379           pTab = pTabList->a[j].pTab;
64380           pS = pTabList->a[j].pSelect;
64381         }else{
64382           pNC = pNC->pNext;
64383         }
64384       }
64385
64386       if( pTab==0 ){
64387         /* FIX ME:
64388         ** This can occurs if you have something like "SELECT new.x;" inside
64389         ** a trigger.  In other words, if you reference the special "new"
64390         ** table in the result set of a select.  We do not have a good way
64391         ** to find the actual table type, so call it "TEXT".  This is really
64392         ** something of a bug, but I do not know how to fix it.
64393         **
64394         ** This code does not produce the correct answer - it just prevents
64395         ** a segfault.  See ticket #1229.
64396         */
64397         zType = "TEXT";
64398         break;
64399       }
64400
64401       assert( pTab );
64402       if( pS ){
64403         /* The "table" is actually a sub-select or a view in the FROM clause
64404         ** of the SELECT statement. Return the declaration type and origin
64405         ** data for the result-set column of the sub-select.
64406         */
64407         if( iCol>=0 && iCol<pS->pEList->nExpr ){
64408           /* If iCol is less than zero, then the expression requests the
64409           ** rowid of the sub-select or view. This expression is legal (see 
64410           ** test case misc2.2.2) - it always evaluates to NULL.
64411           */
64412           NameContext sNC;
64413           Expr *p = pS->pEList->a[iCol].pExpr;
64414           sNC.pSrcList = pS->pSrc;
64415           sNC.pNext = 0;
64416           sNC.pParse = pNC->pParse;
64417           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
64418         }
64419       }else if( pTab->pSchema ){
64420         /* A real table */
64421         assert( !pS );
64422         if( iCol<0 ) iCol = pTab->iPKey;
64423         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
64424         if( iCol<0 ){
64425           zType = "INTEGER";
64426           zOriginCol = "rowid";
64427         }else{
64428           zType = pTab->aCol[iCol].zType;
64429           zOriginCol = pTab->aCol[iCol].zName;
64430         }
64431         zOriginTab = pTab->zName;
64432         if( pNC->pParse ){
64433           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
64434           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
64435         }
64436       }
64437       break;
64438     }
64439 #ifndef SQLITE_OMIT_SUBQUERY
64440     case TK_SELECT: {
64441       /* The expression is a sub-select. Return the declaration type and
64442       ** origin info for the single column in the result set of the SELECT
64443       ** statement.
64444       */
64445       NameContext sNC;
64446       Select *pS = pExpr->pSelect;
64447       Expr *p = pS->pEList->a[0].pExpr;
64448       sNC.pSrcList = pS->pSrc;
64449       sNC.pNext = pNC;
64450       sNC.pParse = pNC->pParse;
64451       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
64452       break;
64453     }
64454 #endif
64455   }
64456   
64457   if( pzOriginDb ){
64458     assert( pzOriginTab && pzOriginCol );
64459     *pzOriginDb = zOriginDb;
64460     *pzOriginTab = zOriginTab;
64461     *pzOriginCol = zOriginCol;
64462   }
64463   return zType;
64464 }
64465
64466 /*
64467 ** Generate code that will tell the VDBE the declaration types of columns
64468 ** in the result set.
64469 */
64470 static void generateColumnTypes(
64471   Parse *pParse,      /* Parser context */
64472   SrcList *pTabList,  /* List of tables */
64473   ExprList *pEList    /* Expressions defining the result set */
64474 ){
64475 #ifndef SQLITE_OMIT_DECLTYPE
64476   Vdbe *v = pParse->pVdbe;
64477   int i;
64478   NameContext sNC;
64479   sNC.pSrcList = pTabList;
64480   sNC.pParse = pParse;
64481   for(i=0; i<pEList->nExpr; i++){
64482     Expr *p = pEList->a[i].pExpr;
64483     const char *zType;
64484 #ifdef SQLITE_ENABLE_COLUMN_METADATA
64485     const char *zOrigDb = 0;
64486     const char *zOrigTab = 0;
64487     const char *zOrigCol = 0;
64488     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
64489
64490     /* The vdbe must make its own copy of the column-type and other 
64491     ** column specific strings, in case the schema is reset before this
64492     ** virtual machine is deleted.
64493     */
64494     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
64495     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
64496     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
64497 #else
64498     zType = columnType(&sNC, p, 0, 0, 0);
64499 #endif
64500     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
64501   }
64502 #endif /* SQLITE_OMIT_DECLTYPE */
64503 }
64504
64505 /*
64506 ** Generate code that will tell the VDBE the names of columns
64507 ** in the result set.  This information is used to provide the
64508 ** azCol[] values in the callback.
64509 */
64510 static void generateColumnNames(
64511   Parse *pParse,      /* Parser context */
64512   SrcList *pTabList,  /* List of tables */
64513   ExprList *pEList    /* Expressions defining the result set */
64514 ){
64515   Vdbe *v = pParse->pVdbe;
64516   int i, j;
64517   sqlite3 *db = pParse->db;
64518   int fullNames, shortNames;
64519
64520 #ifndef SQLITE_OMIT_EXPLAIN
64521   /* If this is an EXPLAIN, skip this step */
64522   if( pParse->explain ){
64523     return;
64524   }
64525 #endif
64526
64527   assert( v!=0 );
64528   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
64529   pParse->colNamesSet = 1;
64530   fullNames = (db->flags & SQLITE_FullColNames)!=0;
64531   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
64532   sqlite3VdbeSetNumCols(v, pEList->nExpr);
64533   for(i=0; i<pEList->nExpr; i++){
64534     Expr *p;
64535     p = pEList->a[i].pExpr;
64536     if( p==0 ) continue;
64537     if( pEList->a[i].zName ){
64538       char *zName = pEList->a[i].zName;
64539       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
64540       continue;
64541     }
64542     if( p->op==TK_COLUMN && pTabList ){
64543       Table *pTab;
64544       char *zCol;
64545       int iCol = p->iColumn;
64546       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
64547       assert( j<pTabList->nSrc );
64548       pTab = pTabList->a[j].pTab;
64549       if( iCol<0 ) iCol = pTab->iPKey;
64550       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
64551       if( iCol<0 ){
64552         zCol = "rowid";
64553       }else{
64554         zCol = pTab->aCol[iCol].zName;
64555       }
64556       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
64557         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
64558       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
64559         char *zName = 0;
64560         char *zTab;
64561  
64562         zTab = pTabList->a[j].zAlias;
64563         if( fullNames || zTab==0 ) zTab = pTab->zName;
64564         sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
64565         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
64566       }else{
64567         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
64568       }
64569     }else if( p->span.z && p->span.z[0] ){
64570       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
64571       /* sqlite3VdbeCompressSpace(v, addr); */
64572     }else{
64573       char zName[30];
64574       assert( p->op!=TK_COLUMN || pTabList==0 );
64575       sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
64576       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
64577     }
64578   }
64579   generateColumnTypes(pParse, pTabList, pEList);
64580 }
64581
64582 #ifndef SQLITE_OMIT_COMPOUND_SELECT
64583 /*
64584 ** Name of the connection operator, used for error messages.
64585 */
64586 static const char *selectOpName(int id){
64587   char *z;
64588   switch( id ){
64589     case TK_ALL:       z = "UNION ALL";   break;
64590     case TK_INTERSECT: z = "INTERSECT";   break;
64591     case TK_EXCEPT:    z = "EXCEPT";      break;
64592     default:           z = "UNION";       break;
64593   }
64594   return z;
64595 }
64596 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
64597
64598 /*
64599 ** Forward declaration
64600 */
64601 static int prepSelectStmt(Parse*, Select*);
64602
64603 /*
64604 ** Given a SELECT statement, generate a Table structure that describes
64605 ** the result set of that SELECT.
64606 */
64607 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
64608   Table *pTab;
64609   int i, j;
64610   ExprList *pEList;
64611   Column *aCol, *pCol;
64612   sqlite3 *db = pParse->db;
64613
64614   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
64615   if( prepSelectStmt(pParse, pSelect) ){
64616     return 0;
64617   }
64618   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
64619     return 0;
64620   }
64621   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
64622   if( pTab==0 ){
64623     return 0;
64624   }
64625   pTab->nRef = 1;
64626   pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
64627   pEList = pSelect->pEList;
64628   pTab->nCol = pEList->nExpr;
64629   assert( pTab->nCol>0 );
64630   pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
64631   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
64632     Expr *p, *pR;
64633     char *zType;
64634     char *zName;
64635     int nName;
64636     CollSeq *pColl;
64637     int cnt;
64638     NameContext sNC;
64639     
64640     /* Get an appropriate name for the column
64641     */
64642     p = pEList->a[i].pExpr;
64643     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
64644     if( (zName = pEList->a[i].zName)!=0 ){
64645       /* If the column contains an "AS <name>" phrase, use <name> as the name */
64646       zName = sqlite3DbStrDup(db, zName);
64647     }else if( p->op==TK_DOT 
64648               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
64649       /* For columns of the from A.B use B as the name */
64650       zName = sqlite3MPrintf(db, "%T", &pR->token);
64651     }else if( p->span.z && p->span.z[0] ){
64652       /* Use the original text of the column expression as its name */
64653       zName = sqlite3MPrintf(db, "%T", &p->span);
64654     }else{
64655       /* If all else fails, make up a name */
64656       zName = sqlite3MPrintf(db, "column%d", i+1);
64657     }
64658     if( !zName || db->mallocFailed ){
64659       db->mallocFailed = 1;
64660       sqlite3_free(zName);
64661       sqlite3DeleteTable(pTab);
64662       return 0;
64663     }
64664     sqlite3Dequote(zName);
64665
64666     /* Make sure the column name is unique.  If the name is not unique,
64667     ** append a integer to the name so that it becomes unique.
64668     */
64669     nName = strlen(zName);
64670     for(j=cnt=0; j<i; j++){
64671       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
64672         zName[nName] = 0;
64673         zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
64674         j = -1;
64675         if( zName==0 ) break;
64676       }
64677     }
64678     pCol->zName = zName;
64679
64680     /* Get the typename, type affinity, and collating sequence for the
64681     ** column.
64682     */
64683     memset(&sNC, 0, sizeof(sNC));
64684     sNC.pSrcList = pSelect->pSrc;
64685     zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
64686     pCol->zType = zType;
64687     pCol->affinity = sqlite3ExprAffinity(p);
64688     pColl = sqlite3ExprCollSeq(pParse, p);
64689     if( pColl ){
64690       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
64691     }
64692   }
64693   pTab->iPKey = -1;
64694   return pTab;
64695 }
64696
64697 /*
64698 ** Prepare a SELECT statement for processing by doing the following
64699 ** things:
64700 **
64701 **    (1)  Make sure VDBE cursor numbers have been assigned to every
64702 **         element of the FROM clause.
64703 **
64704 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
64705 **         defines FROM clause.  When views appear in the FROM clause,
64706 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
64707 **         that implements the view.  A copy is made of the view's SELECT
64708 **         statement so that we can freely modify or delete that statement
64709 **         without worrying about messing up the presistent representation
64710 **         of the view.
64711 **
64712 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
64713 **         on joins and the ON and USING clause of joins.
64714 **
64715 **    (4)  Scan the list of columns in the result set (pEList) looking
64716 **         for instances of the "*" operator or the TABLE.* operator.
64717 **         If found, expand each "*" to be every column in every table
64718 **         and TABLE.* to be every column in TABLE.
64719 **
64720 ** Return 0 on success.  If there are problems, leave an error message
64721 ** in pParse and return non-zero.
64722 */
64723 static int prepSelectStmt(Parse *pParse, Select *p){
64724   int i, j, k, rc;
64725   SrcList *pTabList;
64726   ExprList *pEList;
64727   struct SrcList_item *pFrom;
64728   sqlite3 *db = pParse->db;
64729
64730   if( p==0 || p->pSrc==0 || db->mallocFailed ){
64731     return 1;
64732   }
64733   pTabList = p->pSrc;
64734   pEList = p->pEList;
64735
64736   /* Make sure cursor numbers have been assigned to all entries in
64737   ** the FROM clause of the SELECT statement.
64738   */
64739   sqlite3SrcListAssignCursors(pParse, p->pSrc);
64740
64741   /* Look up every table named in the FROM clause of the select.  If
64742   ** an entry of the FROM clause is a subquery instead of a table or view,
64743   ** then create a transient table structure to describe the subquery.
64744   */
64745   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
64746     Table *pTab;
64747     if( pFrom->pTab!=0 ){
64748       /* This statement has already been prepared.  There is no need
64749       ** to go further. */
64750       assert( i==0 );
64751       return 0;
64752     }
64753     if( pFrom->zName==0 ){
64754 #ifndef SQLITE_OMIT_SUBQUERY
64755       /* A sub-query in the FROM clause of a SELECT */
64756       assert( pFrom->pSelect!=0 );
64757       if( pFrom->zAlias==0 ){
64758         pFrom->zAlias =
64759           sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
64760       }
64761       assert( pFrom->pTab==0 );
64762       pFrom->pTab = pTab = 
64763         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
64764       if( pTab==0 ){
64765         return 1;
64766       }
64767       /* The isEphem flag indicates that the Table structure has been
64768       ** dynamically allocated and may be freed at any time.  In other words,
64769       ** pTab is not pointing to a persistent table structure that defines
64770       ** part of the schema. */
64771       pTab->isEphem = 1;
64772 #endif
64773     }else{
64774       /* An ordinary table or view name in the FROM clause */
64775       assert( pFrom->pTab==0 );
64776       pFrom->pTab = pTab = 
64777         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
64778       if( pTab==0 ){
64779         return 1;
64780       }
64781       pTab->nRef++;
64782 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
64783       if( pTab->pSelect || IsVirtual(pTab) ){
64784         /* We reach here if the named table is a really a view */
64785         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
64786           return 1;
64787         }
64788         /* If pFrom->pSelect!=0 it means we are dealing with a
64789         ** view within a view.  The SELECT structure has already been
64790         ** copied by the outer view so we can skip the copy step here
64791         ** in the inner view.
64792         */
64793         if( pFrom->pSelect==0 ){
64794           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
64795         }
64796       }
64797 #endif
64798     }
64799   }
64800
64801   /* Process NATURAL keywords, and ON and USING clauses of joins.
64802   */
64803   if( sqliteProcessJoin(pParse, p) ) return 1;
64804
64805   /* For every "*" that occurs in the column list, insert the names of
64806   ** all columns in all tables.  And for every TABLE.* insert the names
64807   ** of all columns in TABLE.  The parser inserted a special expression
64808   ** with the TK_ALL operator for each "*" that it found in the column list.
64809   ** The following code just has to locate the TK_ALL expressions and expand
64810   ** each one to the list of all columns in all tables.
64811   **
64812   ** The first loop just checks to see if there are any "*" operators
64813   ** that need expanding.
64814   */
64815   for(k=0; k<pEList->nExpr; k++){
64816     Expr *pE = pEList->a[k].pExpr;
64817     if( pE->op==TK_ALL ) break;
64818     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
64819          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
64820   }
64821   rc = 0;
64822   if( k<pEList->nExpr ){
64823     /*
64824     ** If we get here it means the result set contains one or more "*"
64825     ** operators that need to be expanded.  Loop through each expression
64826     ** in the result set and expand them one by one.
64827     */
64828     struct ExprList_item *a = pEList->a;
64829     ExprList *pNew = 0;
64830     int flags = pParse->db->flags;
64831     int longNames = (flags & SQLITE_FullColNames)!=0 &&
64832                       (flags & SQLITE_ShortColNames)==0;
64833
64834     for(k=0; k<pEList->nExpr; k++){
64835       Expr *pE = a[k].pExpr;
64836       if( pE->op!=TK_ALL &&
64837            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
64838         /* This particular expression does not need to be expanded.
64839         */
64840         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
64841         if( pNew ){
64842           pNew->a[pNew->nExpr-1].zName = a[k].zName;
64843         }else{
64844           rc = 1;
64845         }
64846         a[k].pExpr = 0;
64847         a[k].zName = 0;
64848       }else{
64849         /* This expression is a "*" or a "TABLE.*" and needs to be
64850         ** expanded. */
64851         int tableSeen = 0;      /* Set to 1 when TABLE matches */
64852         char *zTName;            /* text of name of TABLE */
64853         if( pE->op==TK_DOT && pE->pLeft ){
64854           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
64855         }else{
64856           zTName = 0;
64857         }
64858         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
64859           Table *pTab = pFrom->pTab;
64860           char *zTabName = pFrom->zAlias;
64861           if( zTabName==0 || zTabName[0]==0 ){ 
64862             zTabName = pTab->zName;
64863           }
64864           if( zTName && (zTabName==0 || zTabName[0]==0 || 
64865                  sqlite3StrICmp(zTName, zTabName)!=0) ){
64866             continue;
64867           }
64868           tableSeen = 1;
64869           for(j=0; j<pTab->nCol; j++){
64870             Expr *pExpr, *pRight;
64871             char *zName = pTab->aCol[j].zName;
64872
64873             /* If a column is marked as 'hidden' (currently only possible
64874             ** for virtual tables), do not include it in the expanded
64875             ** result-set list.
64876             */
64877             if( IsHiddenColumn(&pTab->aCol[j]) ){
64878               assert(IsVirtual(pTab));
64879               continue;
64880             }
64881
64882             if( i>0 ){
64883               struct SrcList_item *pLeft = &pTabList->a[i-1];
64884               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
64885                         columnIndex(pLeft->pTab, zName)>=0 ){
64886                 /* In a NATURAL join, omit the join columns from the 
64887                 ** table on the right */
64888                 continue;
64889               }
64890               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
64891                 /* In a join with a USING clause, omit columns in the
64892                 ** using clause from the table on the right. */
64893                 continue;
64894               }
64895             }
64896             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
64897             if( pRight==0 ) break;
64898             setQuotedToken(pParse, &pRight->token, zName);
64899             if( zTabName && (longNames || pTabList->nSrc>1) ){
64900               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
64901               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
64902               if( pExpr==0 ) break;
64903               setQuotedToken(pParse, &pLeft->token, zTabName);
64904               setToken(&pExpr->span, 
64905                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
64906               pExpr->span.dyn = 1;
64907               pExpr->token.z = 0;
64908               pExpr->token.n = 0;
64909               pExpr->token.dyn = 0;
64910             }else{
64911               pExpr = pRight;
64912               pExpr->span = pExpr->token;
64913               pExpr->span.dyn = 0;
64914             }
64915             if( longNames ){
64916               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
64917             }else{
64918               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
64919             }
64920           }
64921         }
64922         if( !tableSeen ){
64923           if( zTName ){
64924             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
64925           }else{
64926             sqlite3ErrorMsg(pParse, "no tables specified");
64927           }
64928           rc = 1;
64929         }
64930         sqlite3_free(zTName);
64931       }
64932     }
64933     sqlite3ExprListDelete(pEList);
64934     p->pEList = pNew;
64935   }
64936 #if SQLITE_MAX_COLUMN
64937   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
64938     sqlite3ErrorMsg(pParse, "too many columns in result set");
64939     rc = SQLITE_ERROR;
64940   }
64941 #endif
64942   if( db->mallocFailed ){
64943     rc = SQLITE_NOMEM;
64944   }
64945   return rc;
64946 }
64947
64948 /*
64949 ** pE is a pointer to an expression which is a single term in
64950 ** ORDER BY or GROUP BY clause.
64951 **
64952 ** If pE evaluates to an integer constant i, then return i.
64953 ** This is an indication to the caller that it should sort
64954 ** by the i-th column of the result set.
64955 **
64956 ** If pE is a well-formed expression and the SELECT statement
64957 ** is not compound, then return 0.  This indicates to the
64958 ** caller that it should sort by the value of the ORDER BY
64959 ** expression.
64960 **
64961 ** If the SELECT is compound, then attempt to match pE against
64962 ** result set columns in the left-most SELECT statement.  Return
64963 ** the index i of the matching column, as an indication to the 
64964 ** caller that it should sort by the i-th column.  If there is
64965 ** no match, return -1 and leave an error message in pParse.
64966 */
64967 static int matchOrderByTermToExprList(
64968   Parse *pParse,     /* Parsing context for error messages */
64969   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
64970   Expr *pE,          /* The specific ORDER BY term */
64971   int idx,           /* When ORDER BY term is this */
64972   int isCompound,    /* True if this is a compound SELECT */
64973   u8 *pHasAgg        /* True if expression contains aggregate functions */
64974 ){
64975   int i;             /* Loop counter */
64976   ExprList *pEList;  /* The columns of the result set */
64977   NameContext nc;    /* Name context for resolving pE */
64978
64979
64980   /* If the term is an integer constant, return the value of that
64981   ** constant */
64982   pEList = pSelect->pEList;
64983   if( sqlite3ExprIsInteger(pE, &i) ){
64984     if( i<=0 ){
64985       /* If i is too small, make it too big.  That way the calling
64986       ** function still sees a value that is out of range, but does
64987       ** not confuse the column number with 0 or -1 result code.
64988       */
64989       i = pEList->nExpr+1;
64990     }
64991     return i;
64992   }
64993
64994   /* If the term is a simple identifier that try to match that identifier
64995   ** against a column name in the result set.
64996   */
64997   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
64998     sqlite3 *db = pParse->db;
64999     char *zCol = sqlite3NameFromToken(db, &pE->token);
65000     if( zCol==0 ){
65001       return -1;
65002     }
65003     for(i=0; i<pEList->nExpr; i++){
65004       char *zAs = pEList->a[i].zName;
65005       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
65006         sqlite3_free(zCol);
65007         return i+1;
65008       }
65009     }
65010     sqlite3_free(zCol);
65011   }
65012
65013   /* Resolve all names in the ORDER BY term expression
65014   */
65015   memset(&nc, 0, sizeof(nc));
65016   nc.pParse = pParse;
65017   nc.pSrcList = pSelect->pSrc;
65018   nc.pEList = pEList;
65019   nc.allowAgg = 1;
65020   nc.nErr = 0;
65021   if( sqlite3ExprResolveNames(&nc, pE) ){
65022     if( isCompound ){
65023       sqlite3ErrorClear(pParse);
65024       return 0;
65025     }else{
65026       return -1;
65027     }
65028   }
65029   if( nc.hasAgg && pHasAgg ){
65030     *pHasAgg = 1;
65031   }
65032
65033   /* For a compound SELECT, we need to try to match the ORDER BY
65034   ** expression against an expression in the result set
65035   */
65036   if( isCompound ){
65037     for(i=0; i<pEList->nExpr; i++){
65038       if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
65039         return i+1;
65040       }
65041     }
65042   }
65043   return 0;
65044 }
65045
65046
65047 /*
65048 ** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement.
65049 ** Return the number of errors seen.
65050 **
65051 ** Every term of the ORDER BY or GROUP BY clause needs to be an
65052 ** expression.  If any expression is an integer constant, then
65053 ** that expression is replaced by the corresponding 
65054 ** expression from the result set.
65055 */
65056 static int processOrderGroupBy(
65057   Parse *pParse,        /* Parsing context.  Leave error messages here */
65058   Select *pSelect,      /* The SELECT statement containing the clause */
65059   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
65060   int isOrder,          /* 1 for ORDER BY.  0 for GROUP BY */
65061   u8 *pHasAgg           /* Set to TRUE if any term contains an aggregate */
65062 ){
65063   int i;
65064   sqlite3 *db = pParse->db;
65065   ExprList *pEList;
65066
65067   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
65068 #if SQLITE_MAX_COLUMN
65069   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
65070     const char *zType = isOrder ? "ORDER" : "GROUP";
65071     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
65072     return 1;
65073   }
65074 #endif
65075   pEList = pSelect->pEList;
65076   if( pEList==0 ){
65077     return 0;
65078   }
65079   for(i=0; i<pOrderBy->nExpr; i++){
65080     int iCol;
65081     Expr *pE = pOrderBy->a[i].pExpr;
65082     iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg);
65083     if( iCol<0 ){
65084       return 1;
65085     }
65086     if( iCol>pEList->nExpr ){
65087       const char *zType = isOrder ? "ORDER" : "GROUP";
65088       sqlite3ErrorMsg(pParse, 
65089          "%r %s BY term out of range - should be "
65090          "between 1 and %d", i+1, zType, pEList->nExpr);
65091       return 1;
65092     }
65093     if( iCol>0 ){
65094       CollSeq *pColl = pE->pColl;
65095       int flags = pE->flags & EP_ExpCollate;
65096       sqlite3ExprDelete(pE);
65097       pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr);
65098       pOrderBy->a[i].pExpr = pE;
65099       if( pE && pColl && flags ){
65100         pE->pColl = pColl;
65101         pE->flags |= flags;
65102       }
65103     }
65104   }
65105   return 0;
65106 }
65107
65108 /*
65109 ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
65110 ** the number of errors seen.
65111 **
65112 ** The processing depends on whether the SELECT is simple or compound.
65113 ** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY
65114 ** clause needs to be an expression.  If any expression is an integer
65115 ** constant, then that expression is replaced by the corresponding 
65116 ** expression from the result set.
65117 **
65118 ** For compound SELECT statements, every expression needs to be of
65119 ** type TK_COLUMN with a iTable value as given in the 4th parameter.
65120 ** If any expression is an integer, that becomes the column number.
65121 ** Otherwise, match the expression against result set columns from
65122 ** the left-most SELECT.
65123 */
65124 static int processCompoundOrderBy(
65125   Parse *pParse,        /* Parsing context.  Leave error messages here */
65126   Select *pSelect,      /* The SELECT statement containing the ORDER BY */
65127   int iTable            /* Output table for compound SELECT statements */
65128 ){
65129   int i;
65130   ExprList *pOrderBy;
65131   ExprList *pEList;
65132   sqlite3 *db;
65133   int moreToDo = 1;
65134
65135   pOrderBy = pSelect->pOrderBy;
65136   if( pOrderBy==0 ) return 0;
65137   db = pParse->db;
65138 #if SQLITE_MAX_COLUMN
65139   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
65140     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
65141     return 1;
65142   }
65143 #endif
65144   for(i=0; i<pOrderBy->nExpr; i++){
65145     pOrderBy->a[i].done = 0;
65146   }
65147   while( pSelect->pPrior ){
65148     pSelect = pSelect->pPrior;
65149   }
65150   while( pSelect && moreToDo ){
65151     moreToDo = 0;
65152     for(i=0; i<pOrderBy->nExpr; i++){
65153       int iCol = -1;
65154       Expr *pE, *pDup;
65155       if( pOrderBy->a[i].done ) continue;
65156       pE = pOrderBy->a[i].pExpr;
65157       pDup = sqlite3ExprDup(db, pE);
65158       if( !db->mallocFailed ){
65159         assert(pDup);
65160         iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0);
65161       }
65162       sqlite3ExprDelete(pDup);
65163       if( iCol<0 ){
65164         return 1;
65165       }
65166       pEList = pSelect->pEList;
65167       if( pEList==0 ){
65168         return 1;
65169       }
65170       if( iCol>pEList->nExpr ){
65171         sqlite3ErrorMsg(pParse, 
65172            "%r ORDER BY term out of range - should be "
65173            "between 1 and %d", i+1, pEList->nExpr);
65174         return 1;
65175       }
65176       if( iCol>0 ){
65177         pE->op = TK_COLUMN;
65178         pE->iTable = iTable;
65179         pE->iAgg = -1;
65180         pE->iColumn = iCol-1;
65181         pE->pTab = 0;
65182         pOrderBy->a[i].done = 1;
65183       }else{
65184         moreToDo = 1;
65185       }
65186     }
65187     pSelect = pSelect->pNext;
65188   }
65189   for(i=0; i<pOrderBy->nExpr; i++){
65190     if( pOrderBy->a[i].done==0 ){
65191       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
65192             "column in the result set", i+1);
65193       return 1;
65194     }
65195   }
65196   return 0;
65197 }
65198
65199 /*
65200 ** Get a VDBE for the given parser context.  Create a new one if necessary.
65201 ** If an error occurs, return NULL and leave a message in pParse.
65202 */
65203 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
65204   Vdbe *v = pParse->pVdbe;
65205   if( v==0 ){
65206     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
65207 #ifndef SQLITE_OMIT_TRACE
65208     if( v ){
65209       sqlite3VdbeAddOp0(v, OP_Trace);
65210     }
65211 #endif
65212   }
65213   return v;
65214 }
65215
65216
65217 /*
65218 ** Compute the iLimit and iOffset fields of the SELECT based on the
65219 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
65220 ** that appear in the original SQL statement after the LIMIT and OFFSET
65221 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
65222 ** are the integer memory register numbers for counters used to compute 
65223 ** the limit and offset.  If there is no limit and/or offset, then 
65224 ** iLimit and iOffset are negative.
65225 **
65226 ** This routine changes the values of iLimit and iOffset only if
65227 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
65228 ** iOffset should have been preset to appropriate default values
65229 ** (usually but not always -1) prior to calling this routine.
65230 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
65231 ** redefined.  The UNION ALL operator uses this property to force
65232 ** the reuse of the same limit and offset registers across multiple
65233 ** SELECT statements.
65234 */
65235 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
65236   Vdbe *v = 0;
65237   int iLimit = 0;
65238   int iOffset;
65239   int addr1;
65240
65241   /* 
65242   ** "LIMIT -1" always shows all rows.  There is some
65243   ** contraversy about what the correct behavior should be.
65244   ** The current implementation interprets "LIMIT 0" to mean
65245   ** no rows.
65246   */
65247   if( p->pLimit ){
65248     p->iLimit = iLimit = ++pParse->nMem;
65249     v = sqlite3GetVdbe(pParse);
65250     if( v==0 ) return;
65251     sqlite3ExprCode(pParse, p->pLimit, iLimit);
65252     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
65253     VdbeComment((v, "LIMIT counter"));
65254     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
65255   }
65256   if( p->pOffset ){
65257     p->iOffset = iOffset = ++pParse->nMem;
65258     if( p->pLimit ){
65259       pParse->nMem++;   /* Allocate an extra register for limit+offset */
65260     }
65261     v = sqlite3GetVdbe(pParse);
65262     if( v==0 ) return;
65263     sqlite3ExprCode(pParse, p->pOffset, iOffset);
65264     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
65265     VdbeComment((v, "OFFSET counter"));
65266     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
65267     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
65268     sqlite3VdbeJumpHere(v, addr1);
65269     if( p->pLimit ){
65270       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
65271       VdbeComment((v, "LIMIT+OFFSET"));
65272       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
65273       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
65274       sqlite3VdbeJumpHere(v, addr1);
65275     }
65276   }
65277 }
65278
65279 /*
65280 ** Allocate a virtual index to use for sorting.
65281 */
65282 static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
65283   if( pOrderBy ){
65284     int addr;
65285     assert( pOrderBy->iECursor==0 );
65286     pOrderBy->iECursor = pParse->nTab++;
65287     addr = sqlite3VdbeAddOp2(pParse->pVdbe, OP_OpenEphemeral,
65288                             pOrderBy->iECursor, pOrderBy->nExpr+1);
65289     assert( p->addrOpenEphm[2] == -1 );
65290     p->addrOpenEphm[2] = addr;
65291   }
65292 }
65293
65294 #ifndef SQLITE_OMIT_COMPOUND_SELECT
65295 /*
65296 ** Return the appropriate collating sequence for the iCol-th column of
65297 ** the result set for the compound-select statement "p".  Return NULL if
65298 ** the column has no default collating sequence.
65299 **
65300 ** The collating sequence for the compound select is taken from the
65301 ** left-most term of the select that has a collating sequence.
65302 */
65303 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
65304   CollSeq *pRet;
65305   if( p->pPrior ){
65306     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
65307   }else{
65308     pRet = 0;
65309   }
65310   if( pRet==0 ){
65311     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
65312   }
65313   return pRet;
65314 }
65315 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
65316
65317 #ifndef SQLITE_OMIT_COMPOUND_SELECT
65318 /*
65319 ** This routine is called to process a query that is really the union
65320 ** or intersection of two or more separate queries.
65321 **
65322 ** "p" points to the right-most of the two queries.  the query on the
65323 ** left is p->pPrior.  The left query could also be a compound query
65324 ** in which case this routine will be called recursively. 
65325 **
65326 ** The results of the total query are to be written into a destination
65327 ** of type eDest with parameter iParm.
65328 **
65329 ** Example 1:  Consider a three-way compound SQL statement.
65330 **
65331 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
65332 **
65333 ** This statement is parsed up as follows:
65334 **
65335 **     SELECT c FROM t3
65336 **      |
65337 **      `----->  SELECT b FROM t2
65338 **                |
65339 **                `------>  SELECT a FROM t1
65340 **
65341 ** The arrows in the diagram above represent the Select.pPrior pointer.
65342 ** So if this routine is called with p equal to the t3 query, then
65343 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
65344 **
65345 ** Notice that because of the way SQLite parses compound SELECTs, the
65346 ** individual selects always group from left to right.
65347 */
65348 static int multiSelect(
65349   Parse *pParse,        /* Parsing context */
65350   Select *p,            /* The right-most of SELECTs to be coded */
65351   SelectDest *pDest,    /* What to do with query results */
65352   char *aff             /* If eDest is SRT_Union, the affinity string */
65353 ){
65354   int rc = SQLITE_OK;   /* Success code from a subroutine */
65355   Select *pPrior;       /* Another SELECT immediately to our left */
65356   Vdbe *v;              /* Generate code to this VDBE */
65357   int nCol;             /* Number of columns in the result set */
65358   ExprList *pOrderBy;   /* The ORDER BY clause on p */
65359   int aSetP2[2];        /* Set P2 value of these op to number of columns */
65360   int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
65361   SelectDest dest;      /* Alternative data destination */
65362
65363   dest = *pDest;
65364
65365   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
65366   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
65367   */
65368   if( p==0 || p->pPrior==0 ){
65369     rc = 1;
65370     goto multi_select_end;
65371   }
65372   pPrior = p->pPrior;
65373   assert( pPrior->pRightmost!=pPrior );
65374   assert( pPrior->pRightmost==p->pRightmost );
65375   if( pPrior->pOrderBy ){
65376     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
65377       selectOpName(p->op));
65378     rc = 1;
65379     goto multi_select_end;
65380   }
65381   if( pPrior->pLimit ){
65382     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
65383       selectOpName(p->op));
65384     rc = 1;
65385     goto multi_select_end;
65386   }
65387
65388   /* Make sure we have a valid query engine.  If not, create a new one.
65389   */
65390   v = sqlite3GetVdbe(pParse);
65391   if( v==0 ){
65392     rc = 1;
65393     goto multi_select_end;
65394   }
65395
65396   /* Create the destination temporary table if necessary
65397   */
65398   if( dest.eDest==SRT_EphemTab ){
65399     assert( p->pEList );
65400     assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
65401     aSetP2[nSetP2++] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, 0);
65402     dest.eDest = SRT_Table;
65403   }
65404
65405   /* Generate code for the left and right SELECT statements.
65406   */
65407   pOrderBy = p->pOrderBy;
65408   switch( p->op ){
65409     case TK_ALL: {
65410       if( pOrderBy==0 ){
65411         int addr = 0;
65412         assert( !pPrior->pLimit );
65413         pPrior->pLimit = p->pLimit;
65414         pPrior->pOffset = p->pOffset;
65415         rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0, aff);
65416         p->pLimit = 0;
65417         p->pOffset = 0;
65418         if( rc ){
65419           goto multi_select_end;
65420         }
65421         p->pPrior = 0;
65422         p->iLimit = pPrior->iLimit;
65423         p->iOffset = pPrior->iOffset;
65424         if( p->iLimit>=0 ){
65425           addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
65426           VdbeComment((v, "Jump ahead if LIMIT reached"));
65427         }
65428         rc = sqlite3Select(pParse, p, &dest, 0, 0, 0, aff);
65429         p->pPrior = pPrior;
65430         if( rc ){
65431           goto multi_select_end;
65432         }
65433         if( addr ){
65434           sqlite3VdbeJumpHere(v, addr);
65435         }
65436         break;
65437       }
65438       /* For UNION ALL ... ORDER BY fall through to the next case */
65439     }
65440     case TK_EXCEPT:
65441     case TK_UNION: {
65442       int unionTab;    /* Cursor number of the temporary table holding result */
65443       int op = 0;      /* One of the SRT_ operations to apply to self */
65444       int priorOp;     /* The SRT_ operation to apply to prior selects */
65445       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
65446       int addr;
65447       SelectDest uniondest;
65448
65449       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
65450       if( dest.eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
65451         /* We can reuse a temporary table generated by a SELECT to our
65452         ** right.
65453         */
65454         unionTab = dest.iParm;
65455       }else{
65456         /* We will need to create our own temporary table to hold the
65457         ** intermediate results.
65458         */
65459         unionTab = pParse->nTab++;
65460         if( processCompoundOrderBy(pParse, p, unionTab) ){
65461           rc = 1;
65462           goto multi_select_end;
65463         }
65464         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
65465         if( priorOp==SRT_Table ){
65466           assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
65467           aSetP2[nSetP2++] = addr;
65468         }else{
65469           assert( p->addrOpenEphm[0] == -1 );
65470           p->addrOpenEphm[0] = addr;
65471           p->pRightmost->usesEphm = 1;
65472         }
65473         createSortingIndex(pParse, p, pOrderBy);
65474         assert( p->pEList );
65475       }
65476
65477       /* Code the SELECT statements to our left
65478       */
65479       assert( !pPrior->pOrderBy );
65480       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
65481       rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0, aff);
65482       if( rc ){
65483         goto multi_select_end;
65484       }
65485
65486       /* Code the current SELECT statement
65487       */
65488       switch( p->op ){
65489          case TK_EXCEPT:  op = SRT_Except;   break;
65490          case TK_UNION:   op = SRT_Union;    break;
65491          case TK_ALL:     op = SRT_Table;    break;
65492       }
65493       p->pPrior = 0;
65494       p->pOrderBy = 0;
65495       p->disallowOrderBy = pOrderBy!=0;
65496       pLimit = p->pLimit;
65497       p->pLimit = 0;
65498       pOffset = p->pOffset;
65499       p->pOffset = 0;
65500       uniondest.eDest = op;
65501       rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0, aff);
65502       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
65503       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
65504       sqlite3ExprListDelete(p->pOrderBy);
65505       p->pPrior = pPrior;
65506       p->pOrderBy = pOrderBy;
65507       sqlite3ExprDelete(p->pLimit);
65508       p->pLimit = pLimit;
65509       p->pOffset = pOffset;
65510       p->iLimit = -1;
65511       p->iOffset = -1;
65512       if( rc ){
65513         goto multi_select_end;
65514       }
65515
65516
65517       /* Convert the data in the temporary table into whatever form
65518       ** it is that we currently need.
65519       */      
65520       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
65521         int iCont, iBreak, iStart;
65522         assert( p->pEList );
65523         if( dest.eDest==SRT_Callback ){
65524           Select *pFirst = p;
65525           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
65526           generateColumnNames(pParse, 0, pFirst->pEList);
65527         }
65528         iBreak = sqlite3VdbeMakeLabel(v);
65529         iCont = sqlite3VdbeMakeLabel(v);
65530         computeLimitRegisters(pParse, p, iBreak);
65531         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
65532         iStart = sqlite3VdbeCurrentAddr(v);
65533         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
65534                         pOrderBy, -1, &dest, iCont, iBreak, 0);
65535         sqlite3VdbeResolveLabel(v, iCont);
65536         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
65537         sqlite3VdbeResolveLabel(v, iBreak);
65538         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
65539       }
65540       break;
65541     }
65542     case TK_INTERSECT: {
65543       int tab1, tab2;
65544       int iCont, iBreak, iStart;
65545       Expr *pLimit, *pOffset;
65546       int addr;
65547       SelectDest intersectdest;
65548       int r1;
65549
65550       /* INTERSECT is different from the others since it requires
65551       ** two temporary tables.  Hence it has its own case.  Begin
65552       ** by allocating the tables we will need.
65553       */
65554       tab1 = pParse->nTab++;
65555       tab2 = pParse->nTab++;
65556       if( processCompoundOrderBy(pParse, p, tab1) ){
65557         rc = 1;
65558         goto multi_select_end;
65559       }
65560       createSortingIndex(pParse, p, pOrderBy);
65561
65562       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
65563       assert( p->addrOpenEphm[0] == -1 );
65564       p->addrOpenEphm[0] = addr;
65565       p->pRightmost->usesEphm = 1;
65566       assert( p->pEList );
65567
65568       /* Code the SELECTs to our left into temporary table "tab1".
65569       */
65570       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
65571       rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0, aff);
65572       if( rc ){
65573         goto multi_select_end;
65574       }
65575
65576       /* Code the current SELECT into temporary table "tab2"
65577       */
65578       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
65579       assert( p->addrOpenEphm[1] == -1 );
65580       p->addrOpenEphm[1] = addr;
65581       p->pPrior = 0;
65582       pLimit = p->pLimit;
65583       p->pLimit = 0;
65584       pOffset = p->pOffset;
65585       p->pOffset = 0;
65586       intersectdest.iParm = tab2;
65587       rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0, aff);
65588       p->pPrior = pPrior;
65589       sqlite3ExprDelete(p->pLimit);
65590       p->pLimit = pLimit;
65591       p->pOffset = pOffset;
65592       if( rc ){
65593         goto multi_select_end;
65594       }
65595
65596       /* Generate code to take the intersection of the two temporary
65597       ** tables.
65598       */
65599       assert( p->pEList );
65600       if( dest.eDest==SRT_Callback ){
65601         Select *pFirst = p;
65602         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
65603         generateColumnNames(pParse, 0, pFirst->pEList);
65604       }
65605       iBreak = sqlite3VdbeMakeLabel(v);
65606       iCont = sqlite3VdbeMakeLabel(v);
65607       computeLimitRegisters(pParse, p, iBreak);
65608       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
65609       r1 = sqlite3GetTempReg(pParse);
65610       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
65611       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
65612       sqlite3ReleaseTempReg(pParse, r1);
65613       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
65614                       pOrderBy, -1, &dest, iCont, iBreak, 0);
65615       sqlite3VdbeResolveLabel(v, iCont);
65616       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
65617       sqlite3VdbeResolveLabel(v, iBreak);
65618       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
65619       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
65620       break;
65621     }
65622   }
65623
65624   /* Make sure all SELECTs in the statement have the same number of elements
65625   ** in their result sets.
65626   */
65627   assert( p->pEList && pPrior->pEList );
65628   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
65629     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
65630       " do not have the same number of result columns", selectOpName(p->op));
65631     rc = 1;
65632     goto multi_select_end;
65633   }
65634
65635   /* Set the number of columns in temporary tables
65636   */
65637   nCol = p->pEList->nExpr;
65638   while( nSetP2 ){
65639     sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
65640   }
65641
65642   /* Compute collating sequences used by either the ORDER BY clause or
65643   ** by any temporary tables needed to implement the compound select.
65644   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
65645   ** ORDER BY processing if there is an ORDER BY clause.
65646   **
65647   ** This section is run by the right-most SELECT statement only.
65648   ** SELECT statements to the left always skip this part.  The right-most
65649   ** SELECT might also skip this part if it has no ORDER BY clause and
65650   ** no temp tables are required.
65651   */
65652   if( pOrderBy || p->usesEphm ){
65653     int i;                        /* Loop counter */
65654     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
65655     Select *pLoop;                /* For looping through SELECT statements */
65656     int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
65657     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
65658     CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
65659
65660     assert( p->pRightmost==p );
65661     nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
65662     pKeyInfo = sqlite3DbMallocZero(pParse->db,
65663                        sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
65664     if( !pKeyInfo ){
65665       rc = SQLITE_NOMEM;
65666       goto multi_select_end;
65667     }
65668
65669     pKeyInfo->enc = ENC(pParse->db);
65670     pKeyInfo->nField = nCol;
65671
65672     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
65673       *apColl = multiSelectCollSeq(pParse, p, i);
65674       if( 0==*apColl ){
65675         *apColl = pParse->db->pDfltColl;
65676       }
65677     }
65678
65679     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
65680       for(i=0; i<2; i++){
65681         int addr = pLoop->addrOpenEphm[i];
65682         if( addr<0 ){
65683           /* If [0] is unused then [1] is also unused.  So we can
65684           ** always safely abort as soon as the first unused slot is found */
65685           assert( pLoop->addrOpenEphm[1]<0 );
65686           break;
65687         }
65688         sqlite3VdbeChangeP2(v, addr, nCol);
65689         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
65690         pLoop->addrOpenEphm[i] = -1;
65691       }
65692     }
65693
65694     if( pOrderBy ){
65695       struct ExprList_item *pOTerm = pOrderBy->a;
65696       int nOrderByExpr = pOrderBy->nExpr;
65697       int addr;
65698       u8 *pSortOrder;
65699
65700       /* Reuse the same pKeyInfo for the ORDER BY as was used above for
65701       ** the compound select statements.  Except we have to change out the
65702       ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
65703       ** reused when constructing the pKeyInfo for the ORDER BY, so make
65704       ** a copy.  Sufficient space to hold both the nCol entries for
65705       ** the compound select and the nOrderbyExpr entries for the ORDER BY
65706       ** was allocated above.  But we need to move the compound select
65707       ** entries out of the way before constructing the ORDER BY entries.
65708       ** Move the compound select entries into aCopy[] where they can be
65709       ** accessed and reused when constructing the ORDER BY entries.
65710       ** Because nCol might be greater than or less than nOrderByExpr
65711       ** we have to use memmove() when doing the copy.
65712       */
65713       aCopy = &pKeyInfo->aColl[nOrderByExpr];
65714       pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
65715       memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
65716
65717       apColl = pKeyInfo->aColl;
65718       for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
65719         Expr *pExpr = pOTerm->pExpr;
65720         if( (pExpr->flags & EP_ExpCollate) ){
65721           assert( pExpr->pColl!=0 );
65722           *apColl = pExpr->pColl;
65723         }else{
65724           *apColl = aCopy[pExpr->iColumn];
65725         }
65726         *pSortOrder = pOTerm->sortOrder;
65727       }
65728       assert( p->pRightmost==p );
65729       assert( p->addrOpenEphm[2]>=0 );
65730       addr = p->addrOpenEphm[2];
65731       sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
65732       pKeyInfo->nField = nOrderByExpr;
65733       sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
65734       pKeyInfo = 0;
65735       generateSortTail(pParse, p, v, p->pEList->nExpr, &dest);
65736     }
65737
65738     sqlite3_free(pKeyInfo);
65739   }
65740
65741 multi_select_end:
65742   pDest->iMem = dest.iMem;
65743   pDest->nMem = dest.nMem;
65744   return rc;
65745 }
65746 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
65747
65748 #ifndef SQLITE_OMIT_VIEW
65749 /* Forward Declarations */
65750 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
65751 static void substSelect(sqlite3*, Select *, int, ExprList *);
65752
65753 /*
65754 ** Scan through the expression pExpr.  Replace every reference to
65755 ** a column in table number iTable with a copy of the iColumn-th
65756 ** entry in pEList.  (But leave references to the ROWID column 
65757 ** unchanged.)
65758 **
65759 ** This routine is part of the flattening procedure.  A subquery
65760 ** whose result set is defined by pEList appears as entry in the
65761 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
65762 ** FORM clause entry is iTable.  This routine make the necessary 
65763 ** changes to pExpr so that it refers directly to the source table
65764 ** of the subquery rather the result set of the subquery.
65765 */
65766 static void substExpr(
65767   sqlite3 *db,        /* Report malloc errors to this connection */
65768   Expr *pExpr,        /* Expr in which substitution occurs */
65769   int iTable,         /* Table to be substituted */
65770   ExprList *pEList    /* Substitute expressions */
65771 ){
65772   if( pExpr==0 ) return;
65773   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
65774     if( pExpr->iColumn<0 ){
65775       pExpr->op = TK_NULL;
65776     }else{
65777       Expr *pNew;
65778       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
65779       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
65780       pNew = pEList->a[pExpr->iColumn].pExpr;
65781       assert( pNew!=0 );
65782       pExpr->op = pNew->op;
65783       assert( pExpr->pLeft==0 );
65784       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
65785       assert( pExpr->pRight==0 );
65786       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
65787       assert( pExpr->pList==0 );
65788       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
65789       pExpr->iTable = pNew->iTable;
65790       pExpr->pTab = pNew->pTab;
65791       pExpr->iColumn = pNew->iColumn;
65792       pExpr->iAgg = pNew->iAgg;
65793       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
65794       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
65795       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
65796       pExpr->flags = pNew->flags;
65797     }
65798   }else{
65799     substExpr(db, pExpr->pLeft, iTable, pEList);
65800     substExpr(db, pExpr->pRight, iTable, pEList);
65801     substSelect(db, pExpr->pSelect, iTable, pEList);
65802     substExprList(db, pExpr->pList, iTable, pEList);
65803   }
65804 }
65805 static void substExprList(
65806   sqlite3 *db,         /* Report malloc errors here */
65807   ExprList *pList,     /* List to scan and in which to make substitutes */
65808   int iTable,          /* Table to be substituted */
65809   ExprList *pEList     /* Substitute values */
65810 ){
65811   int i;
65812   if( pList==0 ) return;
65813   for(i=0; i<pList->nExpr; i++){
65814     substExpr(db, pList->a[i].pExpr, iTable, pEList);
65815   }
65816 }
65817 static void substSelect(
65818   sqlite3 *db,         /* Report malloc errors here */
65819   Select *p,           /* SELECT statement in which to make substitutions */
65820   int iTable,          /* Table to be replaced */
65821   ExprList *pEList     /* Substitute values */
65822 ){
65823   if( !p ) return;
65824   substExprList(db, p->pEList, iTable, pEList);
65825   substExprList(db, p->pGroupBy, iTable, pEList);
65826   substExprList(db, p->pOrderBy, iTable, pEList);
65827   substExpr(db, p->pHaving, iTable, pEList);
65828   substExpr(db, p->pWhere, iTable, pEList);
65829   substSelect(db, p->pPrior, iTable, pEList);
65830 }
65831 #endif /* !defined(SQLITE_OMIT_VIEW) */
65832
65833 #ifndef SQLITE_OMIT_VIEW
65834 /*
65835 ** This routine attempts to flatten subqueries in order to speed
65836 ** execution.  It returns 1 if it makes changes and 0 if no flattening
65837 ** occurs.
65838 **
65839 ** To understand the concept of flattening, consider the following
65840 ** query:
65841 **
65842 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
65843 **
65844 ** The default way of implementing this query is to execute the
65845 ** subquery first and store the results in a temporary table, then
65846 ** run the outer query on that temporary table.  This requires two
65847 ** passes over the data.  Furthermore, because the temporary table
65848 ** has no indices, the WHERE clause on the outer query cannot be
65849 ** optimized.
65850 **
65851 ** This routine attempts to rewrite queries such as the above into
65852 ** a single flat select, like this:
65853 **
65854 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
65855 **
65856 ** The code generated for this simpification gives the same result
65857 ** but only has to scan the data once.  And because indices might 
65858 ** exist on the table t1, a complete scan of the data might be
65859 ** avoided.
65860 **
65861 ** Flattening is only attempted if all of the following are true:
65862 **
65863 **   (1)  The subquery and the outer query do not both use aggregates.
65864 **
65865 **   (2)  The subquery is not an aggregate or the outer query is not a join.
65866 **
65867 **   (3)  The subquery is not the right operand of a left outer join, or
65868 **        the subquery is not itself a join.  (Ticket #306)
65869 **
65870 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
65871 **
65872 **   (5)  The subquery is not DISTINCT or the outer query does not use
65873 **        aggregates.
65874 **
65875 **   (6)  The subquery does not use aggregates or the outer query is not
65876 **        DISTINCT.
65877 **
65878 **   (7)  The subquery has a FROM clause.
65879 **
65880 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
65881 **
65882 **   (9)  The subquery does not use LIMIT or the outer query does not use
65883 **        aggregates.
65884 **
65885 **  (10)  The subquery does not use aggregates or the outer query does not
65886 **        use LIMIT.
65887 **
65888 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
65889 **
65890 **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
65891 **        subquery has no WHERE clause.  (added by ticket #350)
65892 **
65893 **  (13)  The subquery and outer query do not both use LIMIT
65894 **
65895 **  (14)  The subquery does not use OFFSET
65896 **
65897 **  (15)  The outer query is not part of a compound select or the
65898 **        subquery does not have both an ORDER BY and a LIMIT clause.
65899 **        (See ticket #2339)
65900 **
65901 **  (16)  The outer query is not an aggregate or the subquery does
65902 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
65903 **        until we introduced the group_concat() function.  
65904 **
65905 ** In this routine, the "p" parameter is a pointer to the outer query.
65906 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
65907 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
65908 **
65909 ** If flattening is not attempted, this routine is a no-op and returns 0.
65910 ** If flattening is attempted this routine returns 1.
65911 **
65912 ** All of the expression analysis must occur on both the outer query and
65913 ** the subquery before this routine runs.
65914 */
65915 static int flattenSubquery(
65916   sqlite3 *db,         /* Database connection */
65917   Select *p,           /* The parent or outer SELECT statement */
65918   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
65919   int isAgg,           /* True if outer SELECT uses aggregate functions */
65920   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
65921 ){
65922   Select *pSub;       /* The inner query or "subquery" */
65923   SrcList *pSrc;      /* The FROM clause of the outer query */
65924   SrcList *pSubSrc;   /* The FROM clause of the subquery */
65925   ExprList *pList;    /* The result set of the outer query */
65926   int iParent;        /* VDBE cursor number of the pSub result set temp table */
65927   int i;              /* Loop counter */
65928   Expr *pWhere;                    /* The WHERE clause */
65929   struct SrcList_item *pSubitem;   /* The subquery */
65930
65931   /* Check to see if flattening is permitted.  Return 0 if not.
65932   */
65933   if( p==0 ) return 0;
65934   pSrc = p->pSrc;
65935   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
65936   pSubitem = &pSrc->a[iFrom];
65937   pSub = pSubitem->pSelect;
65938   assert( pSub!=0 );
65939   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
65940   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
65941   pSubSrc = pSub->pSrc;
65942   assert( pSubSrc );
65943   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
65944   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
65945   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
65946   ** became arbitrary expressions, we were forced to add restrictions (13)
65947   ** and (14). */
65948   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
65949   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
65950   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
65951     return 0;                                            /* Restriction (15) */
65952   }
65953   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
65954   if( (pSub->isDistinct || pSub->pLimit) 
65955          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
65956      return 0;       
65957   }
65958   if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
65959   if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
65960      return 0;                                           /* Restriction (11) */
65961   }
65962   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
65963
65964   /* Restriction 3:  If the subquery is a join, make sure the subquery is 
65965   ** not used as the right operand of an outer join.  Examples of why this
65966   ** is not allowed:
65967   **
65968   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
65969   **
65970   ** If we flatten the above, we would get
65971   **
65972   **         (t1 LEFT OUTER JOIN t2) JOIN t3
65973   **
65974   ** which is not at all the same thing.
65975   */
65976   if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
65977     return 0;
65978   }
65979
65980   /* Restriction 12:  If the subquery is the right operand of a left outer
65981   ** join, make sure the subquery has no WHERE clause.
65982   ** An examples of why this is not allowed:
65983   **
65984   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
65985   **
65986   ** If we flatten the above, we would get
65987   **
65988   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
65989   **
65990   ** But the t2.x>0 test will always fail on a NULL row of t2, which
65991   ** effectively converts the OUTER JOIN into an INNER JOIN.
65992   */
65993   if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
65994     return 0;
65995   }
65996
65997   /* If we reach this point, it means flattening is permitted for the
65998   ** iFrom-th entry of the FROM clause in the outer query.
65999   */
66000
66001   /* Move all of the FROM elements of the subquery into the
66002   ** the FROM clause of the outer query.  Before doing this, remember
66003   ** the cursor number for the original outer query FROM element in
66004   ** iParent.  The iParent cursor will never be used.  Subsequent code
66005   ** will scan expressions looking for iParent references and replace
66006   ** those references with expressions that resolve to the subquery FROM
66007   ** elements we are now copying in.
66008   */
66009   iParent = pSubitem->iCursor;
66010   {
66011     int nSubSrc = pSubSrc->nSrc;
66012     int jointype = pSubitem->jointype;
66013
66014     sqlite3DeleteTable(pSubitem->pTab);
66015     sqlite3_free(pSubitem->zDatabase);
66016     sqlite3_free(pSubitem->zName);
66017     sqlite3_free(pSubitem->zAlias);
66018     pSubitem->pTab = 0;
66019     pSubitem->zDatabase = 0;
66020     pSubitem->zName = 0;
66021     pSubitem->zAlias = 0;
66022     if( nSubSrc>1 ){
66023       int extra = nSubSrc - 1;
66024       for(i=1; i<nSubSrc; i++){
66025         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
66026         if( pSrc==0 ){
66027           p->pSrc = 0;
66028           return 1;
66029         }
66030       }
66031       p->pSrc = pSrc;
66032       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
66033         pSrc->a[i] = pSrc->a[i-extra];
66034       }
66035     }
66036     for(i=0; i<nSubSrc; i++){
66037       pSrc->a[i+iFrom] = pSubSrc->a[i];
66038       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
66039     }
66040     pSrc->a[iFrom].jointype = jointype;
66041   }
66042
66043   /* Now begin substituting subquery result set expressions for 
66044   ** references to the iParent in the outer query.
66045   ** 
66046   ** Example:
66047   **
66048   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
66049   **   \                     \_____________ subquery __________/          /
66050   **    \_____________________ outer query ______________________________/
66051   **
66052   ** We look at every expression in the outer query and every place we see
66053   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
66054   */
66055   pList = p->pEList;
66056   for(i=0; i<pList->nExpr; i++){
66057     Expr *pExpr;
66058     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
66059       pList->a[i].zName = 
66060              sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
66061     }
66062   }
66063   substExprList(db, p->pEList, iParent, pSub->pEList);
66064   if( isAgg ){
66065     substExprList(db, p->pGroupBy, iParent, pSub->pEList);
66066     substExpr(db, p->pHaving, iParent, pSub->pEList);
66067   }
66068   if( pSub->pOrderBy ){
66069     assert( p->pOrderBy==0 );
66070     p->pOrderBy = pSub->pOrderBy;
66071     pSub->pOrderBy = 0;
66072   }else if( p->pOrderBy ){
66073     substExprList(db, p->pOrderBy, iParent, pSub->pEList);
66074   }
66075   if( pSub->pWhere ){
66076     pWhere = sqlite3ExprDup(db, pSub->pWhere);
66077   }else{
66078     pWhere = 0;
66079   }
66080   if( subqueryIsAgg ){
66081     assert( p->pHaving==0 );
66082     p->pHaving = p->pWhere;
66083     p->pWhere = pWhere;
66084     substExpr(db, p->pHaving, iParent, pSub->pEList);
66085     p->pHaving = sqlite3ExprAnd(db, p->pHaving, 
66086                                 sqlite3ExprDup(db, pSub->pHaving));
66087     assert( p->pGroupBy==0 );
66088     p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
66089   }else{
66090     substExpr(db, p->pWhere, iParent, pSub->pEList);
66091     p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
66092   }
66093
66094   /* The flattened query is distinct if either the inner or the
66095   ** outer query is distinct. 
66096   */
66097   p->isDistinct = p->isDistinct || pSub->isDistinct;
66098
66099   /*
66100   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
66101   **
66102   ** One is tempted to try to add a and b to combine the limits.  But this
66103   ** does not work if either limit is negative.
66104   */
66105   if( pSub->pLimit ){
66106     p->pLimit = pSub->pLimit;
66107     pSub->pLimit = 0;
66108   }
66109
66110   /* Finially, delete what is left of the subquery and return
66111   ** success.
66112   */
66113   sqlite3SelectDelete(pSub);
66114   return 1;
66115 }
66116 #endif /* SQLITE_OMIT_VIEW */
66117
66118 /*
66119 ** Analyze the SELECT statement passed as an argument to see if it
66120 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
66121 ** it is, or 0 otherwise. At present, a query is considered to be
66122 ** a min()/max() query if:
66123 **
66124 **   1. There is a single object in the FROM clause.
66125 **
66126 **   2. There is a single expression in the result set, and it is
66127 **      either min(x) or max(x), where x is a column reference.
66128 */
66129 static int minMaxQuery(Parse *pParse, Select *p){
66130   Expr *pExpr;
66131   ExprList *pEList = p->pEList;
66132
66133   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
66134   pExpr = pEList->a[0].pExpr;
66135   pEList = pExpr->pList;
66136   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
66137   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
66138   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
66139   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
66140     return WHERE_ORDERBY_MIN;
66141   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
66142     return WHERE_ORDERBY_MAX;
66143   }
66144   return WHERE_ORDERBY_NORMAL;
66145 }
66146
66147 /*
66148 ** This routine resolves any names used in the result set of the
66149 ** supplied SELECT statement. If the SELECT statement being resolved
66150 ** is a sub-select, then pOuterNC is a pointer to the NameContext 
66151 ** of the parent SELECT.
66152 */
66153 SQLITE_PRIVATE int sqlite3SelectResolve(
66154   Parse *pParse,         /* The parser context */
66155   Select *p,             /* The SELECT statement being coded. */
66156   NameContext *pOuterNC  /* The outer name context. May be NULL. */
66157 ){
66158   ExprList *pEList;          /* Result set. */
66159   int i;                     /* For-loop variable used in multiple places */
66160   NameContext sNC;           /* Local name-context */
66161   ExprList *pGroupBy;        /* The group by clause */
66162
66163   /* If this routine has run before, return immediately. */
66164   if( p->isResolved ){
66165     assert( !pOuterNC );
66166     return SQLITE_OK;
66167   }
66168   p->isResolved = 1;
66169
66170   /* If there have already been errors, do nothing. */
66171   if( pParse->nErr>0 ){
66172     return SQLITE_ERROR;
66173   }
66174
66175   /* Prepare the select statement. This call will allocate all cursors
66176   ** required to handle the tables and subqueries in the FROM clause.
66177   */
66178   if( prepSelectStmt(pParse, p) ){
66179     return SQLITE_ERROR;
66180   }
66181
66182   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
66183   ** are not allowed to refer to any names, so pass an empty NameContext.
66184   */
66185   memset(&sNC, 0, sizeof(sNC));
66186   sNC.pParse = pParse;
66187   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
66188       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
66189     return SQLITE_ERROR;
66190   }
66191
66192   /* Set up the local name-context to pass to ExprResolveNames() to
66193   ** resolve the expression-list.
66194   */
66195   sNC.allowAgg = 1;
66196   sNC.pSrcList = p->pSrc;
66197   sNC.pNext = pOuterNC;
66198
66199   /* Resolve names in the result set. */
66200   pEList = p->pEList;
66201   if( !pEList ) return SQLITE_ERROR;
66202   for(i=0; i<pEList->nExpr; i++){
66203     Expr *pX = pEList->a[i].pExpr;
66204     if( sqlite3ExprResolveNames(&sNC, pX) ){
66205       return SQLITE_ERROR;
66206     }
66207   }
66208
66209   /* If there are no aggregate functions in the result-set, and no GROUP BY 
66210   ** expression, do not allow aggregates in any of the other expressions.
66211   */
66212   assert( !p->isAgg );
66213   pGroupBy = p->pGroupBy;
66214   if( pGroupBy || sNC.hasAgg ){
66215     p->isAgg = 1;
66216   }else{
66217     sNC.allowAgg = 0;
66218   }
66219
66220   /* If a HAVING clause is present, then there must be a GROUP BY clause.
66221   */
66222   if( p->pHaving && !pGroupBy ){
66223     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
66224     return SQLITE_ERROR;
66225   }
66226
66227   /* Add the expression list to the name-context before parsing the
66228   ** other expressions in the SELECT statement. This is so that
66229   ** expressions in the WHERE clause (etc.) can refer to expressions by
66230   ** aliases in the result set.
66231   **
66232   ** Minor point: If this is the case, then the expression will be
66233   ** re-evaluated for each reference to it.
66234   */
66235   sNC.pEList = p->pEList;
66236   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
66237      sqlite3ExprResolveNames(&sNC, p->pHaving) ){
66238     return SQLITE_ERROR;
66239   }
66240   if( p->pPrior==0 ){
66241     if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){
66242       return SQLITE_ERROR;
66243     }
66244   }
66245   if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){
66246     return SQLITE_ERROR;
66247   }
66248
66249   if( pParse->db->mallocFailed ){
66250     return SQLITE_NOMEM;
66251   }
66252
66253   /* Make sure the GROUP BY clause does not contain aggregate functions.
66254   */
66255   if( pGroupBy ){
66256     struct ExprList_item *pItem;
66257   
66258     for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
66259       if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
66260         sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
66261             "the GROUP BY clause");
66262         return SQLITE_ERROR;
66263       }
66264     }
66265   }
66266
66267   /* If this is one SELECT of a compound, be sure to resolve names
66268   ** in the other SELECTs.
66269   */
66270   if( p->pPrior ){
66271     return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
66272   }else{
66273     return SQLITE_OK;
66274   }
66275 }
66276
66277 /*
66278 ** Reset the aggregate accumulator.
66279 **
66280 ** The aggregate accumulator is a set of memory cells that hold
66281 ** intermediate results while calculating an aggregate.  This
66282 ** routine simply stores NULLs in all of those memory cells.
66283 */
66284 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
66285   Vdbe *v = pParse->pVdbe;
66286   int i;
66287   struct AggInfo_func *pFunc;
66288   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
66289     return;
66290   }
66291   for(i=0; i<pAggInfo->nColumn; i++){
66292     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
66293   }
66294   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
66295     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
66296     if( pFunc->iDistinct>=0 ){
66297       Expr *pE = pFunc->pExpr;
66298       if( pE->pList==0 || pE->pList->nExpr!=1 ){
66299         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
66300            "by an expression");
66301         pFunc->iDistinct = -1;
66302       }else{
66303         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
66304         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
66305                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
66306       }
66307     }
66308   }
66309 }
66310
66311 /*
66312 ** Invoke the OP_AggFinalize opcode for every aggregate function
66313 ** in the AggInfo structure.
66314 */
66315 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
66316   Vdbe *v = pParse->pVdbe;
66317   int i;
66318   struct AggInfo_func *pF;
66319   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
66320     ExprList *pList = pF->pExpr->pList;
66321     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
66322                       (void*)pF->pFunc, P4_FUNCDEF);
66323   }
66324 }
66325
66326 /*
66327 ** Update the accumulator memory cells for an aggregate based on
66328 ** the current cursor position.
66329 */
66330 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
66331   Vdbe *v = pParse->pVdbe;
66332   int i;
66333   struct AggInfo_func *pF;
66334   struct AggInfo_col *pC;
66335
66336   pAggInfo->directMode = 1;
66337   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
66338     int nArg;
66339     int addrNext = 0;
66340     int regAgg;
66341     ExprList *pList = pF->pExpr->pList;
66342     if( pList ){
66343       nArg = pList->nExpr;
66344       regAgg = sqlite3GetTempRange(pParse, nArg);
66345       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
66346     }else{
66347       nArg = 0;
66348       regAgg = 0;
66349     }
66350     if( pF->iDistinct>=0 ){
66351       addrNext = sqlite3VdbeMakeLabel(v);
66352       assert( nArg==1 );
66353       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
66354     }
66355     if( pF->pFunc->needCollSeq ){
66356       CollSeq *pColl = 0;
66357       struct ExprList_item *pItem;
66358       int j;
66359       assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
66360       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
66361         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
66362       }
66363       if( !pColl ){
66364         pColl = pParse->db->pDfltColl;
66365       }
66366       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
66367     }
66368     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
66369                       (void*)pF->pFunc, P4_FUNCDEF);
66370     sqlite3VdbeChangeP5(v, nArg);
66371     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
66372     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
66373     if( addrNext ){
66374       sqlite3VdbeResolveLabel(v, addrNext);
66375     }
66376   }
66377   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
66378     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
66379   }
66380   pAggInfo->directMode = 0;
66381 }
66382
66383 #if 0
66384 /*
66385 ** This function is used when a SELECT statement is used to create a
66386 ** temporary table for iterating through when running an INSTEAD OF
66387 ** UPDATE or INSTEAD OF DELETE trigger. 
66388 **
66389 ** If possible, the SELECT statement is modified so that NULL values
66390 ** are stored in the temporary table for all columns for which the 
66391 ** corresponding bit in argument mask is not set. If mask takes the
66392 ** special value 0xffffffff, then all columns are populated.
66393 */
66394 SQLITE_PRIVATE void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){
66395   if( p && !p->pPrior && !p->isDistinct && mask!=0xffffffff ){
66396     ExprList *pEList;
66397     int i;
66398     sqlite3SelectResolve(pParse, p, 0);
66399     pEList = p->pEList;
66400     for(i=0; pEList && i<pEList->nExpr && i<32; i++){
66401       if( !(mask&((u32)1<<i)) ){
66402         sqlite3ExprDelete(pEList->a[i].pExpr);
66403         pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0);
66404       }
66405     }
66406   }
66407 }
66408 #endif
66409
66410 /*
66411 ** Generate code for the given SELECT statement.
66412 **
66413 ** The results are distributed in various ways depending on the
66414 ** contents of the SelectDest structure pointed to by argument pDest
66415 ** as follows:
66416 **
66417 **     pDest->eDest    Result
66418 **     ------------    -------------------------------------------
66419 **     SRT_Callback    Invoke the callback for each row of the result.
66420 **
66421 **     SRT_Mem         Store first result in memory cell pDest->iParm
66422 **
66423 **     SRT_Set         Store non-null results as keys of table pDest->iParm. 
66424 **                     Apply the affinity pDest->affinity before storing them.
66425 **
66426 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
66427 **
66428 **     SRT_Except      Remove results from the temporary table pDest->iParm.
66429 **
66430 **     SRT_Table       Store results in temporary table pDest->iParm
66431 **
66432 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
66433 **                     the result there. The cursor is left open after
66434 **                     returning.
66435 **
66436 **     SRT_Subroutine  For each row returned, push the results onto the
66437 **                     vdbe stack and call the subroutine (via OP_Gosub)
66438 **                     at address pDest->iParm.
66439 **
66440 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
66441 **                     set is not empty.
66442 **
66443 **     SRT_Discard     Throw the results away.
66444 **
66445 ** See the selectInnerLoop() function for a canonical listing of the 
66446 ** allowed values of eDest and their meanings.
66447 **
66448 ** This routine returns the number of errors.  If any errors are
66449 ** encountered, then an appropriate error message is left in
66450 ** pParse->zErrMsg.
66451 **
66452 ** This routine does NOT free the Select structure passed in.  The
66453 ** calling function needs to do that.
66454 **
66455 ** The pParent, parentTab, and *pParentAgg fields are filled in if this
66456 ** SELECT is a subquery.  This routine may try to combine this SELECT
66457 ** with its parent to form a single flat query.  In so doing, it might
66458 ** change the parent query from a non-aggregate to an aggregate query.
66459 ** For that reason, the pParentAgg flag is passed as a pointer, so it
66460 ** can be changed.
66461 **
66462 ** Example 1:   The meaning of the pParent parameter.
66463 **
66464 **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
66465 **    \                      \_______ subquery _______/        /
66466 **     \                                                      /
66467 **      \____________________ outer query ___________________/
66468 **
66469 ** This routine is called for the outer query first.   For that call,
66470 ** pParent will be NULL.  During the processing of the outer query, this 
66471 ** routine is called recursively to handle the subquery.  For the recursive
66472 ** call, pParent will point to the outer query.  Because the subquery is
66473 ** the second element in a three-way join, the parentTab parameter will
66474 ** be 1 (the 2nd value of a 0-indexed array.)
66475 */
66476 SQLITE_PRIVATE int sqlite3Select(
66477   Parse *pParse,         /* The parser context */
66478   Select *p,             /* The SELECT statement being coded. */
66479   SelectDest *pDest,     /* What to do with the query results */
66480   Select *pParent,       /* Another SELECT for which this is a sub-query */
66481   int parentTab,         /* Index in pParent->pSrc of this query */
66482   int *pParentAgg,       /* True if pParent uses aggregate functions */
66483   char *aff              /* If eDest is SRT_Union, the affinity string */
66484 ){
66485   int i, j;              /* Loop counters */
66486   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
66487   Vdbe *v;               /* The virtual machine under construction */
66488   int isAgg;             /* True for select lists like "count(*)" */
66489   ExprList *pEList;      /* List of columns to extract. */
66490   SrcList *pTabList;     /* List of tables to select from */
66491   Expr *pWhere;          /* The WHERE clause.  May be NULL */
66492   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
66493   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
66494   Expr *pHaving;         /* The HAVING clause.  May be NULL */
66495   int isDistinct;        /* True if the DISTINCT keyword is present */
66496   int distinct;          /* Table to use for the distinct set */
66497   int rc = 1;            /* Value to return from this function */
66498   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
66499   AggInfo sAggInfo;      /* Information used by aggregate queries */
66500   int iEnd;              /* Address of the end of the query */
66501   sqlite3 *db;           /* The database connection */
66502
66503   db = pParse->db;
66504   if( p==0 || db->mallocFailed || pParse->nErr ){
66505     return 1;
66506   }
66507   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
66508   memset(&sAggInfo, 0, sizeof(sAggInfo));
66509
66510   pOrderBy = p->pOrderBy;
66511   if( IgnorableOrderby(pDest) ){
66512     p->pOrderBy = 0;
66513
66514     /* In these cases the DISTINCT operator makes no difference to the
66515     ** results, so remove it if it were specified.
66516     */
66517     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
66518            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
66519     p->isDistinct = 0;
66520   }
66521   if( sqlite3SelectResolve(pParse, p, 0) ){
66522     goto select_end;
66523   }
66524   p->pOrderBy = pOrderBy;
66525
66526 #ifndef SQLITE_OMIT_COMPOUND_SELECT
66527   /* If there is are a sequence of queries, do the earlier ones first.
66528   */
66529   if( p->pPrior ){
66530     if( p->pRightmost==0 ){
66531       Select *pLoop, *pRight = 0;
66532       int cnt = 0;
66533       int mxSelect;
66534       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
66535         pLoop->pRightmost = p;
66536         pLoop->pNext = pRight;
66537         pRight = pLoop;
66538       }
66539       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
66540       if( mxSelect && cnt>mxSelect ){
66541         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
66542         return 1;
66543       }
66544     }
66545     return multiSelect(pParse, p, pDest, aff);
66546   }
66547 #endif
66548
66549   /* Make local copies of the parameters for this query.
66550   */
66551   pTabList = p->pSrc;
66552   pWhere = p->pWhere;
66553   pGroupBy = p->pGroupBy;
66554   pHaving = p->pHaving;
66555   isAgg = p->isAgg;
66556   isDistinct = p->isDistinct;
66557   pEList = p->pEList;
66558   if( pEList==0 ) goto select_end;
66559
66560   /* 
66561   ** Do not even attempt to generate any code if we have already seen
66562   ** errors before this routine starts.
66563   */
66564   if( pParse->nErr>0 ) goto select_end;
66565
66566   /* If writing to memory or generating a set
66567   ** only a single column may be output.
66568   */
66569 #ifndef SQLITE_OMIT_SUBQUERY
66570   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
66571     goto select_end;
66572   }
66573 #endif
66574
66575   /* ORDER BY is ignored for some destinations.
66576   */
66577   if( IgnorableOrderby(pDest) ){
66578     pOrderBy = 0;
66579   }
66580
66581   /* Begin generating code.
66582   */
66583   v = sqlite3GetVdbe(pParse);
66584   if( v==0 ) goto select_end;
66585
66586   /* Generate code for all sub-queries in the FROM clause
66587   */
66588 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
66589   for(i=0; i<pTabList->nSrc; i++){
66590     const char *zSavedAuthContext = 0;
66591     int needRestoreContext;
66592     struct SrcList_item *pItem = &pTabList->a[i];
66593     SelectDest dest;
66594
66595     if( pItem->pSelect==0 || pItem->isPopulated ) continue;
66596     if( pItem->zName!=0 ){
66597       zSavedAuthContext = pParse->zAuthContext;
66598       pParse->zAuthContext = pItem->zName;
66599       needRestoreContext = 1;
66600     }else{
66601       needRestoreContext = 0;
66602     }
66603     /* Increment Parse.nHeight by the height of the largest expression
66604     ** tree refered to by this, the parent select. The child select
66605     ** may contain expression trees of at most
66606     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
66607     ** more conservative than necessary, but much easier than enforcing
66608     ** an exact limit.
66609     */
66610     pParse->nHeight += sqlite3SelectExprHeight(p);
66611     sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
66612     sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0);
66613     if( db->mallocFailed ){
66614       goto select_end;
66615     }
66616     pParse->nHeight -= sqlite3SelectExprHeight(p);
66617     if( needRestoreContext ){
66618       pParse->zAuthContext = zSavedAuthContext;
66619     }
66620     pTabList = p->pSrc;
66621     pWhere = p->pWhere;
66622     if( !IgnorableOrderby(pDest) ){
66623       pOrderBy = p->pOrderBy;
66624     }
66625     pGroupBy = p->pGroupBy;
66626     pHaving = p->pHaving;
66627     isDistinct = p->isDistinct;
66628   }
66629 #endif
66630
66631   /* Check to see if this is a subquery that can be "flattened" into its parent.
66632   ** If flattening is a possiblity, do so and return immediately.  
66633   */
66634 #ifndef SQLITE_OMIT_VIEW
66635   if( pParent && pParentAgg &&
66636       flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
66637     if( isAgg ) *pParentAgg = 1;
66638     goto select_end;
66639   }
66640 #endif
66641
66642   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
66643   ** GROUP BY may use an index, DISTINCT never does.
66644   */
66645   if( p->isDistinct && !p->isAgg && !p->pGroupBy ){
66646     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
66647     pGroupBy = p->pGroupBy;
66648     p->isDistinct = 0;
66649     isDistinct = 0;
66650   }
66651
66652   /* If there is an ORDER BY clause, then this sorting
66653   ** index might end up being unused if the data can be 
66654   ** extracted in pre-sorted order.  If that is the case, then the
66655   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
66656   ** we figure out that the sorting index is not needed.  The addrSortIndex
66657   ** variable is used to facilitate that change.
66658   */
66659   if( pOrderBy ){
66660     KeyInfo *pKeyInfo;
66661     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
66662     pOrderBy->iECursor = pParse->nTab++;
66663     p->addrOpenEphm[2] = addrSortIndex =
66664       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
66665                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
66666                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
66667   }else{
66668     addrSortIndex = -1;
66669   }
66670
66671   /* If the output is destined for a temporary table, open that table.
66672   */
66673   if( pDest->eDest==SRT_EphemTab ){
66674     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
66675   }
66676
66677   /* Set the limiter.
66678   */
66679   iEnd = sqlite3VdbeMakeLabel(v);
66680   computeLimitRegisters(pParse, p, iEnd);
66681
66682   /* Open a virtual index to use for the distinct set.
66683   */
66684   if( isDistinct ){
66685     KeyInfo *pKeyInfo;
66686     assert( isAgg || pGroupBy );
66687     distinct = pParse->nTab++;
66688     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
66689     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
66690                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
66691   }else{
66692     distinct = -1;
66693   }
66694
66695   /* Aggregate and non-aggregate queries are handled differently */
66696   if( !isAgg && pGroupBy==0 ){
66697     /* This case is for non-aggregate queries
66698     ** Begin the database scan
66699     */
66700     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
66701     if( pWInfo==0 ) goto select_end;
66702
66703     /* If sorting index that was created by a prior OP_OpenEphemeral 
66704     ** instruction ended up not being needed, then change the OP_OpenEphemeral
66705     ** into an OP_Noop.
66706     */
66707     if( addrSortIndex>=0 && pOrderBy==0 ){
66708       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
66709       p->addrOpenEphm[2] = -1;
66710     }
66711
66712     /* Use the standard inner loop
66713     */
66714     assert(!isDistinct);
66715     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
66716                     pWInfo->iContinue, pWInfo->iBreak, aff);
66717
66718     /* End the database scan loop.
66719     */
66720     sqlite3WhereEnd(pWInfo);
66721   }else{
66722     /* This is the processing for aggregate queries */
66723     NameContext sNC;    /* Name context for processing aggregate information */
66724     int iAMem;          /* First Mem address for storing current GROUP BY */
66725     int iBMem;          /* First Mem address for previous GROUP BY */
66726     int iUseFlag;       /* Mem address holding flag indicating that at least
66727                         ** one row of the input to the aggregator has been
66728                         ** processed */
66729     int iAbortFlag;     /* Mem address which causes query abort if positive */
66730     int groupBySort;    /* Rows come from source in GROUP BY order */
66731
66732
66733     /* The following variables hold addresses or labels for parts of the
66734     ** virtual machine program we are putting together */
66735     int addrOutputRow;      /* Start of subroutine that outputs a result row */
66736     int addrSetAbort;       /* Set the abort flag and return */
66737     int addrInitializeLoop; /* Start of code that initializes the input loop */
66738     int addrTopOfLoop;      /* Top of the input loop */
66739     int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
66740     int addrProcessRow;     /* Code to process a single input row */
66741     int addrEnd;            /* End of all processing */
66742     int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
66743     int addrReset;          /* Subroutine for resetting the accumulator */
66744
66745     addrEnd = sqlite3VdbeMakeLabel(v);
66746
66747     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
66748     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
66749     ** SELECT statement.
66750     */
66751     memset(&sNC, 0, sizeof(sNC));
66752     sNC.pParse = pParse;
66753     sNC.pSrcList = pTabList;
66754     sNC.pAggInfo = &sAggInfo;
66755     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
66756     sAggInfo.pGroupBy = pGroupBy;
66757     sqlite3ExprAnalyzeAggList(&sNC, pEList);
66758     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
66759     if( pHaving ){
66760       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
66761     }
66762     sAggInfo.nAccumulator = sAggInfo.nColumn;
66763     for(i=0; i<sAggInfo.nFunc; i++){
66764       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
66765     }
66766     if( db->mallocFailed ) goto select_end;
66767
66768     /* Processing for aggregates with GROUP BY is very different and
66769     ** much more complex than aggregates without a GROUP BY.
66770     */
66771     if( pGroupBy ){
66772       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
66773
66774       /* Create labels that we will be needing
66775       */
66776      
66777       addrInitializeLoop = sqlite3VdbeMakeLabel(v);
66778       addrGroupByChange = sqlite3VdbeMakeLabel(v);
66779       addrProcessRow = sqlite3VdbeMakeLabel(v);
66780
66781       /* If there is a GROUP BY clause we might need a sorting index to
66782       ** implement it.  Allocate that sorting index now.  If it turns out
66783       ** that we do not need it after all, the OpenEphemeral instruction
66784       ** will be converted into a Noop.  
66785       */
66786       sAggInfo.sortingIdx = pParse->nTab++;
66787       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
66788       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
66789           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
66790           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
66791
66792       /* Initialize memory locations used by GROUP BY aggregate processing
66793       */
66794       iUseFlag = ++pParse->nMem;
66795       iAbortFlag = ++pParse->nMem;
66796       iAMem = pParse->nMem + 1;
66797       pParse->nMem += pGroupBy->nExpr;
66798       iBMem = pParse->nMem + 1;
66799       pParse->nMem += pGroupBy->nExpr;
66800       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
66801       VdbeComment((v, "clear abort flag"));
66802       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
66803       VdbeComment((v, "indicate accumulator empty"));
66804       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop);
66805
66806       /* Generate a subroutine that outputs a single row of the result
66807       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
66808       ** is less than or equal to zero, the subroutine is a no-op.  If
66809       ** the processing calls for the query to abort, this subroutine
66810       ** increments the iAbortFlag memory location before returning in
66811       ** order to signal the caller to abort.
66812       */
66813       addrSetAbort = sqlite3VdbeCurrentAddr(v);
66814       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
66815       VdbeComment((v, "set abort flag"));
66816       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
66817       addrOutputRow = sqlite3VdbeCurrentAddr(v);
66818       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
66819       VdbeComment((v, "Groupby result generator entry point"));
66820       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
66821       finalizeAggFunctions(pParse, &sAggInfo);
66822       if( pHaving ){
66823         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
66824       }
66825       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
66826                       distinct, pDest,
66827                       addrOutputRow+1, addrSetAbort, aff);
66828       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
66829       VdbeComment((v, "end groupby result generator"));
66830
66831       /* Generate a subroutine that will reset the group-by accumulator
66832       */
66833       addrReset = sqlite3VdbeCurrentAddr(v);
66834       resetAccumulator(pParse, &sAggInfo);
66835       sqlite3VdbeAddOp2(v, OP_Return, 0, 0);
66836
66837       /* Begin a loop that will extract all source rows in GROUP BY order.
66838       ** This might involve two separate loops with an OP_Sort in between, or
66839       ** it might be a single loop that uses an index to extract information
66840       ** in the right order to begin with.
66841       */
66842       sqlite3VdbeResolveLabel(v, addrInitializeLoop);
66843       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
66844       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
66845       if( pWInfo==0 ) goto select_end;
66846       if( pGroupBy==0 ){
66847         /* The optimizer is able to deliver rows in group by order so
66848         ** we do not have to sort.  The OP_OpenEphemeral table will be
66849         ** cancelled later because we still need to use the pKeyInfo
66850         */
66851         pGroupBy = p->pGroupBy;
66852         groupBySort = 0;
66853       }else{
66854         /* Rows are coming out in undetermined order.  We have to push
66855         ** each row into a sorting index, terminate the first loop,
66856         ** then loop over the sorting index in order to get the output
66857         ** in sorted order
66858         */
66859         int regBase;
66860         int regRecord;
66861         int nCol;
66862         int nGroupBy;
66863
66864         groupBySort = 1;
66865         nGroupBy = pGroupBy->nExpr;
66866         nCol = nGroupBy + 1;
66867         j = nGroupBy+1;
66868         for(i=0; i<sAggInfo.nColumn; i++){
66869           if( sAggInfo.aCol[i].iSorterColumn>=j ){
66870             nCol++;
66871             j++;
66872           }
66873         }
66874         regBase = sqlite3GetTempRange(pParse, nCol);
66875         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
66876         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
66877         j = nGroupBy+1;
66878         for(i=0; i<sAggInfo.nColumn; i++){
66879           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
66880           if( pCol->iSorterColumn>=j ){
66881             int r1 = j + regBase;
66882             int r2 = sqlite3ExprCodeGetColumn(pParse, 
66883                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
66884             if( r1!=r2 ){
66885               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
66886             }
66887             j++;
66888           }
66889         }
66890         regRecord = sqlite3GetTempReg(pParse);
66891         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
66892         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
66893         sqlite3ReleaseTempReg(pParse, regRecord);
66894         sqlite3ReleaseTempRange(pParse, regBase, nCol);
66895         sqlite3WhereEnd(pWInfo);
66896         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
66897         VdbeComment((v, "GROUP BY sort"));
66898         sAggInfo.useSortingIdx = 1;
66899       }
66900
66901       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
66902       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
66903       ** Then compare the current GROUP BY terms against the GROUP BY terms
66904       ** from the previous row currently stored in a0, a1, a2...
66905       */
66906       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
66907       for(j=0; j<pGroupBy->nExpr; j++){
66908         if( groupBySort ){
66909           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
66910         }else{
66911           sAggInfo.directMode = 1;
66912           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
66913         }
66914       }
66915       for(j=pGroupBy->nExpr-1; j>=0; j--){
66916         if( j==0 ){
66917           sqlite3VdbeAddOp3(v, OP_Eq, iAMem+j, addrProcessRow, iBMem+j);
66918         }else{
66919           sqlite3VdbeAddOp3(v, OP_Ne, iAMem+j, addrGroupByChange, iBMem+j);
66920         }
66921         sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ);
66922         sqlite3VdbeChangeP5(v, SQLITE_NULLEQUAL);
66923       }
66924
66925       /* Generate code that runs whenever the GROUP BY changes.
66926       ** Change in the GROUP BY are detected by the previous code
66927       ** block.  If there were no changes, this block is skipped.
66928       **
66929       ** This code copies current group by terms in b0,b1,b2,...
66930       ** over to a0,a1,a2.  It then calls the output subroutine
66931       ** and resets the aggregate accumulator registers in preparation
66932       ** for the next GROUP BY batch.
66933       */
66934       sqlite3VdbeResolveLabel(v, addrGroupByChange);
66935       for(j=0; j<pGroupBy->nExpr; j++){
66936         sqlite3ExprCodeMove(pParse, iBMem+j, iAMem+j);
66937       }
66938       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
66939       VdbeComment((v, "output one row"));
66940       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
66941       VdbeComment((v, "check abort flag"));
66942       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset);
66943       VdbeComment((v, "reset accumulator"));
66944
66945       /* Update the aggregate accumulators based on the content of
66946       ** the current row
66947       */
66948       sqlite3VdbeResolveLabel(v, addrProcessRow);
66949       updateAccumulator(pParse, &sAggInfo);
66950       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
66951       VdbeComment((v, "indicate data in accumulator"));
66952
66953       /* End of the loop
66954       */
66955       if( groupBySort ){
66956         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
66957       }else{
66958         sqlite3WhereEnd(pWInfo);
66959         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
66960       }
66961
66962       /* Output the final row of result
66963       */
66964       sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow);
66965       VdbeComment((v, "output final row"));
66966       
66967     } /* endif pGroupBy */
66968     else {
66969       ExprList *pMinMax = 0;
66970       ExprList *pDel = 0;
66971       u8 flag;
66972
66973       /* Check if the query is of one of the following forms:
66974       **
66975       **   SELECT min(x) FROM ...
66976       **   SELECT max(x) FROM ...
66977       **
66978       ** If it is, then ask the code in where.c to attempt to sort results
66979       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
66980       ** If where.c is able to produce results sorted in this order, then
66981       ** add vdbe code to break out of the processing loop after the 
66982       ** first iteration (since the first iteration of the loop is 
66983       ** guaranteed to operate on the row with the minimum or maximum 
66984       ** value of x, the only row required).
66985       **
66986       ** A special flag must be passed to sqlite3WhereBegin() to slightly
66987       ** modify behaviour as follows:
66988       **
66989       **   + If the query is a "SELECT min(x)", then the loop coded by
66990       **     where.c should not iterate over any values with a NULL value
66991       **     for x.
66992       **
66993       **   + The optimizer code in where.c (the thing that decides which
66994       **     index or indices to use) should place a different priority on 
66995       **     satisfying the 'ORDER BY' clause than it does in other cases.
66996       **     Refer to code and comments in where.c for details.
66997       */
66998       flag = minMaxQuery(pParse, p);
66999       if( flag ){
67000         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
67001         if( pMinMax && !db->mallocFailed ){
67002           pMinMax->a[0].sortOrder = ((flag==WHERE_ORDERBY_MIN)?0:1);
67003           pMinMax->a[0].pExpr->op = TK_COLUMN;
67004         }
67005       }
67006
67007       /* This case runs if the aggregate has no GROUP BY clause.  The
67008       ** processing is much simpler since there is only a single row
67009       ** of output.
67010       */
67011       resetAccumulator(pParse, &sAggInfo);
67012       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
67013       if( pWInfo==0 ){
67014         sqlite3ExprListDelete(pDel);
67015         goto select_end;
67016       }
67017       updateAccumulator(pParse, &sAggInfo);
67018       if( !pMinMax && flag ){
67019         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
67020         VdbeComment((v, "%s() by index", (flag==WHERE_ORDERBY_MIN?"min":"max")));
67021       }
67022       sqlite3WhereEnd(pWInfo);
67023       finalizeAggFunctions(pParse, &sAggInfo);
67024       pOrderBy = 0;
67025       if( pHaving ){
67026         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
67027       }
67028       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
67029                       pDest, addrEnd, addrEnd, aff);
67030
67031       sqlite3ExprListDelete(pDel);
67032     }
67033     sqlite3VdbeResolveLabel(v, addrEnd);
67034     
67035   } /* endif aggregate query */
67036
67037   /* If there is an ORDER BY clause, then we need to sort the results
67038   ** and send them to the callback one by one.
67039   */
67040   if( pOrderBy ){
67041     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
67042   }
67043
67044 #ifndef SQLITE_OMIT_SUBQUERY
67045   /* If this was a subquery, we have now converted the subquery into a
67046   ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
67047   ** this subquery from being evaluated again and to force the use of
67048   ** the temporary table.
67049   */
67050   if( pParent ){
67051     assert( pParent->pSrc->nSrc>parentTab );
67052     assert( pParent->pSrc->a[parentTab].pSelect==p );
67053     pParent->pSrc->a[parentTab].isPopulated = 1;
67054   }
67055 #endif
67056
67057   /* Jump here to skip this query
67058   */
67059   sqlite3VdbeResolveLabel(v, iEnd);
67060
67061   /* The SELECT was successfully coded.   Set the return code to 0
67062   ** to indicate no errors.
67063   */
67064   rc = 0;
67065
67066   /* Control jumps to here if an error is encountered above, or upon
67067   ** successful coding of the SELECT.
67068   */
67069 select_end:
67070
67071   /* Identify column names if we will be using them in a callback.  This
67072   ** step is skipped if the output is going to some other destination.
67073   */
67074   if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){
67075     generateColumnNames(pParse, pTabList, pEList);
67076   }
67077
67078   sqlite3_free(sAggInfo.aCol);
67079   sqlite3_free(sAggInfo.aFunc);
67080   return rc;
67081 }
67082
67083 #if defined(SQLITE_DEBUG)
67084 /*
67085 *******************************************************************************
67086 ** The following code is used for testing and debugging only.  The code
67087 ** that follows does not appear in normal builds.
67088 **
67089 ** These routines are used to print out the content of all or part of a 
67090 ** parse structures such as Select or Expr.  Such printouts are useful
67091 ** for helping to understand what is happening inside the code generator
67092 ** during the execution of complex SELECT statements.
67093 **
67094 ** These routine are not called anywhere from within the normal
67095 ** code base.  Then are intended to be called from within the debugger
67096 ** or from temporary "printf" statements inserted for debugging.
67097 */
67098 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
67099   if( p->token.z && p->token.n>0 ){
67100     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
67101   }else{
67102     sqlite3DebugPrintf("(%d", p->op);
67103   }
67104   if( p->pLeft ){
67105     sqlite3DebugPrintf(" ");
67106     sqlite3PrintExpr(p->pLeft);
67107   }
67108   if( p->pRight ){
67109     sqlite3DebugPrintf(" ");
67110     sqlite3PrintExpr(p->pRight);
67111   }
67112   sqlite3DebugPrintf(")");
67113 }
67114 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
67115   int i;
67116   for(i=0; i<pList->nExpr; i++){
67117     sqlite3PrintExpr(pList->a[i].pExpr);
67118     if( i<pList->nExpr-1 ){
67119       sqlite3DebugPrintf(", ");
67120     }
67121   }
67122 }
67123 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
67124   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
67125   sqlite3PrintExprList(p->pEList);
67126   sqlite3DebugPrintf("\n");
67127   if( p->pSrc ){
67128     char *zPrefix;
67129     int i;
67130     zPrefix = "FROM";
67131     for(i=0; i<p->pSrc->nSrc; i++){
67132       struct SrcList_item *pItem = &p->pSrc->a[i];
67133       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
67134       zPrefix = "";
67135       if( pItem->pSelect ){
67136         sqlite3DebugPrintf("(\n");
67137         sqlite3PrintSelect(pItem->pSelect, indent+10);
67138         sqlite3DebugPrintf("%*s)", indent+8, "");
67139       }else if( pItem->zName ){
67140         sqlite3DebugPrintf("%s", pItem->zName);
67141       }
67142       if( pItem->pTab ){
67143         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
67144       }
67145       if( pItem->zAlias ){
67146         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
67147       }
67148       if( i<p->pSrc->nSrc-1 ){
67149         sqlite3DebugPrintf(",");
67150       }
67151       sqlite3DebugPrintf("\n");
67152     }
67153   }
67154   if( p->pWhere ){
67155     sqlite3DebugPrintf("%*s WHERE ", indent, "");
67156     sqlite3PrintExpr(p->pWhere);
67157     sqlite3DebugPrintf("\n");
67158   }
67159   if( p->pGroupBy ){
67160     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
67161     sqlite3PrintExprList(p->pGroupBy);
67162     sqlite3DebugPrintf("\n");
67163   }
67164   if( p->pHaving ){
67165     sqlite3DebugPrintf("%*s HAVING ", indent, "");
67166     sqlite3PrintExpr(p->pHaving);
67167     sqlite3DebugPrintf("\n");
67168   }
67169   if( p->pOrderBy ){
67170     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
67171     sqlite3PrintExprList(p->pOrderBy);
67172     sqlite3DebugPrintf("\n");
67173   }
67174 }
67175 /* End of the structure debug printing code
67176 *****************************************************************************/
67177 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
67178
67179 /************** End of select.c **********************************************/
67180 /************** Begin file table.c *******************************************/
67181 /*
67182 ** 2001 September 15
67183 **
67184 ** The author disclaims copyright to this source code.  In place of
67185 ** a legal notice, here is a blessing:
67186 **
67187 **    May you do good and not evil.
67188 **    May you find forgiveness for yourself and forgive others.
67189 **    May you share freely, never taking more than you give.
67190 **
67191 *************************************************************************
67192 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
67193 ** interface routines.  These are just wrappers around the main
67194 ** interface routine of sqlite3_exec().
67195 **
67196 ** These routines are in a separate files so that they will not be linked
67197 ** if they are not used.
67198 */
67199
67200 #ifndef SQLITE_OMIT_GET_TABLE
67201
67202 /*
67203 ** This structure is used to pass data from sqlite3_get_table() through
67204 ** to the callback function is uses to build the result.
67205 */
67206 typedef struct TabResult {
67207   char **azResult;
67208   char *zErrMsg;
67209   int nResult;
67210   int nAlloc;
67211   int nRow;
67212   int nColumn;
67213   int nData;
67214   int rc;
67215 } TabResult;
67216
67217 /*
67218 ** This routine is called once for each row in the result table.  Its job
67219 ** is to fill in the TabResult structure appropriately, allocating new
67220 ** memory as necessary.
67221 */
67222 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
67223   TabResult *p = (TabResult*)pArg;
67224   int need;
67225   int i;
67226   char *z;
67227
67228   /* Make sure there is enough space in p->azResult to hold everything
67229   ** we need to remember from this invocation of the callback.
67230   */
67231   if( p->nRow==0 && argv!=0 ){
67232     need = nCol*2;
67233   }else{
67234     need = nCol;
67235   }
67236   if( p->nData + need >= p->nAlloc ){
67237     char **azNew;
67238     p->nAlloc = p->nAlloc*2 + need + 1;
67239     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
67240     if( azNew==0 ) goto malloc_failed;
67241     p->azResult = azNew;
67242   }
67243
67244   /* If this is the first row, then generate an extra row containing
67245   ** the names of all columns.
67246   */
67247   if( p->nRow==0 ){
67248     p->nColumn = nCol;
67249     for(i=0; i<nCol; i++){
67250       z = sqlite3_mprintf("%s", colv[i]);
67251       if( z==0 ) goto malloc_failed;
67252       p->azResult[p->nData++] = z;
67253     }
67254   }else if( p->nColumn!=nCol ){
67255     sqlite3_free(p->zErrMsg);
67256     p->zErrMsg = sqlite3_mprintf(
67257        "sqlite3_get_table() called with two or more incompatible queries"
67258     );
67259     p->rc = SQLITE_ERROR;
67260     return 1;
67261   }
67262
67263   /* Copy over the row data
67264   */
67265   if( argv!=0 ){
67266     for(i=0; i<nCol; i++){
67267       if( argv[i]==0 ){
67268         z = 0;
67269       }else{
67270         int n = strlen(argv[i])+1;
67271         z = sqlite3_malloc( n );
67272         if( z==0 ) goto malloc_failed;
67273         memcpy(z, argv[i], n);
67274       }
67275       p->azResult[p->nData++] = z;
67276     }
67277     p->nRow++;
67278   }
67279   return 0;
67280
67281 malloc_failed:
67282   p->rc = SQLITE_NOMEM;
67283   return 1;
67284 }
67285
67286 /*
67287 ** Query the database.  But instead of invoking a callback for each row,
67288 ** malloc() for space to hold the result and return the entire results
67289 ** at the conclusion of the call.
67290 **
67291 ** The result that is written to ***pazResult is held in memory obtained
67292 ** from malloc().  But the caller cannot free this memory directly.  
67293 ** Instead, the entire table should be passed to sqlite3_free_table() when
67294 ** the calling procedure is finished using it.
67295 */
67296 SQLITE_API int sqlite3_get_table(
67297   sqlite3 *db,                /* The database on which the SQL executes */
67298   const char *zSql,           /* The SQL to be executed */
67299   char ***pazResult,          /* Write the result table here */
67300   int *pnRow,                 /* Write the number of rows in the result here */
67301   int *pnColumn,              /* Write the number of columns of result here */
67302   char **pzErrMsg             /* Write error messages here */
67303 ){
67304   int rc;
67305   TabResult res;
67306
67307   *pazResult = 0;
67308   if( pnColumn ) *pnColumn = 0;
67309   if( pnRow ) *pnRow = 0;
67310   res.zErrMsg = 0;
67311   res.nResult = 0;
67312   res.nRow = 0;
67313   res.nColumn = 0;
67314   res.nData = 1;
67315   res.nAlloc = 20;
67316   res.rc = SQLITE_OK;
67317   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
67318   if( res.azResult==0 ){
67319      db->errCode = SQLITE_NOMEM;
67320      return SQLITE_NOMEM;
67321   }
67322   res.azResult[0] = 0;
67323   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
67324   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
67325   res.azResult[0] = (char*)res.nData;
67326   if( (rc&0xff)==SQLITE_ABORT ){
67327     sqlite3_free_table(&res.azResult[1]);
67328     if( res.zErrMsg ){
67329       if( pzErrMsg ){
67330         sqlite3_free(*pzErrMsg);
67331         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
67332       }
67333       sqlite3_free(res.zErrMsg);
67334     }
67335     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
67336     return res.rc;
67337   }
67338   sqlite3_free(res.zErrMsg);
67339   if( rc!=SQLITE_OK ){
67340     sqlite3_free_table(&res.azResult[1]);
67341     return rc;
67342   }
67343   if( res.nAlloc>res.nData ){
67344     char **azNew;
67345     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
67346     if( azNew==0 ){
67347       sqlite3_free_table(&res.azResult[1]);
67348       db->errCode = SQLITE_NOMEM;
67349       return SQLITE_NOMEM;
67350     }
67351     res.nAlloc = res.nData+1;
67352     res.azResult = azNew;
67353   }
67354   *pazResult = &res.azResult[1];
67355   if( pnColumn ) *pnColumn = res.nColumn;
67356   if( pnRow ) *pnRow = res.nRow;
67357   return rc;
67358 }
67359
67360 /*
67361 ** This routine frees the space the sqlite3_get_table() malloced.
67362 */
67363 SQLITE_API void sqlite3_free_table(
67364   char **azResult            /* Result returned from from sqlite3_get_table() */
67365 ){
67366   if( azResult ){
67367     int i, n;
67368     azResult--;
67369     assert( azResult!=0 );
67370     n = (int)azResult[0];
67371     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
67372     sqlite3_free(azResult);
67373   }
67374 }
67375
67376 #endif /* SQLITE_OMIT_GET_TABLE */
67377
67378 /************** End of table.c ***********************************************/
67379 /************** Begin file trigger.c *****************************************/
67380 /*
67381 **
67382 ** The author disclaims copyright to this source code.  In place of
67383 ** a legal notice, here is a blessing:
67384 **
67385 **    May you do good and not evil.
67386 **    May you find forgiveness for yourself and forgive others.
67387 **    May you share freely, never taking more than you give.
67388 **
67389 *************************************************************************
67390 *
67391 */
67392
67393 #ifndef SQLITE_OMIT_TRIGGER
67394 /*
67395 ** Delete a linked list of TriggerStep structures.
67396 */
67397 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
67398   while( pTriggerStep ){
67399     TriggerStep * pTmp = pTriggerStep;
67400     pTriggerStep = pTriggerStep->pNext;
67401
67402     if( pTmp->target.dyn ) sqlite3_free((char*)pTmp->target.z);
67403     sqlite3ExprDelete(pTmp->pWhere);
67404     sqlite3ExprListDelete(pTmp->pExprList);
67405     sqlite3SelectDelete(pTmp->pSelect);
67406     sqlite3IdListDelete(pTmp->pIdList);
67407
67408     sqlite3_free(pTmp);
67409   }
67410 }
67411
67412 /*
67413 ** This is called by the parser when it sees a CREATE TRIGGER statement
67414 ** up to the point of the BEGIN before the trigger actions.  A Trigger
67415 ** structure is generated based on the information available and stored
67416 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
67417 ** sqlite3FinishTrigger() function is called to complete the trigger
67418 ** construction process.
67419 */
67420 SQLITE_PRIVATE void sqlite3BeginTrigger(
67421   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
67422   Token *pName1,      /* The name of the trigger */
67423   Token *pName2,      /* The name of the trigger */
67424   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
67425   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
67426   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
67427   SrcList *pTableName,/* The name of the table/view the trigger applies to */
67428   Expr *pWhen,        /* WHEN clause */
67429   int isTemp,         /* True if the TEMPORARY keyword is present */
67430   int noErr           /* Suppress errors if the trigger already exists */
67431 ){
67432   Trigger *pTrigger = 0;
67433   Table *pTab;
67434   char *zName = 0;        /* Name of the trigger */
67435   sqlite3 *db = pParse->db;
67436   int iDb;                /* The database to store the trigger in */
67437   Token *pName;           /* The unqualified db name */
67438   DbFixer sFix;
67439   int iTabDb;
67440
67441   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
67442   assert( pName2!=0 );
67443   if( isTemp ){
67444     /* If TEMP was specified, then the trigger name may not be qualified. */
67445     if( pName2->n>0 ){
67446       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
67447       goto trigger_cleanup;
67448     }
67449     iDb = 1;
67450     pName = pName1;
67451   }else{
67452     /* Figure out the db that the the trigger will be created in */
67453     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
67454     if( iDb<0 ){
67455       goto trigger_cleanup;
67456     }
67457   }
67458
67459   /* If the trigger name was unqualified, and the table is a temp table,
67460   ** then set iDb to 1 to create the trigger in the temporary database.
67461   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
67462   ** exist, the error is caught by the block below.
67463   */
67464   if( !pTableName || db->mallocFailed ){
67465     goto trigger_cleanup;
67466   }
67467   pTab = sqlite3SrcListLookup(pParse, pTableName);
67468   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
67469     iDb = 1;
67470   }
67471
67472   /* Ensure the table name matches database name and that the table exists */
67473   if( db->mallocFailed ) goto trigger_cleanup;
67474   assert( pTableName->nSrc==1 );
67475   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
67476       sqlite3FixSrcList(&sFix, pTableName) ){
67477     goto trigger_cleanup;
67478   }
67479   pTab = sqlite3SrcListLookup(pParse, pTableName);
67480   if( !pTab ){
67481     /* The table does not exist. */
67482     goto trigger_cleanup;
67483   }
67484   if( IsVirtual(pTab) ){
67485     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
67486     goto trigger_cleanup;
67487   }
67488
67489   /* Check that the trigger name is not reserved and that no trigger of the
67490   ** specified name exists */
67491   zName = sqlite3NameFromToken(db, pName);
67492   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
67493     goto trigger_cleanup;
67494   }
67495   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
67496     if( !noErr ){
67497       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
67498     }
67499     goto trigger_cleanup;
67500   }
67501
67502   /* Do not create a trigger on a system table */
67503   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
67504     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
67505     pParse->nErr++;
67506     goto trigger_cleanup;
67507   }
67508
67509   /* INSTEAD of triggers are only for views and views only support INSTEAD
67510   ** of triggers.
67511   */
67512   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
67513     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
67514         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
67515     goto trigger_cleanup;
67516   }
67517   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
67518     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
67519         " trigger on table: %S", pTableName, 0);
67520     goto trigger_cleanup;
67521   }
67522   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
67523
67524 #ifndef SQLITE_OMIT_AUTHORIZATION
67525   {
67526     int code = SQLITE_CREATE_TRIGGER;
67527     const char *zDb = db->aDb[iTabDb].zName;
67528     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
67529     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
67530     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
67531       goto trigger_cleanup;
67532     }
67533     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
67534       goto trigger_cleanup;
67535     }
67536   }
67537 #endif
67538
67539   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
67540   ** cannot appear on views.  So we might as well translate every
67541   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
67542   ** elsewhere.
67543   */
67544   if (tr_tm == TK_INSTEAD){
67545     tr_tm = TK_BEFORE;
67546   }
67547
67548   /* Build the Trigger object */
67549   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
67550   if( pTrigger==0 ) goto trigger_cleanup;
67551   pTrigger->name = zName;
67552   zName = 0;
67553   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
67554   pTrigger->pSchema = db->aDb[iDb].pSchema;
67555   pTrigger->pTabSchema = pTab->pSchema;
67556   pTrigger->op = op;
67557   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
67558   pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
67559   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
67560   sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
67561   assert( pParse->pNewTrigger==0 );
67562   pParse->pNewTrigger = pTrigger;
67563
67564 trigger_cleanup:
67565   sqlite3_free(zName);
67566   sqlite3SrcListDelete(pTableName);
67567   sqlite3IdListDelete(pColumns);
67568   sqlite3ExprDelete(pWhen);
67569   if( !pParse->pNewTrigger ){
67570     sqlite3DeleteTrigger(pTrigger);
67571   }else{
67572     assert( pParse->pNewTrigger==pTrigger );
67573   }
67574 }
67575
67576 /*
67577 ** This routine is called after all of the trigger actions have been parsed
67578 ** in order to complete the process of building the trigger.
67579 */
67580 SQLITE_PRIVATE void sqlite3FinishTrigger(
67581   Parse *pParse,          /* Parser context */
67582   TriggerStep *pStepList, /* The triggered program */
67583   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
67584 ){
67585   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
67586   sqlite3 *db = pParse->db;  /* The database */
67587   DbFixer sFix;
67588   int iDb;                   /* Database containing the trigger */
67589
67590   pTrig = pParse->pNewTrigger;
67591   pParse->pNewTrigger = 0;
67592   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
67593   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
67594   pTrig->step_list = pStepList;
67595   while( pStepList ){
67596     pStepList->pTrig = pTrig;
67597     pStepList = pStepList->pNext;
67598   }
67599   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
67600           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
67601     goto triggerfinish_cleanup;
67602   }
67603
67604   /* if we are not initializing, and this trigger is not on a TEMP table, 
67605   ** build the sqlite_master entry
67606   */
67607   if( !db->init.busy ){
67608     Vdbe *v;
67609     char *z;
67610
67611     /* Make an entry in the sqlite_master table */
67612     v = sqlite3GetVdbe(pParse);
67613     if( v==0 ) goto triggerfinish_cleanup;
67614     sqlite3BeginWriteOperation(pParse, 0, iDb);
67615     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
67616     sqlite3NestedParse(pParse,
67617        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
67618        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
67619        pTrig->table, z);
67620     sqlite3_free(z);
67621     sqlite3ChangeCookie(pParse, iDb);
67622     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
67623         db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
67624     );
67625   }
67626
67627   if( db->init.busy ){
67628     int n;
67629     Table *pTab;
67630     Trigger *pDel;
67631     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
67632                      pTrig->name, strlen(pTrig->name), pTrig);
67633     if( pDel ){
67634       assert( pDel==pTrig );
67635       db->mallocFailed = 1;
67636       goto triggerfinish_cleanup;
67637     }
67638     n = strlen(pTrig->table) + 1;
67639     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
67640     assert( pTab!=0 );
67641     pTrig->pNext = pTab->pTrigger;
67642     pTab->pTrigger = pTrig;
67643     pTrig = 0;
67644   }
67645
67646 triggerfinish_cleanup:
67647   sqlite3DeleteTrigger(pTrig);
67648   assert( !pParse->pNewTrigger );
67649   sqlite3DeleteTriggerStep(pStepList);
67650 }
67651
67652 /*
67653 ** Make a copy of all components of the given trigger step.  This has
67654 ** the effect of copying all Expr.token.z values into memory obtained
67655 ** from sqlite3_malloc().  As initially created, the Expr.token.z values
67656 ** all point to the input string that was fed to the parser.  But that
67657 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
67658 ** call that started the parser exits.  This routine makes a persistent
67659 ** copy of all the Expr.token.z strings so that the TriggerStep structure
67660 ** will be valid even after the sqlite3_exec() call returns.
67661 */
67662 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
67663   if( p->target.z ){
67664     p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
67665     p->target.dyn = 1;
67666   }
67667   if( p->pSelect ){
67668     Select *pNew = sqlite3SelectDup(db, p->pSelect);
67669     sqlite3SelectDelete(p->pSelect);
67670     p->pSelect = pNew;
67671   }
67672   if( p->pWhere ){
67673     Expr *pNew = sqlite3ExprDup(db, p->pWhere);
67674     sqlite3ExprDelete(p->pWhere);
67675     p->pWhere = pNew;
67676   }
67677   if( p->pExprList ){
67678     ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
67679     sqlite3ExprListDelete(p->pExprList);
67680     p->pExprList = pNew;
67681   }
67682   if( p->pIdList ){
67683     IdList *pNew = sqlite3IdListDup(db, p->pIdList);
67684     sqlite3IdListDelete(p->pIdList);
67685     p->pIdList = pNew;
67686   }
67687 }
67688
67689 /*
67690 ** Turn a SELECT statement (that the pSelect parameter points to) into
67691 ** a trigger step.  Return a pointer to a TriggerStep structure.
67692 **
67693 ** The parser calls this routine when it finds a SELECT statement in
67694 ** body of a TRIGGER.  
67695 */
67696 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
67697   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
67698   if( pTriggerStep==0 ) {
67699     sqlite3SelectDelete(pSelect);
67700     return 0;
67701   }
67702
67703   pTriggerStep->op = TK_SELECT;
67704   pTriggerStep->pSelect = pSelect;
67705   pTriggerStep->orconf = OE_Default;
67706   sqlitePersistTriggerStep(db, pTriggerStep);
67707
67708   return pTriggerStep;
67709 }
67710
67711 /*
67712 ** Build a trigger step out of an INSERT statement.  Return a pointer
67713 ** to the new trigger step.
67714 **
67715 ** The parser calls this routine when it sees an INSERT inside the
67716 ** body of a trigger.
67717 */
67718 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
67719   sqlite3 *db,        /* The database connection */
67720   Token *pTableName,  /* Name of the table into which we insert */
67721   IdList *pColumn,    /* List of columns in pTableName to insert into */
67722   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
67723   Select *pSelect,    /* A SELECT statement that supplies values */
67724   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
67725 ){
67726   TriggerStep *pTriggerStep;
67727
67728   assert(pEList == 0 || pSelect == 0);
67729   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
67730
67731   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
67732   if( pTriggerStep ){
67733     pTriggerStep->op = TK_INSERT;
67734     pTriggerStep->pSelect = pSelect;
67735     pTriggerStep->target  = *pTableName;
67736     pTriggerStep->pIdList = pColumn;
67737     pTriggerStep->pExprList = pEList;
67738     pTriggerStep->orconf = orconf;
67739     sqlitePersistTriggerStep(db, pTriggerStep);
67740   }else{
67741     sqlite3IdListDelete(pColumn);
67742     sqlite3ExprListDelete(pEList);
67743     sqlite3SelectDelete(pSelect);
67744   }
67745
67746   return pTriggerStep;
67747 }
67748
67749 /*
67750 ** Construct a trigger step that implements an UPDATE statement and return
67751 ** a pointer to that trigger step.  The parser calls this routine when it
67752 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
67753 */
67754 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
67755   sqlite3 *db,         /* The database connection */
67756   Token *pTableName,   /* Name of the table to be updated */
67757   ExprList *pEList,    /* The SET clause: list of column and new values */
67758   Expr *pWhere,        /* The WHERE clause */
67759   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
67760 ){
67761   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
67762   if( pTriggerStep==0 ){
67763      sqlite3ExprListDelete(pEList);
67764      sqlite3ExprDelete(pWhere);
67765      return 0;
67766   }
67767
67768   pTriggerStep->op = TK_UPDATE;
67769   pTriggerStep->target  = *pTableName;
67770   pTriggerStep->pExprList = pEList;
67771   pTriggerStep->pWhere = pWhere;
67772   pTriggerStep->orconf = orconf;
67773   sqlitePersistTriggerStep(db, pTriggerStep);
67774
67775   return pTriggerStep;
67776 }
67777
67778 /*
67779 ** Construct a trigger step that implements a DELETE statement and return
67780 ** a pointer to that trigger step.  The parser calls this routine when it
67781 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
67782 */
67783 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
67784   sqlite3 *db,            /* Database connection */
67785   Token *pTableName,      /* The table from which rows are deleted */
67786   Expr *pWhere            /* The WHERE clause */
67787 ){
67788   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
67789   if( pTriggerStep==0 ){
67790     sqlite3ExprDelete(pWhere);
67791     return 0;
67792   }
67793
67794   pTriggerStep->op = TK_DELETE;
67795   pTriggerStep->target  = *pTableName;
67796   pTriggerStep->pWhere = pWhere;
67797   pTriggerStep->orconf = OE_Default;
67798   sqlitePersistTriggerStep(db, pTriggerStep);
67799
67800   return pTriggerStep;
67801 }
67802
67803 /* 
67804 ** Recursively delete a Trigger structure
67805 */
67806 SQLITE_PRIVATE void sqlite3DeleteTrigger(Trigger *pTrigger){
67807   if( pTrigger==0 ) return;
67808   sqlite3DeleteTriggerStep(pTrigger->step_list);
67809   sqlite3_free(pTrigger->name);
67810   sqlite3_free(pTrigger->table);
67811   sqlite3ExprDelete(pTrigger->pWhen);
67812   sqlite3IdListDelete(pTrigger->pColumns);
67813   if( pTrigger->nameToken.dyn ) sqlite3_free((char*)pTrigger->nameToken.z);
67814   sqlite3_free(pTrigger);
67815 }
67816
67817 /*
67818 ** This function is called to drop a trigger from the database schema. 
67819 **
67820 ** This may be called directly from the parser and therefore identifies
67821 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
67822 ** same job as this routine except it takes a pointer to the trigger
67823 ** instead of the trigger name.
67824 **/
67825 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
67826   Trigger *pTrigger = 0;
67827   int i;
67828   const char *zDb;
67829   const char *zName;
67830   int nName;
67831   sqlite3 *db = pParse->db;
67832
67833   if( db->mallocFailed ) goto drop_trigger_cleanup;
67834   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
67835     goto drop_trigger_cleanup;
67836   }
67837
67838   assert( pName->nSrc==1 );
67839   zDb = pName->a[0].zDatabase;
67840   zName = pName->a[0].zName;
67841   nName = strlen(zName);
67842   for(i=OMIT_TEMPDB; i<db->nDb; i++){
67843     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
67844     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
67845     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
67846     if( pTrigger ) break;
67847   }
67848   if( !pTrigger ){
67849     if( !noErr ){
67850       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
67851     }
67852     goto drop_trigger_cleanup;
67853   }
67854   sqlite3DropTriggerPtr(pParse, pTrigger);
67855
67856 drop_trigger_cleanup:
67857   sqlite3SrcListDelete(pName);
67858 }
67859
67860 /*
67861 ** Return a pointer to the Table structure for the table that a trigger
67862 ** is set on.
67863 */
67864 static Table *tableOfTrigger(Trigger *pTrigger){
67865   int n = strlen(pTrigger->table) + 1;
67866   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
67867 }
67868
67869
67870 /*
67871 ** Drop a trigger given a pointer to that trigger. 
67872 */
67873 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
67874   Table   *pTable;
67875   Vdbe *v;
67876   sqlite3 *db = pParse->db;
67877   int iDb;
67878
67879   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
67880   assert( iDb>=0 && iDb<db->nDb );
67881   pTable = tableOfTrigger(pTrigger);
67882   assert( pTable );
67883   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
67884 #ifndef SQLITE_OMIT_AUTHORIZATION
67885   {
67886     int code = SQLITE_DROP_TRIGGER;
67887     const char *zDb = db->aDb[iDb].zName;
67888     const char *zTab = SCHEMA_TABLE(iDb);
67889     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
67890     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
67891       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
67892       return;
67893     }
67894   }
67895 #endif
67896
67897   /* Generate code to destroy the database record of the trigger.
67898   */
67899   assert( pTable!=0 );
67900   if( (v = sqlite3GetVdbe(pParse))!=0 ){
67901     int base;
67902     static const VdbeOpList dropTrigger[] = {
67903       { OP_Rewind,     0, ADDR(9),  0},
67904       { OP_String8,    0, 1,        0}, /* 1 */
67905       { OP_Column,     0, 1,        2},
67906       { OP_Ne,         2, ADDR(8),  1},
67907       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
67908       { OP_Column,     0, 0,        2},
67909       { OP_Ne,         2, ADDR(8),  1},
67910       { OP_Delete,     0, 0,        0},
67911       { OP_Next,       0, ADDR(1),  0}, /* 8 */
67912     };
67913
67914     sqlite3BeginWriteOperation(pParse, 0, iDb);
67915     sqlite3OpenMasterTable(pParse, iDb);
67916     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
67917     sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
67918     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
67919     sqlite3ChangeCookie(pParse, iDb);
67920     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
67921     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
67922   }
67923 }
67924
67925 /*
67926 ** Remove a trigger from the hash tables of the sqlite* pointer.
67927 */
67928 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
67929   Trigger *pTrigger;
67930   int nName = strlen(zName);
67931   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
67932                                zName, nName, 0);
67933   if( pTrigger ){
67934     Table *pTable = tableOfTrigger(pTrigger);
67935     assert( pTable!=0 );
67936     if( pTable->pTrigger == pTrigger ){
67937       pTable->pTrigger = pTrigger->pNext;
67938     }else{
67939       Trigger *cc = pTable->pTrigger;
67940       while( cc ){ 
67941         if( cc->pNext == pTrigger ){
67942           cc->pNext = cc->pNext->pNext;
67943           break;
67944         }
67945         cc = cc->pNext;
67946       }
67947       assert(cc);
67948     }
67949     sqlite3DeleteTrigger(pTrigger);
67950     db->flags |= SQLITE_InternChanges;
67951   }
67952 }
67953
67954 /*
67955 ** pEList is the SET clause of an UPDATE statement.  Each entry
67956 ** in pEList is of the format <id>=<expr>.  If any of the entries
67957 ** in pEList have an <id> which matches an identifier in pIdList,
67958 ** then return TRUE.  If pIdList==NULL, then it is considered a
67959 ** wildcard that matches anything.  Likewise if pEList==NULL then
67960 ** it matches anything so always return true.  Return false only
67961 ** if there is no match.
67962 */
67963 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
67964   int e;
67965   if( !pIdList || !pEList ) return 1;
67966   for(e=0; e<pEList->nExpr; e++){
67967     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
67968   }
67969   return 0; 
67970 }
67971
67972 /*
67973 ** Return a bit vector to indicate what kind of triggers exist for operation
67974 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
67975 ** that are being updated.  Triggers only match if the ON clause of the
67976 ** trigger definition overlaps the set of columns being updated.
67977 **
67978 ** The returned bit vector is some combination of TRIGGER_BEFORE and
67979 ** TRIGGER_AFTER.
67980 */
67981 SQLITE_PRIVATE int sqlite3TriggersExist(
67982   Parse *pParse,          /* Used to check for recursive triggers */
67983   Table *pTab,            /* The table the contains the triggers */
67984   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
67985   ExprList *pChanges      /* Columns that change in an UPDATE statement */
67986 ){
67987   Trigger *pTrigger;
67988   int mask = 0;
67989
67990   pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
67991   while( pTrigger ){
67992     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
67993       mask |= pTrigger->tr_tm;
67994     }
67995     pTrigger = pTrigger->pNext;
67996   }
67997   return mask;
67998 }
67999
68000 /*
68001 ** Convert the pStep->target token into a SrcList and return a pointer
68002 ** to that SrcList.
68003 **
68004 ** This routine adds a specific database name, if needed, to the target when
68005 ** forming the SrcList.  This prevents a trigger in one database from
68006 ** referring to a target in another database.  An exception is when the
68007 ** trigger is in TEMP in which case it can refer to any other database it
68008 ** wants.
68009 */
68010 static SrcList *targetSrcList(
68011   Parse *pParse,       /* The parsing context */
68012   TriggerStep *pStep   /* The trigger containing the target token */
68013 ){
68014   Token sDb;           /* Dummy database name token */
68015   int iDb;             /* Index of the database to use */
68016   SrcList *pSrc;       /* SrcList to be returned */
68017
68018   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
68019   if( iDb==0 || iDb>=2 ){
68020     assert( iDb<pParse->db->nDb );
68021     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
68022     sDb.n = strlen((char*)sDb.z);
68023     pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
68024   } else {
68025     pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
68026   }
68027   return pSrc;
68028 }
68029
68030 /*
68031 ** Generate VDBE code for zero or more statements inside the body of a
68032 ** trigger.  
68033 */
68034 static int codeTriggerProgram(
68035   Parse *pParse,            /* The parser context */
68036   TriggerStep *pStepList,   /* List of statements inside the trigger body */
68037   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
68038 ){
68039   TriggerStep * pTriggerStep = pStepList;
68040   int orconf;
68041   Vdbe *v = pParse->pVdbe;
68042   sqlite3 *db = pParse->db;
68043
68044   assert( pTriggerStep!=0 );
68045   assert( v!=0 );
68046   sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
68047   VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
68048   while( pTriggerStep ){
68049     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
68050     pParse->trigStack->orconf = orconf;
68051     switch( pTriggerStep->op ){
68052       case TK_SELECT: {
68053         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
68054         if( ss ){
68055           SelectDest dest;
68056
68057           sqlite3SelectDestInit(&dest, SRT_Discard, 0);
68058           sqlite3SelectResolve(pParse, ss, 0);
68059           sqlite3Select(pParse, ss, &dest, 0, 0, 0, 0);
68060           sqlite3SelectDelete(ss);
68061         }
68062         break;
68063       }
68064       case TK_UPDATE: {
68065         SrcList *pSrc;
68066         pSrc = targetSrcList(pParse, pTriggerStep);
68067         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
68068         sqlite3Update(pParse, pSrc,
68069                 sqlite3ExprListDup(db, pTriggerStep->pExprList), 
68070                 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
68071         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
68072         break;
68073       }
68074       case TK_INSERT: {
68075         SrcList *pSrc;
68076         pSrc = targetSrcList(pParse, pTriggerStep);
68077         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
68078         sqlite3Insert(pParse, pSrc,
68079           sqlite3ExprListDup(db, pTriggerStep->pExprList), 
68080           sqlite3SelectDup(db, pTriggerStep->pSelect), 
68081           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
68082         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
68083         break;
68084       }
68085       case TK_DELETE: {
68086         SrcList *pSrc;
68087         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
68088         pSrc = targetSrcList(pParse, pTriggerStep);
68089         sqlite3DeleteFrom(pParse, pSrc, 
68090                           sqlite3ExprDup(db, pTriggerStep->pWhere));
68091         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
68092         break;
68093       }
68094       default:
68095         assert(0);
68096     } 
68097     pTriggerStep = pTriggerStep->pNext;
68098   }
68099   sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
68100   VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
68101
68102   return 0;
68103 }
68104
68105 /*
68106 ** This is called to code FOR EACH ROW triggers.
68107 **
68108 ** When the code that this function generates is executed, the following 
68109 ** must be true:
68110 **
68111 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
68112 **    can be indices of cursors in temporary tables.  See below.)
68113 **
68114 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
68115 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
68116 **    a row containing values to be substituted for new.* expressions in the
68117 **    trigger program(s).
68118 **
68119 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
68120 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
68121 **    a row containing values to be substituted for old.* expressions in the
68122 **    trigger program(s).
68123 **
68124 ** If they are not NULL, the piOldColMask and piNewColMask output variables
68125 ** are set to values that describe the columns used by the trigger program
68126 ** in the OLD.* and NEW.* tables respectively. If column N of the 
68127 ** pseudo-table is read at least once, the corresponding bit of the output
68128 ** mask is set. If a column with an index greater than 32 is read, the
68129 ** output mask is set to the special value 0xffffffff.
68130 **
68131 */
68132 SQLITE_PRIVATE int sqlite3CodeRowTrigger(
68133   Parse *pParse,       /* Parse context */
68134   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
68135   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
68136   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
68137   Table *pTab,         /* The table to code triggers from */
68138   int newIdx,          /* The indice of the "new" row to access */
68139   int oldIdx,          /* The indice of the "old" row to access */
68140   int orconf,          /* ON CONFLICT policy */
68141   int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
68142   u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
68143   u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
68144 ){
68145   Trigger *p;
68146   sqlite3 *db = pParse->db;
68147   TriggerStack trigStackEntry;
68148
68149   trigStackEntry.oldColMask = 0;
68150   trigStackEntry.newColMask = 0;
68151
68152   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
68153   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
68154
68155   assert(newIdx != -1 || oldIdx != -1);
68156
68157   for(p=pTab->pTrigger; p; p=p->pNext){
68158     int fire_this = 0;
68159
68160     /* Determine whether we should code this trigger */
68161     if( 
68162       p->op==op && 
68163       p->tr_tm==tr_tm && 
68164       (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
68165       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
68166     ){
68167       TriggerStack *pS;      /* Pointer to trigger-stack entry */
68168       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
68169       if( !pS ){
68170         fire_this = 1;
68171       }
68172 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
68173       else{
68174         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
68175             p->name);
68176         return SQLITE_ERROR;
68177       }
68178 #endif
68179     }
68180  
68181     if( fire_this ){
68182       int endTrigger;
68183       Expr * whenExpr;
68184       AuthContext sContext;
68185       NameContext sNC;
68186
68187 #ifndef SQLITE_OMIT_TRACE
68188       sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
68189                         sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
68190                         P4_DYNAMIC);
68191 #endif
68192       memset(&sNC, 0, sizeof(sNC));
68193       sNC.pParse = pParse;
68194
68195       /* Push an entry on to the trigger stack */
68196       trigStackEntry.pTrigger = p;
68197       trigStackEntry.newIdx = newIdx;
68198       trigStackEntry.oldIdx = oldIdx;
68199       trigStackEntry.pTab = pTab;
68200       trigStackEntry.pNext = pParse->trigStack;
68201       trigStackEntry.ignoreJump = ignoreJump;
68202       pParse->trigStack = &trigStackEntry;
68203       sqlite3AuthContextPush(pParse, &sContext, p->name);
68204
68205       /* code the WHEN clause */
68206       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
68207       whenExpr = sqlite3ExprDup(db, p->pWhen);
68208       if( db->mallocFailed || sqlite3ExprResolveNames(&sNC, whenExpr) ){
68209         pParse->trigStack = trigStackEntry.pNext;
68210         sqlite3ExprDelete(whenExpr);
68211         return 1;
68212       }
68213       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
68214       sqlite3ExprDelete(whenExpr);
68215
68216       codeTriggerProgram(pParse, p->step_list, orconf); 
68217
68218       /* Pop the entry off the trigger stack */
68219       pParse->trigStack = trigStackEntry.pNext;
68220       sqlite3AuthContextPop(&sContext);
68221
68222       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
68223     }
68224   }
68225   if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
68226   if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
68227   return 0;
68228 }
68229 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
68230
68231 /************** End of trigger.c *********************************************/
68232 /************** Begin file update.c ******************************************/
68233 /*
68234 ** 2001 September 15
68235 **
68236 ** The author disclaims copyright to this source code.  In place of
68237 ** a legal notice, here is a blessing:
68238 **
68239 **    May you do good and not evil.
68240 **    May you find forgiveness for yourself and forgive others.
68241 **    May you share freely, never taking more than you give.
68242 **
68243 *************************************************************************
68244 ** This file contains C code routines that are called by the parser
68245 ** to handle UPDATE statements.
68246 **
68247 ** $Id: update.c,v 1.178 2008/04/28 18:46:43 drh Exp $
68248 */
68249
68250 #ifndef SQLITE_OMIT_VIRTUALTABLE
68251 /* Forward declaration */
68252 static void updateVirtualTable(
68253   Parse *pParse,       /* The parsing context */
68254   SrcList *pSrc,       /* The virtual table to be modified */
68255   Table *pTab,         /* The virtual table */
68256   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
68257   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
68258   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
68259   Expr *pWhere         /* WHERE clause of the UPDATE statement */
68260 );
68261 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68262
68263 /*
68264 ** The most recently coded instruction was an OP_Column to retrieve the
68265 ** i-th column of table pTab. This routine sets the P4 parameter of the 
68266 ** OP_Column to the default value, if any.
68267 **
68268 ** The default value of a column is specified by a DEFAULT clause in the 
68269 ** column definition. This was either supplied by the user when the table
68270 ** was created, or added later to the table definition by an ALTER TABLE
68271 ** command. If the latter, then the row-records in the table btree on disk
68272 ** may not contain a value for the column and the default value, taken
68273 ** from the P4 parameter of the OP_Column instruction, is returned instead.
68274 ** If the former, then all row-records are guaranteed to include a value
68275 ** for the column and the P4 value is not required.
68276 **
68277 ** Column definitions created by an ALTER TABLE command may only have 
68278 ** literal default values specified: a number, null or a string. (If a more
68279 ** complicated default expression value was provided, it is evaluated 
68280 ** when the ALTER TABLE is executed and one of the literal values written
68281 ** into the sqlite_master table.)
68282 **
68283 ** Therefore, the P4 parameter is only required if the default value for
68284 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
68285 ** function is capable of transforming these types of expressions into
68286 ** sqlite3_value objects.
68287 */
68288 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
68289   if( pTab && !pTab->pSelect ){
68290     sqlite3_value *pValue;
68291     u8 enc = ENC(sqlite3VdbeDb(v));
68292     Column *pCol = &pTab->aCol[i];
68293     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
68294     assert( i<pTab->nCol );
68295     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
68296                          pCol->affinity, &pValue);
68297     if( pValue ){
68298       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
68299     }
68300   }
68301 }
68302
68303 /*
68304 ** Process an UPDATE statement.
68305 **
68306 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
68307 **          \_______/ \________/     \______/       \________________/
68308 *            onError   pTabList      pChanges             pWhere
68309 */
68310 SQLITE_PRIVATE void sqlite3Update(
68311   Parse *pParse,         /* The parser context */
68312   SrcList *pTabList,     /* The table in which we should change things */
68313   ExprList *pChanges,    /* Things to be changed */
68314   Expr *pWhere,          /* The WHERE clause.  May be null */
68315   int onError            /* How to handle constraint errors */
68316 ){
68317   int i, j;              /* Loop counters */
68318   Table *pTab;           /* The table to be updated */
68319   int addr = 0;          /* VDBE instruction address of the start of the loop */
68320   WhereInfo *pWInfo;     /* Information about the WHERE clause */
68321   Vdbe *v;               /* The virtual database engine */
68322   Index *pIdx;           /* For looping over indices */
68323   int nIdx;              /* Number of indices that need updating */
68324   int iCur;              /* VDBE Cursor number of pTab */
68325   sqlite3 *db;           /* The database structure */
68326   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
68327   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
68328                          ** an expression for the i-th column of the table.
68329                          ** aXRef[i]==-1 if the i-th column is not changed. */
68330   int chngRowid;         /* True if the record number is being changed */
68331   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
68332   int openAll = 0;       /* True if all indices need to be opened */
68333   AuthContext sContext;  /* The authorization context */
68334   NameContext sNC;       /* The name-context to resolve expressions in */
68335   int iDb;               /* Database containing the table being updated */
68336   int j1;                /* Addresses of jump instructions */
68337   int okOnePass;         /* True for one-pass algorithm without the FIFO */
68338
68339 #ifndef SQLITE_OMIT_TRIGGER
68340   int isView;                  /* Trying to update a view */
68341   int triggers_exist = 0;      /* True if any row triggers exist */
68342 #endif
68343   int iBeginAfterTrigger;      /* Address of after trigger program */
68344   int iEndAfterTrigger;        /* Exit of after trigger program */
68345   int iBeginBeforeTrigger;     /* Address of before trigger program */
68346   int iEndBeforeTrigger;       /* Exit of before trigger program */
68347   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
68348   u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
68349
68350   int newIdx      = -1;  /* index of trigger "new" temp table       */
68351   int oldIdx      = -1;  /* index of trigger "old" temp table       */
68352
68353   /* Register Allocations */
68354   int regRowCount = 0;   /* A count of rows changed */
68355   int regOldRowid;       /* The old rowid */
68356   int regNewRowid;       /* The new rowid */
68357   int regData;           /* New data for the row */
68358
68359   sContext.pParse = 0;
68360   db = pParse->db;
68361   if( pParse->nErr || db->mallocFailed ){
68362     goto update_cleanup;
68363   }
68364   assert( pTabList->nSrc==1 );
68365
68366   /* Locate the table which we want to update. 
68367   */
68368   pTab = sqlite3SrcListLookup(pParse, pTabList);
68369   if( pTab==0 ) goto update_cleanup;
68370   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68371
68372   /* Figure out if we have any triggers and if the table being
68373   ** updated is a view
68374   */
68375 #ifndef SQLITE_OMIT_TRIGGER
68376   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
68377   isView = pTab->pSelect!=0;
68378 #else
68379 # define triggers_exist 0
68380 # define isView 0
68381 #endif
68382 #ifdef SQLITE_OMIT_VIEW
68383 # undef isView
68384 # define isView 0
68385 #endif
68386
68387   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
68388     goto update_cleanup;
68389   }
68390   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
68391     goto update_cleanup;
68392   }
68393   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
68394   if( aXRef==0 ) goto update_cleanup;
68395   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
68396
68397   /* If there are FOR EACH ROW triggers, allocate cursors for the
68398   ** special OLD and NEW tables
68399   */
68400   if( triggers_exist ){
68401     newIdx = pParse->nTab++;
68402     oldIdx = pParse->nTab++;
68403   }
68404
68405   /* Allocate a cursors for the main database table and for all indices.
68406   ** The index cursors might not be used, but if they are used they
68407   ** need to occur right after the database cursor.  So go ahead and
68408   ** allocate enough space, just in case.
68409   */
68410   pTabList->a[0].iCursor = iCur = pParse->nTab++;
68411   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68412     pParse->nTab++;
68413   }
68414
68415   /* Initialize the name-context */
68416   memset(&sNC, 0, sizeof(sNC));
68417   sNC.pParse = pParse;
68418   sNC.pSrcList = pTabList;
68419
68420   /* Resolve the column names in all the expressions of the
68421   ** of the UPDATE statement.  Also find the column index
68422   ** for each column to be updated in the pChanges array.  For each
68423   ** column to be updated, make sure we have authorization to change
68424   ** that column.
68425   */
68426   chngRowid = 0;
68427   for(i=0; i<pChanges->nExpr; i++){
68428     if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
68429       goto update_cleanup;
68430     }
68431     for(j=0; j<pTab->nCol; j++){
68432       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
68433         if( j==pTab->iPKey ){
68434           chngRowid = 1;
68435           pRowidExpr = pChanges->a[i].pExpr;
68436         }
68437         aXRef[j] = i;
68438         break;
68439       }
68440     }
68441     if( j>=pTab->nCol ){
68442       if( sqlite3IsRowid(pChanges->a[i].zName) ){
68443         chngRowid = 1;
68444         pRowidExpr = pChanges->a[i].pExpr;
68445       }else{
68446         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
68447         goto update_cleanup;
68448       }
68449     }
68450 #ifndef SQLITE_OMIT_AUTHORIZATION
68451     {
68452       int rc;
68453       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
68454                            pTab->aCol[j].zName, db->aDb[iDb].zName);
68455       if( rc==SQLITE_DENY ){
68456         goto update_cleanup;
68457       }else if( rc==SQLITE_IGNORE ){
68458         aXRef[j] = -1;
68459       }
68460     }
68461 #endif
68462   }
68463
68464   /* Allocate memory for the array aRegIdx[].  There is one entry in the
68465   ** array for each index associated with table being updated.  Fill in
68466   ** the value with a register number for indices that are to be used
68467   ** and with zero for unused indices.
68468   */
68469   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
68470   if( nIdx>0 ){
68471     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
68472     if( aRegIdx==0 ) goto update_cleanup;
68473   }
68474   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
68475     int reg;
68476     if( chngRowid ){
68477       reg = ++pParse->nMem;
68478     }else{
68479       reg = 0;
68480       for(i=0; i<pIdx->nColumn; i++){
68481         if( aXRef[pIdx->aiColumn[i]]>=0 ){
68482           reg = ++pParse->nMem;
68483           break;
68484         }
68485       }
68486     }
68487     aRegIdx[j] = reg;
68488   }
68489
68490   /* Allocate a block of register used to store the change record
68491   ** sent to sqlite3GenerateConstraintChecks().  There are either
68492   ** one or two registers for holding the rowid.  One rowid register
68493   ** is used if chngRowid is false and two are used if chngRowid is
68494   ** true.  Following these are pTab->nCol register holding column
68495   ** data.
68496   */
68497   regOldRowid = regNewRowid = pParse->nMem + 1;
68498   pParse->nMem += pTab->nCol + 1;
68499   if( chngRowid ){
68500     regNewRowid++;
68501     pParse->nMem++;
68502   }
68503   regData = regNewRowid+1;
68504  
68505
68506   /* Begin generating code.
68507   */
68508   v = sqlite3GetVdbe(pParse);
68509   if( v==0 ) goto update_cleanup;
68510   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
68511   sqlite3BeginWriteOperation(pParse, 1, iDb);
68512
68513 #ifndef SQLITE_OMIT_VIRTUALTABLE
68514   /* Virtual tables must be handled separately */
68515   if( IsVirtual(pTab) ){
68516     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
68517                        pWhere);
68518     pWhere = 0;
68519     pTabList = 0;
68520     goto update_cleanup;
68521   }
68522 #endif
68523
68524   /* Start the view context
68525   */
68526   if( isView ){
68527     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
68528   }
68529
68530   /* Generate the code for triggers.
68531   */
68532   if( triggers_exist ){
68533     int iGoto;
68534
68535     /* Create pseudo-tables for NEW and OLD
68536     */
68537     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
68538     sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
68539     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
68540     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
68541
68542     iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
68543     addr = sqlite3VdbeMakeLabel(v);
68544     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
68545     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
68546           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
68547       goto update_cleanup;
68548     }
68549     iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
68550     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
68551     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
68552           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
68553       goto update_cleanup;
68554     }
68555     iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
68556     sqlite3VdbeJumpHere(v, iGoto);
68557   }
68558
68559   /* If we are trying to update a view, realize that view into
68560   ** a ephemeral table.
68561   */
68562   if( isView ){
68563     sqlite3MaterializeView(pParse, pTab->pSelect, pWhere, iCur);
68564   }
68565
68566   /* Resolve the column names in all the expressions in the
68567   ** WHERE clause.
68568   */
68569   if( sqlite3ExprResolveNames(&sNC, pWhere) ){
68570     goto update_cleanup;
68571   }
68572
68573   /* Begin the database scan
68574   */
68575   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
68576   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
68577                              WHERE_ONEPASS_DESIRED);
68578   if( pWInfo==0 ) goto update_cleanup;
68579   okOnePass = pWInfo->okOnePass;
68580
68581   /* Remember the rowid of every item to be updated.
68582   */
68583   sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
68584   if( !okOnePass ) sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0);
68585
68586   /* End the database scan loop.
68587   */
68588   sqlite3WhereEnd(pWInfo);
68589
68590   /* Initialize the count of updated rows
68591   */
68592   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
68593     regRowCount = ++pParse->nMem;
68594     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
68595   }
68596
68597   if( !isView && !IsVirtual(pTab) ){
68598     /* 
68599     ** Open every index that needs updating.  Note that if any
68600     ** index could potentially invoke a REPLACE conflict resolution 
68601     ** action, then we need to open all indices because we might need
68602     ** to be deleting some records.
68603     */
68604     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
68605     if( onError==OE_Replace ){
68606       openAll = 1;
68607     }else{
68608       openAll = 0;
68609       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68610         if( pIdx->onError==OE_Replace ){
68611           openAll = 1;
68612           break;
68613         }
68614       }
68615     }
68616     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
68617       if( openAll || aRegIdx[i]>0 ){
68618         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
68619         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
68620                        (char*)pKey, P4_KEYINFO_HANDOFF);
68621         assert( pParse->nTab>iCur+i+1 );
68622       }
68623     }
68624   }
68625   
68626   /* Jump back to this point if a trigger encounters an IGNORE constraint. */
68627   if( triggers_exist ){
68628     sqlite3VdbeResolveLabel(v, addr);
68629   }
68630
68631   /* Top of the update loop */
68632   if( okOnePass ){
68633     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
68634     addr = sqlite3VdbeAddOp0(v, OP_Goto);
68635     sqlite3VdbeJumpHere(v, a1);
68636   }else{
68637     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, regOldRowid, 0);
68638   }
68639
68640   if( triggers_exist ){
68641     int regRowid;
68642     int regRow;
68643     int regCols;
68644
68645     /* Make cursor iCur point to the record that is being updated.
68646     */
68647     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
68648
68649     /* Generate the OLD table
68650     */
68651     regRowid = sqlite3GetTempReg(pParse);
68652     regRow = sqlite3GetTempReg(pParse);
68653     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
68654     if( !old_col_mask ){
68655       sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
68656     }else{
68657       sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
68658     }
68659     sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
68660
68661     /* Generate the NEW table
68662     */
68663     if( chngRowid ){
68664       sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
68665     }else{
68666       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
68667     }
68668     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
68669     for(i=0; i<pTab->nCol; i++){
68670       if( i==pTab->iPKey ){
68671         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
68672         continue;
68673       }
68674       j = aXRef[i];
68675       if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
68676         if( j<0 ){
68677           sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
68678           sqlite3ColumnDefault(v, pTab, i);
68679         }else{
68680           sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
68681         }
68682       }else{
68683         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
68684       }
68685     }
68686     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
68687     if( !isView ){
68688       sqlite3TableAffinityStr(v, pTab);
68689       sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
68690     }
68691     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
68692     if( pParse->nErr ) goto update_cleanup;
68693     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
68694     sqlite3ReleaseTempReg(pParse, regRowid);
68695     sqlite3ReleaseTempReg(pParse, regRow);
68696
68697     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
68698     sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
68699   }
68700
68701   if( !isView && !IsVirtual(pTab) ){
68702     /* Loop over every record that needs updating.  We have to load
68703     ** the old data for each record to be updated because some columns
68704     ** might not change and we will need to copy the old value.
68705     ** Also, the old data is needed to delete the old index entries.
68706     ** So make the cursor point at the old record.
68707     */
68708     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
68709
68710     /* If the record number will change, push the record number as it
68711     ** will be after the update. (The old record number is currently
68712     ** on top of the stack.)
68713     */
68714     if( chngRowid ){
68715       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
68716       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
68717     }
68718
68719     /* Compute new data for this record.  
68720     */
68721     for(i=0; i<pTab->nCol; i++){
68722       if( i==pTab->iPKey ){
68723         sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
68724         continue;
68725       }
68726       j = aXRef[i];
68727       if( j<0 ){
68728         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
68729         sqlite3ColumnDefault(v, pTab, i);
68730       }else{
68731         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
68732       }
68733     }
68734
68735     /* Do constraint checks
68736     */
68737     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
68738                                     aRegIdx, chngRowid, 1,
68739                                     onError, addr);
68740
68741     /* Delete the old indices for the current record.
68742     */
68743     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
68744     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
68745
68746     /* If changing the record number, delete the old record.
68747     */
68748     if( chngRowid ){
68749       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
68750     }
68751     sqlite3VdbeJumpHere(v, j1);
68752
68753     /* Create the new index entries and the new record.
68754     */
68755     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
68756                              aRegIdx, chngRowid, 1, -1, 0);
68757   }
68758
68759   /* Increment the row counter 
68760   */
68761   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
68762     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
68763   }
68764
68765   /* If there are triggers, close all the cursors after each iteration
68766   ** through the loop.  The fire the after triggers.
68767   */
68768   if( triggers_exist ){
68769     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
68770     sqlite3VdbeJumpHere(v, iEndAfterTrigger);
68771   }
68772
68773   /* Repeat the above with the next record to be updated, until
68774   ** all record selected by the WHERE clause have been updated.
68775   */
68776   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
68777   sqlite3VdbeJumpHere(v, addr);
68778
68779   /* Close all tables */
68780   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
68781     if( openAll || aRegIdx[i]>0 ){
68782       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
68783     }
68784   }
68785   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
68786   if( triggers_exist ){
68787     sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
68788     sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
68789   }
68790
68791   /*
68792   ** Return the number of rows that were changed. If this routine is 
68793   ** generating code because of a call to sqlite3NestedParse(), do not
68794   ** invoke the callback function.
68795   */
68796   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
68797     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
68798     sqlite3VdbeSetNumCols(v, 1);
68799     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P4_STATIC);
68800   }
68801
68802 update_cleanup:
68803   sqlite3AuthContextPop(&sContext);
68804   sqlite3_free(aRegIdx);
68805   sqlite3_free(aXRef);
68806   sqlite3SrcListDelete(pTabList);
68807   sqlite3ExprListDelete(pChanges);
68808   sqlite3ExprDelete(pWhere);
68809   return;
68810 }
68811
68812 #ifndef SQLITE_OMIT_VIRTUALTABLE
68813 /*
68814 ** Generate code for an UPDATE of a virtual table.
68815 **
68816 ** The strategy is that we create an ephemerial table that contains
68817 ** for each row to be changed:
68818 **
68819 **   (A)  The original rowid of that row.
68820 **   (B)  The revised rowid for the row. (note1)
68821 **   (C)  The content of every column in the row.
68822 **
68823 ** Then we loop over this ephemeral table and for each row in
68824 ** the ephermeral table call VUpdate.
68825 **
68826 ** When finished, drop the ephemeral table.
68827 **
68828 ** (note1) Actually, if we know in advance that (A) is always the same
68829 ** as (B) we only store (A), then duplicate (A) when pulling
68830 ** it out of the ephemeral table before calling VUpdate.
68831 */
68832 static void updateVirtualTable(
68833   Parse *pParse,       /* The parsing context */
68834   SrcList *pSrc,       /* The virtual table to be modified */
68835   Table *pTab,         /* The virtual table */
68836   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
68837   Expr *pRowid,        /* Expression used to recompute the rowid */
68838   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
68839   Expr *pWhere         /* WHERE clause of the UPDATE statement */
68840 ){
68841   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
68842   ExprList *pEList = 0;     /* The result set of the SELECT statement */
68843   Select *pSelect = 0;      /* The SELECT statement */
68844   Expr *pExpr;              /* Temporary expression */
68845   int ephemTab;             /* Table holding the result of the SELECT */
68846   int i;                    /* Loop counter */
68847   int addr;                 /* Address of top of loop */
68848   int iReg;                 /* First register in set passed to OP_VUpdate */
68849   sqlite3 *db = pParse->db; /* Database connection */
68850   const char *pVtab = (const char*)pTab->pVtab;
68851   SelectDest dest;
68852
68853   /* Construct the SELECT statement that will find the new values for
68854   ** all updated rows. 
68855   */
68856   pEList = sqlite3ExprListAppend(pParse, 0, 
68857                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
68858   if( pRowid ){
68859     pEList = sqlite3ExprListAppend(pParse, pEList,
68860                                    sqlite3ExprDup(db, pRowid), 0);
68861   }
68862   assert( pTab->iPKey<0 );
68863   for(i=0; i<pTab->nCol; i++){
68864     if( aXRef[i]>=0 ){
68865       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
68866     }else{
68867       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
68868     }
68869     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
68870   }
68871   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
68872   
68873   /* Create the ephemeral table into which the update results will
68874   ** be stored.
68875   */
68876   assert( v );
68877   ephemTab = pParse->nTab++;
68878   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
68879
68880   /* fill the ephemeral table 
68881   */
68882   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
68883   sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0);
68884
68885   /* Generate code to scan the ephemeral table and call VUpdate. */
68886   iReg = ++pParse->nMem;
68887   pParse->nMem += pTab->nCol+1;
68888   sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
68889   addr = sqlite3VdbeCurrentAddr(v);
68890   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
68891   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
68892   for(i=0; i<pTab->nCol; i++){
68893     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
68894   }
68895   sqlite3VtabMakeWritable(pParse, pTab);
68896   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
68897   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
68898   sqlite3VdbeJumpHere(v, addr-1);
68899   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
68900
68901   /* Cleanup */
68902   sqlite3SelectDelete(pSelect);  
68903 }
68904 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68905
68906 /* Make sure "isView" gets undefined in case this file becomes part of
68907 ** the amalgamation - so that subsequent files do not see isView as a
68908 ** macro. */
68909 #undef isView
68910
68911 /************** End of update.c **********************************************/
68912 /************** Begin file vacuum.c ******************************************/
68913 /*
68914 ** 2003 April 6
68915 **
68916 ** The author disclaims copyright to this source code.  In place of
68917 ** a legal notice, here is a blessing:
68918 **
68919 **    May you do good and not evil.
68920 **    May you find forgiveness for yourself and forgive others.
68921 **    May you share freely, never taking more than you give.
68922 **
68923 *************************************************************************
68924 ** This file contains code used to implement the VACUUM command.
68925 **
68926 ** Most of the code in this file may be omitted by defining the
68927 ** SQLITE_OMIT_VACUUM macro.
68928 **
68929 ** $Id: vacuum.c,v 1.78 2008/04/30 16:38:23 drh Exp $
68930 */
68931
68932 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
68933 /*
68934 ** Execute zSql on database db. Return an error code.
68935 */
68936 static int execSql(sqlite3 *db, const char *zSql){
68937   sqlite3_stmt *pStmt;
68938   if( !zSql ){
68939     return SQLITE_NOMEM;
68940   }
68941   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
68942     return sqlite3_errcode(db);
68943   }
68944   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
68945   return sqlite3_finalize(pStmt);
68946 }
68947
68948 /*
68949 ** Execute zSql on database db. The statement returns exactly
68950 ** one column. Execute this as SQL on the same database.
68951 */
68952 static int execExecSql(sqlite3 *db, const char *zSql){
68953   sqlite3_stmt *pStmt;
68954   int rc;
68955
68956   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
68957   if( rc!=SQLITE_OK ) return rc;
68958
68959   while( SQLITE_ROW==sqlite3_step(pStmt) ){
68960     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
68961     if( rc!=SQLITE_OK ){
68962       sqlite3_finalize(pStmt);
68963       return rc;
68964     }
68965   }
68966
68967   return sqlite3_finalize(pStmt);
68968 }
68969
68970 /*
68971 ** The non-standard VACUUM command is used to clean up the database,
68972 ** collapse free space, etc.  It is modelled after the VACUUM command
68973 ** in PostgreSQL.
68974 **
68975 ** In version 1.0.x of SQLite, the VACUUM command would call
68976 ** gdbm_reorganize() on all the database tables.  But beginning
68977 ** with 2.0.0, SQLite no longer uses GDBM so this command has
68978 ** become a no-op.
68979 */
68980 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
68981   Vdbe *v = sqlite3GetVdbe(pParse);
68982   if( v ){
68983     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
68984   }
68985   return;
68986 }
68987
68988 /*
68989 ** This routine implements the OP_Vacuum opcode of the VDBE.
68990 */
68991 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
68992   int rc = SQLITE_OK;     /* Return code from service routines */
68993   Btree *pMain;           /* The database being vacuumed */
68994   Btree *pTemp;           /* The temporary database we vacuum into */
68995   char *zSql = 0;         /* SQL statements */
68996   int saved_flags;        /* Saved value of the db->flags */
68997   Db *pDb = 0;            /* Database to detach at end of vacuum */
68998   int nRes;
68999
69000   /* Save the current value of the write-schema flag before setting it. */
69001   saved_flags = db->flags;
69002   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
69003
69004   if( !db->autoCommit ){
69005     sqlite3SetString(pzErrMsg, "cannot VACUUM from within a transaction", 
69006        (char*)0);
69007     rc = SQLITE_ERROR;
69008     goto end_of_vacuum;
69009   }
69010   pMain = db->aDb[0].pBt;
69011
69012   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
69013   ** can be set to 'off' for this file, as it is not recovered if a crash
69014   ** occurs anyway. The integrity of the database is maintained by a
69015   ** (possibly synchronous) transaction opened on the main database before
69016   ** sqlite3BtreeCopyFile() is called.
69017   **
69018   ** An optimisation would be to use a non-journaled pager.
69019   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
69020   ** that actually made the VACUUM run slower.  Very little journalling
69021   ** actually occurs when doing a vacuum since the vacuum_db is initially
69022   ** empty.  Only the journal header is written.  Apparently it takes more
69023   ** time to parse and run the PRAGMA to turn journalling off than it does
69024   ** to write the journal header file.
69025   */
69026   zSql = "ATTACH '' AS vacuum_db;";
69027   rc = execSql(db, zSql);
69028   if( rc!=SQLITE_OK ) goto end_of_vacuum;
69029   pDb = &db->aDb[db->nDb-1];
69030   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
69031   pTemp = db->aDb[db->nDb-1].pBt;
69032
69033   nRes = sqlite3BtreeGetReserve(pMain);
69034   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes)
69035    || sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes)
69036    || db->mallocFailed 
69037   ){
69038     rc = SQLITE_NOMEM;
69039     goto end_of_vacuum;
69040   }
69041   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
69042   if( rc!=SQLITE_OK ){
69043     goto end_of_vacuum;
69044   }
69045
69046 #ifndef SQLITE_OMIT_AUTOVACUUM
69047   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
69048                                            sqlite3BtreeGetAutoVacuum(pMain));
69049 #endif
69050
69051   /* Begin a transaction */
69052   rc = execSql(db, "BEGIN EXCLUSIVE;");
69053   if( rc!=SQLITE_OK ) goto end_of_vacuum;
69054
69055   /* Query the schema of the main database. Create a mirror schema
69056   ** in the temporary database.
69057   */
69058   rc = execExecSql(db, 
69059       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
69060       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
69061       "   AND rootpage>0"
69062   );
69063   if( rc!=SQLITE_OK ) goto end_of_vacuum;
69064   rc = execExecSql(db, 
69065       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
69066       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
69067   if( rc!=SQLITE_OK ) goto end_of_vacuum;
69068   rc = execExecSql(db, 
69069       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
69070       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
69071   if( rc!=SQLITE_OK ) goto end_of_vacuum;
69072
69073   /* Loop through the tables in the main database. For each, do
69074   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
69075   ** the contents to the temporary database.
69076   */
69077   rc = execExecSql(db, 
69078       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
69079       "|| ' SELECT * FROM ' || quote(name) || ';'"
69080       "FROM sqlite_master "
69081       "WHERE type = 'table' AND name!='sqlite_sequence' "
69082       "  AND rootpage>0"
69083
69084   );
69085   if( rc!=SQLITE_OK ) goto end_of_vacuum;
69086
69087   /* Copy over the sequence table
69088   */
69089   rc = execExecSql(db, 
69090       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
69091       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
69092   );
69093   if( rc!=SQLITE_OK ) goto end_of_vacuum;
69094   rc = execExecSql(db, 
69095       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
69096       "|| ' SELECT * FROM ' || quote(name) || ';' "
69097       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
69098   );
69099   if( rc!=SQLITE_OK ) goto end_of_vacuum;
69100
69101
69102   /* Copy the triggers, views, and virtual tables from the main database
69103   ** over to the temporary database.  None of these objects has any
69104   ** associated storage, so all we have to do is copy their entries
69105   ** from the SQLITE_MASTER table.
69106   */
69107   rc = execSql(db,
69108       "INSERT INTO vacuum_db.sqlite_master "
69109       "  SELECT type, name, tbl_name, rootpage, sql"
69110       "    FROM sqlite_master"
69111       "   WHERE type='view' OR type='trigger'"
69112       "      OR (type='table' AND rootpage=0)"
69113   );
69114   if( rc ) goto end_of_vacuum;
69115
69116   /* At this point, unless the main db was completely empty, there is now a
69117   ** transaction open on the vacuum database, but not on the main database.
69118   ** Open a btree level transaction on the main database. This allows a
69119   ** call to sqlite3BtreeCopyFile(). The main database btree level
69120   ** transaction is then committed, so the SQL level never knows it was
69121   ** opened for writing. This way, the SQL transaction used to create the
69122   ** temporary database never needs to be committed.
69123   */
69124   if( rc==SQLITE_OK ){
69125     u32 meta;
69126     int i;
69127
69128     /* This array determines which meta meta values are preserved in the
69129     ** vacuum.  Even entries are the meta value number and odd entries
69130     ** are an increment to apply to the meta value after the vacuum.
69131     ** The increment is used to increase the schema cookie so that other
69132     ** connections to the same database will know to reread the schema.
69133     */
69134     static const unsigned char aCopy[] = {
69135        1, 1,    /* Add one to the old schema cookie */
69136        3, 0,    /* Preserve the default page cache size */
69137        5, 0,    /* Preserve the default text encoding */
69138        6, 0,    /* Preserve the user version */
69139     };
69140
69141     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
69142     assert( 1==sqlite3BtreeIsInTrans(pMain) );
69143
69144     /* Copy Btree meta values */
69145     for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
69146       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
69147       if( rc!=SQLITE_OK ) goto end_of_vacuum;
69148       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
69149       if( rc!=SQLITE_OK ) goto end_of_vacuum;
69150     }
69151
69152     rc = sqlite3BtreeCopyFile(pMain, pTemp);
69153     if( rc!=SQLITE_OK ) goto end_of_vacuum;
69154     rc = sqlite3BtreeCommit(pTemp);
69155     if( rc!=SQLITE_OK ) goto end_of_vacuum;
69156     rc = sqlite3BtreeCommit(pMain);
69157   }
69158
69159   if( rc==SQLITE_OK ){
69160     rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes);
69161   }
69162
69163 end_of_vacuum:
69164   /* Restore the original value of db->flags */
69165   db->flags = saved_flags;
69166
69167   /* Currently there is an SQL level transaction open on the vacuum
69168   ** database. No locks are held on any other files (since the main file
69169   ** was committed at the btree level). So it safe to end the transaction
69170   ** by manually setting the autoCommit flag to true and detaching the
69171   ** vacuum database. The vacuum_db journal file is deleted when the pager
69172   ** is closed by the DETACH.
69173   */
69174   db->autoCommit = 1;
69175
69176   if( pDb ){
69177     sqlite3BtreeClose(pDb->pBt);
69178     pDb->pBt = 0;
69179     pDb->pSchema = 0;
69180   }
69181
69182   sqlite3ResetInternalSchema(db, 0);
69183
69184   return rc;
69185 }
69186 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
69187
69188 /************** End of vacuum.c **********************************************/
69189 /************** Begin file vtab.c ********************************************/
69190 /*
69191 ** 2006 June 10
69192 **
69193 ** The author disclaims copyright to this source code.  In place of
69194 ** a legal notice, here is a blessing:
69195 **
69196 **    May you do good and not evil.
69197 **    May you find forgiveness for yourself and forgive others.
69198 **    May you share freely, never taking more than you give.
69199 **
69200 *************************************************************************
69201 ** This file contains code used to help implement virtual tables.
69202 **
69203 ** $Id: vtab.c,v 1.69 2008/05/05 13:23:04 drh Exp $
69204 */
69205 #ifndef SQLITE_OMIT_VIRTUALTABLE
69206
69207 static int createModule(
69208   sqlite3 *db,                    /* Database in which module is registered */
69209   const char *zName,              /* Name assigned to this module */
69210   const sqlite3_module *pModule,  /* The definition of the module */
69211   void *pAux,                     /* Context pointer for xCreate/xConnect */
69212   void (*xDestroy)(void *)        /* Module destructor function */
69213 ) {
69214   int rc, nName;
69215   Module *pMod;
69216
69217   sqlite3_mutex_enter(db->mutex);
69218   nName = strlen(zName);
69219   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
69220   if( pMod ){
69221     char *zCopy = (char *)(&pMod[1]);
69222     memcpy(zCopy, zName, nName+1);
69223     pMod->zName = zCopy;
69224     pMod->pModule = pModule;
69225     pMod->pAux = pAux;
69226     pMod->xDestroy = xDestroy;
69227     pMod = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
69228     if( pMod && pMod->xDestroy ){
69229       pMod->xDestroy(pMod->pAux);
69230     }
69231     sqlite3_free(pMod);
69232     sqlite3ResetInternalSchema(db, 0);
69233   }
69234   rc = sqlite3ApiExit(db, SQLITE_OK);
69235   sqlite3_mutex_leave(db->mutex);
69236   return rc;
69237 }
69238
69239
69240 /*
69241 ** External API function used to create a new virtual-table module.
69242 */
69243 SQLITE_API int sqlite3_create_module(
69244   sqlite3 *db,                    /* Database in which module is registered */
69245   const char *zName,              /* Name assigned to this module */
69246   const sqlite3_module *pModule,  /* The definition of the module */
69247   void *pAux                      /* Context pointer for xCreate/xConnect */
69248 ){
69249   return createModule(db, zName, pModule, pAux, 0);
69250 }
69251
69252 /*
69253 ** External API function used to create a new virtual-table module.
69254 */
69255 SQLITE_API int sqlite3_create_module_v2(
69256   sqlite3 *db,                    /* Database in which module is registered */
69257   const char *zName,              /* Name assigned to this module */
69258   const sqlite3_module *pModule,  /* The definition of the module */
69259   void *pAux,                     /* Context pointer for xCreate/xConnect */
69260   void (*xDestroy)(void *)        /* Module destructor function */
69261 ){
69262   return createModule(db, zName, pModule, pAux, xDestroy);
69263 }
69264
69265 /*
69266 ** Lock the virtual table so that it cannot be disconnected.
69267 ** Locks nest.  Every lock should have a corresponding unlock.
69268 ** If an unlock is omitted, resources leaks will occur.  
69269 **
69270 ** If a disconnect is attempted while a virtual table is locked,
69271 ** the disconnect is deferred until all locks have been removed.
69272 */
69273 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
69274   pVtab->nRef++;
69275 }
69276
69277 /*
69278 ** Unlock a virtual table.  When the last lock is removed,
69279 ** disconnect the virtual table.
69280 */
69281 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
69282   pVtab->nRef--;
69283   assert(db);
69284   assert( sqlite3SafetyCheckOk(db) );
69285   if( pVtab->nRef==0 ){
69286     if( db->magic==SQLITE_MAGIC_BUSY ){
69287       (void)sqlite3SafetyOff(db);
69288       pVtab->pModule->xDisconnect(pVtab);
69289       (void)sqlite3SafetyOn(db);
69290     } else {
69291       pVtab->pModule->xDisconnect(pVtab);
69292     }
69293   }
69294 }
69295
69296 /*
69297 ** Clear any and all virtual-table information from the Table record.
69298 ** This routine is called, for example, just before deleting the Table
69299 ** record.
69300 */
69301 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
69302   sqlite3_vtab *pVtab = p->pVtab;
69303   if( pVtab ){
69304     assert( p->pMod && p->pMod->pModule );
69305     sqlite3VtabUnlock(p->pSchema->db, pVtab);
69306     p->pVtab = 0;
69307   }
69308   if( p->azModuleArg ){
69309     int i;
69310     for(i=0; i<p->nModuleArg; i++){
69311       sqlite3_free(p->azModuleArg[i]);
69312     }
69313     sqlite3_free(p->azModuleArg);
69314   }
69315 }
69316
69317 /*
69318 ** Add a new module argument to pTable->azModuleArg[].
69319 ** The string is not copied - the pointer is stored.  The
69320 ** string will be freed automatically when the table is
69321 ** deleted.
69322 */
69323 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
69324   int i = pTable->nModuleArg++;
69325   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
69326   char **azModuleArg;
69327   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
69328   if( azModuleArg==0 ){
69329     int j;
69330     for(j=0; j<i; j++){
69331       sqlite3_free(pTable->azModuleArg[j]);
69332     }
69333     sqlite3_free(zArg);
69334     sqlite3_free(pTable->azModuleArg);
69335     pTable->nModuleArg = 0;
69336   }else{
69337     azModuleArg[i] = zArg;
69338     azModuleArg[i+1] = 0;
69339   }
69340   pTable->azModuleArg = azModuleArg;
69341 }
69342
69343 /*
69344 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
69345 ** statement.  The module name has been parsed, but the optional list
69346 ** of parameters that follow the module name are still pending.
69347 */
69348 SQLITE_PRIVATE void sqlite3VtabBeginParse(
69349   Parse *pParse,        /* Parsing context */
69350   Token *pName1,        /* Name of new table, or database name */
69351   Token *pName2,        /* Name of new table or NULL */
69352   Token *pModuleName    /* Name of the module for the virtual table */
69353 ){
69354   int iDb;              /* The database the table is being created in */
69355   Table *pTable;        /* The new virtual table */
69356   sqlite3 *db;          /* Database connection */
69357
69358   if( pParse->db->flags & SQLITE_SharedCache ){
69359     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
69360     return;
69361   }
69362
69363   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
69364   pTable = pParse->pNewTable;
69365   if( pTable==0 || pParse->nErr ) return;
69366   assert( 0==pTable->pIndex );
69367
69368   db = pParse->db;
69369   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
69370   assert( iDb>=0 );
69371
69372   pTable->isVirtual = 1;
69373   pTable->nModuleArg = 0;
69374   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
69375   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
69376   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
69377   pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
69378
69379 #ifndef SQLITE_OMIT_AUTHORIZATION
69380   /* Creating a virtual table invokes the authorization callback twice.
69381   ** The first invocation, to obtain permission to INSERT a row into the
69382   ** sqlite_master table, has already been made by sqlite3StartTable().
69383   ** The second call, to obtain permission to create the table, is made now.
69384   */
69385   if( pTable->azModuleArg ){
69386     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
69387             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
69388   }
69389 #endif
69390 }
69391
69392 /*
69393 ** This routine takes the module argument that has been accumulating
69394 ** in pParse->zArg[] and appends it to the list of arguments on the
69395 ** virtual table currently under construction in pParse->pTable.
69396 */
69397 static void addArgumentToVtab(Parse *pParse){
69398   if( pParse->sArg.z && pParse->pNewTable ){
69399     const char *z = (const char*)pParse->sArg.z;
69400     int n = pParse->sArg.n;
69401     sqlite3 *db = pParse->db;
69402     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
69403   }
69404 }
69405
69406 /*
69407 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
69408 ** has been completely parsed.
69409 */
69410 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
69411   Table *pTab;        /* The table being constructed */
69412   sqlite3 *db;        /* The database connection */
69413   char *zModule;      /* The module name of the table: USING modulename */
69414   Module *pMod = 0;
69415
69416   addArgumentToVtab(pParse);
69417   pParse->sArg.z = 0;
69418
69419   /* Lookup the module name. */
69420   pTab = pParse->pNewTable;
69421   if( pTab==0 ) return;
69422   db = pParse->db;
69423   if( pTab->nModuleArg<1 ) return;
69424   zModule = pTab->azModuleArg[0];
69425   pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
69426   pTab->pMod = pMod;
69427   
69428   /* If the CREATE VIRTUAL TABLE statement is being entered for the
69429   ** first time (in other words if the virtual table is actually being
69430   ** created now instead of just being read out of sqlite_master) then
69431   ** do additional initialization work and store the statement text
69432   ** in the sqlite_master table.
69433   */
69434   if( !db->init.busy ){
69435     char *zStmt;
69436     char *zWhere;
69437     int iDb;
69438     Vdbe *v;
69439
69440     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
69441     if( pEnd ){
69442       pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
69443     }
69444     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
69445
69446     /* A slot for the record has already been allocated in the 
69447     ** SQLITE_MASTER table.  We just need to update that slot with all
69448     ** the information we've collected.  
69449     **
69450     ** The VM register number pParse->regRowid holds the rowid of an
69451     ** entry in the sqlite_master table tht was created for this vtab
69452     ** by sqlite3StartTable().
69453     */
69454     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69455     sqlite3NestedParse(pParse,
69456       "UPDATE %Q.%s "
69457          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
69458        "WHERE rowid=#%d",
69459       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69460       pTab->zName,
69461       pTab->zName,
69462       zStmt,
69463       pParse->regRowid
69464     );
69465     sqlite3_free(zStmt);
69466     v = sqlite3GetVdbe(pParse);
69467     sqlite3ChangeCookie(pParse, iDb);
69468
69469     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
69470     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
69471     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
69472     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
69473                          pTab->zName, strlen(pTab->zName) + 1);
69474   }
69475
69476   /* If we are rereading the sqlite_master table create the in-memory
69477   ** record of the table. If the module has already been registered,
69478   ** also call the xConnect method here.
69479   */
69480   else {
69481     Table *pOld;
69482     Schema *pSchema = pTab->pSchema;
69483     const char *zName = pTab->zName;
69484     int nName = strlen(zName) + 1;
69485     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
69486     if( pOld ){
69487       db->mallocFailed = 1;
69488       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
69489       return;
69490     }
69491     pSchema->db = pParse->db;
69492     pParse->pNewTable = 0;
69493   }
69494 }
69495
69496 /*
69497 ** The parser calls this routine when it sees the first token
69498 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
69499 */
69500 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
69501   addArgumentToVtab(pParse);
69502   pParse->sArg.z = 0;
69503   pParse->sArg.n = 0;
69504 }
69505
69506 /*
69507 ** The parser calls this routine for each token after the first token
69508 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
69509 */
69510 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
69511   Token *pArg = &pParse->sArg;
69512   if( pArg->z==0 ){
69513     pArg->z = p->z;
69514     pArg->n = p->n;
69515   }else{
69516     assert(pArg->z < p->z);
69517     pArg->n = (p->z + p->n - pArg->z);
69518   }
69519 }
69520
69521 /*
69522 ** Invoke a virtual table constructor (either xCreate or xConnect). The
69523 ** pointer to the function to invoke is passed as the fourth parameter
69524 ** to this procedure.
69525 */
69526 static int vtabCallConstructor(
69527   sqlite3 *db, 
69528   Table *pTab,
69529   Module *pMod,
69530   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
69531   char **pzErr
69532 ){
69533   int rc;
69534   int rc2;
69535   sqlite3_vtab *pVtab = 0;
69536   const char *const*azArg = (const char *const*)pTab->azModuleArg;
69537   int nArg = pTab->nModuleArg;
69538   char *zErr = 0;
69539   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
69540
69541   if( !zModuleName ){
69542     return SQLITE_NOMEM;
69543   }
69544
69545   assert( !db->pVTab );
69546   assert( xConstruct );
69547
69548   db->pVTab = pTab;
69549   rc = sqlite3SafetyOff(db);
69550   assert( rc==SQLITE_OK );
69551   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
69552   rc2 = sqlite3SafetyOn(db);
69553   if( rc==SQLITE_OK && pVtab ){
69554     pVtab->pModule = pMod->pModule;
69555     pVtab->nRef = 1;
69556     pTab->pVtab = pVtab;
69557   }
69558
69559   if( SQLITE_OK!=rc ){
69560     if( zErr==0 ){
69561       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
69562     }else {
69563       *pzErr = sqlite3MPrintf(db, "%s", zErr);
69564       sqlite3_free(zErr);
69565     }
69566   }else if( db->pVTab ){
69567     const char *zFormat = "vtable constructor did not declare schema: %s";
69568     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
69569     rc = SQLITE_ERROR;
69570   } 
69571   if( rc==SQLITE_OK ){
69572     rc = rc2;
69573   }
69574   db->pVTab = 0;
69575   sqlite3_free(zModuleName);
69576
69577   /* If everything went according to plan, loop through the columns
69578   ** of the table to see if any of them contain the token "hidden".
69579   ** If so, set the Column.isHidden flag and remove the token from
69580   ** the type string.
69581   */
69582   if( rc==SQLITE_OK ){
69583     int iCol;
69584     for(iCol=0; iCol<pTab->nCol; iCol++){
69585       char *zType = pTab->aCol[iCol].zType;
69586       int nType;
69587       int i = 0;
69588       if( !zType ) continue;
69589       nType = strlen(zType);
69590       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
69591         for(i=0; i<nType; i++){
69592           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
69593            && (zType[i+7]=='\0' || zType[i+7]==' ')
69594           ){
69595             i++;
69596             break;
69597           }
69598         }
69599       }
69600       if( i<nType ){
69601         int j;
69602         int nDel = 6 + (zType[i+6] ? 1 : 0);
69603         for(j=i; (j+nDel)<=nType; j++){
69604           zType[j] = zType[j+nDel];
69605         }
69606         if( zType[i]=='\0' && i>0 ){
69607           assert(zType[i-1]==' ');
69608           zType[i-1] = '\0';
69609         }
69610         pTab->aCol[iCol].isHidden = 1;
69611       }
69612     }
69613   }
69614   return rc;
69615 }
69616
69617 /*
69618 ** This function is invoked by the parser to call the xConnect() method
69619 ** of the virtual table pTab. If an error occurs, an error code is returned 
69620 ** and an error left in pParse.
69621 **
69622 ** This call is a no-op if table pTab is not a virtual table.
69623 */
69624 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
69625   Module *pMod;
69626   int rc = SQLITE_OK;
69627
69628   if( !pTab || !pTab->isVirtual || pTab->pVtab ){
69629     return SQLITE_OK;
69630   }
69631
69632   pMod = pTab->pMod;
69633   if( !pMod ){
69634     const char *zModule = pTab->azModuleArg[0];
69635     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
69636     rc = SQLITE_ERROR;
69637   } else {
69638     char *zErr = 0;
69639     sqlite3 *db = pParse->db;
69640     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
69641     if( rc!=SQLITE_OK ){
69642       sqlite3ErrorMsg(pParse, "%s", zErr);
69643     }
69644     sqlite3_free(zErr);
69645   }
69646
69647   return rc;
69648 }
69649
69650 /*
69651 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
69652 */
69653 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
69654   const int ARRAY_INCR = 5;
69655
69656   /* Grow the sqlite3.aVTrans array if required */
69657   if( (db->nVTrans%ARRAY_INCR)==0 ){
69658     sqlite3_vtab **aVTrans;
69659     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
69660     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
69661     if( !aVTrans ){
69662       return SQLITE_NOMEM;
69663     }
69664     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
69665     db->aVTrans = aVTrans;
69666   }
69667
69668   /* Add pVtab to the end of sqlite3.aVTrans */
69669   db->aVTrans[db->nVTrans++] = pVtab;
69670   sqlite3VtabLock(pVtab);
69671   return SQLITE_OK;
69672 }
69673
69674 /*
69675 ** This function is invoked by the vdbe to call the xCreate method
69676 ** of the virtual table named zTab in database iDb. 
69677 **
69678 ** If an error occurs, *pzErr is set to point an an English language
69679 ** description of the error and an SQLITE_XXX error code is returned.
69680 ** In this case the caller must call sqlite3_free() on *pzErr.
69681 */
69682 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
69683   int rc = SQLITE_OK;
69684   Table *pTab;
69685   Module *pMod;
69686   const char *zModule;
69687
69688   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
69689   assert(pTab && pTab->isVirtual && !pTab->pVtab);
69690   pMod = pTab->pMod;
69691   zModule = pTab->azModuleArg[0];
69692
69693   /* If the module has been registered and includes a Create method, 
69694   ** invoke it now. If the module has not been registered, return an 
69695   ** error. Otherwise, do nothing.
69696   */
69697   if( !pMod ){
69698     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
69699     rc = SQLITE_ERROR;
69700   }else{
69701     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
69702   }
69703
69704   if( rc==SQLITE_OK && pTab->pVtab ){
69705       rc = addToVTrans(db, pTab->pVtab);
69706   }
69707
69708   return rc;
69709 }
69710
69711 /*
69712 ** This function is used to set the schema of a virtual table.  It is only
69713 ** valid to call this function from within the xCreate() or xConnect() of a
69714 ** virtual table module.
69715 */
69716 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
69717   Parse sParse;
69718
69719   int rc = SQLITE_OK;
69720   Table *pTab;
69721   char *zErr = 0;
69722
69723   sqlite3_mutex_enter(db->mutex);
69724   pTab = db->pVTab;
69725   if( !pTab ){
69726     sqlite3Error(db, SQLITE_MISUSE, 0);
69727     sqlite3_mutex_leave(db->mutex);
69728     return SQLITE_MISUSE;
69729   }
69730   assert(pTab->isVirtual && pTab->nCol==0 && pTab->aCol==0);
69731
69732   memset(&sParse, 0, sizeof(Parse));
69733   sParse.declareVtab = 1;
69734   sParse.db = db;
69735
69736   if( 
69737       SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) && 
69738       sParse.pNewTable && 
69739       !sParse.pNewTable->pSelect && 
69740       !sParse.pNewTable->isVirtual 
69741   ){
69742     pTab->aCol = sParse.pNewTable->aCol;
69743     pTab->nCol = sParse.pNewTable->nCol;
69744     sParse.pNewTable->nCol = 0;
69745     sParse.pNewTable->aCol = 0;
69746     db->pVTab = 0;
69747   } else {
69748     sqlite3Error(db, SQLITE_ERROR, zErr);
69749     sqlite3_free(zErr);
69750     rc = SQLITE_ERROR;
69751   }
69752   sParse.declareVtab = 0;
69753
69754   sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
69755   sqlite3DeleteTable(sParse.pNewTable);
69756   sParse.pNewTable = 0;
69757
69758   assert( (rc&0xff)==rc );
69759   rc = sqlite3ApiExit(db, rc);
69760   sqlite3_mutex_leave(db->mutex);
69761   return rc;
69762 }
69763
69764 /*
69765 ** This function is invoked by the vdbe to call the xDestroy method
69766 ** of the virtual table named zTab in database iDb. This occurs
69767 ** when a DROP TABLE is mentioned.
69768 **
69769 ** This call is a no-op if zTab is not a virtual table.
69770 */
69771 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
69772 {
69773   int rc = SQLITE_OK;
69774   Table *pTab;
69775
69776   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
69777   assert(pTab);
69778   if( pTab->pVtab ){
69779     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
69780     rc = sqlite3SafetyOff(db);
69781     assert( rc==SQLITE_OK );
69782     if( xDestroy ){
69783       rc = xDestroy(pTab->pVtab);
69784     }
69785     (void)sqlite3SafetyOn(db);
69786     if( rc==SQLITE_OK ){
69787       int i;
69788       for(i=0; i<db->nVTrans; i++){
69789         if( db->aVTrans[i]==pTab->pVtab ){
69790           db->aVTrans[i] = db->aVTrans[--db->nVTrans];
69791           break;
69792         }
69793       }
69794       pTab->pVtab = 0;
69795     }
69796   }
69797
69798   return rc;
69799 }
69800
69801 /*
69802 ** This function invokes either the xRollback or xCommit method
69803 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
69804 ** called is identified by the second argument, "offset", which is
69805 ** the offset of the method to call in the sqlite3_module structure.
69806 **
69807 ** The array is cleared after invoking the callbacks. 
69808 */
69809 static void callFinaliser(sqlite3 *db, int offset){
69810   int i;
69811   if( db->aVTrans ){
69812     for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
69813       sqlite3_vtab *pVtab = db->aVTrans[i];
69814       int (*x)(sqlite3_vtab *);
69815       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
69816       if( x ) x(pVtab);
69817       sqlite3VtabUnlock(db, pVtab);
69818     }
69819     sqlite3_free(db->aVTrans);
69820     db->nVTrans = 0;
69821     db->aVTrans = 0;
69822   }
69823 }
69824
69825 /*
69826 ** If argument rc2 is not SQLITE_OK, then return it and do nothing. 
69827 ** Otherwise, invoke the xSync method of all virtual tables in the 
69828 ** sqlite3.aVTrans array. Return the error code for the first error 
69829 ** that occurs, or SQLITE_OK if all xSync operations are successful.
69830 */
69831 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, int rc2){
69832   int i;
69833   int rc = SQLITE_OK;
69834   int rcsafety;
69835   sqlite3_vtab **aVTrans = db->aVTrans;
69836   if( rc2!=SQLITE_OK ) return rc2;
69837
69838   rc = sqlite3SafetyOff(db);
69839   db->aVTrans = 0;
69840   for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
69841     sqlite3_vtab *pVtab = aVTrans[i];
69842     int (*x)(sqlite3_vtab *);
69843     x = pVtab->pModule->xSync;
69844     if( x ){
69845       rc = x(pVtab);
69846     }
69847   }
69848   db->aVTrans = aVTrans;
69849   rcsafety = sqlite3SafetyOn(db);
69850
69851   if( rc==SQLITE_OK ){
69852     rc = rcsafety;
69853   }
69854   return rc;
69855 }
69856
69857 /*
69858 ** Invoke the xRollback method of all virtual tables in the 
69859 ** sqlite3.aVTrans array. Then clear the array itself.
69860 */
69861 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
69862   callFinaliser(db, offsetof(sqlite3_module,xRollback));
69863   return SQLITE_OK;
69864 }
69865
69866 /*
69867 ** Invoke the xCommit method of all virtual tables in the 
69868 ** sqlite3.aVTrans array. Then clear the array itself.
69869 */
69870 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
69871   callFinaliser(db, offsetof(sqlite3_module,xCommit));
69872   return SQLITE_OK;
69873 }
69874
69875 /*
69876 ** If the virtual table pVtab supports the transaction interface
69877 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
69878 ** not currently open, invoke the xBegin method now.
69879 **
69880 ** If the xBegin call is successful, place the sqlite3_vtab pointer
69881 ** in the sqlite3.aVTrans array.
69882 */
69883 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
69884   int rc = SQLITE_OK;
69885   const sqlite3_module *pModule;
69886
69887   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
69888   ** than zero, then this function is being called from within a
69889   ** virtual module xSync() callback. It is illegal to write to 
69890   ** virtual module tables in this case, so return SQLITE_LOCKED.
69891   */
69892   if( 0==db->aVTrans && db->nVTrans>0 ){
69893     return SQLITE_LOCKED;
69894   }
69895   if( !pVtab ){
69896     return SQLITE_OK;
69897   } 
69898   pModule = pVtab->pModule;
69899
69900   if( pModule->xBegin ){
69901     int i;
69902
69903
69904     /* If pVtab is already in the aVTrans array, return early */
69905     for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
69906       if( db->aVTrans[i]==pVtab ){
69907         return SQLITE_OK;
69908       }
69909     }
69910
69911     /* Invoke the xBegin method */
69912     rc = pModule->xBegin(pVtab);
69913     if( rc!=SQLITE_OK ){
69914       return rc;
69915     }
69916
69917     rc = addToVTrans(db, pVtab);
69918   }
69919   return rc;
69920 }
69921
69922 /*
69923 ** The first parameter (pDef) is a function implementation.  The
69924 ** second parameter (pExpr) is the first argument to this function.
69925 ** If pExpr is a column in a virtual table, then let the virtual
69926 ** table implementation have an opportunity to overload the function.
69927 **
69928 ** This routine is used to allow virtual table implementations to
69929 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
69930 **
69931 ** Return either the pDef argument (indicating no change) or a 
69932 ** new FuncDef structure that is marked as ephemeral using the
69933 ** SQLITE_FUNC_EPHEM flag.
69934 */
69935 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
69936   sqlite3 *db,    /* Database connection for reporting malloc problems */
69937   FuncDef *pDef,  /* Function to possibly overload */
69938   int nArg,       /* Number of arguments to the function */
69939   Expr *pExpr     /* First argument to the function */
69940 ){
69941   Table *pTab;
69942   sqlite3_vtab *pVtab;
69943   sqlite3_module *pMod;
69944   void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
69945   void *pArg;
69946   FuncDef *pNew;
69947   int rc = 0;
69948   char *zLowerName;
69949   unsigned char *z;
69950
69951
69952   /* Check to see the left operand is a column in a virtual table */
69953   if( pExpr==0 ) return pDef;
69954   if( pExpr->op!=TK_COLUMN ) return pDef;
69955   pTab = pExpr->pTab;
69956   if( pTab==0 ) return pDef;
69957   if( !pTab->isVirtual ) return pDef;
69958   pVtab = pTab->pVtab;
69959   assert( pVtab!=0 );
69960   assert( pVtab->pModule!=0 );
69961   pMod = (sqlite3_module *)pVtab->pModule;
69962   if( pMod->xFindFunction==0 ) return pDef;
69963  
69964   /* Call the xFindFunction method on the virtual table implementation
69965   ** to see if the implementation wants to overload this function 
69966   */
69967   zLowerName = sqlite3DbStrDup(db, pDef->zName);
69968   if( zLowerName ){
69969     for(z=(unsigned char*)zLowerName; *z; z++){
69970       *z = sqlite3UpperToLower[*z];
69971     }
69972     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
69973     sqlite3_free(zLowerName);
69974   }
69975   if( rc==0 ){
69976     return pDef;
69977   }
69978
69979   /* Create a new ephemeral function definition for the overloaded
69980   ** function */
69981   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + strlen(pDef->zName) );
69982   if( pNew==0 ){
69983     return pDef;
69984   }
69985   *pNew = *pDef;
69986   memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
69987   pNew->xFunc = xFunc;
69988   pNew->pUserData = pArg;
69989   pNew->flags |= SQLITE_FUNC_EPHEM;
69990   return pNew;
69991 }
69992
69993 /*
69994 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
69995 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
69996 ** array if it is missing.  If pTab is already in the array, this routine
69997 ** is a no-op.
69998 */
69999 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
70000   int i, n;
70001   assert( IsVirtual(pTab) );
70002   for(i=0; i<pParse->nVtabLock; i++){
70003     if( pTab==pParse->apVtabLock[i] ) return;
70004   }
70005   n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
70006   pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
70007   if( pParse->apVtabLock ){
70008     pParse->apVtabLock[pParse->nVtabLock++] = pTab;
70009   }else{
70010     pParse->db->mallocFailed = 1;
70011   }
70012 }
70013
70014 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70015
70016 /************** End of vtab.c ************************************************/
70017 /************** Begin file where.c *******************************************/
70018 /*
70019 ** 2001 September 15
70020 **
70021 ** The author disclaims copyright to this source code.  In place of
70022 ** a legal notice, here is a blessing:
70023 **
70024 **    May you do good and not evil.
70025 **    May you find forgiveness for yourself and forgive others.
70026 **    May you share freely, never taking more than you give.
70027 **
70028 *************************************************************************
70029 ** This module contains C code that generates VDBE code used to process
70030 ** the WHERE clause of SQL statements.  This module is reponsible for
70031 ** generating the code that loops through a table looking for applicable
70032 ** rows.  Indices are selected and used to speed the search when doing
70033 ** so is applicable.  Because this module is responsible for selecting
70034 ** indices, you might also think of this module as the "query optimizer".
70035 **
70036 ** $Id: where.c,v 1.302 2008/04/19 14:40:44 drh Exp $
70037 */
70038
70039 /*
70040 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
70041 */
70042 #define BMS  (sizeof(Bitmask)*8)
70043
70044 /*
70045 ** Trace output macros
70046 */
70047 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
70048 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
70049 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
70050 #else
70051 # define WHERETRACE(X)
70052 #endif
70053
70054 /* Forward reference
70055 */
70056 typedef struct WhereClause WhereClause;
70057 typedef struct ExprMaskSet ExprMaskSet;
70058
70059 /*
70060 ** The query generator uses an array of instances of this structure to
70061 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
70062 ** clause subexpression is separated from the others by an AND operator.
70063 **
70064 ** All WhereTerms are collected into a single WhereClause structure.  
70065 ** The following identity holds:
70066 **
70067 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
70068 **
70069 ** When a term is of the form:
70070 **
70071 **              X <op> <expr>
70072 **
70073 ** where X is a column name and <op> is one of certain operators,
70074 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
70075 ** cursor number and column number for X.  WhereTerm.operator records
70076 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
70077 ** use of a bitmask encoding for the operator allows us to search
70078 ** quickly for terms that match any of several different operators.
70079 **
70080 ** prereqRight and prereqAll record sets of cursor numbers,
70081 ** but they do so indirectly.  A single ExprMaskSet structure translates
70082 ** cursor number into bits and the translated bit is stored in the prereq
70083 ** fields.  The translation is used in order to maximize the number of
70084 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
70085 ** spread out over the non-negative integers.  For example, the cursor
70086 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
70087 ** translates these sparse cursor numbers into consecutive integers
70088 ** beginning with 0 in order to make the best possible use of the available
70089 ** bits in the Bitmask.  So, in the example above, the cursor numbers
70090 ** would be mapped into integers 0 through 7.
70091 */
70092 typedef struct WhereTerm WhereTerm;
70093 struct WhereTerm {
70094   Expr *pExpr;            /* Pointer to the subexpression */
70095   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
70096   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
70097   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
70098   u16 eOperator;          /* A WO_xx value describing <op> */
70099   u8 flags;               /* Bit flags.  See below */
70100   u8 nChild;              /* Number of children that must disable us */
70101   WhereClause *pWC;       /* The clause this term is part of */
70102   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
70103   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
70104 };
70105
70106 /*
70107 ** Allowed values of WhereTerm.flags
70108 */
70109 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(pExpr) */
70110 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
70111 #define TERM_CODED      0x04   /* This term is already coded */
70112 #define TERM_COPIED     0x08   /* Has a child */
70113 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
70114
70115 /*
70116 ** An instance of the following structure holds all information about a
70117 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
70118 */
70119 struct WhereClause {
70120   Parse *pParse;           /* The parser context */
70121   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
70122   int nTerm;               /* Number of terms */
70123   int nSlot;               /* Number of entries in a[] */
70124   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
70125   WhereTerm aStatic[10];   /* Initial static space for a[] */
70126 };
70127
70128 /*
70129 ** An instance of the following structure keeps track of a mapping
70130 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
70131 **
70132 ** The VDBE cursor numbers are small integers contained in 
70133 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
70134 ** clause, the cursor numbers might not begin with 0 and they might
70135 ** contain gaps in the numbering sequence.  But we want to make maximum
70136 ** use of the bits in our bitmasks.  This structure provides a mapping
70137 ** from the sparse cursor numbers into consecutive integers beginning
70138 ** with 0.
70139 **
70140 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
70141 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
70142 **
70143 ** For example, if the WHERE clause expression used these VDBE
70144 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
70145 ** would map those cursor numbers into bits 0 through 5.
70146 **
70147 ** Note that the mapping is not necessarily ordered.  In the example
70148 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
70149 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
70150 ** does not really matter.  What is important is that sparse cursor
70151 ** numbers all get mapped into bit numbers that begin with 0 and contain
70152 ** no gaps.
70153 */
70154 struct ExprMaskSet {
70155   int n;                        /* Number of assigned cursor values */
70156   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
70157 };
70158
70159
70160 /*
70161 ** Bitmasks for the operators that indices are able to exploit.  An
70162 ** OR-ed combination of these values can be used when searching for
70163 ** terms in the where clause.
70164 */
70165 #define WO_IN     1
70166 #define WO_EQ     2
70167 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
70168 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
70169 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
70170 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
70171 #define WO_MATCH  64
70172 #define WO_ISNULL 128
70173
70174 /*
70175 ** Value for flags returned by bestIndex().  
70176 **
70177 ** The least significant byte is reserved as a mask for WO_ values above.
70178 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
70179 ** But if the table is the right table of a left join, WhereLevel.flags
70180 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
70181 ** the "op" parameter to findTerm when we are resolving equality constraints.
70182 ** ISNULL constraints will then not be used on the right table of a left
70183 ** join.  Tickets #2177 and #2189.
70184 */
70185 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
70186 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
70187 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
70188 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
70189 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
70190 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
70191 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
70192 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
70193 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
70194 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
70195 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
70196 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
70197
70198 /*
70199 ** Initialize a preallocated WhereClause structure.
70200 */
70201 static void whereClauseInit(
70202   WhereClause *pWC,        /* The WhereClause to be initialized */
70203   Parse *pParse,           /* The parsing context */
70204   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
70205 ){
70206   pWC->pParse = pParse;
70207   pWC->pMaskSet = pMaskSet;
70208   pWC->nTerm = 0;
70209   pWC->nSlot = ArraySize(pWC->aStatic);
70210   pWC->a = pWC->aStatic;
70211 }
70212
70213 /*
70214 ** Deallocate a WhereClause structure.  The WhereClause structure
70215 ** itself is not freed.  This routine is the inverse of whereClauseInit().
70216 */
70217 static void whereClauseClear(WhereClause *pWC){
70218   int i;
70219   WhereTerm *a;
70220   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
70221     if( a->flags & TERM_DYNAMIC ){
70222       sqlite3ExprDelete(a->pExpr);
70223     }
70224   }
70225   if( pWC->a!=pWC->aStatic ){
70226     sqlite3_free(pWC->a);
70227   }
70228 }
70229
70230 /*
70231 ** Add a new entries to the WhereClause structure.  Increase the allocated
70232 ** space as necessary.
70233 **
70234 ** If the flags argument includes TERM_DYNAMIC, then responsibility
70235 ** for freeing the expression p is assumed by the WhereClause object.
70236 **
70237 ** WARNING:  This routine might reallocate the space used to store
70238 ** WhereTerms.  All pointers to WhereTerms should be invalided after
70239 ** calling this routine.  Such pointers may be reinitialized by referencing
70240 ** the pWC->a[] array.
70241 */
70242 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
70243   WhereTerm *pTerm;
70244   int idx;
70245   if( pWC->nTerm>=pWC->nSlot ){
70246     WhereTerm *pOld = pWC->a;
70247     pWC->a = sqlite3_malloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
70248     if( pWC->a==0 ){
70249       pWC->pParse->db->mallocFailed = 1;
70250       if( flags & TERM_DYNAMIC ){
70251         sqlite3ExprDelete(p);
70252       }
70253       pWC->a = pOld;
70254       return 0;
70255     }
70256     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
70257     if( pOld!=pWC->aStatic ){
70258       sqlite3_free(pOld);
70259     }
70260     pWC->nSlot *= 2;
70261   }
70262   pTerm = &pWC->a[idx = pWC->nTerm];
70263   pWC->nTerm++;
70264   pTerm->pExpr = p;
70265   pTerm->flags = flags;
70266   pTerm->pWC = pWC;
70267   pTerm->iParent = -1;
70268   return idx;
70269 }
70270
70271 /*
70272 ** This routine identifies subexpressions in the WHERE clause where
70273 ** each subexpression is separated by the AND operator or some other
70274 ** operator specified in the op parameter.  The WhereClause structure
70275 ** is filled with pointers to subexpressions.  For example:
70276 **
70277 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
70278 **           \________/     \_______________/     \________________/
70279 **            slot[0]            slot[1]               slot[2]
70280 **
70281 ** The original WHERE clause in pExpr is unaltered.  All this routine
70282 ** does is make slot[] entries point to substructure within pExpr.
70283 **
70284 ** In the previous sentence and in the diagram, "slot[]" refers to
70285 ** the WhereClause.a[] array.  This array grows as needed to contain
70286 ** all terms of the WHERE clause.
70287 */
70288 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
70289   if( pExpr==0 ) return;
70290   if( pExpr->op!=op ){
70291     whereClauseInsert(pWC, pExpr, 0);
70292   }else{
70293     whereSplit(pWC, pExpr->pLeft, op);
70294     whereSplit(pWC, pExpr->pRight, op);
70295   }
70296 }
70297
70298 /*
70299 ** Initialize an expression mask set
70300 */
70301 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
70302
70303 /*
70304 ** Return the bitmask for the given cursor number.  Return 0 if
70305 ** iCursor is not in the set.
70306 */
70307 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
70308   int i;
70309   for(i=0; i<pMaskSet->n; i++){
70310     if( pMaskSet->ix[i]==iCursor ){
70311       return ((Bitmask)1)<<i;
70312     }
70313   }
70314   return 0;
70315 }
70316
70317 /*
70318 ** Create a new mask for cursor iCursor.
70319 **
70320 ** There is one cursor per table in the FROM clause.  The number of
70321 ** tables in the FROM clause is limited by a test early in the
70322 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
70323 ** array will never overflow.
70324 */
70325 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
70326   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
70327   pMaskSet->ix[pMaskSet->n++] = iCursor;
70328 }
70329
70330 /*
70331 ** This routine walks (recursively) an expression tree and generates
70332 ** a bitmask indicating which tables are used in that expression
70333 ** tree.
70334 **
70335 ** In order for this routine to work, the calling function must have
70336 ** previously invoked sqlite3ExprResolveNames() on the expression.  See
70337 ** the header comment on that routine for additional information.
70338 ** The sqlite3ExprResolveNames() routines looks for column names and
70339 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
70340 ** the VDBE cursor number of the table.  This routine just has to
70341 ** translate the cursor numbers into bitmask values and OR all
70342 ** the bitmasks together.
70343 */
70344 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
70345 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
70346 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
70347   Bitmask mask = 0;
70348   if( p==0 ) return 0;
70349   if( p->op==TK_COLUMN ){
70350     mask = getMask(pMaskSet, p->iTable);
70351     return mask;
70352   }
70353   mask = exprTableUsage(pMaskSet, p->pRight);
70354   mask |= exprTableUsage(pMaskSet, p->pLeft);
70355   mask |= exprListTableUsage(pMaskSet, p->pList);
70356   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
70357   return mask;
70358 }
70359 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
70360   int i;
70361   Bitmask mask = 0;
70362   if( pList ){
70363     for(i=0; i<pList->nExpr; i++){
70364       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
70365     }
70366   }
70367   return mask;
70368 }
70369 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
70370   Bitmask mask = 0;
70371   while( pS ){
70372     mask |= exprListTableUsage(pMaskSet, pS->pEList);
70373     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
70374     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
70375     mask |= exprTableUsage(pMaskSet, pS->pWhere);
70376     mask |= exprTableUsage(pMaskSet, pS->pHaving);
70377     pS = pS->pPrior;
70378   }
70379   return mask;
70380 }
70381
70382 /*
70383 ** Return TRUE if the given operator is one of the operators that is
70384 ** allowed for an indexable WHERE clause term.  The allowed operators are
70385 ** "=", "<", ">", "<=", ">=", and "IN".
70386 */
70387 static int allowedOp(int op){
70388   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
70389   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
70390   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
70391   assert( TK_GE==TK_EQ+4 );
70392   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
70393 }
70394
70395 /*
70396 ** Swap two objects of type T.
70397 */
70398 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
70399
70400 /*
70401 ** Commute a comparision operator.  Expressions of the form "X op Y"
70402 ** are converted into "Y op X".
70403 **
70404 ** If a collation sequence is associated with either the left or right
70405 ** side of the comparison, it remains associated with the same side after
70406 ** the commutation. So "Y collate NOCASE op X" becomes 
70407 ** "X collate NOCASE op Y". This is because any collation sequence on
70408 ** the left hand side of a comparison overrides any collation sequence 
70409 ** attached to the right. For the same reason the EP_ExpCollate flag
70410 ** is not commuted.
70411 */
70412 static void exprCommute(Expr *pExpr){
70413   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
70414   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
70415   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
70416   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
70417   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
70418   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
70419   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
70420   if( pExpr->op>=TK_GT ){
70421     assert( TK_LT==TK_GT+2 );
70422     assert( TK_GE==TK_LE+2 );
70423     assert( TK_GT>TK_EQ );
70424     assert( TK_GT<TK_LE );
70425     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
70426     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
70427   }
70428 }
70429
70430 /*
70431 ** Translate from TK_xx operator to WO_xx bitmask.
70432 */
70433 static int operatorMask(int op){
70434   int c;
70435   assert( allowedOp(op) );
70436   if( op==TK_IN ){
70437     c = WO_IN;
70438   }else if( op==TK_ISNULL ){
70439     c = WO_ISNULL;
70440   }else{
70441     c = WO_EQ<<(op-TK_EQ);
70442   }
70443   assert( op!=TK_ISNULL || c==WO_ISNULL );
70444   assert( op!=TK_IN || c==WO_IN );
70445   assert( op!=TK_EQ || c==WO_EQ );
70446   assert( op!=TK_LT || c==WO_LT );
70447   assert( op!=TK_LE || c==WO_LE );
70448   assert( op!=TK_GT || c==WO_GT );
70449   assert( op!=TK_GE || c==WO_GE );
70450   return c;
70451 }
70452
70453 /*
70454 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
70455 ** where X is a reference to the iColumn of table iCur and <op> is one of
70456 ** the WO_xx operator codes specified by the op parameter.
70457 ** Return a pointer to the term.  Return 0 if not found.
70458 */
70459 static WhereTerm *findTerm(
70460   WhereClause *pWC,     /* The WHERE clause to be searched */
70461   int iCur,             /* Cursor number of LHS */
70462   int iColumn,          /* Column number of LHS */
70463   Bitmask notReady,     /* RHS must not overlap with this mask */
70464   u16 op,               /* Mask of WO_xx values describing operator */
70465   Index *pIdx           /* Must be compatible with this index, if not NULL */
70466 ){
70467   WhereTerm *pTerm;
70468   int k;
70469   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
70470     if( pTerm->leftCursor==iCur
70471        && (pTerm->prereqRight & notReady)==0
70472        && pTerm->leftColumn==iColumn
70473        && (pTerm->eOperator & op)!=0
70474     ){
70475       if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
70476         Expr *pX = pTerm->pExpr;
70477         CollSeq *pColl;
70478         char idxaff;
70479         int j;
70480         Parse *pParse = pWC->pParse;
70481
70482         idxaff = pIdx->pTable->aCol[iColumn].affinity;
70483         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
70484
70485         /* Figure out the collation sequence required from an index for
70486         ** it to be useful for optimising expression pX. Store this
70487         ** value in variable pColl.
70488         */
70489         assert(pX->pLeft);
70490         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
70491         if( !pColl ){
70492           pColl = pParse->db->pDfltColl;
70493         }
70494
70495         for(j=0; j<pIdx->nColumn && pIdx->aiColumn[j]!=iColumn; j++){}
70496         assert( j<pIdx->nColumn );
70497         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
70498       }
70499       return pTerm;
70500     }
70501   }
70502   return 0;
70503 }
70504
70505 /* Forward reference */
70506 static void exprAnalyze(SrcList*, WhereClause*, int);
70507
70508 /*
70509 ** Call exprAnalyze on all terms in a WHERE clause.  
70510 **
70511 **
70512 */
70513 static void exprAnalyzeAll(
70514   SrcList *pTabList,       /* the FROM clause */
70515   WhereClause *pWC         /* the WHERE clause to be analyzed */
70516 ){
70517   int i;
70518   for(i=pWC->nTerm-1; i>=0; i--){
70519     exprAnalyze(pTabList, pWC, i);
70520   }
70521 }
70522
70523 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
70524 /*
70525 ** Check to see if the given expression is a LIKE or GLOB operator that
70526 ** can be optimized using inequality constraints.  Return TRUE if it is
70527 ** so and false if not.
70528 **
70529 ** In order for the operator to be optimizible, the RHS must be a string
70530 ** literal that does not begin with a wildcard.  
70531 */
70532 static int isLikeOrGlob(
70533   sqlite3 *db,      /* The database */
70534   Expr *pExpr,      /* Test this expression */
70535   int *pnPattern,   /* Number of non-wildcard prefix characters */
70536   int *pisComplete, /* True if the only wildcard is % in the last character */
70537   int *pnoCase      /* True if uppercase is equivalent to lowercase */
70538 ){
70539   const char *z;
70540   Expr *pRight, *pLeft;
70541   ExprList *pList;
70542   int c, cnt;
70543   char wc[3];
70544   CollSeq *pColl;
70545
70546   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
70547     return 0;
70548   }
70549 #ifdef SQLITE_EBCDIC
70550   if( *pnoCase ) return 0;
70551 #endif
70552   pList = pExpr->pList;
70553   pRight = pList->a[0].pExpr;
70554   if( pRight->op!=TK_STRING
70555    && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){
70556     return 0;
70557   }
70558   pLeft = pList->a[1].pExpr;
70559   if( pLeft->op!=TK_COLUMN ){
70560     return 0;
70561   }
70562   pColl = pLeft->pColl;
70563   assert( pColl!=0 || pLeft->iColumn==-1 );
70564   if( pColl==0 ){
70565     /* No collation is defined for the ROWID.  Use the default. */
70566     pColl = db->pDfltColl;
70567   }
70568   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
70569       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
70570     return 0;
70571   }
70572   sqlite3DequoteExpr(db, pRight);
70573   z = (char *)pRight->token.z;
70574   cnt = 0;
70575   if( z ){
70576     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
70577   }
70578   if( cnt==0 || 255==(u8)z[cnt] ){
70579     return 0;
70580   }
70581   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
70582   *pnPattern = cnt;
70583   return 1;
70584 }
70585 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
70586
70587
70588 #ifndef SQLITE_OMIT_VIRTUALTABLE
70589 /*
70590 ** Check to see if the given expression is of the form
70591 **
70592 **         column MATCH expr
70593 **
70594 ** If it is then return TRUE.  If not, return FALSE.
70595 */
70596 static int isMatchOfColumn(
70597   Expr *pExpr      /* Test this expression */
70598 ){
70599   ExprList *pList;
70600
70601   if( pExpr->op!=TK_FUNCTION ){
70602     return 0;
70603   }
70604   if( pExpr->token.n!=5 ||
70605        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
70606     return 0;
70607   }
70608   pList = pExpr->pList;
70609   if( pList->nExpr!=2 ){
70610     return 0;
70611   }
70612   if( pList->a[1].pExpr->op != TK_COLUMN ){
70613     return 0;
70614   }
70615   return 1;
70616 }
70617 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70618
70619 /*
70620 ** If the pBase expression originated in the ON or USING clause of
70621 ** a join, then transfer the appropriate markings over to derived.
70622 */
70623 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
70624   pDerived->flags |= pBase->flags & EP_FromJoin;
70625   pDerived->iRightJoinTable = pBase->iRightJoinTable;
70626 }
70627
70628 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
70629 /*
70630 ** Return TRUE if the given term of an OR clause can be converted
70631 ** into an IN clause.  The iCursor and iColumn define the left-hand
70632 ** side of the IN clause.
70633 **
70634 ** The context is that we have multiple OR-connected equality terms
70635 ** like this:
70636 **
70637 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
70638 **
70639 ** The pOrTerm input to this routine corresponds to a single term of
70640 ** this OR clause.  In order for the term to be a condidate for
70641 ** conversion to an IN operator, the following must be true:
70642 **
70643 **     *  The left-hand side of the term must be the column which
70644 **        is identified by iCursor and iColumn.
70645 **
70646 **     *  If the right-hand side is also a column, then the affinities
70647 **        of both right and left sides must be such that no type
70648 **        conversions are required on the right.  (Ticket #2249)
70649 **
70650 ** If both of these conditions are true, then return true.  Otherwise
70651 ** return false.
70652 */
70653 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
70654   int affLeft, affRight;
70655   assert( pOrTerm->eOperator==WO_EQ );
70656   if( pOrTerm->leftCursor!=iCursor ){
70657     return 0;
70658   }
70659   if( pOrTerm->leftColumn!=iColumn ){
70660     return 0;
70661   }
70662   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
70663   if( affRight==0 ){
70664     return 1;
70665   }
70666   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
70667   if( affRight!=affLeft ){
70668     return 0;
70669   }
70670   return 1;
70671 }
70672
70673 /*
70674 ** Return true if the given term of an OR clause can be ignored during
70675 ** a check to make sure all OR terms are candidates for optimization.
70676 ** In other words, return true if a call to the orTermIsOptCandidate()
70677 ** above returned false but it is not necessary to disqualify the
70678 ** optimization.
70679 **
70680 ** Suppose the original OR phrase was this:
70681 **
70682 **           a=4  OR  a=11  OR  a=b
70683 **
70684 ** During analysis, the third term gets flipped around and duplicate
70685 ** so that we are left with this:
70686 **
70687 **           a=4  OR  a=11  OR  a=b  OR  b=a
70688 **
70689 ** Since the last two terms are duplicates, only one of them
70690 ** has to qualify in order for the whole phrase to qualify.  When
70691 ** this routine is called, we know that pOrTerm did not qualify.
70692 ** This routine merely checks to see if pOrTerm has a duplicate that
70693 ** might qualify.  If there is a duplicate that has not yet been
70694 ** disqualified, then return true.  If there are no duplicates, or
70695 ** the duplicate has also been disqualifed, return false.
70696 */
70697 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
70698   if( pOrTerm->flags & TERM_COPIED ){
70699     /* This is the original term.  The duplicate is to the left had
70700     ** has not yet been analyzed and thus has not yet been disqualified. */
70701     return 1;
70702   }
70703   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
70704      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
70705     /* This is a duplicate term.  The original qualified so this one
70706     ** does not have to. */
70707     return 1;
70708   }
70709   /* This is either a singleton term or else it is a duplicate for
70710   ** which the original did not qualify.  Either way we are done for. */
70711   return 0;
70712 }
70713 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
70714
70715 /*
70716 ** The input to this routine is an WhereTerm structure with only the
70717 ** "pExpr" field filled in.  The job of this routine is to analyze the
70718 ** subexpression and populate all the other fields of the WhereTerm
70719 ** structure.
70720 **
70721 ** If the expression is of the form "<expr> <op> X" it gets commuted
70722 ** to the standard form of "X <op> <expr>".  If the expression is of
70723 ** the form "X <op> Y" where both X and Y are columns, then the original
70724 ** expression is unchanged and a new virtual expression of the form
70725 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
70726 */
70727 static void exprAnalyze(
70728   SrcList *pSrc,            /* the FROM clause */
70729   WhereClause *pWC,         /* the WHERE clause */
70730   int idxTerm               /* Index of the term to be analyzed */
70731 ){
70732   WhereTerm *pTerm;
70733   ExprMaskSet *pMaskSet;
70734   Expr *pExpr;
70735   Bitmask prereqLeft;
70736   Bitmask prereqAll;
70737   Bitmask extraRight = 0;
70738   int nPattern;
70739   int isComplete;
70740   int noCase;
70741   int op;
70742   Parse *pParse = pWC->pParse;
70743   sqlite3 *db = pParse->db;
70744
70745   if( db->mallocFailed ){
70746     return;
70747   }
70748   pTerm = &pWC->a[idxTerm];
70749   pMaskSet = pWC->pMaskSet;
70750   pExpr = pTerm->pExpr;
70751   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
70752   op = pExpr->op;
70753   if( op==TK_IN ){
70754     assert( pExpr->pRight==0 );
70755     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
70756                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
70757   }else if( op==TK_ISNULL ){
70758     pTerm->prereqRight = 0;
70759   }else{
70760     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
70761   }
70762   prereqAll = exprTableUsage(pMaskSet, pExpr);
70763   if( ExprHasProperty(pExpr, EP_FromJoin) ){
70764     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
70765     prereqAll |= x;
70766     extraRight = x-1;  /* ON clause terms may not be used with an index
70767                        ** on left table of a LEFT JOIN.  Ticket #3015 */
70768   }
70769   pTerm->prereqAll = prereqAll;
70770   pTerm->leftCursor = -1;
70771   pTerm->iParent = -1;
70772   pTerm->eOperator = 0;
70773   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
70774     Expr *pLeft = pExpr->pLeft;
70775     Expr *pRight = pExpr->pRight;
70776     if( pLeft->op==TK_COLUMN ){
70777       pTerm->leftCursor = pLeft->iTable;
70778       pTerm->leftColumn = pLeft->iColumn;
70779       pTerm->eOperator = operatorMask(op);
70780     }
70781     if( pRight && pRight->op==TK_COLUMN ){
70782       WhereTerm *pNew;
70783       Expr *pDup;
70784       if( pTerm->leftCursor>=0 ){
70785         int idxNew;
70786         pDup = sqlite3ExprDup(db, pExpr);
70787         if( db->mallocFailed ){
70788           sqlite3ExprDelete(pDup);
70789           return;
70790         }
70791         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
70792         if( idxNew==0 ) return;
70793         pNew = &pWC->a[idxNew];
70794         pNew->iParent = idxTerm;
70795         pTerm = &pWC->a[idxTerm];
70796         pTerm->nChild = 1;
70797         pTerm->flags |= TERM_COPIED;
70798       }else{
70799         pDup = pExpr;
70800         pNew = pTerm;
70801       }
70802       exprCommute(pDup);
70803       pLeft = pDup->pLeft;
70804       pNew->leftCursor = pLeft->iTable;
70805       pNew->leftColumn = pLeft->iColumn;
70806       pNew->prereqRight = prereqLeft;
70807       pNew->prereqAll = prereqAll;
70808       pNew->eOperator = operatorMask(pDup->op);
70809     }
70810   }
70811
70812 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
70813   /* If a term is the BETWEEN operator, create two new virtual terms
70814   ** that define the range that the BETWEEN implements.
70815   */
70816   else if( pExpr->op==TK_BETWEEN ){
70817     ExprList *pList = pExpr->pList;
70818     int i;
70819     static const u8 ops[] = {TK_GE, TK_LE};
70820     assert( pList!=0 );
70821     assert( pList->nExpr==2 );
70822     for(i=0; i<2; i++){
70823       Expr *pNewExpr;
70824       int idxNew;
70825       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
70826                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
70827       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
70828       exprAnalyze(pSrc, pWC, idxNew);
70829       pTerm = &pWC->a[idxTerm];
70830       pWC->a[idxNew].iParent = idxTerm;
70831     }
70832     pTerm->nChild = 2;
70833   }
70834 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
70835
70836 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
70837   /* Attempt to convert OR-connected terms into an IN operator so that
70838   ** they can make use of indices.  Example:
70839   **
70840   **      x = expr1  OR  expr2 = x  OR  x = expr3
70841   **
70842   ** is converted into
70843   **
70844   **      x IN (expr1,expr2,expr3)
70845   **
70846   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
70847   ** the compiler for the the IN operator is part of sub-queries.
70848   */
70849   else if( pExpr->op==TK_OR ){
70850     int ok;
70851     int i, j;
70852     int iColumn, iCursor;
70853     WhereClause sOr;
70854     WhereTerm *pOrTerm;
70855
70856     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
70857     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
70858     whereSplit(&sOr, pExpr, TK_OR);
70859     exprAnalyzeAll(pSrc, &sOr);
70860     assert( sOr.nTerm>=2 );
70861     j = 0;
70862     if( db->mallocFailed ) goto or_not_possible;
70863     do{
70864       assert( j<sOr.nTerm );
70865       iColumn = sOr.a[j].leftColumn;
70866       iCursor = sOr.a[j].leftCursor;
70867       ok = iCursor>=0;
70868       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
70869         if( pOrTerm->eOperator!=WO_EQ ){
70870           goto or_not_possible;
70871         }
70872         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
70873           pOrTerm->flags |= TERM_OR_OK;
70874         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
70875           pOrTerm->flags &= ~TERM_OR_OK;
70876         }else{
70877           ok = 0;
70878         }
70879       }
70880     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
70881     if( ok ){
70882       ExprList *pList = 0;
70883       Expr *pNew, *pDup;
70884       Expr *pLeft = 0;
70885       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
70886         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
70887         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
70888         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
70889         pLeft = pOrTerm->pExpr->pLeft;
70890       }
70891       assert( pLeft!=0 );
70892       pDup = sqlite3ExprDup(db, pLeft);
70893       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
70894       if( pNew ){
70895         int idxNew;
70896         transferJoinMarkings(pNew, pExpr);
70897         pNew->pList = pList;
70898         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
70899         exprAnalyze(pSrc, pWC, idxNew);
70900         pTerm = &pWC->a[idxTerm];
70901         pWC->a[idxNew].iParent = idxTerm;
70902         pTerm->nChild = 1;
70903       }else{
70904         sqlite3ExprListDelete(pList);
70905       }
70906     }
70907 or_not_possible:
70908     whereClauseClear(&sOr);
70909   }
70910 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
70911
70912 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
70913   /* Add constraints to reduce the search space on a LIKE or GLOB
70914   ** operator.
70915   **
70916   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
70917   **
70918   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
70919   **
70920   ** The last character of the prefix "abc" is incremented to form the
70921   ** termination condidtion "abd".  This trick of incrementing the last
70922   ** is not 255 and if the character set is not EBCDIC.  
70923   */
70924   if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete, &noCase) ){
70925     Expr *pLeft, *pRight;
70926     Expr *pStr1, *pStr2;
70927     Expr *pNewExpr1, *pNewExpr2;
70928     int idxNew1, idxNew2;
70929
70930     pLeft = pExpr->pList->a[1].pExpr;
70931     pRight = pExpr->pList->a[0].pExpr;
70932     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
70933     if( pStr1 ){
70934       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
70935       pStr1->token.n = nPattern;
70936       pStr1->flags = EP_Dequoted;
70937     }
70938     pStr2 = sqlite3ExprDup(db, pStr1);
70939     if( !db->mallocFailed ){
70940       u8 c, *pC;
70941       assert( pStr2->token.dyn );
70942       pC = (u8*)&pStr2->token.z[nPattern-1];
70943       c = *pC;
70944       if( noCase ) c = sqlite3UpperToLower[c];
70945       *pC = c + 1;
70946     }
70947     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
70948     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
70949     exprAnalyze(pSrc, pWC, idxNew1);
70950     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
70951     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
70952     exprAnalyze(pSrc, pWC, idxNew2);
70953     pTerm = &pWC->a[idxTerm];
70954     if( isComplete ){
70955       pWC->a[idxNew1].iParent = idxTerm;
70956       pWC->a[idxNew2].iParent = idxTerm;
70957       pTerm->nChild = 2;
70958     }
70959   }
70960 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
70961
70962 #ifndef SQLITE_OMIT_VIRTUALTABLE
70963   /* Add a WO_MATCH auxiliary term to the constraint set if the
70964   ** current expression is of the form:  column MATCH expr.
70965   ** This information is used by the xBestIndex methods of
70966   ** virtual tables.  The native query optimizer does not attempt
70967   ** to do anything with MATCH functions.
70968   */
70969   if( isMatchOfColumn(pExpr) ){
70970     int idxNew;
70971     Expr *pRight, *pLeft;
70972     WhereTerm *pNewTerm;
70973     Bitmask prereqColumn, prereqExpr;
70974
70975     pRight = pExpr->pList->a[0].pExpr;
70976     pLeft = pExpr->pList->a[1].pExpr;
70977     prereqExpr = exprTableUsage(pMaskSet, pRight);
70978     prereqColumn = exprTableUsage(pMaskSet, pLeft);
70979     if( (prereqExpr & prereqColumn)==0 ){
70980       Expr *pNewExpr;
70981       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
70982       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
70983       pNewTerm = &pWC->a[idxNew];
70984       pNewTerm->prereqRight = prereqExpr;
70985       pNewTerm->leftCursor = pLeft->iTable;
70986       pNewTerm->leftColumn = pLeft->iColumn;
70987       pNewTerm->eOperator = WO_MATCH;
70988       pNewTerm->iParent = idxTerm;
70989       pTerm = &pWC->a[idxTerm];
70990       pTerm->nChild = 1;
70991       pTerm->flags |= TERM_COPIED;
70992       pNewTerm->prereqAll = pTerm->prereqAll;
70993     }
70994   }
70995 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70996
70997   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
70998   ** an index for tables to the left of the join.
70999   */
71000   pTerm->prereqRight |= extraRight;
71001 }
71002
71003 /*
71004 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
71005 ** a reference to any table other than the iBase table.
71006 */
71007 static int referencesOtherTables(
71008   ExprList *pList,          /* Search expressions in ths list */
71009   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
71010   int iFirst,               /* Be searching with the iFirst-th expression */
71011   int iBase                 /* Ignore references to this table */
71012 ){
71013   Bitmask allowed = ~getMask(pMaskSet, iBase);
71014   while( iFirst<pList->nExpr ){
71015     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
71016       return 1;
71017     }
71018   }
71019   return 0;
71020 }
71021
71022
71023 /*
71024 ** This routine decides if pIdx can be used to satisfy the ORDER BY
71025 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
71026 ** ORDER BY clause, this routine returns 0.
71027 **
71028 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
71029 ** left-most table in the FROM clause of that same SELECT statement and
71030 ** the table has a cursor number of "base".  pIdx is an index on pTab.
71031 **
71032 ** nEqCol is the number of columns of pIdx that are used as equality
71033 ** constraints.  Any of these columns may be missing from the ORDER BY
71034 ** clause and the match can still be a success.
71035 **
71036 ** All terms of the ORDER BY that match against the index must be either
71037 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
71038 ** index do not need to satisfy this constraint.)  The *pbRev value is
71039 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
71040 ** the ORDER BY clause is all ASC.
71041 */
71042 static int isSortingIndex(
71043   Parse *pParse,          /* Parsing context */
71044   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
71045   Index *pIdx,            /* The index we are testing */
71046   int base,               /* Cursor number for the table to be sorted */
71047   ExprList *pOrderBy,     /* The ORDER BY clause */
71048   int nEqCol,             /* Number of index columns with == constraints */
71049   int *pbRev              /* Set to 1 if ORDER BY is DESC */
71050 ){
71051   int i, j;                       /* Loop counters */
71052   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
71053   int nTerm;                      /* Number of ORDER BY terms */
71054   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
71055   sqlite3 *db = pParse->db;
71056
71057   assert( pOrderBy!=0 );
71058   nTerm = pOrderBy->nExpr;
71059   assert( nTerm>0 );
71060
71061   /* Match terms of the ORDER BY clause against columns of
71062   ** the index.
71063   **
71064   ** Note that indices have pIdx->nColumn regular columns plus
71065   ** one additional column containing the rowid.  The rowid column
71066   ** of the index is also allowed to match against the ORDER BY
71067   ** clause.
71068   */
71069   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
71070     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
71071     CollSeq *pColl;    /* The collating sequence of pExpr */
71072     int termSortOrder; /* Sort order for this term */
71073     int iColumn;       /* The i-th column of the index.  -1 for rowid */
71074     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
71075     const char *zColl; /* Name of the collating sequence for i-th index term */
71076
71077     pExpr = pTerm->pExpr;
71078     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
71079       /* Can not use an index sort on anything that is not a column in the
71080       ** left-most table of the FROM clause */
71081       break;
71082     }
71083     pColl = sqlite3ExprCollSeq(pParse, pExpr);
71084     if( !pColl ){
71085       pColl = db->pDfltColl;
71086     }
71087     if( i<pIdx->nColumn ){
71088       iColumn = pIdx->aiColumn[i];
71089       if( iColumn==pIdx->pTable->iPKey ){
71090         iColumn = -1;
71091       }
71092       iSortOrder = pIdx->aSortOrder[i];
71093       zColl = pIdx->azColl[i];
71094     }else{
71095       iColumn = -1;
71096       iSortOrder = 0;
71097       zColl = pColl->zName;
71098     }
71099     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
71100       /* Term j of the ORDER BY clause does not match column i of the index */
71101       if( i<nEqCol ){
71102         /* If an index column that is constrained by == fails to match an
71103         ** ORDER BY term, that is OK.  Just ignore that column of the index
71104         */
71105         continue;
71106       }else{
71107         /* If an index column fails to match and is not constrained by ==
71108         ** then the index cannot satisfy the ORDER BY constraint.
71109         */
71110         return 0;
71111       }
71112     }
71113     assert( pIdx->aSortOrder!=0 );
71114     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
71115     assert( iSortOrder==0 || iSortOrder==1 );
71116     termSortOrder = iSortOrder ^ pTerm->sortOrder;
71117     if( i>nEqCol ){
71118       if( termSortOrder!=sortOrder ){
71119         /* Indices can only be used if all ORDER BY terms past the
71120         ** equality constraints are all either DESC or ASC. */
71121         return 0;
71122       }
71123     }else{
71124       sortOrder = termSortOrder;
71125     }
71126     j++;
71127     pTerm++;
71128     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
71129       /* If the indexed column is the primary key and everything matches
71130       ** so far and none of the ORDER BY terms to the right reference other
71131       ** tables in the join, then we are assured that the index can be used 
71132       ** to sort because the primary key is unique and so none of the other
71133       ** columns will make any difference
71134       */
71135       j = nTerm;
71136     }
71137   }
71138
71139   *pbRev = sortOrder!=0;
71140   if( j>=nTerm ){
71141     /* All terms of the ORDER BY clause are covered by this index so
71142     ** this index can be used for sorting. */
71143     return 1;
71144   }
71145   if( pIdx->onError!=OE_None && i==pIdx->nColumn
71146       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
71147     /* All terms of this index match some prefix of the ORDER BY clause
71148     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
71149     ** clause reference other tables in a join.  If this is all true then
71150     ** the order by clause is superfluous. */
71151     return 1;
71152   }
71153   return 0;
71154 }
71155
71156 /*
71157 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
71158 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
71159 ** true for reverse ROWID and false for forward ROWID order.
71160 */
71161 static int sortableByRowid(
71162   int base,               /* Cursor number for table to be sorted */
71163   ExprList *pOrderBy,     /* The ORDER BY clause */
71164   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
71165   int *pbRev              /* Set to 1 if ORDER BY is DESC */
71166 ){
71167   Expr *p;
71168
71169   assert( pOrderBy!=0 );
71170   assert( pOrderBy->nExpr>0 );
71171   p = pOrderBy->a[0].pExpr;
71172   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
71173     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
71174     *pbRev = pOrderBy->a[0].sortOrder;
71175     return 1;
71176   }
71177   return 0;
71178 }
71179
71180 /*
71181 ** Prepare a crude estimate of the logarithm of the input value.
71182 ** The results need not be exact.  This is only used for estimating
71183 ** the total cost of performing operatings with O(logN) or O(NlogN)
71184 ** complexity.  Because N is just a guess, it is no great tragedy if
71185 ** logN is a little off.
71186 */
71187 static double estLog(double N){
71188   double logN = 1;
71189   double x = 10;
71190   while( N>x ){
71191     logN += 1;
71192     x *= 10;
71193   }
71194   return logN;
71195 }
71196
71197 /*
71198 ** Two routines for printing the content of an sqlite3_index_info
71199 ** structure.  Used for testing and debugging only.  If neither
71200 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
71201 ** are no-ops.
71202 */
71203 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
71204 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
71205   int i;
71206   if( !sqlite3WhereTrace ) return;
71207   for(i=0; i<p->nConstraint; i++){
71208     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
71209        i,
71210        p->aConstraint[i].iColumn,
71211        p->aConstraint[i].iTermOffset,
71212        p->aConstraint[i].op,
71213        p->aConstraint[i].usable);
71214   }
71215   for(i=0; i<p->nOrderBy; i++){
71216     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
71217        i,
71218        p->aOrderBy[i].iColumn,
71219        p->aOrderBy[i].desc);
71220   }
71221 }
71222 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
71223   int i;
71224   if( !sqlite3WhereTrace ) return;
71225   for(i=0; i<p->nConstraint; i++){
71226     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
71227        i,
71228        p->aConstraintUsage[i].argvIndex,
71229        p->aConstraintUsage[i].omit);
71230   }
71231   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
71232   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
71233   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
71234   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
71235 }
71236 #else
71237 #define TRACE_IDX_INPUTS(A)
71238 #define TRACE_IDX_OUTPUTS(A)
71239 #endif
71240
71241 #ifndef SQLITE_OMIT_VIRTUALTABLE
71242 /*
71243 ** Compute the best index for a virtual table.
71244 **
71245 ** The best index is computed by the xBestIndex method of the virtual
71246 ** table module.  This routine is really just a wrapper that sets up
71247 ** the sqlite3_index_info structure that is used to communicate with
71248 ** xBestIndex.
71249 **
71250 ** In a join, this routine might be called multiple times for the
71251 ** same virtual table.  The sqlite3_index_info structure is created
71252 ** and initialized on the first invocation and reused on all subsequent
71253 ** invocations.  The sqlite3_index_info structure is also used when
71254 ** code is generated to access the virtual table.  The whereInfoDelete() 
71255 ** routine takes care of freeing the sqlite3_index_info structure after
71256 ** everybody has finished with it.
71257 */
71258 static double bestVirtualIndex(
71259   Parse *pParse,                 /* The parsing context */
71260   WhereClause *pWC,              /* The WHERE clause */
71261   struct SrcList_item *pSrc,     /* The FROM clause term to search */
71262   Bitmask notReady,              /* Mask of cursors that are not available */
71263   ExprList *pOrderBy,            /* The order by clause */
71264   int orderByUsable,             /* True if we can potential sort */
71265   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
71266 ){
71267   Table *pTab = pSrc->pTab;
71268   sqlite3_index_info *pIdxInfo;
71269   struct sqlite3_index_constraint *pIdxCons;
71270   struct sqlite3_index_orderby *pIdxOrderBy;
71271   struct sqlite3_index_constraint_usage *pUsage;
71272   WhereTerm *pTerm;
71273   int i, j;
71274   int nOrderBy;
71275   int rc;
71276
71277   /* If the sqlite3_index_info structure has not been previously
71278   ** allocated and initialized for this virtual table, then allocate
71279   ** and initialize it now
71280   */
71281   pIdxInfo = *ppIdxInfo;
71282   if( pIdxInfo==0 ){
71283     WhereTerm *pTerm;
71284     int nTerm;
71285     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
71286
71287     /* Count the number of possible WHERE clause constraints referring
71288     ** to this virtual table */
71289     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
71290       if( pTerm->leftCursor != pSrc->iCursor ) continue;
71291       if( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
71292       testcase( pTerm->eOperator==WO_IN );
71293       testcase( pTerm->eOperator==WO_ISNULL );
71294       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
71295       nTerm++;
71296     }
71297
71298     /* If the ORDER BY clause contains only columns in the current 
71299     ** virtual table then allocate space for the aOrderBy part of
71300     ** the sqlite3_index_info structure.
71301     */
71302     nOrderBy = 0;
71303     if( pOrderBy ){
71304       for(i=0; i<pOrderBy->nExpr; i++){
71305         Expr *pExpr = pOrderBy->a[i].pExpr;
71306         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
71307       }
71308       if( i==pOrderBy->nExpr ){
71309         nOrderBy = pOrderBy->nExpr;
71310       }
71311     }
71312
71313     /* Allocate the sqlite3_index_info structure
71314     */
71315     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
71316                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
71317                              + sizeof(*pIdxOrderBy)*nOrderBy );
71318     if( pIdxInfo==0 ){
71319       sqlite3ErrorMsg(pParse, "out of memory");
71320       return 0.0;
71321     }
71322     *ppIdxInfo = pIdxInfo;
71323
71324     /* Initialize the structure.  The sqlite3_index_info structure contains
71325     ** many fields that are declared "const" to prevent xBestIndex from
71326     ** changing them.  We have to do some funky casting in order to
71327     ** initialize those fields.
71328     */
71329     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
71330     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
71331     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
71332     *(int*)&pIdxInfo->nConstraint = nTerm;
71333     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
71334     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
71335     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
71336     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
71337                                                                      pUsage;
71338
71339     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
71340       if( pTerm->leftCursor != pSrc->iCursor ) continue;
71341       if( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
71342       testcase( pTerm->eOperator==WO_IN );
71343       testcase( pTerm->eOperator==WO_ISNULL );
71344       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
71345       pIdxCons[j].iColumn = pTerm->leftColumn;
71346       pIdxCons[j].iTermOffset = i;
71347       pIdxCons[j].op = pTerm->eOperator;
71348       /* The direct assignment in the previous line is possible only because
71349       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
71350       ** following asserts verify this fact. */
71351       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
71352       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
71353       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
71354       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
71355       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
71356       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
71357       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
71358       j++;
71359     }
71360     for(i=0; i<nOrderBy; i++){
71361       Expr *pExpr = pOrderBy->a[i].pExpr;
71362       pIdxOrderBy[i].iColumn = pExpr->iColumn;
71363       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
71364     }
71365   }
71366
71367   /* At this point, the sqlite3_index_info structure that pIdxInfo points
71368   ** to will have been initialized, either during the current invocation or
71369   ** during some prior invocation.  Now we just have to customize the
71370   ** details of pIdxInfo for the current invocation and pass it to
71371   ** xBestIndex.
71372   */
71373
71374   /* The module name must be defined. Also, by this point there must
71375   ** be a pointer to an sqlite3_vtab structure. Otherwise
71376   ** sqlite3ViewGetColumnNames() would have picked up the error. 
71377   */
71378   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
71379   assert( pTab->pVtab );
71380 #if 0
71381   if( pTab->pVtab==0 ){
71382     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
71383         pTab->azModuleArg[0], pTab->zName);
71384     return 0.0;
71385   }
71386 #endif
71387
71388   /* Set the aConstraint[].usable fields and initialize all 
71389   ** output variables to zero.
71390   **
71391   ** aConstraint[].usable is true for constraints where the right-hand
71392   ** side contains only references to tables to the left of the current
71393   ** table.  In other words, if the constraint is of the form:
71394   **
71395   **           column = expr
71396   **
71397   ** and we are evaluating a join, then the constraint on column is 
71398   ** only valid if all tables referenced in expr occur to the left
71399   ** of the table containing column.
71400   **
71401   ** The aConstraints[] array contains entries for all constraints
71402   ** on the current table.  That way we only have to compute it once
71403   ** even though we might try to pick the best index multiple times.
71404   ** For each attempt at picking an index, the order of tables in the
71405   ** join might be different so we have to recompute the usable flag
71406   ** each time.
71407   */
71408   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
71409   pUsage = pIdxInfo->aConstraintUsage;
71410   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
71411     j = pIdxCons->iTermOffset;
71412     pTerm = &pWC->a[j];
71413     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
71414   }
71415   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
71416   if( pIdxInfo->needToFreeIdxStr ){
71417     sqlite3_free(pIdxInfo->idxStr);
71418   }
71419   pIdxInfo->idxStr = 0;
71420   pIdxInfo->idxNum = 0;
71421   pIdxInfo->needToFreeIdxStr = 0;
71422   pIdxInfo->orderByConsumed = 0;
71423   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
71424   nOrderBy = pIdxInfo->nOrderBy;
71425   if( pIdxInfo->nOrderBy && !orderByUsable ){
71426     *(int*)&pIdxInfo->nOrderBy = 0;
71427   }
71428
71429   (void)sqlite3SafetyOff(pParse->db);
71430   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
71431   TRACE_IDX_INPUTS(pIdxInfo);
71432   rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo);
71433   TRACE_IDX_OUTPUTS(pIdxInfo);
71434   (void)sqlite3SafetyOn(pParse->db);
71435
71436   for(i=0; i<pIdxInfo->nConstraint; i++){
71437     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
71438       sqlite3ErrorMsg(pParse, 
71439           "table %s: xBestIndex returned an invalid plan", pTab->zName);
71440       return 0.0;
71441     }
71442   }
71443
71444   if( rc!=SQLITE_OK ){
71445     if( rc==SQLITE_NOMEM ){
71446       pParse->db->mallocFailed = 1;
71447     }else {
71448       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
71449     }
71450   }
71451   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
71452
71453   return pIdxInfo->estimatedCost;
71454 }
71455 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71456
71457 /*
71458 ** Find the best index for accessing a particular table.  Return a pointer
71459 ** to the index, flags that describe how the index should be used, the
71460 ** number of equality constraints, and the "cost" for this index.
71461 **
71462 ** The lowest cost index wins.  The cost is an estimate of the amount of
71463 ** CPU and disk I/O need to process the request using the selected index.
71464 ** Factors that influence cost include:
71465 **
71466 **    *  The estimated number of rows that will be retrieved.  (The
71467 **       fewer the better.)
71468 **
71469 **    *  Whether or not sorting must occur.
71470 **
71471 **    *  Whether or not there must be separate lookups in the
71472 **       index and in the main table.
71473 **
71474 */
71475 static double bestIndex(
71476   Parse *pParse,              /* The parsing context */
71477   WhereClause *pWC,           /* The WHERE clause */
71478   struct SrcList_item *pSrc,  /* The FROM clause term to search */
71479   Bitmask notReady,           /* Mask of cursors that are not available */
71480   ExprList *pOrderBy,         /* The order by clause */
71481   Index **ppIndex,            /* Make *ppIndex point to the best index */
71482   int *pFlags,                /* Put flags describing this choice in *pFlags */
71483   int *pnEq                   /* Put the number of == or IN constraints here */
71484 ){
71485   WhereTerm *pTerm;
71486   Index *bestIdx = 0;         /* Index that gives the lowest cost */
71487   double lowestCost;          /* The cost of using bestIdx */
71488   int bestFlags = 0;          /* Flags associated with bestIdx */
71489   int bestNEq = 0;            /* Best value for nEq */
71490   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
71491   Index *pProbe;              /* An index we are evaluating */
71492   int rev;                    /* True to scan in reverse order */
71493   int flags;                  /* Flags associated with pProbe */
71494   int nEq;                    /* Number of == or IN constraints */
71495   int eqTermMask;             /* Mask of valid equality operators */
71496   double cost;                /* Cost of using pProbe */
71497
71498   WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
71499   lowestCost = SQLITE_BIG_DBL;
71500   pProbe = pSrc->pTab->pIndex;
71501
71502   /* If the table has no indices and there are no terms in the where
71503   ** clause that refer to the ROWID, then we will never be able to do
71504   ** anything other than a full table scan on this table.  We might as
71505   ** well put it first in the join order.  That way, perhaps it can be
71506   ** referenced by other tables in the join.
71507   */
71508   if( pProbe==0 &&
71509      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
71510      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
71511     *pFlags = 0;
71512     *ppIndex = 0;
71513     *pnEq = 0;
71514     return 0.0;
71515   }
71516
71517   /* Check for a rowid=EXPR or rowid IN (...) constraints
71518   */
71519   pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
71520   if( pTerm ){
71521     Expr *pExpr;
71522     *ppIndex = 0;
71523     bestFlags = WHERE_ROWID_EQ;
71524     if( pTerm->eOperator & WO_EQ ){
71525       /* Rowid== is always the best pick.  Look no further.  Because only
71526       ** a single row is generated, output is always in sorted order */
71527       *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
71528       *pnEq = 1;
71529       WHERETRACE(("... best is rowid\n"));
71530       return 0.0;
71531     }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
71532       /* Rowid IN (LIST): cost is NlogN where N is the number of list
71533       ** elements.  */
71534       lowestCost = pExpr->pList->nExpr;
71535       lowestCost *= estLog(lowestCost);
71536     }else{
71537       /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
71538       ** in the result of the inner select.  We have no way to estimate
71539       ** that value so make a wild guess. */
71540       lowestCost = 200;
71541     }
71542     WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
71543   }
71544
71545   /* Estimate the cost of a table scan.  If we do not know how many
71546   ** entries are in the table, use 1 million as a guess.
71547   */
71548   cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
71549   WHERETRACE(("... table scan base cost: %.9g\n", cost));
71550   flags = WHERE_ROWID_RANGE;
71551
71552   /* Check for constraints on a range of rowids in a table scan.
71553   */
71554   pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
71555   if( pTerm ){
71556     if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
71557       flags |= WHERE_TOP_LIMIT;
71558       cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
71559     }
71560     if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
71561       flags |= WHERE_BTM_LIMIT;
71562       cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
71563     }
71564     WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
71565   }else{
71566     flags = 0;
71567   }
71568
71569   /* If the table scan does not satisfy the ORDER BY clause, increase
71570   ** the cost by NlogN to cover the expense of sorting. */
71571   if( pOrderBy ){
71572     if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
71573       flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
71574       if( rev ){
71575         flags |= WHERE_REVERSE;
71576       }
71577     }else{
71578       cost += cost*estLog(cost);
71579       WHERETRACE(("... sorting increases cost to %.9g\n", cost));
71580     }
71581   }
71582   if( cost<lowestCost ){
71583     lowestCost = cost;
71584     bestFlags = flags;
71585   }
71586
71587   /* If the pSrc table is the right table of a LEFT JOIN then we may not
71588   ** use an index to satisfy IS NULL constraints on that table.  This is
71589   ** because columns might end up being NULL if the table does not match -
71590   ** a circumstance which the index cannot help us discover.  Ticket #2177.
71591   */
71592   if( (pSrc->jointype & JT_LEFT)!=0 ){
71593     eqTermMask = WO_EQ|WO_IN;
71594   }else{
71595     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
71596   }
71597
71598   /* Look at each index.
71599   */
71600   for(; pProbe; pProbe=pProbe->pNext){
71601     int i;                       /* Loop counter */
71602     double inMultiplier = 1;
71603
71604     WHERETRACE(("... index %s:\n", pProbe->zName));
71605
71606     /* Count the number of columns in the index that are satisfied
71607     ** by x=EXPR constraints or x IN (...) constraints.
71608     */
71609     flags = 0;
71610     for(i=0; i<pProbe->nColumn; i++){
71611       int j = pProbe->aiColumn[i];
71612       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
71613       if( pTerm==0 ) break;
71614       flags |= WHERE_COLUMN_EQ;
71615       if( pTerm->eOperator & WO_IN ){
71616         Expr *pExpr = pTerm->pExpr;
71617         flags |= WHERE_COLUMN_IN;
71618         if( pExpr->pSelect!=0 ){
71619           inMultiplier *= 25;
71620         }else if( pExpr->pList!=0 ){
71621           inMultiplier *= pExpr->pList->nExpr + 1;
71622         }
71623       }
71624     }
71625     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
71626     nEq = i;
71627     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
71628          && nEq==pProbe->nColumn ){
71629       flags |= WHERE_UNIQUE;
71630     }
71631     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
71632
71633     /* Look for range constraints
71634     */
71635     if( nEq<pProbe->nColumn ){
71636       int j = pProbe->aiColumn[nEq];
71637       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
71638       if( pTerm ){
71639         flags |= WHERE_COLUMN_RANGE;
71640         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
71641           flags |= WHERE_TOP_LIMIT;
71642           cost /= 3;
71643         }
71644         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
71645           flags |= WHERE_BTM_LIMIT;
71646           cost /= 3;
71647         }
71648         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
71649       }
71650     }
71651
71652     /* Add the additional cost of sorting if that is a factor.
71653     */
71654     if( pOrderBy ){
71655       if( (flags & WHERE_COLUMN_IN)==0 &&
71656            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
71657         if( flags==0 ){
71658           flags = WHERE_COLUMN_RANGE;
71659         }
71660         flags |= WHERE_ORDERBY;
71661         if( rev ){
71662           flags |= WHERE_REVERSE;
71663         }
71664       }else{
71665         cost += cost*estLog(cost);
71666         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
71667       }
71668     }
71669
71670     /* Check to see if we can get away with using just the index without
71671     ** ever reading the table.  If that is the case, then halve the
71672     ** cost of this index.
71673     */
71674     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
71675       Bitmask m = pSrc->colUsed;
71676       int j;
71677       for(j=0; j<pProbe->nColumn; j++){
71678         int x = pProbe->aiColumn[j];
71679         if( x<BMS-1 ){
71680           m &= ~(((Bitmask)1)<<x);
71681         }
71682       }
71683       if( m==0 ){
71684         flags |= WHERE_IDX_ONLY;
71685         cost /= 2;
71686         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
71687       }
71688     }
71689
71690     /* If this index has achieved the lowest cost so far, then use it.
71691     */
71692     if( flags && cost < lowestCost ){
71693       bestIdx = pProbe;
71694       lowestCost = cost;
71695       bestFlags = flags;
71696       bestNEq = nEq;
71697     }
71698   }
71699
71700   /* Report the best result
71701   */
71702   *ppIndex = bestIdx;
71703   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
71704         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
71705   *pFlags = bestFlags | eqTermMask;
71706   *pnEq = bestNEq;
71707   return lowestCost;
71708 }
71709
71710
71711 /*
71712 ** Disable a term in the WHERE clause.  Except, do not disable the term
71713 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
71714 ** or USING clause of that join.
71715 **
71716 ** Consider the term t2.z='ok' in the following queries:
71717 **
71718 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
71719 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
71720 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
71721 **
71722 ** The t2.z='ok' is disabled in the in (2) because it originates
71723 ** in the ON clause.  The term is disabled in (3) because it is not part
71724 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
71725 **
71726 ** Disabling a term causes that term to not be tested in the inner loop
71727 ** of the join.  Disabling is an optimization.  When terms are satisfied
71728 ** by indices, we disable them to prevent redundant tests in the inner
71729 ** loop.  We would get the correct results if nothing were ever disabled,
71730 ** but joins might run a little slower.  The trick is to disable as much
71731 ** as we can without disabling too much.  If we disabled in (1), we'd get
71732 ** the wrong answer.  See ticket #813.
71733 */
71734 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
71735   if( pTerm
71736       && (pTerm->flags & TERM_CODED)==0
71737       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
71738   ){
71739     pTerm->flags |= TERM_CODED;
71740     if( pTerm->iParent>=0 ){
71741       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
71742       if( (--pOther->nChild)==0 ){
71743         disableTerm(pLevel, pOther);
71744       }
71745     }
71746   }
71747 }
71748
71749 /*
71750 ** Apply the affinities associated with the first n columns of index
71751 ** pIdx to the values in the n registers starting at base.
71752 */
71753 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
71754   if( n>0 ){
71755     Vdbe *v = pParse->pVdbe;
71756     assert( v!=0 );
71757     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
71758     sqlite3IndexAffinityStr(v, pIdx);
71759     sqlite3ExprCacheAffinityChange(pParse, base, n);
71760   }
71761 }
71762
71763
71764 /*
71765 ** Generate code for a single equality term of the WHERE clause.  An equality
71766 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
71767 ** coded.
71768 **
71769 ** The current value for the constraint is left in register iReg.
71770 **
71771 ** For a constraint of the form X=expr, the expression is evaluated and its
71772 ** result is left on the stack.  For constraints of the form X IN (...)
71773 ** this routine sets up a loop that will iterate over all values of X.
71774 */
71775 static int codeEqualityTerm(
71776   Parse *pParse,      /* The parsing context */
71777   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
71778   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
71779   int iTarget         /* Attempt to leave results in this register */
71780 ){
71781   Expr *pX = pTerm->pExpr;
71782   Vdbe *v = pParse->pVdbe;
71783   int iReg;                  /* Register holding results */
71784
71785   if( iTarget<=0 ){
71786     iReg = iTarget = sqlite3GetTempReg(pParse);
71787   }
71788   if( pX->op==TK_EQ ){
71789     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
71790   }else if( pX->op==TK_ISNULL ){
71791     iReg = iTarget;
71792     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
71793 #ifndef SQLITE_OMIT_SUBQUERY
71794   }else{
71795     int eType;
71796     int iTab;
71797     struct InLoop *pIn;
71798
71799     assert( pX->op==TK_IN );
71800     iReg = iTarget;
71801     eType = sqlite3FindInIndex(pParse, pX, 1);
71802     iTab = pX->iTable;
71803     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
71804     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
71805     if( pLevel->nIn==0 ){
71806       pLevel->nxt = sqlite3VdbeMakeLabel(v);
71807     }
71808     pLevel->nIn++;
71809     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
71810                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
71811     pIn = pLevel->aInLoop;
71812     if( pIn ){
71813       pIn += pLevel->nIn - 1;
71814       pIn->iCur = iTab;
71815       if( eType==IN_INDEX_ROWID ){
71816         pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
71817       }else{
71818         pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
71819       }
71820       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
71821     }else{
71822       pLevel->nIn = 0;
71823     }
71824 #endif
71825   }
71826   disableTerm(pLevel, pTerm);
71827   return iReg;
71828 }
71829
71830 /*
71831 ** Generate code that will evaluate all == and IN constraints for an
71832 ** index.  The values for all constraints are left on the stack.
71833 **
71834 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
71835 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
71836 ** The index has as many as three equality constraints, but in this
71837 ** example, the third "c" value is an inequality.  So only two 
71838 ** constraints are coded.  This routine will generate code to evaluate
71839 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
71840 ** on the stack - a is the deepest and b the shallowest.
71841 **
71842 ** In the example above nEq==2.  But this subroutine works for any value
71843 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
71844 ** The only thing it does is allocate the pLevel->iMem memory cell.
71845 **
71846 ** This routine always allocates at least one memory cell and puts
71847 ** the address of that memory cell in pLevel->iMem.  The code that
71848 ** calls this routine will use pLevel->iMem to store the termination
71849 ** key value of the loop.  If one or more IN operators appear, then
71850 ** this routine allocates an additional nEq memory cells for internal
71851 ** use.
71852 */
71853 static int codeAllEqualityTerms(
71854   Parse *pParse,        /* Parsing context */
71855   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
71856   WhereClause *pWC,     /* The WHERE clause */
71857   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
71858   int nExtraReg         /* Number of extra registers to allocate */
71859 ){
71860   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
71861   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
71862   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
71863   int iCur = pLevel->iTabCur;   /* The cursor of the table */
71864   WhereTerm *pTerm;             /* A single constraint term */
71865   int j;                        /* Loop counter */
71866   int regBase;                  /* Base register */
71867
71868   /* Figure out how many memory cells we will need then allocate them.
71869   ** We always need at least one used to store the loop terminator
71870   ** value.  If there are IN operators we'll need one for each == or
71871   ** IN constraint.
71872   */
71873   pLevel->iMem = pParse->nMem + 1;
71874   regBase = pParse->nMem + 2;
71875   pParse->nMem += pLevel->nEq + 2 + nExtraReg;
71876
71877   /* Evaluate the equality constraints
71878   */
71879   assert( pIdx->nColumn>=nEq );
71880   for(j=0; j<nEq; j++){
71881     int r1;
71882     int k = pIdx->aiColumn[j];
71883     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
71884     if( pTerm==0 ) break;
71885     assert( (pTerm->flags & TERM_CODED)==0 );
71886     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
71887     if( r1!=regBase+j ){
71888       sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
71889     }
71890     testcase( pTerm->eOperator & WO_ISNULL );
71891     testcase( pTerm->eOperator & WO_IN );
71892     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
71893       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
71894     }
71895   }
71896   return regBase;
71897 }
71898
71899 #if defined(SQLITE_TEST)
71900 /*
71901 ** The following variable holds a text description of query plan generated
71902 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
71903 ** overwrites the previous.  This information is used for testing and
71904 ** analysis only.
71905 */
71906 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
71907 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
71908
71909 #endif /* SQLITE_TEST */
71910
71911
71912 /*
71913 ** Free a WhereInfo structure
71914 */
71915 static void whereInfoFree(WhereInfo *pWInfo){
71916   if( pWInfo ){
71917     int i;
71918     for(i=0; i<pWInfo->nLevel; i++){
71919       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
71920       if( pInfo ){
71921         assert( pInfo->needToFreeIdxStr==0 );
71922         sqlite3_free(pInfo);
71923       }
71924     }
71925     sqlite3_free(pWInfo);
71926   }
71927 }
71928
71929
71930 /*
71931 ** Generate the beginning of the loop used for WHERE clause processing.
71932 ** The return value is a pointer to an opaque structure that contains
71933 ** information needed to terminate the loop.  Later, the calling routine
71934 ** should invoke sqlite3WhereEnd() with the return value of this function
71935 ** in order to complete the WHERE clause processing.
71936 **
71937 ** If an error occurs, this routine returns NULL.
71938 **
71939 ** The basic idea is to do a nested loop, one loop for each table in
71940 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
71941 ** same as a SELECT with only a single table in the FROM clause.)  For
71942 ** example, if the SQL is this:
71943 **
71944 **       SELECT * FROM t1, t2, t3 WHERE ...;
71945 **
71946 ** Then the code generated is conceptually like the following:
71947 **
71948 **      foreach row1 in t1 do       \    Code generated
71949 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
71950 **          foreach row3 in t3 do   /
71951 **            ...
71952 **          end                     \    Code generated
71953 **        end                        |-- by sqlite3WhereEnd()
71954 **      end                         /
71955 **
71956 ** Note that the loops might not be nested in the order in which they
71957 ** appear in the FROM clause if a different order is better able to make
71958 ** use of indices.  Note also that when the IN operator appears in
71959 ** the WHERE clause, it might result in additional nested loops for
71960 ** scanning through all values on the right-hand side of the IN.
71961 **
71962 ** There are Btree cursors associated with each table.  t1 uses cursor
71963 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
71964 ** And so forth.  This routine generates code to open those VDBE cursors
71965 ** and sqlite3WhereEnd() generates the code to close them.
71966 **
71967 ** The code that sqlite3WhereBegin() generates leaves the cursors named
71968 ** in pTabList pointing at their appropriate entries.  The [...] code
71969 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
71970 ** data from the various tables of the loop.
71971 **
71972 ** If the WHERE clause is empty, the foreach loops must each scan their
71973 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
71974 ** the tables have indices and there are terms in the WHERE clause that
71975 ** refer to those indices, a complete table scan can be avoided and the
71976 ** code will run much faster.  Most of the work of this routine is checking
71977 ** to see if there are indices that can be used to speed up the loop.
71978 **
71979 ** Terms of the WHERE clause are also used to limit which rows actually
71980 ** make it to the "..." in the middle of the loop.  After each "foreach",
71981 ** terms of the WHERE clause that use only terms in that loop and outer
71982 ** loops are evaluated and if false a jump is made around all subsequent
71983 ** inner loops (or around the "..." if the test occurs within the inner-
71984 ** most loop)
71985 **
71986 ** OUTER JOINS
71987 **
71988 ** An outer join of tables t1 and t2 is conceptally coded as follows:
71989 **
71990 **    foreach row1 in t1 do
71991 **      flag = 0
71992 **      foreach row2 in t2 do
71993 **        start:
71994 **          ...
71995 **          flag = 1
71996 **      end
71997 **      if flag==0 then
71998 **        move the row2 cursor to a null row
71999 **        goto start
72000 **      fi
72001 **    end
72002 **
72003 ** ORDER BY CLAUSE PROCESSING
72004 **
72005 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
72006 ** if there is one.  If there is no ORDER BY clause or if this routine
72007 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
72008 **
72009 ** If an index can be used so that the natural output order of the table
72010 ** scan is correct for the ORDER BY clause, then that index is used and
72011 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
72012 ** unnecessary sort of the result set if an index appropriate for the
72013 ** ORDER BY clause already exists.
72014 **
72015 ** If the where clause loops cannot be arranged to provide the correct
72016 ** output order, then the *ppOrderBy is unchanged.
72017 */
72018 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
72019   Parse *pParse,        /* The parser context */
72020   SrcList *pTabList,    /* A list of all tables to be scanned */
72021   Expr *pWhere,         /* The WHERE clause */
72022   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
72023   u8 wflags             /* One of the WHERE_* flags defined in sqliteInt.h */
72024 ){
72025   int i;                     /* Loop counter */
72026   WhereInfo *pWInfo;         /* Will become the return value of this function */
72027   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
72028   int brk, cont = 0;         /* Addresses used during code generation */
72029   Bitmask notReady;          /* Cursors that are not yet positioned */
72030   WhereTerm *pTerm;          /* A single term in the WHERE clause */
72031   ExprMaskSet maskSet;       /* The expression mask set */
72032   WhereClause wc;            /* The WHERE clause is divided into these terms */
72033   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
72034   WhereLevel *pLevel;             /* A single level in the pWInfo list */
72035   int iFrom;                      /* First unused FROM clause element */
72036   int andFlags;              /* AND-ed combination of all wc.a[].flags */
72037   sqlite3 *db;               /* Database connection */
72038   ExprList *pOrderBy = 0;
72039
72040   /* The number of tables in the FROM clause is limited by the number of
72041   ** bits in a Bitmask 
72042   */
72043   if( pTabList->nSrc>BMS ){
72044     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
72045     return 0;
72046   }
72047
72048   if( ppOrderBy ){
72049     pOrderBy = *ppOrderBy;
72050   }
72051
72052   /* Split the WHERE clause into separate subexpressions where each
72053   ** subexpression is separated by an AND operator.
72054   */
72055   initMaskSet(&maskSet);
72056   whereClauseInit(&wc, pParse, &maskSet);
72057   sqlite3ExprCodeConstants(pParse, pWhere);
72058   whereSplit(&wc, pWhere, TK_AND);
72059     
72060   /* Allocate and initialize the WhereInfo structure that will become the
72061   ** return value.
72062   */
72063   db = pParse->db;
72064   pWInfo = sqlite3DbMallocZero(db,  
72065                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
72066   if( db->mallocFailed ){
72067     goto whereBeginNoMem;
72068   }
72069   pWInfo->nLevel = pTabList->nSrc;
72070   pWInfo->pParse = pParse;
72071   pWInfo->pTabList = pTabList;
72072   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
72073
72074   /* Special case: a WHERE clause that is constant.  Evaluate the
72075   ** expression and either jump over all of the code or fall thru.
72076   */
72077   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
72078     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
72079     pWhere = 0;
72080   }
72081
72082   /* Assign a bit from the bitmask to every term in the FROM clause.
72083   **
72084   ** When assigning bitmask values to FROM clause cursors, it must be
72085   ** the case that if X is the bitmask for the N-th FROM clause term then
72086   ** the bitmask for all FROM clause terms to the left of the N-th term
72087   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
72088   ** its Expr.iRightJoinTable value to find the bitmask of the right table
72089   ** of the join.  Subtracting one from the right table bitmask gives a
72090   ** bitmask for all tables to the left of the join.  Knowing the bitmask
72091   ** for all tables to the left of a left join is important.  Ticket #3015.
72092   */
72093   for(i=0; i<pTabList->nSrc; i++){
72094     createMask(&maskSet, pTabList->a[i].iCursor);
72095   }
72096 #ifndef NDEBUG
72097   {
72098     Bitmask toTheLeft = 0;
72099     for(i=0; i<pTabList->nSrc; i++){
72100       Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor);
72101       assert( (m-1)==toTheLeft );
72102       toTheLeft |= m;
72103     }
72104   }
72105 #endif
72106
72107   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
72108   ** add new virtual terms onto the end of the WHERE clause.  We do not
72109   ** want to analyze these virtual terms, so start analyzing at the end
72110   ** and work forward so that the added virtual terms are never processed.
72111   */
72112   exprAnalyzeAll(pTabList, &wc);
72113   if( db->mallocFailed ){
72114     goto whereBeginNoMem;
72115   }
72116
72117   /* Chose the best index to use for each table in the FROM clause.
72118   **
72119   ** This loop fills in the following fields:
72120   **
72121   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
72122   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
72123   **   pWInfo->a[].nEq       The number of == and IN constraints
72124   **   pWInfo->a[].iFrom     When term of the FROM clause is being coded
72125   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
72126   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
72127   **
72128   ** This loop also figures out the nesting order of tables in the FROM
72129   ** clause.
72130   */
72131   notReady = ~(Bitmask)0;
72132   pTabItem = pTabList->a;
72133   pLevel = pWInfo->a;
72134   andFlags = ~0;
72135   WHERETRACE(("*** Optimizer Start ***\n"));
72136   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
72137     Index *pIdx;                /* Index for FROM table at pTabItem */
72138     int flags;                  /* Flags asssociated with pIdx */
72139     int nEq;                    /* Number of == or IN constraints */
72140     double cost;                /* The cost for pIdx */
72141     int j;                      /* For looping over FROM tables */
72142     Index *pBest = 0;           /* The best index seen so far */
72143     int bestFlags = 0;          /* Flags associated with pBest */
72144     int bestNEq = 0;            /* nEq associated with pBest */
72145     double lowestCost;          /* Cost of the pBest */
72146     int bestJ = 0;              /* The value of j */
72147     Bitmask m;                  /* Bitmask value for j or bestJ */
72148     int once = 0;               /* True when first table is seen */
72149     sqlite3_index_info *pIndex; /* Current virtual index */
72150
72151     lowestCost = SQLITE_BIG_DBL;
72152     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
72153       int doNotReorder;  /* True if this table should not be reordered */
72154
72155       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
72156       if( once && doNotReorder ) break;
72157       m = getMask(&maskSet, pTabItem->iCursor);
72158       if( (m & notReady)==0 ){
72159         if( j==iFrom ) iFrom++;
72160         continue;
72161       }
72162       assert( pTabItem->pTab );
72163 #ifndef SQLITE_OMIT_VIRTUALTABLE
72164       if( IsVirtual(pTabItem->pTab) ){
72165         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
72166         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
72167                                 ppOrderBy ? *ppOrderBy : 0, i==0,
72168                                 ppIdxInfo);
72169         flags = WHERE_VIRTUALTABLE;
72170         pIndex = *ppIdxInfo;
72171         if( pIndex && pIndex->orderByConsumed ){
72172           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
72173         }
72174         pIdx = 0;
72175         nEq = 0;
72176         if( (SQLITE_BIG_DBL/2.0)<cost ){
72177           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
72178           ** inital value of lowestCost in this loop. If it is, then
72179           ** the (cost<lowestCost) test below will never be true and
72180           ** pLevel->pBestIdx never set.
72181           */ 
72182           cost = (SQLITE_BIG_DBL/2.0);
72183         }
72184       }else 
72185 #endif
72186       {
72187         cost = bestIndex(pParse, &wc, pTabItem, notReady,
72188                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
72189                          &pIdx, &flags, &nEq);
72190         pIndex = 0;
72191       }
72192       if( cost<lowestCost ){
72193         once = 1;
72194         lowestCost = cost;
72195         pBest = pIdx;
72196         bestFlags = flags;
72197         bestNEq = nEq;
72198         bestJ = j;
72199         pLevel->pBestIdx = pIndex;
72200       }
72201       if( doNotReorder ) break;
72202     }
72203     WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ,
72204            pLevel-pWInfo->a));
72205     if( (bestFlags & WHERE_ORDERBY)!=0 ){
72206       *ppOrderBy = 0;
72207     }
72208     andFlags &= bestFlags;
72209     pLevel->flags = bestFlags;
72210     pLevel->pIdx = pBest;
72211     pLevel->nEq = bestNEq;
72212     pLevel->aInLoop = 0;
72213     pLevel->nIn = 0;
72214     if( pBest ){
72215       pLevel->iIdxCur = pParse->nTab++;
72216     }else{
72217       pLevel->iIdxCur = -1;
72218     }
72219     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
72220     pLevel->iFrom = bestJ;
72221   }
72222   WHERETRACE(("*** Optimizer Finished ***\n"));
72223
72224   /* If the total query only selects a single row, then the ORDER BY
72225   ** clause is irrelevant.
72226   */
72227   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
72228     *ppOrderBy = 0;
72229   }
72230
72231   /* If the caller is an UPDATE or DELETE statement that is requesting
72232   ** to use a one-pass algorithm, determine if this is appropriate.
72233   ** The one-pass algorithm only works if the WHERE clause constraints
72234   ** the statement to update a single row.
72235   */
72236   assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
72237   if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
72238     pWInfo->okOnePass = 1;
72239     pWInfo->a[0].flags &= ~WHERE_IDX_ONLY;
72240   }
72241
72242   /* Open all tables in the pTabList and any indices selected for
72243   ** searching those tables.
72244   */
72245   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
72246   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
72247     Table *pTab;     /* Table to open */
72248     Index *pIx;      /* Index used to access pTab (if any) */
72249     int iDb;         /* Index of database containing table/index */
72250     int iIdxCur = pLevel->iIdxCur;
72251
72252 #ifndef SQLITE_OMIT_EXPLAIN
72253     if( pParse->explain==2 ){
72254       char *zMsg;
72255       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
72256       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
72257       if( pItem->zAlias ){
72258         zMsg = sqlite3MPrintf(db, "%z AS %s", zMsg, pItem->zAlias);
72259       }
72260       if( (pIx = pLevel->pIdx)!=0 ){
72261         zMsg = sqlite3MPrintf(db, "%z WITH INDEX %s", zMsg, pIx->zName);
72262       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
72263         zMsg = sqlite3MPrintf(db, "%z USING PRIMARY KEY", zMsg);
72264       }
72265 #ifndef SQLITE_OMIT_VIRTUALTABLE
72266       else if( pLevel->pBestIdx ){
72267         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
72268         zMsg = sqlite3MPrintf(db, "%z VIRTUAL TABLE INDEX %d:%s", zMsg,
72269                     pBestIdx->idxNum, pBestIdx->idxStr);
72270       }
72271 #endif
72272       if( pLevel->flags & WHERE_ORDERBY ){
72273         zMsg = sqlite3MPrintf(db, "%z ORDER BY", zMsg);
72274       }
72275       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
72276     }
72277 #endif /* SQLITE_OMIT_EXPLAIN */
72278     pTabItem = &pTabList->a[pLevel->iFrom];
72279     pTab = pTabItem->pTab;
72280     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
72281     if( pTab->isEphem || pTab->pSelect ) continue;
72282 #ifndef SQLITE_OMIT_VIRTUALTABLE
72283     if( pLevel->pBestIdx ){
72284       int iCur = pTabItem->iCursor;
72285       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
72286                         (const char*)pTab->pVtab, P4_VTAB);
72287     }else
72288 #endif
72289     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
72290       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
72291       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
72292       if( !pWInfo->okOnePass && pTab->nCol<(sizeof(Bitmask)*8) ){
72293         Bitmask b = pTabItem->colUsed;
72294         int n = 0;
72295         for(; b; b=b>>1, n++){}
72296         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
72297         assert( n<=pTab->nCol );
72298       }
72299     }else{
72300       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72301     }
72302     pLevel->iTabCur = pTabItem->iCursor;
72303     if( (pIx = pLevel->pIdx)!=0 ){
72304       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
72305       assert( pIx->pSchema==pTab->pSchema );
72306       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
72307       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
72308                         (char*)pKey, P4_KEYINFO_HANDOFF);
72309       VdbeComment((v, "%s", pIx->zName));
72310     }
72311     sqlite3CodeVerifySchema(pParse, iDb);
72312   }
72313   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
72314
72315   /* Generate the code to do the search.  Each iteration of the for
72316   ** loop below generates code for a single nested loop of the VM
72317   ** program.
72318   */
72319   notReady = ~(Bitmask)0;
72320   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
72321     int j;
72322     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
72323     Index *pIdx;       /* The index we will be using */
72324     int nxt;           /* Where to jump to continue with the next IN case */
72325     int iIdxCur;       /* The VDBE cursor for the index */
72326     int omitTable;     /* True if we use the index only */
72327     int bRev;          /* True if we need to scan in reverse order */
72328
72329     pTabItem = &pTabList->a[pLevel->iFrom];
72330     iCur = pTabItem->iCursor;
72331     pIdx = pLevel->pIdx;
72332     iIdxCur = pLevel->iIdxCur;
72333     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
72334     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
72335
72336     /* Create labels for the "break" and "continue" instructions
72337     ** for the current loop.  Jump to brk to break out of a loop.
72338     ** Jump to cont to go immediately to the next iteration of the
72339     ** loop.
72340     **
72341     ** When there is an IN operator, we also have a "nxt" label that
72342     ** means to continue with the next IN value combination.  When
72343     ** there are no IN operators in the constraints, the "nxt" label
72344     ** is the same as "brk".
72345     */
72346     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
72347     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
72348
72349     /* If this is the right table of a LEFT OUTER JOIN, allocate and
72350     ** initialize a memory cell that records if this table matches any
72351     ** row of the left table of the join.
72352     */
72353     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
72354       pLevel->iLeftJoin = ++pParse->nMem;
72355       sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
72356       VdbeComment((v, "init LEFT JOIN no-match flag"));
72357     }
72358
72359 #ifndef SQLITE_OMIT_VIRTUALTABLE
72360     if( pLevel->pBestIdx ){
72361       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
72362       **          to access the data.
72363       */
72364       int j;
72365       int iReg;   /* P3 Value for OP_VFilter */
72366       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
72367       int nConstraint = pBestIdx->nConstraint;
72368       struct sqlite3_index_constraint_usage *aUsage =
72369                                                   pBestIdx->aConstraintUsage;
72370       const struct sqlite3_index_constraint *aConstraint =
72371                                                   pBestIdx->aConstraint;
72372
72373       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
72374       for(j=1; j<=nConstraint; j++){
72375         int k;
72376         for(k=0; k<nConstraint; k++){
72377           if( aUsage[k].argvIndex==j ){
72378             int iTerm = aConstraint[k].iTermOffset;
72379             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
72380             break;
72381           }
72382         }
72383         if( k==nConstraint ) break;
72384       }
72385       sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
72386       sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
72387       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
72388                         pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
72389       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
72390       pBestIdx->needToFreeIdxStr = 0;
72391       for(j=0; j<pBestIdx->nConstraint; j++){
72392         if( aUsage[j].omit ){
72393           int iTerm = aConstraint[j].iTermOffset;
72394           disableTerm(pLevel, &wc.a[iTerm]);
72395         }
72396       }
72397       pLevel->op = OP_VNext;
72398       pLevel->p1 = iCur;
72399       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
72400     }else
72401 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72402
72403     if( pLevel->flags & WHERE_ROWID_EQ ){
72404       /* Case 1:  We can directly reference a single row using an
72405       **          equality comparison against the ROWID field.  Or
72406       **          we reference multiple rows using a "rowid IN (...)"
72407       **          construct.
72408       */
72409       int r1;
72410       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
72411       assert( pTerm!=0 );
72412       assert( pTerm->pExpr!=0 );
72413       assert( pTerm->leftCursor==iCur );
72414       assert( omitTable==0 );
72415       r1 = codeEqualityTerm(pParse, pTerm, pLevel, 0);
72416       nxt = pLevel->nxt;
72417       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt);
72418       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
72419       VdbeComment((v, "pk"));
72420       pLevel->op = OP_Noop;
72421     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
72422       /* Case 2:  We have an inequality comparison against the ROWID field.
72423       */
72424       int testOp = OP_Noop;
72425       int start;
72426       WhereTerm *pStart, *pEnd;
72427
72428       assert( omitTable==0 );
72429       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
72430       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
72431       if( bRev ){
72432         pTerm = pStart;
72433         pStart = pEnd;
72434         pEnd = pTerm;
72435       }
72436       if( pStart ){
72437         Expr *pX;
72438         int r1, regFree1;
72439         pX = pStart->pExpr;
72440         assert( pX!=0 );
72441         assert( pStart->leftCursor==iCur );
72442         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &regFree1);
72443         sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, 
72444                              pX->op==TK_LE || pX->op==TK_GT);
72445         sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
72446         VdbeComment((v, "pk"));
72447         sqlite3ReleaseTempReg(pParse, regFree1);
72448         disableTerm(pLevel, pStart);
72449       }else{
72450         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
72451       }
72452       if( pEnd ){
72453         Expr *pX;
72454         pX = pEnd->pExpr;
72455         assert( pX!=0 );
72456         assert( pEnd->leftCursor==iCur );
72457         pLevel->iMem = ++pParse->nMem;
72458         sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
72459         if( pX->op==TK_LT || pX->op==TK_GT ){
72460           testOp = bRev ? OP_Le : OP_Ge;
72461         }else{
72462           testOp = bRev ? OP_Lt : OP_Gt;
72463         }
72464         disableTerm(pLevel, pEnd);
72465       }
72466       start = sqlite3VdbeCurrentAddr(v);
72467       pLevel->op = bRev ? OP_Prev : OP_Next;
72468       pLevel->p1 = iCur;
72469       pLevel->p2 = start;
72470       if( testOp!=OP_Noop ){
72471         int r1 = sqlite3GetTempReg(pParse);
72472         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
72473         /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
72474         sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
72475         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
72476         sqlite3ReleaseTempReg(pParse, r1);
72477       }
72478     }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
72479       /* Case 3: A scan using an index.
72480       **
72481       **         The WHERE clause may contain zero or more equality 
72482       **         terms ("==" or "IN" operators) that refer to the N
72483       **         left-most columns of the index. It may also contain
72484       **         inequality constraints (>, <, >= or <=) on the indexed
72485       **         column that immediately follows the N equalities. Only 
72486       **         the right-most column can be an inequality - the rest must
72487       **         use the "==" and "IN" operators. For example, if the 
72488       **         index is on (x,y,z), then the following clauses are all 
72489       **         optimized:
72490       **
72491       **            x=5
72492       **            x=5 AND y=10
72493       **            x=5 AND y<10
72494       **            x=5 AND y>5 AND y<10
72495       **            x=5 AND y=5 AND z<=10
72496       **
72497       **         The z<10 term of the following cannot be used, only
72498       **         the x=5 term:
72499       **
72500       **            x=5 AND z<10
72501       **
72502       **         N may be zero if there are inequality constraints.
72503       **         If there are no inequality constraints, then N is at
72504       **         least one.
72505       **
72506       **         This case is also used when there are no WHERE clause
72507       **         constraints but an index is selected anyway, in order
72508       **         to force the output order to conform to an ORDER BY.
72509       */  
72510       int aStartOp[] = {
72511         0,
72512         0,
72513         OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
72514         OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
72515         OP_MoveGt,           /* 4: (start_constraints  && !startEq && !bRev) */
72516         OP_MoveLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
72517         OP_MoveGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
72518         OP_MoveLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
72519       };
72520       int aEndOp[] = {
72521         OP_Noop,             /* 0: (!end_constraints) */
72522         OP_IdxGE,            /* 1: (end_constraints && !bRev) */
72523         OP_IdxLT             /* 2: (end_constraints && bRev) */
72524       };
72525       int nEq = pLevel->nEq;
72526       int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
72527       int regBase;                 /* Base register holding constraint values */
72528       int r1;                      /* Temp register */
72529       WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
72530       WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
72531       int startEq;                 /* True if range start uses ==, >= or <= */
72532       int endEq;                   /* True if range end uses ==, >= or <= */
72533       int start_constraints;       /* Start of range is constrained */
72534       int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
72535       int nConstraint;             /* Number of constraint terms */
72536       int op;
72537
72538       /* Generate code to evaluate all constraint terms using == or IN
72539       ** and store the values of those terms in an array of registers
72540       ** starting at regBase.
72541       */
72542       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
72543       nxt = pLevel->nxt;
72544
72545       /* If this loop satisfies a sort order (pOrderBy) request that 
72546       ** was passed to this function to implement a "SELECT min(x) ..." 
72547       ** query, then the caller will only allow the loop to run for
72548       ** a single iteration. This means that the first row returned
72549       ** should not have a NULL value stored in 'x'. If column 'x' is
72550       ** the first one after the nEq equality constraints in the index,
72551       ** this requires some special handling.
72552       */
72553       if( (wflags&WHERE_ORDERBY_MIN)!=0
72554        && (pLevel->flags&WHERE_ORDERBY)
72555        && (pIdx->nColumn>nEq)
72556        && (pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq])
72557       ){
72558         isMinQuery = 1;
72559       }
72560
72561       /* Find any inequality constraint terms for the start and end 
72562       ** of the range. 
72563       */
72564       if( pLevel->flags & WHERE_TOP_LIMIT ){
72565         pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
72566       }
72567       if( pLevel->flags & WHERE_BTM_LIMIT ){
72568         pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
72569       }
72570
72571       /* If we are doing a reverse order scan on an ascending index, or
72572       ** a forward order scan on a descending index, interchange the 
72573       ** start and end terms (pRangeStart and pRangeEnd).
72574       */
72575       if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
72576         SWAP(WhereTerm *, pRangeEnd, pRangeStart);
72577       }
72578
72579       testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
72580       testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
72581       testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
72582       testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
72583       startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
72584       endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
72585       start_constraints = pRangeStart || nEq>0;
72586
72587       /* Seek the index cursor to the start of the range. */
72588       nConstraint = nEq;
72589       if( pRangeStart ){
72590         int dcc = pParse->disableColCache;
72591         if( pRangeEnd ){
72592           pParse->disableColCache = 1;
72593         }
72594         sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
72595         pParse->disableColCache = dcc;
72596         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
72597         nConstraint++;
72598       }else if( isMinQuery ){
72599         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
72600         nConstraint++;
72601         startEq = 0;
72602         start_constraints = 1;
72603       }
72604       codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
72605       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
72606       assert( op!=0 );
72607       testcase( op==OP_Rewind );
72608       testcase( op==OP_Last );
72609       testcase( op==OP_MoveGt );
72610       testcase( op==OP_MoveGe );
72611       testcase( op==OP_MoveLe );
72612       testcase( op==OP_MoveLt );
72613       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, 
72614                         (char*)nConstraint, P4_INT32);
72615
72616       /* Load the value for the inequality constraint at the end of the
72617       ** range (if any).
72618       */
72619       nConstraint = nEq;
72620       if( pRangeEnd ){
72621         sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
72622         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
72623         codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
72624         nConstraint++;
72625       }
72626
72627       /* Top of the loop body */
72628       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
72629
72630       /* Check if the index cursor is past the end of the range. */
72631       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
72632       testcase( op==OP_Noop );
72633       testcase( op==OP_IdxGE );
72634       testcase( op==OP_IdxLT );
72635       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
72636                         (char*)nConstraint, P4_INT32);
72637       sqlite3VdbeChangeP5(v, endEq!=bRev);
72638
72639       /* If there are inequality constraints, check that the value
72640       ** of the table column that the inequality contrains is not NULL.
72641       ** If it is, jump to the next iteration of the loop.
72642       */
72643       r1 = sqlite3GetTempReg(pParse);
72644       testcase( pLevel->flags & WHERE_BTM_LIMIT );
72645       testcase( pLevel->flags & WHERE_TOP_LIMIT );
72646       if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
72647         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
72648         sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
72649       }
72650
72651       /* Seek the table cursor, if required */
72652       if( !omitTable ){
72653         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
72654         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
72655       }
72656       sqlite3ReleaseTempReg(pParse, r1);
72657
72658       /* Record the instruction used to terminate the loop. Disable 
72659       ** WHERE clause terms made redundant by the index range scan.
72660       */
72661       pLevel->op = bRev ? OP_Prev : OP_Next;
72662       pLevel->p1 = iIdxCur;
72663       disableTerm(pLevel, pRangeStart);
72664       disableTerm(pLevel, pRangeEnd);
72665     }else{
72666       /* Case 4:  There is no usable index.  We must do a complete
72667       **          scan of the entire table.
72668       */
72669       assert( omitTable==0 );
72670       assert( bRev==0 );
72671       pLevel->op = OP_Next;
72672       pLevel->p1 = iCur;
72673       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
72674     }
72675     notReady &= ~getMask(&maskSet, iCur);
72676
72677     /* Insert code to test every subexpression that can be completely
72678     ** computed using the current set of tables.
72679     */
72680     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
72681       Expr *pE;
72682       testcase( pTerm->flags & TERM_VIRTUAL );
72683       testcase( pTerm->flags & TERM_CODED );
72684       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
72685       if( (pTerm->prereqAll & notReady)!=0 ) continue;
72686       pE = pTerm->pExpr;
72687       assert( pE!=0 );
72688       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
72689         continue;
72690       }
72691       sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
72692       pTerm->flags |= TERM_CODED;
72693     }
72694
72695     /* For a LEFT OUTER JOIN, generate code that will record the fact that
72696     ** at least one row of the right table has matched the left table.  
72697     */
72698     if( pLevel->iLeftJoin ){
72699       pLevel->top = sqlite3VdbeCurrentAddr(v);
72700       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
72701       VdbeComment((v, "record LEFT JOIN hit"));
72702       sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
72703       sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
72704       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
72705         testcase( pTerm->flags & TERM_VIRTUAL );
72706         testcase( pTerm->flags & TERM_CODED );
72707         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
72708         if( (pTerm->prereqAll & notReady)!=0 ) continue;
72709         assert( pTerm->pExpr );
72710         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
72711         pTerm->flags |= TERM_CODED;
72712       }
72713     }
72714   }
72715
72716 #ifdef SQLITE_TEST  /* For testing and debugging use only */
72717   /* Record in the query plan information about the current table
72718   ** and the index used to access it (if any).  If the table itself
72719   ** is not used, its name is just '{}'.  If no index is used
72720   ** the index is listed as "{}".  If the primary key is used the
72721   ** index name is '*'.
72722   */
72723   for(i=0; i<pTabList->nSrc; i++){
72724     char *z;
72725     int n;
72726     pLevel = &pWInfo->a[i];
72727     pTabItem = &pTabList->a[pLevel->iFrom];
72728     z = pTabItem->zAlias;
72729     if( z==0 ) z = pTabItem->pTab->zName;
72730     n = strlen(z);
72731     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
72732       if( pLevel->flags & WHERE_IDX_ONLY ){
72733         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
72734         nQPlan += 2;
72735       }else{
72736         memcpy(&sqlite3_query_plan[nQPlan], z, n);
72737         nQPlan += n;
72738       }
72739       sqlite3_query_plan[nQPlan++] = ' ';
72740     }
72741     testcase( pLevel->flags & WHERE_ROWID_EQ );
72742     testcase( pLevel->flags & WHERE_ROWID_RANGE );
72743     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
72744       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
72745       nQPlan += 2;
72746     }else if( pLevel->pIdx==0 ){
72747       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
72748       nQPlan += 3;
72749     }else{
72750       n = strlen(pLevel->pIdx->zName);
72751       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
72752         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
72753         nQPlan += n;
72754         sqlite3_query_plan[nQPlan++] = ' ';
72755       }
72756     }
72757   }
72758   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
72759     sqlite3_query_plan[--nQPlan] = 0;
72760   }
72761   sqlite3_query_plan[nQPlan] = 0;
72762   nQPlan = 0;
72763 #endif /* SQLITE_TEST // Testing and debugging use only */
72764
72765   /* Record the continuation address in the WhereInfo structure.  Then
72766   ** clean up and return.
72767   */
72768   pWInfo->iContinue = cont;
72769   whereClauseClear(&wc);
72770   return pWInfo;
72771
72772   /* Jump here if malloc fails */
72773 whereBeginNoMem:
72774   whereClauseClear(&wc);
72775   whereInfoFree(pWInfo);
72776   return 0;
72777 }
72778
72779 /*
72780 ** Generate the end of the WHERE loop.  See comments on 
72781 ** sqlite3WhereBegin() for additional information.
72782 */
72783 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
72784   Vdbe *v = pWInfo->pParse->pVdbe;
72785   int i;
72786   WhereLevel *pLevel;
72787   SrcList *pTabList = pWInfo->pTabList;
72788
72789   /* Generate loop termination code.
72790   */
72791   sqlite3ExprClearColumnCache(pWInfo->pParse, -1);
72792   for(i=pTabList->nSrc-1; i>=0; i--){
72793     pLevel = &pWInfo->a[i];
72794     sqlite3VdbeResolveLabel(v, pLevel->cont);
72795     if( pLevel->op!=OP_Noop ){
72796       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
72797     }
72798     if( pLevel->nIn ){
72799       struct InLoop *pIn;
72800       int j;
72801       sqlite3VdbeResolveLabel(v, pLevel->nxt);
72802       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
72803         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
72804         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
72805         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
72806       }
72807       sqlite3_free(pLevel->aInLoop);
72808     }
72809     sqlite3VdbeResolveLabel(v, pLevel->brk);
72810     if( pLevel->iLeftJoin ){
72811       int addr;
72812       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
72813       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
72814       if( pLevel->iIdxCur>=0 ){
72815         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
72816       }
72817       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
72818       sqlite3VdbeJumpHere(v, addr);
72819     }
72820   }
72821
72822   /* The "break" point is here, just past the end of the outer loop.
72823   ** Set it.
72824   */
72825   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
72826
72827   /* Close all of the cursors that were opened by sqlite3WhereBegin.
72828   */
72829   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
72830     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
72831     Table *pTab = pTabItem->pTab;
72832     assert( pTab!=0 );
72833     if( pTab->isEphem || pTab->pSelect ) continue;
72834     if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){
72835       sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
72836     }
72837     if( pLevel->pIdx!=0 ){
72838       sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
72839     }
72840
72841     /* If this scan uses an index, make code substitutions to read data
72842     ** from the index in preference to the table. Sometimes, this means
72843     ** the table need never be read from. This is a performance boost,
72844     ** as the vdbe level waits until the table is read before actually
72845     ** seeking the table cursor to the record corresponding to the current
72846     ** position in the index.
72847     ** 
72848     ** Calls to the code generator in between sqlite3WhereBegin and
72849     ** sqlite3WhereEnd will have created code that references the table
72850     ** directly.  This loop scans all that code looking for opcodes
72851     ** that reference the table and converts them into opcodes that
72852     ** reference the index.
72853     */
72854     if( pLevel->pIdx ){
72855       int k, j, last;
72856       VdbeOp *pOp;
72857       Index *pIdx = pLevel->pIdx;
72858       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
72859
72860       assert( pIdx!=0 );
72861       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
72862       last = sqlite3VdbeCurrentAddr(v);
72863       for(k=pWInfo->iTop; k<last; k++, pOp++){
72864         if( pOp->p1!=pLevel->iTabCur ) continue;
72865         if( pOp->opcode==OP_Column ){
72866           for(j=0; j<pIdx->nColumn; j++){
72867             if( pOp->p2==pIdx->aiColumn[j] ){
72868               pOp->p2 = j;
72869               pOp->p1 = pLevel->iIdxCur;
72870               break;
72871             }
72872           }
72873           assert(!useIndexOnly || j<pIdx->nColumn);
72874         }else if( pOp->opcode==OP_Rowid ){
72875           pOp->p1 = pLevel->iIdxCur;
72876           pOp->opcode = OP_IdxRowid;
72877         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
72878           pOp->opcode = OP_Noop;
72879         }
72880       }
72881     }
72882   }
72883
72884   /* Final cleanup
72885   */
72886   whereInfoFree(pWInfo);
72887   return;
72888 }
72889
72890 /************** End of where.c ***********************************************/
72891 /************** Begin file parse.c *******************************************/
72892 /* Driver template for the LEMON parser generator.
72893 ** The author disclaims copyright to this source code.
72894 */
72895 /* First off, code is include which follows the "include" declaration
72896 ** in the input file. */
72897
72898
72899 /*
72900 ** An instance of this structure holds information about the
72901 ** LIMIT clause of a SELECT statement.
72902 */
72903 struct LimitVal {
72904   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
72905   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
72906 };
72907
72908 /*
72909 ** An instance of this structure is used to store the LIKE,
72910 ** GLOB, NOT LIKE, and NOT GLOB operators.
72911 */
72912 struct LikeOp {
72913   Token eOperator;  /* "like" or "glob" or "regexp" */
72914   int not;         /* True if the NOT keyword is present */
72915 };
72916
72917 /*
72918 ** An instance of the following structure describes the event of a
72919 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
72920 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
72921 **
72922 **      UPDATE ON (a,b,c)
72923 **
72924 ** Then the "b" IdList records the list "a,b,c".
72925 */
72926 struct TrigEvent { int a; IdList * b; };
72927
72928 /*
72929 ** An instance of this structure holds the ATTACH key and the key type.
72930 */
72931 struct AttachKey { int type;  Token key; };
72932
72933 /* Next is all token values, in a form suitable for use by makeheaders.
72934 ** This section will be null unless lemon is run with the -m switch.
72935 */
72936 /* 
72937 ** These constants (all generated automatically by the parser generator)
72938 ** specify the various kinds of tokens (terminals) that the parser
72939 ** understands. 
72940 **
72941 ** Each symbol here is a terminal symbol in the grammar.
72942 */
72943 /* Make sure the INTERFACE macro is defined.
72944 */
72945 #ifndef INTERFACE
72946 # define INTERFACE 1
72947 #endif
72948 /* The next thing included is series of defines which control
72949 ** various aspects of the generated parser.
72950 **    YYCODETYPE         is the data type used for storing terminal
72951 **                       and nonterminal numbers.  "unsigned char" is
72952 **                       used if there are fewer than 250 terminals
72953 **                       and nonterminals.  "int" is used otherwise.
72954 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
72955 **                       to no legal terminal or nonterminal number.  This
72956 **                       number is used to fill in empty slots of the hash 
72957 **                       table.
72958 **    YYFALLBACK         If defined, this indicates that one or more tokens
72959 **                       have fall-back values which should be used if the
72960 **                       original value of the token will not parse.
72961 **    YYACTIONTYPE       is the data type used for storing terminal
72962 **                       and nonterminal numbers.  "unsigned char" is
72963 **                       used if there are fewer than 250 rules and
72964 **                       states combined.  "int" is used otherwise.
72965 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
72966 **                       directly to the parser from the tokenizer.
72967 **    YYMINORTYPE        is the data type used for all minor tokens.
72968 **                       This is typically a union of many types, one of
72969 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
72970 **                       for base tokens is called "yy0".
72971 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
72972 **                       zero the stack is dynamically sized using realloc()
72973 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
72974 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
72975 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
72976 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
72977 **    YYNSTATE           the combined number of states.
72978 **    YYNRULE            the number of rules in the grammar
72979 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
72980 **                       defined, then do no error processing.
72981 */
72982 #define YYCODETYPE unsigned char
72983 #define YYNOCODE 248
72984 #define YYACTIONTYPE unsigned short int
72985 #define YYWILDCARD 59
72986 #define sqlite3ParserTOKENTYPE Token
72987 typedef union {
72988   sqlite3ParserTOKENTYPE yy0;
72989   int yy46;
72990   struct LikeOp yy72;
72991   Expr* yy172;
72992   ExprList* yy174;
72993   Select* yy219;
72994   struct LimitVal yy234;
72995   TriggerStep* yy243;
72996   struct TrigEvent yy370;
72997   SrcList* yy373;
72998   struct {int value; int mask;} yy405;
72999   Token yy410;
73000   IdList* yy432;
73001 } YYMINORTYPE;
73002 #ifndef YYSTACKDEPTH
73003 #define YYSTACKDEPTH 100
73004 #endif
73005 #define sqlite3ParserARG_SDECL Parse *pParse;
73006 #define sqlite3ParserARG_PDECL ,Parse *pParse
73007 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
73008 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
73009 #define YYNSTATE 589
73010 #define YYNRULE 313
73011 #define YYFALLBACK 1
73012 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
73013 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
73014 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
73015
73016 /* The yyzerominor constant is used to initialize instances of
73017 ** YYMINORTYPE objects to zero. */
73018 static const YYMINORTYPE yyzerominor;
73019
73020 /* Next are that tables used to determine what action to take based on the
73021 ** current state and lookahead token.  These tables are used to implement
73022 ** functions that take a state number and lookahead value and return an
73023 ** action integer.  
73024 **
73025 ** Suppose the action integer is N.  Then the action is determined as
73026 ** follows
73027 **
73028 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
73029 **                                      token onto the stack and goto state N.
73030 **
73031 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
73032 **
73033 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
73034 **
73035 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
73036 **
73037 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
73038 **                                      slots in the yy_action[] table.
73039 **
73040 ** The action table is constructed as a single large table named yy_action[].
73041 ** Given state S and lookahead X, the action is computed as
73042 **
73043 **      yy_action[ yy_shift_ofst[S] + X ]
73044 **
73045 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
73046 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
73047 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
73048 ** and that yy_default[S] should be used instead.  
73049 **
73050 ** The formula above is for computing the action when the lookahead is
73051 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
73052 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
73053 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
73054 ** YY_SHIFT_USE_DFLT.
73055 **
73056 ** The following are the tables generated in this section:
73057 **
73058 **  yy_action[]        A single table containing all actions.
73059 **  yy_lookahead[]     A table containing the lookahead for each entry in
73060 **                     yy_action.  Used to detect hash collisions.
73061 **  yy_shift_ofst[]    For each state, the offset into yy_action for
73062 **                     shifting terminals.
73063 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
73064 **                     shifting non-terminals after a reduce.
73065 **  yy_default[]       Default action for each state.
73066 */
73067 static const YYACTIONTYPE yy_action[] = {
73068  /*     0 */   292,  903,  124,  588,  409,  172,    2,  418,   61,   61,
73069  /*    10 */    61,   61,  519,   63,   63,   63,   63,   64,   64,   65,
73070  /*    20 */    65,   65,   66,  210,  447,  212,  425,  431,   68,   63,
73071  /*    30 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  210,
73072  /*    40 */   391,  388,  396,  451,   60,   59,  297,  435,  436,  432,
73073  /*    50 */   432,   62,   62,   61,   61,   61,   61,  263,   63,   63,
73074  /*    60 */    63,   63,   64,   64,   65,   65,   65,   66,  210,  292,
73075  /*    70 */   493,  494,  418,  489,  208,   82,   67,  420,   69,  154,
73076  /*    80 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
73077  /*    90 */   210,   67,  462,   69,  154,  425,  431,  574,  264,   58,
73078  /*   100 */    64,   64,   65,   65,   65,   66,  210,  397,  398,  422,
73079  /*   110 */   422,  422,  292,   60,   59,  297,  435,  436,  432,  432,
73080  /*   120 */    62,   62,   61,   61,   61,   61,  317,   63,   63,   63,
73081  /*   130 */    63,   64,   64,   65,   65,   65,   66,  210,  425,  431,
73082  /*   140 */    94,   65,   65,   65,   66,  210,  396,  210,  414,   34,
73083  /*   150 */    56,  298,  442,  443,  410,  418,   60,   59,  297,  435,
73084  /*   160 */   436,  432,  432,   62,   62,   61,   61,   61,   61,  208,
73085  /*   170 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
73086  /*   180 */   210,  292,  372,  524,  295,  572,  113,  408,  522,  451,
73087  /*   190 */   331,  317,  407,   20,  244,  340,  519,  396,  478,  531,
73088  /*   200 */   505,  447,  212,  571,  570,  245,  530,  425,  431,  149,
73089  /*   210 */   150,  397,  398,  414,   41,  211,  151,  533,  488,  489,
73090  /*   220 */   418,  568,  569,  420,  292,   60,   59,  297,  435,  436,
73091  /*   230 */   432,  432,   62,   62,   61,   61,   61,   61,  317,   63,
73092  /*   240 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  210,
73093  /*   250 */   425,  431,  447,  333,  215,  422,  422,  422,  363,  299,
73094  /*   260 */   414,   41,  397,  398,  366,  567,  211,  292,   60,   59,
73095  /*   270 */   297,  435,  436,  432,  432,   62,   62,   61,   61,   61,
73096  /*   280 */    61,  396,   63,   63,   63,   63,   64,   64,   65,   65,
73097  /*   290 */    65,   66,  210,  425,  431,  491,  300,  524,  474,   66,
73098  /*   300 */   210,  214,  474,  229,  411,  286,  534,   20,  449,  523,
73099  /*   310 */   168,   60,   59,  297,  435,  436,  432,  432,   62,   62,
73100  /*   320 */    61,   61,   61,   61,  474,   63,   63,   63,   63,   64,
73101  /*   330 */    64,   65,   65,   65,   66,  210,  209,  480,  317,   77,
73102  /*   340 */   292,  239,  300,   55,  484,  490,  397,  398,  181,  547,
73103  /*   350 */   494,  345,  348,  349,   67,  152,   69,  154,  339,  524,
73104  /*   360 */   414,   35,  350,  241,  221,  370,  425,  431,  579,   20,
73105  /*   370 */   164,  118,  243,  343,  248,  344,  176,  322,  442,  443,
73106  /*   380 */   414,    3,   80,  252,   60,   59,  297,  435,  436,  432,
73107  /*   390 */   432,   62,   62,   61,   61,   61,   61,  174,   63,   63,
73108  /*   400 */    63,   63,   64,   64,   65,   65,   65,   66,  210,  292,
73109  /*   410 */   221,  550,  236,  487,  510,  353,  317,  118,  243,  343,
73110  /*   420 */   248,  344,  176,  181,  317,  532,  345,  348,  349,  252,
73111  /*   430 */   223,  415,  155,  464,  511,  425,  431,  350,  414,   34,
73112  /*   440 */   465,  211,  177,  175,  160,  525,  414,   34,  338,  549,
73113  /*   450 */   449,  323,  168,   60,   59,  297,  435,  436,  432,  432,
73114  /*   460 */    62,   62,   61,   61,   61,   61,  415,   63,   63,   63,
73115  /*   470 */    63,   64,   64,   65,   65,   65,   66,  210,  292,  542,
73116  /*   480 */   335,  517,  504,  541,  456,  572,  302,   19,  331,  144,
73117  /*   490 */   317,  390,  317,  330,    2,  362,  457,  294,  483,  373,
73118  /*   500 */   269,  268,  252,  571,  425,  431,  589,  391,  388,  458,
73119  /*   510 */   208,  495,  414,   49,  414,   49,  303,  586,  894,  230,
73120  /*   520 */   894,  496,   60,   59,  297,  435,  436,  432,  432,   62,
73121  /*   530 */    62,   61,   61,   61,   61,  201,   63,   63,   63,   63,
73122  /*   540 */    64,   64,   65,   65,   65,   66,  210,  292,  317,  181,
73123  /*   550 */   439,  255,  345,  348,  349,  370,  153,  583,  308,  251,
73124  /*   560 */   309,  452,   76,  350,   78,  382,  211,  426,  427,  415,
73125  /*   570 */   414,   27,  319,  425,  431,  440,    1,   22,  586,  893,
73126  /*   580 */   396,  893,  544,  478,  320,  263,  438,  438,  429,  430,
73127  /*   590 */   415,   60,   59,  297,  435,  436,  432,  432,   62,   62,
73128  /*   600 */    61,   61,   61,   61,  237,   63,   63,   63,   63,   64,
73129  /*   610 */    64,   65,   65,   65,   66,  210,  292,  428,  583,  374,
73130  /*   620 */   224,   93,  517,    9,  159,  396,  557,  396,  456,   67,
73131  /*   630 */   396,   69,  154,  399,  400,  401,  320,  328,  438,  438,
73132  /*   640 */   457,  336,  425,  431,  361,  397,  398,  320,  433,  438,
73133  /*   650 */   438,  582,  291,  458,  238,  327,  318,  222,  546,  292,
73134  /*   660 */    60,   59,  297,  435,  436,  432,  432,   62,   62,   61,
73135  /*   670 */    61,   61,   61,  225,   63,   63,   63,   63,   64,   64,
73136  /*   680 */    65,   65,   65,   66,  210,  425,  431,  482,  313,  392,
73137  /*   690 */   397,  398,  397,  398,  207,  397,  398,  825,  273,  517,
73138  /*   700 */   251,  200,  292,   60,   59,  297,  435,  436,  432,  432,
73139  /*   710 */    62,   62,   61,   61,   61,   61,  470,   63,   63,   63,
73140  /*   720 */    63,   64,   64,   65,   65,   65,   66,  210,  425,  431,
73141  /*   730 */   171,  160,  263,  263,  304,  415,  276,  395,  274,  263,
73142  /*   740 */   517,  517,  263,  517,  192,  292,   60,   70,  297,  435,
73143  /*   750 */   436,  432,  432,   62,   62,   61,   61,   61,   61,  379,
73144  /*   760 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
73145  /*   770 */   210,  425,  431,  384,  559,  305,  306,  251,  415,  320,
73146  /*   780 */   560,  438,  438,  561,  540,  360,  540,  387,  292,  196,
73147  /*   790 */    59,  297,  435,  436,  432,  432,   62,   62,   61,   61,
73148  /*   800 */    61,   61,  371,   63,   63,   63,   63,   64,   64,   65,
73149  /*   810 */    65,   65,   66,  210,  425,  431,  396,  275,  251,  251,
73150  /*   820 */   172,  250,  418,  415,  386,  367,  178,  179,  180,  469,
73151  /*   830 */   311,  123,  156,    5,  297,  435,  436,  432,  432,   62,
73152  /*   840 */    62,   61,   61,   61,   61,  317,   63,   63,   63,   63,
73153  /*   850 */    64,   64,   65,   65,   65,   66,  210,   72,  324,  194,
73154  /*   860 */     4,  317,  263,  317,  296,  263,  415,  414,   28,  317,
73155  /*   870 */   257,  317,  321,   72,  324,  317,    4,  119,  165,  177,
73156  /*   880 */   296,  397,  398,  414,   23,  414,   32,  418,  321,  326,
73157  /*   890 */   421,  414,   53,  414,   52,  317,  158,  414,   98,  451,
73158  /*   900 */   317,  263,  317,  277,  317,  326,  378,  471,  261,  317,
73159  /*   910 */   259,   18,  478,  445,  445,  451,  317,  414,   96,   75,
73160  /*   920 */    74,  469,  414,  101,  414,  102,  414,  112,   73,  315,
73161  /*   930 */   316,  414,  114,  420,  294,   75,   74,  481,  414,   16,
73162  /*   940 */   381,  317,  279,  467,   73,  315,  316,   72,  324,  420,
73163  /*   950 */     4,  208,  317,  183,  296,  317,  186,  128,   84,  208,
73164  /*   960 */     8,  341,  321,  414,   99,  422,  422,  422,  423,  424,
73165  /*   970 */    11,  623,  380,  307,  414,   33,  413,  414,   97,  326,
73166  /*   980 */   412,  422,  422,  422,  423,  424,   11,  415,  413,  451,
73167  /*   990 */   415,  162,  412,  317,  499,  500,  226,  227,  228,  104,
73168  /*  1000 */   448,  476,  317,  173,  507,  317,  509,  508,  317,   75,
73169  /*  1010 */    74,  329,  205,   21,  281,  414,   24,  418,   73,  315,
73170  /*  1020 */   316,  282,  317,  420,  414,   54,  460,  414,  115,  317,
73171  /*  1030 */   414,  116,  502,  203,  147,  549,  514,  468,  128,  202,
73172  /*  1040 */   317,  473,  204,  317,  414,  117,  317,  477,  317,  584,
73173  /*  1050 */   317,  414,   25,  317,  249,  422,  422,  422,  423,  424,
73174  /*  1060 */    11,  506,  414,   36,  512,  414,   37,  317,  414,   26,
73175  /*  1070 */   414,   38,  414,   39,  526,  414,   40,  317,  254,  317,
73176  /*  1080 */   128,  317,  418,  317,  256,  377,  278,  268,  585,  414,
73177  /*  1090 */    42,  293,  317,  352,  317,  128,  208,  513,  258,  414,
73178  /*  1100 */    43,  414,   44,  414,   29,  414,   30,  545,  260,  128,
73179  /*  1110 */   317,  553,  317,  173,  414,   45,  414,   46,  317,  262,
73180  /*  1120 */   383,  554,  317,   91,  564,  317,   91,  317,  581,  189,
73181  /*  1130 */   290,  357,  414,   47,  414,   48,  267,  365,  368,  369,
73182  /*  1140 */   414,   31,  270,  271,  414,   10,  272,  414,   50,  414,
73183  /*  1150 */    51,  556,  566,  280,  283,  284,  578,  146,  419,  405,
73184  /*  1160 */   231,  505,  444,  325,  516,  463,  163,  446,  552,  394,
73185  /*  1170 */   466,  563,  246,  515,  518,  520,  402,  403,  404,    7,
73186  /*  1180 */   314,   84,  232,  334,  347,   83,  332,   57,  170,   79,
73187  /*  1190 */   213,  461,  125,   85,  337,  342,  492,  502,  497,  301,
73188  /*  1200 */   498,  416,  105,  219,  247,  218,  503,  501,  233,  220,
73189  /*  1210 */   287,  234,  527,  528,  235,  529,  417,  521,  354,  288,
73190  /*  1220 */   184,  121,  185,  240,  535,  475,  242,  356,  187,  479,
73191  /*  1230 */   188,  358,  537,   88,  190,  548,  364,  193,  132,  376,
73192  /*  1240 */   555,  375,  133,  134,  135,  310,  562,  138,  136,  575,
73193  /*  1250 */   576,  577,  580,  100,  393,  406,  217,  142,  624,  625,
73194  /*  1260 */   103,  141,  265,  166,  167,  434,   71,  453,  441,  437,
73195  /*  1270 */   450,  143,  538,  157,  120,  454,  161,  472,  455,  169,
73196  /*  1280 */   459,   81,    6,   12,   13,   92,   95,  126,  216,  127,
73197  /*  1290 */   111,  485,  486,   17,   86,  346,  106,  122,  253,  107,
73198  /*  1300 */    87,  108,  182,  245,  355,  145,  351,  536,  129,  359,
73199  /*  1310 */   312,  130,  543,  173,  539,  266,  191,  109,  289,  551,
73200  /*  1320 */   195,   14,  131,  198,  197,  558,  137,  199,  139,  140,
73201  /*  1330 */    15,  565,   89,   90,  573,  110,  385,  206,  148,  389,
73202  /*  1340 */   285,  587,
73203 };
73204 static const YYCODETYPE yy_lookahead[] = {
73205  /*     0 */    16,  139,  140,  141,  168,   21,  144,   23,   69,   70,
73206  /*    10 */    71,   72,  176,   74,   75,   76,   77,   78,   79,   80,
73207  /*    20 */    81,   82,   83,   84,   78,   79,   42,   43,   73,   74,
73208  /*    30 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
73209  /*    40 */     1,    2,   23,   58,   60,   61,   62,   63,   64,   65,
73210  /*    50 */    66,   67,   68,   69,   70,   71,   72,  147,   74,   75,
73211  /*    60 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
73212  /*    70 */   185,  186,   88,   88,  110,   22,  217,   92,  219,  220,
73213  /*    80 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
73214  /*    90 */    84,  217,  218,  219,  220,   42,   43,  238,  188,   46,
73215  /*   100 */    78,   79,   80,   81,   82,   83,   84,   88,   89,  124,
73216  /*   110 */   125,  126,   16,   60,   61,   62,   63,   64,   65,   66,
73217  /*   120 */    67,   68,   69,   70,   71,   72,  147,   74,   75,   76,
73218  /*   130 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
73219  /*   140 */    44,   80,   81,   82,   83,   84,   23,   84,  169,  170,
73220  /*   150 */    19,  164,  165,  166,   23,   23,   60,   61,   62,   63,
73221  /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  110,
73222  /*   170 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
73223  /*   180 */    84,   16,  123,  147,  150,  147,   21,  167,  168,   58,
73224  /*   190 */   211,  147,  156,  157,   92,  216,  176,   23,  147,  176,
73225  /*   200 */   177,   78,   79,  165,  166,  103,  183,   42,   43,   78,
73226  /*   210 */    79,   88,   89,  169,  170,  228,  180,  181,  169,   88,
73227  /*   220 */    88,   98,   99,   92,   16,   60,   61,   62,   63,   64,
73228  /*   230 */    65,   66,   67,   68,   69,   70,   71,   72,  147,   74,
73229  /*   240 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
73230  /*   250 */    42,   43,   78,  209,  210,  124,  125,  126,  224,  208,
73231  /*   260 */   169,  170,   88,   89,  230,  227,  228,   16,   60,   61,
73232  /*   270 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
73233  /*   280 */    72,   23,   74,   75,   76,   77,   78,   79,   80,   81,
73234  /*   290 */    82,   83,   84,   42,   43,  160,   16,  147,  161,   83,
73235  /*   300 */    84,  210,  161,  153,  169,  158,  156,  157,  161,  162,
73236  /*   310 */   163,   60,   61,   62,   63,   64,   65,   66,   67,   68,
73237  /*   320 */    69,   70,   71,   72,  161,   74,   75,   76,   77,   78,
73238  /*   330 */    79,   80,   81,   82,   83,   84,  192,  200,  147,  131,
73239  /*   340 */    16,  200,   16,  199,   20,  169,   88,   89,   90,  185,
73240  /*   350 */   186,   93,   94,   95,  217,   22,  219,  220,  147,  147,
73241  /*   360 */   169,  170,  104,  200,   84,  147,   42,   43,  156,  157,
73242  /*   370 */    90,   91,   92,   93,   94,   95,   96,  164,  165,  166,
73243  /*   380 */   169,  170,  131,  103,   60,   61,   62,   63,   64,   65,
73244  /*   390 */    66,   67,   68,   69,   70,   71,   72,  155,   74,   75,
73245  /*   400 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
73246  /*   410 */    84,   11,  221,   20,   30,   16,  147,   91,   92,   93,
73247  /*   420 */    94,   95,   96,   90,  147,  181,   93,   94,   95,  103,
73248  /*   430 */   212,  189,  155,   27,   50,   42,   43,  104,  169,  170,
73249  /*   440 */    34,  228,   43,  201,  202,  181,  169,  170,  206,   49,
73250  /*   450 */   161,  162,  163,   60,   61,   62,   63,   64,   65,   66,
73251  /*   460 */    67,   68,   69,   70,   71,   72,  189,   74,   75,   76,
73252  /*   470 */    77,   78,   79,   80,   81,   82,   83,   84,   16,   25,
73253  /*   480 */   211,  147,   20,   29,   12,  147,  102,   19,  211,   21,
73254  /*   490 */   147,  141,  147,  216,  144,   41,   24,   98,   20,   99,
73255  /*   500 */   100,  101,  103,  165,   42,   43,    0,    1,    2,   37,
73256  /*   510 */   110,   39,  169,  170,  169,  170,  182,   19,   20,  190,
73257  /*   520 */    22,   49,   60,   61,   62,   63,   64,   65,   66,   67,
73258  /*   530 */    68,   69,   70,   71,   72,  155,   74,   75,   76,   77,
73259  /*   540 */    78,   79,   80,   81,   82,   83,   84,   16,  147,   90,
73260  /*   550 */    20,   20,   93,   94,   95,  147,  155,   59,  215,  225,
73261  /*   560 */   215,   20,  130,  104,  132,  227,  228,   42,   43,  189,
73262  /*   570 */   169,  170,   16,   42,   43,   20,   19,   22,   19,   20,
73263  /*   580 */    23,   22,   18,  147,  106,  147,  108,  109,   63,   64,
73264  /*   590 */   189,   60,   61,   62,   63,   64,   65,   66,   67,   68,
73265  /*   600 */    69,   70,   71,   72,  147,   74,   75,   76,   77,   78,
73266  /*   610 */    79,   80,   81,   82,   83,   84,   16,   92,   59,   55,
73267  /*   620 */   212,   21,  147,   19,  147,   23,  188,   23,   12,  217,
73268  /*   630 */    23,  219,  220,    7,    8,    9,  106,  186,  108,  109,
73269  /*   640 */    24,  147,   42,   43,  208,   88,   89,  106,   92,  108,
73270  /*   650 */   109,  244,  245,   37,  147,   39,  147,  182,   94,   16,
73271  /*   660 */    60,   61,   62,   63,   64,   65,   66,   67,   68,   69,
73272  /*   670 */    70,   71,   72,  145,   74,   75,   76,   77,   78,   79,
73273  /*   680 */    80,   81,   82,   83,   84,   42,   43,   80,  142,  143,
73274  /*   690 */    88,   89,   88,   89,  148,   88,   89,  133,   14,  147,
73275  /*   700 */   225,  155,   16,   60,   61,   62,   63,   64,   65,   66,
73276  /*   710 */    67,   68,   69,   70,   71,   72,  114,   74,   75,   76,
73277  /*   720 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
73278  /*   730 */   201,  202,  147,  147,  182,  189,   52,  147,   54,  147,
73279  /*   740 */   147,  147,  147,  147,  155,   16,   60,   61,   62,   63,
73280  /*   750 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  213,
73281  /*   760 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
73282  /*   770 */    84,   42,   43,  188,  188,  182,  182,  225,  189,  106,
73283  /*   780 */   188,  108,  109,  188,   99,  100,  101,  241,   16,  155,
73284  /*   790 */    61,   62,   63,   64,   65,   66,   67,   68,   69,   70,
73285  /*   800 */    71,   72,  213,   74,   75,   76,   77,   78,   79,   80,
73286  /*   810 */    81,   82,   83,   84,   42,   43,   23,  133,  225,  225,
73287  /*   820 */    21,  225,   23,  189,  239,  236,   99,  100,  101,   22,
73288  /*   830 */   242,  243,  155,  191,   62,   63,   64,   65,   66,   67,
73289  /*   840 */    68,   69,   70,   71,   72,  147,   74,   75,   76,   77,
73290  /*   850 */    78,   79,   80,   81,   82,   83,   84,   16,   17,   22,
73291  /*   860 */    19,  147,  147,  147,   23,  147,  189,  169,  170,  147,
73292  /*   870 */    14,  147,   31,   16,   17,  147,   19,  147,   19,   43,
73293  /*   880 */    23,   88,   89,  169,  170,  169,  170,   88,   31,   48,
73294  /*   890 */   147,  169,  170,  169,  170,  147,   89,  169,  170,   58,
73295  /*   900 */   147,  147,  147,  188,  147,   48,  188,  114,   52,  147,
73296  /*   910 */    54,   19,  147,  124,  125,   58,  147,  169,  170,   78,
73297  /*   920 */    79,  114,  169,  170,  169,  170,  169,  170,   87,   88,
73298  /*   930 */    89,  169,  170,   92,   98,   78,   79,   80,  169,  170,
73299  /*   940 */    91,  147,  188,   22,   87,   88,   89,   16,   17,   92,
73300  /*   950 */    19,  110,  147,  155,   23,  147,  155,   22,  121,  110,
73301  /*   960 */    68,   80,   31,  169,  170,  124,  125,  126,  127,  128,
73302  /*   970 */   129,  112,  123,  208,  169,  170,  107,  169,  170,   48,
73303  /*   980 */   111,  124,  125,  126,  127,  128,  129,  189,  107,   58,
73304  /*   990 */   189,    5,  111,  147,    7,    8,   10,   11,   12,   13,
73305  /*  1000 */   161,   20,  147,   22,  178,  147,   91,   92,  147,   78,
73306  /*  1010 */    79,  147,   26,   19,   28,  169,  170,   23,   87,   88,
73307  /*  1020 */    89,   35,  147,   92,  169,  170,  147,  169,  170,  147,
73308  /*  1030 */   169,  170,   97,   47,  113,   49,   20,  203,   22,   53,
73309  /*  1040 */   147,  147,   56,  147,  169,  170,  147,  147,  147,   20,
73310  /*  1050 */   147,  169,  170,  147,  147,  124,  125,  126,  127,  128,
73311  /*  1060 */   129,  147,  169,  170,  178,  169,  170,  147,  169,  170,
73312  /*  1070 */   169,  170,  169,  170,  147,  169,  170,  147,   20,  147,
73313  /*  1080 */    22,  147,   88,  147,  147,   99,  100,  101,   59,  169,
73314  /*  1090 */   170,  105,  147,   20,  147,   22,  110,  178,  147,  169,
73315  /*  1100 */   170,  169,  170,  169,  170,  169,  170,   20,  147,   22,
73316  /*  1110 */   147,   20,  147,   22,  169,  170,  169,  170,  147,  147,
73317  /*  1120 */   134,   20,  147,   22,   20,  147,   22,  147,   20,  232,
73318  /*  1130 */    22,  233,  169,  170,  169,  170,  147,  147,  147,  147,
73319  /*  1140 */   169,  170,  147,  147,  169,  170,  147,  169,  170,  169,
73320  /*  1150 */   170,  147,  147,  147,  147,  147,  147,  191,  161,  149,
73321  /*  1160 */   193,  177,  229,  223,  161,  172,    6,  229,  194,  146,
73322  /*  1170 */   172,  194,  172,  172,  172,  161,  146,  146,  146,   22,
73323  /*  1180 */   154,  121,  194,  118,  173,  119,  116,  120,  112,  130,
73324  /*  1190 */   222,  152,  152,   98,  115,   98,  171,   97,  171,   40,
73325  /*  1200 */   179,  189,   19,   84,  171,  226,  171,  173,  195,  226,
73326  /*  1210 */   174,  196,  171,  171,  197,  171,  198,  179,   15,  174,
73327  /*  1220 */   151,   60,  151,  204,  152,  205,  204,  152,  151,  205,
73328  /*  1230 */   152,   38,  152,  130,  151,  184,  152,  184,   19,   15,
73329  /*  1240 */   194,  152,  187,  187,  187,  152,  194,  184,  187,   33,
73330  /*  1250 */   152,  152,  137,  159,    1,   20,  175,  214,  112,  112,
73331  /*  1260 */   175,  214,  234,  112,  112,   92,   19,   11,   20,  107,
73332  /*  1270 */    20,   19,  235,   19,   32,   20,  112,  114,   20,   22,
73333  /*  1280 */    20,   22,  117,   22,  117,  237,  237,   19,   44,   20,
73334  /*  1290 */   240,   20,   20,  231,   19,   44,   19,  243,   20,   19,
73335  /*  1300 */    19,   19,   96,  103,   16,   21,   44,   17,   98,   36,
73336  /*  1310 */   246,   45,   45,   22,   51,  133,   98,   19,    5,    1,
73337  /*  1320 */   122,   19,  102,   14,  113,   17,  113,  115,  102,  122,
73338  /*  1330 */    19,  123,   68,   68,   20,   14,   57,  135,   19,    3,
73339  /*  1340 */   136,    4,
73340 };
73341 #define YY_SHIFT_USE_DFLT (-62)
73342 #define YY_SHIFT_MAX 389
73343 static const short yy_shift_ofst[] = {
73344  /*     0 */    39,  841,  986,  -16,  841,  931,  931,  258,  123,  -36,
73345  /*    10 */    96,  931,  931,  931,  931,  931,  -45,  400,  174,   19,
73346  /*    20 */   132,  -54,  -54,   53,  165,  208,  251,  324,  393,  462,
73347  /*    30 */   531,  600,  643,  686,  643,  643,  643,  643,  643,  643,
73348  /*    40 */   643,  643,  643,  643,  643,  643,  643,  643,  643,  643,
73349  /*    50 */   643,  643,  729,  772,  772,  857,  931,  931,  931,  931,
73350  /*    60 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
73351  /*    70 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
73352  /*    80 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
73353  /*    90 */   931,  931,  931,  931,  931,  931,  -61,  -61,    6,    6,
73354  /*   100 */   280,   22,   61,  399,  564,   19,   19,   19,   19,   19,
73355  /*   110 */    19,   19,  216,  132,   63,  -62,  -62,  -62,  131,  326,
73356  /*   120 */   472,  472,  498,  559,  506,  799,   19,  799,   19,   19,
73357  /*   130 */    19,   19,   19,   19,   19,   19,   19,   19,   19,   19,
73358  /*   140 */    19,  849,   59,  -36,  -36,  -36,  -62,  -62,  -62,  -15,
73359  /*   150 */   -15,  333,  459,  478,  557,  530,  541,  616,  602,  793,
73360  /*   160 */   604,  607,  626,   19,   19,  881,   19,   19,  994,   19,
73361  /*   170 */    19,  807,   19,   19,  673,  807,   19,   19,  384,  384,
73362  /*   180 */   384,   19,   19,  673,   19,   19,  673,   19,  454,  685,
73363  /*   190 */    19,   19,  673,   19,   19,   19,  673,   19,   19,   19,
73364  /*   200 */   673,  673,   19,   19,   19,   19,   19,  468,  869,  921,
73365  /*   210 */   132,  789,  789,  432,  406,  406,  406,  836,  406,  132,
73366  /*   220 */   406,  132,  935,  837,  837, 1160, 1160, 1160, 1160, 1157,
73367  /*   230 */   -36, 1060, 1065, 1066, 1070, 1067, 1059, 1076, 1076, 1095,
73368  /*   240 */  1079, 1095, 1079, 1097, 1097, 1159, 1097, 1100, 1097, 1183,
73369  /*   250 */  1119, 1119, 1159, 1097, 1097, 1097, 1183, 1203, 1076, 1203,
73370  /*   260 */  1076, 1203, 1076, 1076, 1193, 1103, 1203, 1076, 1161, 1161,
73371  /*   270 */  1219, 1060, 1076, 1224, 1224, 1224, 1224, 1060, 1161, 1219,
73372  /*   280 */  1076, 1216, 1216, 1076, 1076, 1115,  -62,  -62,  -62,  -62,
73373  /*   290 */   -62,  -62,  525,  684,  727,  856,  859,  556,  555,  981,
73374  /*   300 */   102,  987,  915, 1016, 1058, 1073, 1087, 1091, 1101, 1104,
73375  /*   310 */   892, 1108, 1029, 1253, 1235, 1146, 1147, 1151, 1152, 1173,
73376  /*   320 */  1162, 1247, 1248, 1250, 1252, 1256, 1254, 1255, 1257, 1258,
73377  /*   330 */  1260, 1259, 1165, 1261, 1167, 1259, 1163, 1268, 1269, 1164,
73378  /*   340 */  1271, 1272, 1242, 1244, 1275, 1251, 1277, 1278, 1280, 1281,
73379  /*   350 */  1262, 1282, 1206, 1200, 1288, 1290, 1284, 1210, 1273, 1263,
73380  /*   360 */  1266, 1291, 1267, 1182, 1218, 1298, 1313, 1318, 1220, 1264,
73381  /*   370 */  1265, 1198, 1302, 1211, 1309, 1212, 1308, 1213, 1226, 1207,
73382  /*   380 */  1311, 1208, 1314, 1321, 1279, 1202, 1204, 1319, 1336, 1337,
73383 };
73384 #define YY_REDUCE_USE_DFLT (-165)
73385 #define YY_REDUCE_MAX 291
73386 static const short yy_reduce_ofst[] = {
73387  /*     0 */  -138,  277,  546,  137,  401,  -21,   44,   36,   38,  242,
73388  /*    10 */  -141,  191,   91,  269,  343,  345, -126,  589,  338,  150,
73389  /*    20 */   147,  -13,  213,  412,  412,  412,  412,  412,  412,  412,
73390  /*    30 */   412,  412,  412,  412,  412,  412,  412,  412,  412,  412,
73391  /*    40 */   412,  412,  412,  412,  412,  412,  412,  412,  412,  412,
73392  /*    50 */   412,  412,  412,  412,  412,  211,  698,  714,  716,  722,
73393  /*    60 */   724,  728,  748,  753,  755,  757,  762,  769,  794,  805,
73394  /*    70 */   808,  846,  855,  858,  861,  875,  882,  893,  896,  899,
73395  /*    80 */   901,  903,  906,  920,  930,  932,  934,  936,  945,  947,
73396  /*    90 */   963,  965,  971,  975,  978,  980,  412,  412,  412,  412,
73397  /*   100 */    20,  412,  412,   23,   34,  334,  475,  552,  593,  594,
73398  /*   110 */   585,  212,  412,  289,  412,  412,  412,  412,  135, -164,
73399  /*   120 */  -115,  164,  407,  407,  350,  141,   51,  163,  596,  -90,
73400  /*   130 */   436,  218,  765,  438,  586,  592,  595,  715,  718,  408,
73401  /*   140 */   754,  380,  634,  677,  798,  801,  144,  529,  588,   49,
73402  /*   150 */   176,  244,  264,  329,  457,  329,  329,  451,  477,  494,
73403  /*   160 */   507,  509,  528,  590,  730,  642,  509,  743,  839,  864,
73404  /*   170 */   879,  834,  894,  900,  329,  834,  907,  914,  826,  886,
73405  /*   180 */   919,  927,  937,  329,  951,  961,  329,  972,  897,  898,
73406  /*   190 */   989,  990,  329,  991,  992,  995,  329,  996,  999, 1004,
73407  /*   200 */   329,  329, 1005, 1006, 1007, 1008, 1009, 1010,  966,  967,
73408  /*   210 */   997,  933,  938,  940,  993,  998, 1000,  984, 1001, 1003,
73409  /*   220 */  1002, 1014, 1011,  974,  977, 1023, 1030, 1031, 1032, 1026,
73410  /*   230 */  1012,  988, 1013, 1015, 1017, 1018,  968, 1039, 1040, 1019,
73411  /*   240 */  1020, 1022, 1024, 1025, 1027, 1021, 1033, 1034, 1035, 1036,
73412  /*   250 */   979,  983, 1038, 1041, 1042, 1044, 1045, 1069, 1072, 1071,
73413  /*   260 */  1075, 1077, 1078, 1080, 1028, 1037, 1083, 1084, 1051, 1053,
73414  /*   270 */  1043, 1046, 1089, 1055, 1056, 1057, 1061, 1052, 1063, 1047,
73415  /*   280 */  1093, 1048, 1049, 1098, 1099, 1050, 1094, 1081, 1085, 1062,
73416  /*   290 */  1054, 1064,
73417 };
73418 static const YYACTIONTYPE yy_default[] = {
73419  /*     0 */   595,  820,  902,  710,  902,  820,  902,  902,  848,  714,
73420  /*    10 */   877,  818,  902,  902,  902,  902,  792,  902,  848,  902,
73421  /*    20 */   626,  848,  848,  743,  902,  902,  902,  902,  902,  902,
73422  /*    30 */   902,  902,  744,  902,  822,  817,  813,  815,  814,  821,
73423  /*    40 */   745,  734,  741,  748,  726,  861,  750,  751,  757,  758,
73424  /*    50 */   878,  876,  780,  779,  798,  902,  902,  902,  902,  902,
73425  /*    60 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73426  /*    70 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73427  /*    80 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73428  /*    90 */   902,  902,  902,  902,  902,  902,  782,  804,  781,  791,
73429  /*   100 */   619,  783,  784,  679,  614,  902,  902,  902,  902,  902,
73430  /*   110 */   902,  902,  785,  902,  786,  799,  800,  801,  902,  902,
73431  /*   120 */   902,  902,  902,  902,  595,  710,  902,  710,  902,  902,
73432  /*   130 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73433  /*   140 */   902,  902,  902,  902,  902,  902,  704,  714,  895,  902,
73434  /*   150 */   902,  670,  902,  902,  902,  902,  902,  902,  902,  902,
73435  /*   160 */   902,  902,  602,  600,  902,  702,  902,  902,  628,  902,
73436  /*   170 */   902,  712,  902,  902,  717,  718,  902,  902,  902,  902,
73437  /*   180 */   902,  902,  902,  616,  902,  902,  691,  902,  854,  902,
73438  /*   190 */   902,  902,  868,  902,  902,  902,  866,  902,  902,  902,
73439  /*   200 */   693,  753,  834,  902,  881,  883,  902,  902,  702,  711,
73440  /*   210 */   902,  902,  902,  816,  737,  737,  737,  649,  737,  902,
73441  /*   220 */   737,  902,  652,  747,  747,  599,  599,  599,  599,  669,
73442  /*   230 */   902,  747,  738,  740,  730,  742,  902,  719,  719,  727,
73443  /*   240 */   729,  727,  729,  681,  681,  666,  681,  652,  681,  826,
73444  /*   250 */   831,  831,  666,  681,  681,  681,  826,  611,  719,  611,
73445  /*   260 */   719,  611,  719,  719,  858,  860,  611,  719,  683,  683,
73446  /*   270 */   759,  747,  719,  690,  690,  690,  690,  747,  683,  759,
73447  /*   280 */   719,  880,  880,  719,  719,  888,  636,  654,  654,  863,
73448  /*   290 */   895,  900,  902,  902,  902,  902,  766,  902,  902,  902,
73449  /*   300 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73450  /*   310 */   841,  902,  902,  902,  902,  771,  767,  902,  768,  902,
73451  /*   320 */   696,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73452  /*   330 */   902,  819,  902,  731,  902,  739,  902,  902,  902,  902,
73453  /*   340 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73454  /*   350 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73455  /*   360 */   856,  857,  902,  902,  902,  902,  902,  902,  902,  902,
73456  /*   370 */   902,  902,  902,  902,  902,  902,  902,  902,  902,  902,
73457  /*   380 */   902,  902,  902,  902,  887,  902,  902,  890,  596,  902,
73458  /*   390 */   590,  593,  592,  594,  598,  601,  623,  624,  625,  603,
73459  /*   400 */   604,  605,  606,  607,  608,  609,  615,  617,  635,  637,
73460  /*   410 */   621,  639,  700,  701,  763,  694,  695,  699,  622,  774,
73461  /*   420 */   765,  769,  770,  772,  773,  787,  788,  790,  796,  803,
73462  /*   430 */   806,  789,  794,  795,  797,  802,  805,  697,  698,  809,
73463  /*   440 */   629,  630,  633,  634,  844,  846,  845,  847,  632,  631,
73464  /*   450 */   775,  778,  811,  812,  869,  870,  871,  872,  873,  807,
73465  /*   460 */   720,  810,  793,  732,  735,  736,  733,  703,  713,  722,
73466  /*   470 */   723,  724,  725,  708,  709,  715,  728,  761,  762,  716,
73467  /*   480 */   705,  706,  707,  808,  764,  776,  777,  640,  641,  771,
73468  /*   490 */   642,  643,  644,  682,  685,  686,  687,  645,  664,  667,
73469  /*   500 */   668,  646,  653,  647,  648,  655,  656,  657,  660,  661,
73470  /*   510 */   662,  663,  658,  659,  827,  828,  832,  830,  829,  650,
73471  /*   520 */   651,  665,  638,  627,  620,  671,  674,  675,  676,  677,
73472  /*   530 */   678,  680,  672,  673,  618,  610,  612,  721,  850,  859,
73473  /*   540 */   855,  851,  852,  853,  613,  823,  824,  684,  755,  756,
73474  /*   550 */   849,  862,  864,  760,  865,  867,  892,  688,  689,  692,
73475  /*   560 */   833,  874,  746,  749,  752,  754,  835,  836,  837,  838,
73476  /*   570 */   839,  842,  843,  840,  875,  879,  882,  884,  885,  886,
73477  /*   580 */   889,  891,  896,  897,  898,  901,  899,  597,  591,
73478 };
73479 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
73480
73481 /* The next table maps tokens into fallback tokens.  If a construct
73482 ** like the following:
73483 ** 
73484 **      %fallback ID X Y Z.
73485 **
73486 ** appears in the grammer, then ID becomes a fallback token for X, Y,
73487 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
73488 ** but it does not parse, the type of the token is changed to ID and
73489 ** the parse is retried before an error is thrown.
73490 */
73491 #ifdef YYFALLBACK
73492 static const YYCODETYPE yyFallback[] = {
73493     0,  /*          $ => nothing */
73494     0,  /*       SEMI => nothing */
73495    23,  /*    EXPLAIN => ID */
73496    23,  /*      QUERY => ID */
73497    23,  /*       PLAN => ID */
73498    23,  /*      BEGIN => ID */
73499     0,  /* TRANSACTION => nothing */
73500    23,  /*   DEFERRED => ID */
73501    23,  /*  IMMEDIATE => ID */
73502    23,  /*  EXCLUSIVE => ID */
73503     0,  /*     COMMIT => nothing */
73504    23,  /*        END => ID */
73505     0,  /*   ROLLBACK => nothing */
73506     0,  /*     CREATE => nothing */
73507     0,  /*      TABLE => nothing */
73508    23,  /*         IF => ID */
73509     0,  /*        NOT => nothing */
73510     0,  /*     EXISTS => nothing */
73511    23,  /*       TEMP => ID */
73512     0,  /*         LP => nothing */
73513     0,  /*         RP => nothing */
73514     0,  /*         AS => nothing */
73515     0,  /*      COMMA => nothing */
73516     0,  /*         ID => nothing */
73517    23,  /*      ABORT => ID */
73518    23,  /*      AFTER => ID */
73519    23,  /*    ANALYZE => ID */
73520    23,  /*        ASC => ID */
73521    23,  /*     ATTACH => ID */
73522    23,  /*     BEFORE => ID */
73523    23,  /*    CASCADE => ID */
73524    23,  /*       CAST => ID */
73525    23,  /*   CONFLICT => ID */
73526    23,  /*   DATABASE => ID */
73527    23,  /*       DESC => ID */
73528    23,  /*     DETACH => ID */
73529    23,  /*       EACH => ID */
73530    23,  /*       FAIL => ID */
73531    23,  /*        FOR => ID */
73532    23,  /*     IGNORE => ID */
73533    23,  /*  INITIALLY => ID */
73534    23,  /*    INSTEAD => ID */
73535    23,  /*    LIKE_KW => ID */
73536    23,  /*      MATCH => ID */
73537    23,  /*        KEY => ID */
73538    23,  /*         OF => ID */
73539    23,  /*     OFFSET => ID */
73540    23,  /*     PRAGMA => ID */
73541    23,  /*      RAISE => ID */
73542    23,  /*    REPLACE => ID */
73543    23,  /*   RESTRICT => ID */
73544    23,  /*        ROW => ID */
73545    23,  /*    TRIGGER => ID */
73546    23,  /*     VACUUM => ID */
73547    23,  /*       VIEW => ID */
73548    23,  /*    VIRTUAL => ID */
73549    23,  /*    REINDEX => ID */
73550    23,  /*     RENAME => ID */
73551    23,  /*   CTIME_KW => ID */
73552     0,  /*        ANY => nothing */
73553     0,  /*         OR => nothing */
73554     0,  /*        AND => nothing */
73555     0,  /*         IS => nothing */
73556     0,  /*    BETWEEN => nothing */
73557     0,  /*         IN => nothing */
73558     0,  /*     ISNULL => nothing */
73559     0,  /*    NOTNULL => nothing */
73560     0,  /*         NE => nothing */
73561     0,  /*         EQ => nothing */
73562     0,  /*         GT => nothing */
73563     0,  /*         LE => nothing */
73564     0,  /*         LT => nothing */
73565     0,  /*         GE => nothing */
73566     0,  /*     ESCAPE => nothing */
73567     0,  /*     BITAND => nothing */
73568     0,  /*      BITOR => nothing */
73569     0,  /*     LSHIFT => nothing */
73570     0,  /*     RSHIFT => nothing */
73571     0,  /*       PLUS => nothing */
73572     0,  /*      MINUS => nothing */
73573     0,  /*       STAR => nothing */
73574     0,  /*      SLASH => nothing */
73575     0,  /*        REM => nothing */
73576     0,  /*     CONCAT => nothing */
73577     0,  /*    COLLATE => nothing */
73578     0,  /*     UMINUS => nothing */
73579     0,  /*      UPLUS => nothing */
73580     0,  /*     BITNOT => nothing */
73581     0,  /*     STRING => nothing */
73582     0,  /*    JOIN_KW => nothing */
73583     0,  /* CONSTRAINT => nothing */
73584     0,  /*    DEFAULT => nothing */
73585     0,  /*       NULL => nothing */
73586     0,  /*    PRIMARY => nothing */
73587     0,  /*     UNIQUE => nothing */
73588     0,  /*      CHECK => nothing */
73589     0,  /* REFERENCES => nothing */
73590     0,  /*   AUTOINCR => nothing */
73591     0,  /*         ON => nothing */
73592     0,  /*     DELETE => nothing */
73593     0,  /*     UPDATE => nothing */
73594     0,  /*     INSERT => nothing */
73595     0,  /*        SET => nothing */
73596     0,  /* DEFERRABLE => nothing */
73597     0,  /*    FOREIGN => nothing */
73598     0,  /*       DROP => nothing */
73599     0,  /*      UNION => nothing */
73600     0,  /*        ALL => nothing */
73601     0,  /*     EXCEPT => nothing */
73602     0,  /*  INTERSECT => nothing */
73603     0,  /*     SELECT => nothing */
73604     0,  /*   DISTINCT => nothing */
73605     0,  /*        DOT => nothing */
73606     0,  /*       FROM => nothing */
73607     0,  /*       JOIN => nothing */
73608     0,  /*      USING => nothing */
73609     0,  /*      ORDER => nothing */
73610     0,  /*         BY => nothing */
73611     0,  /*      GROUP => nothing */
73612     0,  /*     HAVING => nothing */
73613     0,  /*      LIMIT => nothing */
73614     0,  /*      WHERE => nothing */
73615     0,  /*       INTO => nothing */
73616     0,  /*     VALUES => nothing */
73617     0,  /*    INTEGER => nothing */
73618     0,  /*      FLOAT => nothing */
73619     0,  /*       BLOB => nothing */
73620     0,  /*   REGISTER => nothing */
73621     0,  /*   VARIABLE => nothing */
73622     0,  /*       CASE => nothing */
73623     0,  /*       WHEN => nothing */
73624     0,  /*       THEN => nothing */
73625     0,  /*       ELSE => nothing */
73626     0,  /*      INDEX => nothing */
73627     0,  /*      ALTER => nothing */
73628     0,  /*         TO => nothing */
73629     0,  /*        ADD => nothing */
73630     0,  /*   COLUMNKW => nothing */
73631 };
73632 #endif /* YYFALLBACK */
73633
73634 /* The following structure represents a single element of the
73635 ** parser's stack.  Information stored includes:
73636 **
73637 **   +  The state number for the parser at this level of the stack.
73638 **
73639 **   +  The value of the token stored at this level of the stack.
73640 **      (In other words, the "major" token.)
73641 **
73642 **   +  The semantic value stored at this level of the stack.  This is
73643 **      the information used by the action routines in the grammar.
73644 **      It is sometimes called the "minor" token.
73645 */
73646 struct yyStackEntry {
73647   int stateno;       /* The state-number */
73648   int major;         /* The major token value.  This is the code
73649                      ** number for the token at this stack level */
73650   YYMINORTYPE minor; /* The user-supplied minor token value.  This
73651                      ** is the value of the token  */
73652 };
73653 typedef struct yyStackEntry yyStackEntry;
73654
73655 /* The state of the parser is completely contained in an instance of
73656 ** the following structure */
73657 struct yyParser {
73658   int yyidx;                    /* Index of top element in stack */
73659   int yyerrcnt;                 /* Shifts left before out of the error */
73660   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
73661 #if YYSTACKDEPTH<=0
73662   int yystksz;                  /* Current side of the stack */
73663   yyStackEntry *yystack;        /* The parser's stack */
73664 #else
73665   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
73666 #endif
73667 };
73668 typedef struct yyParser yyParser;
73669
73670 #ifndef NDEBUG
73671 static FILE *yyTraceFILE = 0;
73672 static char *yyTracePrompt = 0;
73673 #endif /* NDEBUG */
73674
73675 #ifndef NDEBUG
73676 /* 
73677 ** Turn parser tracing on by giving a stream to which to write the trace
73678 ** and a prompt to preface each trace message.  Tracing is turned off
73679 ** by making either argument NULL 
73680 **
73681 ** Inputs:
73682 ** <ul>
73683 ** <li> A FILE* to which trace output should be written.
73684 **      If NULL, then tracing is turned off.
73685 ** <li> A prefix string written at the beginning of every
73686 **      line of trace output.  If NULL, then tracing is
73687 **      turned off.
73688 ** </ul>
73689 **
73690 ** Outputs:
73691 ** None.
73692 */
73693 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
73694   yyTraceFILE = TraceFILE;
73695   yyTracePrompt = zTracePrompt;
73696   if( yyTraceFILE==0 ) yyTracePrompt = 0;
73697   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
73698 }
73699 #endif /* NDEBUG */
73700
73701 #ifndef NDEBUG
73702 /* For tracing shifts, the names of all terminals and nonterminals
73703 ** are required.  The following table supplies these names */
73704 static const char *const yyTokenName[] = { 
73705   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
73706   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
73707   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
73708   "ROLLBACK",      "CREATE",        "TABLE",         "IF",          
73709   "NOT",           "EXISTS",        "TEMP",          "LP",          
73710   "RP",            "AS",            "COMMA",         "ID",          
73711   "ABORT",         "AFTER",         "ANALYZE",       "ASC",         
73712   "ATTACH",        "BEFORE",        "CASCADE",       "CAST",        
73713   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
73714   "EACH",          "FAIL",          "FOR",           "IGNORE",      
73715   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
73716   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
73717   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
73718   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
73719   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
73720   "OR",            "AND",           "IS",            "BETWEEN",     
73721   "IN",            "ISNULL",        "NOTNULL",       "NE",          
73722   "EQ",            "GT",            "LE",            "LT",          
73723   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
73724   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
73725   "STAR",          "SLASH",         "REM",           "CONCAT",      
73726   "COLLATE",       "UMINUS",        "UPLUS",         "BITNOT",      
73727   "STRING",        "JOIN_KW",       "CONSTRAINT",    "DEFAULT",     
73728   "NULL",          "PRIMARY",       "UNIQUE",        "CHECK",       
73729   "REFERENCES",    "AUTOINCR",      "ON",            "DELETE",      
73730   "UPDATE",        "INSERT",        "SET",           "DEFERRABLE",  
73731   "FOREIGN",       "DROP",          "UNION",         "ALL",         
73732   "EXCEPT",        "INTERSECT",     "SELECT",        "DISTINCT",    
73733   "DOT",           "FROM",          "JOIN",          "USING",       
73734   "ORDER",         "BY",            "GROUP",         "HAVING",      
73735   "LIMIT",         "WHERE",         "INTO",          "VALUES",      
73736   "INTEGER",       "FLOAT",         "BLOB",          "REGISTER",    
73737   "VARIABLE",      "CASE",          "WHEN",          "THEN",        
73738   "ELSE",          "INDEX",         "ALTER",         "TO",          
73739   "ADD",           "COLUMNKW",      "error",         "input",       
73740   "cmdlist",       "ecmd",          "cmdx",          "cmd",         
73741   "explain",       "transtype",     "trans_opt",     "nm",          
73742   "create_table",  "create_table_args",  "temp",          "ifnotexists", 
73743   "dbnm",          "columnlist",    "conslist_opt",  "select",      
73744   "column",        "columnid",      "type",          "carglist",    
73745   "id",            "ids",           "typetoken",     "typename",    
73746   "signed",        "plus_num",      "minus_num",     "carg",        
73747   "ccons",         "term",          "expr",          "onconf",      
73748   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
73749   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
73750   "conslist",      "tcons",         "idxlist",       "defer_subclause_opt",
73751   "orconf",        "resolvetype",   "raisetype",     "ifexists",    
73752   "fullname",      "oneselect",     "multiselect_op",  "distinct",    
73753   "selcollist",    "from",          "where_opt",     "groupby_opt", 
73754   "having_opt",    "orderby_opt",   "limit_opt",     "sclp",        
73755   "as",            "seltablist",    "stl_prefix",    "joinop",      
73756   "on_opt",        "using_opt",     "seltablist_paren",  "joinop2",     
73757   "inscollist",    "sortlist",      "sortitem",      "nexprlist",   
73758   "setlist",       "insert_cmd",    "inscollist_opt",  "itemlist",    
73759   "exprlist",      "likeop",        "escape",        "between_op",  
73760   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
73761   "uniqueflag",    "idxitem",       "collate",       "nmnum",       
73762   "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
73763   "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
73764   "trigger_cmd",   "database_kw_opt",  "key_opt",       "add_column_fullname",
73765   "kwcolumn_opt",  "create_vtab",   "vtabarglist",   "vtabarg",     
73766   "vtabargtoken",  "lp",            "anylist",     
73767 };
73768 #endif /* NDEBUG */
73769
73770 #ifndef NDEBUG
73771 /* For tracing reduce actions, the names of all rules are required.
73772 */
73773 static const char *const yyRuleName[] = {
73774  /*   0 */ "input ::= cmdlist",
73775  /*   1 */ "cmdlist ::= cmdlist ecmd",
73776  /*   2 */ "cmdlist ::= ecmd",
73777  /*   3 */ "cmdx ::= cmd",
73778  /*   4 */ "ecmd ::= SEMI",
73779  /*   5 */ "ecmd ::= explain cmdx SEMI",
73780  /*   6 */ "explain ::=",
73781  /*   7 */ "explain ::= EXPLAIN",
73782  /*   8 */ "explain ::= EXPLAIN QUERY PLAN",
73783  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
73784  /*  10 */ "trans_opt ::=",
73785  /*  11 */ "trans_opt ::= TRANSACTION",
73786  /*  12 */ "trans_opt ::= TRANSACTION nm",
73787  /*  13 */ "transtype ::=",
73788  /*  14 */ "transtype ::= DEFERRED",
73789  /*  15 */ "transtype ::= IMMEDIATE",
73790  /*  16 */ "transtype ::= EXCLUSIVE",
73791  /*  17 */ "cmd ::= COMMIT trans_opt",
73792  /*  18 */ "cmd ::= END trans_opt",
73793  /*  19 */ "cmd ::= ROLLBACK trans_opt",
73794  /*  20 */ "cmd ::= create_table create_table_args",
73795  /*  21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
73796  /*  22 */ "ifnotexists ::=",
73797  /*  23 */ "ifnotexists ::= IF NOT EXISTS",
73798  /*  24 */ "temp ::= TEMP",
73799  /*  25 */ "temp ::=",
73800  /*  26 */ "create_table_args ::= LP columnlist conslist_opt RP",
73801  /*  27 */ "create_table_args ::= AS select",
73802  /*  28 */ "columnlist ::= columnlist COMMA column",
73803  /*  29 */ "columnlist ::= column",
73804  /*  30 */ "column ::= columnid type carglist",
73805  /*  31 */ "columnid ::= nm",
73806  /*  32 */ "id ::= ID",
73807  /*  33 */ "ids ::= ID|STRING",
73808  /*  34 */ "nm ::= ID",
73809  /*  35 */ "nm ::= STRING",
73810  /*  36 */ "nm ::= JOIN_KW",
73811  /*  37 */ "type ::=",
73812  /*  38 */ "type ::= typetoken",
73813  /*  39 */ "typetoken ::= typename",
73814  /*  40 */ "typetoken ::= typename LP signed RP",
73815  /*  41 */ "typetoken ::= typename LP signed COMMA signed RP",
73816  /*  42 */ "typename ::= ids",
73817  /*  43 */ "typename ::= typename ids",
73818  /*  44 */ "signed ::= plus_num",
73819  /*  45 */ "signed ::= minus_num",
73820  /*  46 */ "carglist ::= carglist carg",
73821  /*  47 */ "carglist ::=",
73822  /*  48 */ "carg ::= CONSTRAINT nm ccons",
73823  /*  49 */ "carg ::= ccons",
73824  /*  50 */ "ccons ::= DEFAULT term",
73825  /*  51 */ "ccons ::= DEFAULT LP expr RP",
73826  /*  52 */ "ccons ::= DEFAULT PLUS term",
73827  /*  53 */ "ccons ::= DEFAULT MINUS term",
73828  /*  54 */ "ccons ::= DEFAULT id",
73829  /*  55 */ "ccons ::= NULL onconf",
73830  /*  56 */ "ccons ::= NOT NULL onconf",
73831  /*  57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
73832  /*  58 */ "ccons ::= UNIQUE onconf",
73833  /*  59 */ "ccons ::= CHECK LP expr RP",
73834  /*  60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
73835  /*  61 */ "ccons ::= defer_subclause",
73836  /*  62 */ "ccons ::= COLLATE ids",
73837  /*  63 */ "autoinc ::=",
73838  /*  64 */ "autoinc ::= AUTOINCR",
73839  /*  65 */ "refargs ::=",
73840  /*  66 */ "refargs ::= refargs refarg",
73841  /*  67 */ "refarg ::= MATCH nm",
73842  /*  68 */ "refarg ::= ON DELETE refact",
73843  /*  69 */ "refarg ::= ON UPDATE refact",
73844  /*  70 */ "refarg ::= ON INSERT refact",
73845  /*  71 */ "refact ::= SET NULL",
73846  /*  72 */ "refact ::= SET DEFAULT",
73847  /*  73 */ "refact ::= CASCADE",
73848  /*  74 */ "refact ::= RESTRICT",
73849  /*  75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
73850  /*  76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
73851  /*  77 */ "init_deferred_pred_opt ::=",
73852  /*  78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
73853  /*  79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
73854  /*  80 */ "conslist_opt ::=",
73855  /*  81 */ "conslist_opt ::= COMMA conslist",
73856  /*  82 */ "conslist ::= conslist COMMA tcons",
73857  /*  83 */ "conslist ::= conslist tcons",
73858  /*  84 */ "conslist ::= tcons",
73859  /*  85 */ "tcons ::= CONSTRAINT nm",
73860  /*  86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
73861  /*  87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
73862  /*  88 */ "tcons ::= CHECK LP expr RP onconf",
73863  /*  89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
73864  /*  90 */ "defer_subclause_opt ::=",
73865  /*  91 */ "defer_subclause_opt ::= defer_subclause",
73866  /*  92 */ "onconf ::=",
73867  /*  93 */ "onconf ::= ON CONFLICT resolvetype",
73868  /*  94 */ "orconf ::=",
73869  /*  95 */ "orconf ::= OR resolvetype",
73870  /*  96 */ "resolvetype ::= raisetype",
73871  /*  97 */ "resolvetype ::= IGNORE",
73872  /*  98 */ "resolvetype ::= REPLACE",
73873  /*  99 */ "cmd ::= DROP TABLE ifexists fullname",
73874  /* 100 */ "ifexists ::= IF EXISTS",
73875  /* 101 */ "ifexists ::=",
73876  /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
73877  /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
73878  /* 104 */ "cmd ::= select",
73879  /* 105 */ "select ::= oneselect",
73880  /* 106 */ "select ::= select multiselect_op oneselect",
73881  /* 107 */ "multiselect_op ::= UNION",
73882  /* 108 */ "multiselect_op ::= UNION ALL",
73883  /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
73884  /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
73885  /* 111 */ "distinct ::= DISTINCT",
73886  /* 112 */ "distinct ::= ALL",
73887  /* 113 */ "distinct ::=",
73888  /* 114 */ "sclp ::= selcollist COMMA",
73889  /* 115 */ "sclp ::=",
73890  /* 116 */ "selcollist ::= sclp expr as",
73891  /* 117 */ "selcollist ::= sclp STAR",
73892  /* 118 */ "selcollist ::= sclp nm DOT STAR",
73893  /* 119 */ "as ::= AS nm",
73894  /* 120 */ "as ::= ids",
73895  /* 121 */ "as ::=",
73896  /* 122 */ "from ::=",
73897  /* 123 */ "from ::= FROM seltablist",
73898  /* 124 */ "stl_prefix ::= seltablist joinop",
73899  /* 125 */ "stl_prefix ::=",
73900  /* 126 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
73901  /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
73902  /* 128 */ "seltablist_paren ::= select",
73903  /* 129 */ "seltablist_paren ::= seltablist",
73904  /* 130 */ "dbnm ::=",
73905  /* 131 */ "dbnm ::= DOT nm",
73906  /* 132 */ "fullname ::= nm dbnm",
73907  /* 133 */ "joinop ::= COMMA|JOIN",
73908  /* 134 */ "joinop ::= JOIN_KW JOIN",
73909  /* 135 */ "joinop ::= JOIN_KW nm JOIN",
73910  /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
73911  /* 137 */ "on_opt ::= ON expr",
73912  /* 138 */ "on_opt ::=",
73913  /* 139 */ "using_opt ::= USING LP inscollist RP",
73914  /* 140 */ "using_opt ::=",
73915  /* 141 */ "orderby_opt ::=",
73916  /* 142 */ "orderby_opt ::= ORDER BY sortlist",
73917  /* 143 */ "sortlist ::= sortlist COMMA sortitem sortorder",
73918  /* 144 */ "sortlist ::= sortitem sortorder",
73919  /* 145 */ "sortitem ::= expr",
73920  /* 146 */ "sortorder ::= ASC",
73921  /* 147 */ "sortorder ::= DESC",
73922  /* 148 */ "sortorder ::=",
73923  /* 149 */ "groupby_opt ::=",
73924  /* 150 */ "groupby_opt ::= GROUP BY nexprlist",
73925  /* 151 */ "having_opt ::=",
73926  /* 152 */ "having_opt ::= HAVING expr",
73927  /* 153 */ "limit_opt ::=",
73928  /* 154 */ "limit_opt ::= LIMIT expr",
73929  /* 155 */ "limit_opt ::= LIMIT expr OFFSET expr",
73930  /* 156 */ "limit_opt ::= LIMIT expr COMMA expr",
73931  /* 157 */ "cmd ::= DELETE FROM fullname where_opt",
73932  /* 158 */ "where_opt ::=",
73933  /* 159 */ "where_opt ::= WHERE expr",
73934  /* 160 */ "cmd ::= UPDATE orconf fullname SET setlist where_opt",
73935  /* 161 */ "setlist ::= setlist COMMA nm EQ expr",
73936  /* 162 */ "setlist ::= nm EQ expr",
73937  /* 163 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
73938  /* 164 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
73939  /* 165 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
73940  /* 166 */ "insert_cmd ::= INSERT orconf",
73941  /* 167 */ "insert_cmd ::= REPLACE",
73942  /* 168 */ "itemlist ::= itemlist COMMA expr",
73943  /* 169 */ "itemlist ::= expr",
73944  /* 170 */ "inscollist_opt ::=",
73945  /* 171 */ "inscollist_opt ::= LP inscollist RP",
73946  /* 172 */ "inscollist ::= inscollist COMMA nm",
73947  /* 173 */ "inscollist ::= nm",
73948  /* 174 */ "expr ::= term",
73949  /* 175 */ "expr ::= LP expr RP",
73950  /* 176 */ "term ::= NULL",
73951  /* 177 */ "expr ::= ID",
73952  /* 178 */ "expr ::= JOIN_KW",
73953  /* 179 */ "expr ::= nm DOT nm",
73954  /* 180 */ "expr ::= nm DOT nm DOT nm",
73955  /* 181 */ "term ::= INTEGER|FLOAT|BLOB",
73956  /* 182 */ "term ::= STRING",
73957  /* 183 */ "expr ::= REGISTER",
73958  /* 184 */ "expr ::= VARIABLE",
73959  /* 185 */ "expr ::= expr COLLATE ids",
73960  /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
73961  /* 187 */ "expr ::= ID LP distinct exprlist RP",
73962  /* 188 */ "expr ::= ID LP STAR RP",
73963  /* 189 */ "term ::= CTIME_KW",
73964  /* 190 */ "expr ::= expr AND expr",
73965  /* 191 */ "expr ::= expr OR expr",
73966  /* 192 */ "expr ::= expr LT|GT|GE|LE expr",
73967  /* 193 */ "expr ::= expr EQ|NE expr",
73968  /* 194 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
73969  /* 195 */ "expr ::= expr PLUS|MINUS expr",
73970  /* 196 */ "expr ::= expr STAR|SLASH|REM expr",
73971  /* 197 */ "expr ::= expr CONCAT expr",
73972  /* 198 */ "likeop ::= LIKE_KW",
73973  /* 199 */ "likeop ::= NOT LIKE_KW",
73974  /* 200 */ "likeop ::= MATCH",
73975  /* 201 */ "likeop ::= NOT MATCH",
73976  /* 202 */ "escape ::= ESCAPE expr",
73977  /* 203 */ "escape ::=",
73978  /* 204 */ "expr ::= expr likeop expr escape",
73979  /* 205 */ "expr ::= expr ISNULL|NOTNULL",
73980  /* 206 */ "expr ::= expr IS NULL",
73981  /* 207 */ "expr ::= expr NOT NULL",
73982  /* 208 */ "expr ::= expr IS NOT NULL",
73983  /* 209 */ "expr ::= NOT expr",
73984  /* 210 */ "expr ::= BITNOT expr",
73985  /* 211 */ "expr ::= MINUS expr",
73986  /* 212 */ "expr ::= PLUS expr",
73987  /* 213 */ "between_op ::= BETWEEN",
73988  /* 214 */ "between_op ::= NOT BETWEEN",
73989  /* 215 */ "expr ::= expr between_op expr AND expr",
73990  /* 216 */ "in_op ::= IN",
73991  /* 217 */ "in_op ::= NOT IN",
73992  /* 218 */ "expr ::= expr in_op LP exprlist RP",
73993  /* 219 */ "expr ::= LP select RP",
73994  /* 220 */ "expr ::= expr in_op LP select RP",
73995  /* 221 */ "expr ::= expr in_op nm dbnm",
73996  /* 222 */ "expr ::= EXISTS LP select RP",
73997  /* 223 */ "expr ::= CASE case_operand case_exprlist case_else END",
73998  /* 224 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
73999  /* 225 */ "case_exprlist ::= WHEN expr THEN expr",
74000  /* 226 */ "case_else ::= ELSE expr",
74001  /* 227 */ "case_else ::=",
74002  /* 228 */ "case_operand ::= expr",
74003  /* 229 */ "case_operand ::=",
74004  /* 230 */ "exprlist ::= nexprlist",
74005  /* 231 */ "exprlist ::=",
74006  /* 232 */ "nexprlist ::= nexprlist COMMA expr",
74007  /* 233 */ "nexprlist ::= expr",
74008  /* 234 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
74009  /* 235 */ "uniqueflag ::= UNIQUE",
74010  /* 236 */ "uniqueflag ::=",
74011  /* 237 */ "idxlist_opt ::=",
74012  /* 238 */ "idxlist_opt ::= LP idxlist RP",
74013  /* 239 */ "idxlist ::= idxlist COMMA idxitem collate sortorder",
74014  /* 240 */ "idxlist ::= idxitem collate sortorder",
74015  /* 241 */ "idxitem ::= nm",
74016  /* 242 */ "collate ::=",
74017  /* 243 */ "collate ::= COLLATE ids",
74018  /* 244 */ "cmd ::= DROP INDEX ifexists fullname",
74019  /* 245 */ "cmd ::= VACUUM",
74020  /* 246 */ "cmd ::= VACUUM nm",
74021  /* 247 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
74022  /* 248 */ "cmd ::= PRAGMA nm dbnm EQ ON",
74023  /* 249 */ "cmd ::= PRAGMA nm dbnm EQ DELETE",
74024  /* 250 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
74025  /* 251 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
74026  /* 252 */ "cmd ::= PRAGMA nm dbnm",
74027  /* 253 */ "nmnum ::= plus_num",
74028  /* 254 */ "nmnum ::= nm",
74029  /* 255 */ "plus_num ::= plus_opt number",
74030  /* 256 */ "minus_num ::= MINUS number",
74031  /* 257 */ "number ::= INTEGER|FLOAT",
74032  /* 258 */ "plus_opt ::= PLUS",
74033  /* 259 */ "plus_opt ::=",
74034  /* 260 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
74035  /* 261 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
74036  /* 262 */ "trigger_time ::= BEFORE",
74037  /* 263 */ "trigger_time ::= AFTER",
74038  /* 264 */ "trigger_time ::= INSTEAD OF",
74039  /* 265 */ "trigger_time ::=",
74040  /* 266 */ "trigger_event ::= DELETE|INSERT",
74041  /* 267 */ "trigger_event ::= UPDATE",
74042  /* 268 */ "trigger_event ::= UPDATE OF inscollist",
74043  /* 269 */ "foreach_clause ::=",
74044  /* 270 */ "foreach_clause ::= FOR EACH ROW",
74045  /* 271 */ "when_clause ::=",
74046  /* 272 */ "when_clause ::= WHEN expr",
74047  /* 273 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
74048  /* 274 */ "trigger_cmd_list ::=",
74049  /* 275 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
74050  /* 276 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
74051  /* 277 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
74052  /* 278 */ "trigger_cmd ::= DELETE FROM nm where_opt",
74053  /* 279 */ "trigger_cmd ::= select",
74054  /* 280 */ "expr ::= RAISE LP IGNORE RP",
74055  /* 281 */ "expr ::= RAISE LP raisetype COMMA nm RP",
74056  /* 282 */ "raisetype ::= ROLLBACK",
74057  /* 283 */ "raisetype ::= ABORT",
74058  /* 284 */ "raisetype ::= FAIL",
74059  /* 285 */ "cmd ::= DROP TRIGGER ifexists fullname",
74060  /* 286 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
74061  /* 287 */ "cmd ::= DETACH database_kw_opt expr",
74062  /* 288 */ "key_opt ::=",
74063  /* 289 */ "key_opt ::= KEY expr",
74064  /* 290 */ "database_kw_opt ::= DATABASE",
74065  /* 291 */ "database_kw_opt ::=",
74066  /* 292 */ "cmd ::= REINDEX",
74067  /* 293 */ "cmd ::= REINDEX nm dbnm",
74068  /* 294 */ "cmd ::= ANALYZE",
74069  /* 295 */ "cmd ::= ANALYZE nm dbnm",
74070  /* 296 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
74071  /* 297 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
74072  /* 298 */ "add_column_fullname ::= fullname",
74073  /* 299 */ "kwcolumn_opt ::=",
74074  /* 300 */ "kwcolumn_opt ::= COLUMNKW",
74075  /* 301 */ "cmd ::= create_vtab",
74076  /* 302 */ "cmd ::= create_vtab LP vtabarglist RP",
74077  /* 303 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
74078  /* 304 */ "vtabarglist ::= vtabarg",
74079  /* 305 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
74080  /* 306 */ "vtabarg ::=",
74081  /* 307 */ "vtabarg ::= vtabarg vtabargtoken",
74082  /* 308 */ "vtabargtoken ::= ANY",
74083  /* 309 */ "vtabargtoken ::= lp anylist RP",
74084  /* 310 */ "lp ::= LP",
74085  /* 311 */ "anylist ::=",
74086  /* 312 */ "anylist ::= anylist ANY",
74087 };
74088 #endif /* NDEBUG */
74089
74090
74091 #if YYSTACKDEPTH<=0
74092 /*
74093 ** Try to increase the size of the parser stack.
74094 */
74095 static void yyGrowStack(yyParser *p){
74096   int newSize;
74097   yyStackEntry *pNew;
74098
74099   newSize = p->yystksz*2 + 100;
74100   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
74101   if( pNew ){
74102     p->yystack = pNew;
74103     p->yystksz = newSize;
74104 #ifndef NDEBUG
74105     if( yyTraceFILE ){
74106       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
74107               yyTracePrompt, p->yystksz);
74108     }
74109 #endif
74110   }
74111 }
74112 #endif
74113
74114 /* 
74115 ** This function allocates a new parser.
74116 ** The only argument is a pointer to a function which works like
74117 ** malloc.
74118 **
74119 ** Inputs:
74120 ** A pointer to the function used to allocate memory.
74121 **
74122 ** Outputs:
74123 ** A pointer to a parser.  This pointer is used in subsequent calls
74124 ** to sqlite3Parser and sqlite3ParserFree.
74125 */
74126 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
74127   yyParser *pParser;
74128   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
74129   if( pParser ){
74130     pParser->yyidx = -1;
74131 #if YYSTACKDEPTH<=0
74132     yyGrowStack(pParser);
74133 #endif
74134   }
74135   return pParser;
74136 }
74137
74138 /* The following function deletes the value associated with a
74139 ** symbol.  The symbol can be either a terminal or nonterminal.
74140 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
74141 ** the value.
74142 */
74143 static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){
74144   switch( yymajor ){
74145     /* Here is inserted the actions which take place when a
74146     ** terminal or non-terminal is destroyed.  This can happen
74147     ** when the symbol is popped from the stack during a
74148     ** reduce or during error processing or when a parser is 
74149     ** being destroyed before it is finished parsing.
74150     **
74151     ** Note: during a reduce, the only symbols destroyed are those
74152     ** which appear on the RHS of the rule, but which are not used
74153     ** inside the C code.
74154     */
74155     case 155: /* select */
74156 {
74157 sqlite3SelectDelete((yypminor->yy219));
74158 }
74159       break;
74160     case 169: /* term */
74161 {
74162 sqlite3ExprDelete((yypminor->yy172));
74163 }
74164       break;
74165     case 170: /* expr */
74166 {
74167 sqlite3ExprDelete((yypminor->yy172));
74168 }
74169       break;
74170     case 174: /* idxlist_opt */
74171 {
74172 sqlite3ExprListDelete((yypminor->yy174));
74173 }
74174       break;
74175     case 182: /* idxlist */
74176 {
74177 sqlite3ExprListDelete((yypminor->yy174));
74178 }
74179       break;
74180     case 188: /* fullname */
74181 {
74182 sqlite3SrcListDelete((yypminor->yy373));
74183 }
74184       break;
74185     case 189: /* oneselect */
74186 {
74187 sqlite3SelectDelete((yypminor->yy219));
74188 }
74189       break;
74190     case 192: /* selcollist */
74191 {
74192 sqlite3ExprListDelete((yypminor->yy174));
74193 }
74194       break;
74195     case 193: /* from */
74196 {
74197 sqlite3SrcListDelete((yypminor->yy373));
74198 }
74199       break;
74200     case 194: /* where_opt */
74201 {
74202 sqlite3ExprDelete((yypminor->yy172));
74203 }
74204       break;
74205     case 195: /* groupby_opt */
74206 {
74207 sqlite3ExprListDelete((yypminor->yy174));
74208 }
74209       break;
74210     case 196: /* having_opt */
74211 {
74212 sqlite3ExprDelete((yypminor->yy172));
74213 }
74214       break;
74215     case 197: /* orderby_opt */
74216 {
74217 sqlite3ExprListDelete((yypminor->yy174));
74218 }
74219       break;
74220     case 199: /* sclp */
74221 {
74222 sqlite3ExprListDelete((yypminor->yy174));
74223 }
74224       break;
74225     case 201: /* seltablist */
74226 {
74227 sqlite3SrcListDelete((yypminor->yy373));
74228 }
74229       break;
74230     case 202: /* stl_prefix */
74231 {
74232 sqlite3SrcListDelete((yypminor->yy373));
74233 }
74234       break;
74235     case 204: /* on_opt */
74236 {
74237 sqlite3ExprDelete((yypminor->yy172));
74238 }
74239       break;
74240     case 205: /* using_opt */
74241 {
74242 sqlite3IdListDelete((yypminor->yy432));
74243 }
74244       break;
74245     case 206: /* seltablist_paren */
74246 {
74247 sqlite3SelectDelete((yypminor->yy219));
74248 }
74249       break;
74250     case 208: /* inscollist */
74251 {
74252 sqlite3IdListDelete((yypminor->yy432));
74253 }
74254       break;
74255     case 209: /* sortlist */
74256 {
74257 sqlite3ExprListDelete((yypminor->yy174));
74258 }
74259       break;
74260     case 210: /* sortitem */
74261 {
74262 sqlite3ExprDelete((yypminor->yy172));
74263 }
74264       break;
74265     case 211: /* nexprlist */
74266 {
74267 sqlite3ExprListDelete((yypminor->yy174));
74268 }
74269       break;
74270     case 212: /* setlist */
74271 {
74272 sqlite3ExprListDelete((yypminor->yy174));
74273 }
74274       break;
74275     case 214: /* inscollist_opt */
74276 {
74277 sqlite3IdListDelete((yypminor->yy432));
74278 }
74279       break;
74280     case 215: /* itemlist */
74281 {
74282 sqlite3ExprListDelete((yypminor->yy174));
74283 }
74284       break;
74285     case 216: /* exprlist */
74286 {
74287 sqlite3ExprListDelete((yypminor->yy174));
74288 }
74289       break;
74290     case 218: /* escape */
74291 {
74292 sqlite3ExprDelete((yypminor->yy172));
74293 }
74294       break;
74295     case 221: /* case_operand */
74296 {
74297 sqlite3ExprDelete((yypminor->yy172));
74298 }
74299       break;
74300     case 222: /* case_exprlist */
74301 {
74302 sqlite3ExprListDelete((yypminor->yy174));
74303 }
74304       break;
74305     case 223: /* case_else */
74306 {
74307 sqlite3ExprDelete((yypminor->yy172));
74308 }
74309       break;
74310     case 231: /* trigger_cmd_list */
74311 {
74312 sqlite3DeleteTriggerStep((yypminor->yy243));
74313 }
74314       break;
74315     case 233: /* trigger_event */
74316 {
74317 sqlite3IdListDelete((yypminor->yy370).b);
74318 }
74319       break;
74320     case 235: /* when_clause */
74321 {
74322 sqlite3ExprDelete((yypminor->yy172));
74323 }
74324       break;
74325     case 236: /* trigger_cmd */
74326 {
74327 sqlite3DeleteTriggerStep((yypminor->yy243));
74328 }
74329       break;
74330     case 238: /* key_opt */
74331 {
74332 sqlite3ExprDelete((yypminor->yy172));
74333 }
74334       break;
74335     default:  break;   /* If no destructor action specified: do nothing */
74336   }
74337 }
74338
74339 /*
74340 ** Pop the parser's stack once.
74341 **
74342 ** If there is a destructor routine associated with the token which
74343 ** is popped from the stack, then call it.
74344 **
74345 ** Return the major token number for the symbol popped.
74346 */
74347 static int yy_pop_parser_stack(yyParser *pParser){
74348   YYCODETYPE yymajor;
74349   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
74350
74351   if( pParser->yyidx<0 ) return 0;
74352 #ifndef NDEBUG
74353   if( yyTraceFILE && pParser->yyidx>=0 ){
74354     fprintf(yyTraceFILE,"%sPopping %s\n",
74355       yyTracePrompt,
74356       yyTokenName[yytos->major]);
74357   }
74358 #endif
74359   yymajor = yytos->major;
74360   yy_destructor( yymajor, &yytos->minor);
74361   pParser->yyidx--;
74362   return yymajor;
74363 }
74364
74365 /* 
74366 ** Deallocate and destroy a parser.  Destructors are all called for
74367 ** all stack elements before shutting the parser down.
74368 **
74369 ** Inputs:
74370 ** <ul>
74371 ** <li>  A pointer to the parser.  This should be a pointer
74372 **       obtained from sqlite3ParserAlloc.
74373 ** <li>  A pointer to a function used to reclaim memory obtained
74374 **       from malloc.
74375 ** </ul>
74376 */
74377 SQLITE_PRIVATE void sqlite3ParserFree(
74378   void *p,                    /* The parser to be deleted */
74379   void (*freeProc)(void*)     /* Function used to reclaim memory */
74380 ){
74381   yyParser *pParser = (yyParser*)p;
74382   if( pParser==0 ) return;
74383   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
74384 #if YYSTACKDEPTH<=0
74385   free(pParser->yystack);
74386 #endif
74387   (*freeProc)((void*)pParser);
74388 }
74389
74390 /*
74391 ** Find the appropriate action for a parser given the terminal
74392 ** look-ahead token iLookAhead.
74393 **
74394 ** If the look-ahead token is YYNOCODE, then check to see if the action is
74395 ** independent of the look-ahead.  If it is, return the action, otherwise
74396 ** return YY_NO_ACTION.
74397 */
74398 static int yy_find_shift_action(
74399   yyParser *pParser,        /* The parser */
74400   YYCODETYPE iLookAhead     /* The look-ahead token */
74401 ){
74402   int i;
74403   int stateno = pParser->yystack[pParser->yyidx].stateno;
74404  
74405   if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
74406     return yy_default[stateno];
74407   }
74408   assert( iLookAhead!=YYNOCODE );
74409   i += iLookAhead;
74410   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
74411     if( iLookAhead>0 ){
74412 #ifdef YYFALLBACK
74413       int iFallback;            /* Fallback token */
74414       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
74415              && (iFallback = yyFallback[iLookAhead])!=0 ){
74416 #ifndef NDEBUG
74417         if( yyTraceFILE ){
74418           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
74419              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
74420         }
74421 #endif
74422         return yy_find_shift_action(pParser, iFallback);
74423       }
74424 #endif
74425 #ifdef YYWILDCARD
74426       {
74427         int j = i - iLookAhead + YYWILDCARD;
74428         if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
74429 #ifndef NDEBUG
74430           if( yyTraceFILE ){
74431             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
74432                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
74433           }
74434 #endif /* NDEBUG */
74435           return yy_action[j];
74436         }
74437       }
74438 #endif /* YYWILDCARD */
74439     }
74440     return yy_default[stateno];
74441   }else{
74442     return yy_action[i];
74443   }
74444 }
74445
74446 /*
74447 ** Find the appropriate action for a parser given the non-terminal
74448 ** look-ahead token iLookAhead.
74449 **
74450 ** If the look-ahead token is YYNOCODE, then check to see if the action is
74451 ** independent of the look-ahead.  If it is, return the action, otherwise
74452 ** return YY_NO_ACTION.
74453 */
74454 static int yy_find_reduce_action(
74455   int stateno,              /* Current state number */
74456   YYCODETYPE iLookAhead     /* The look-ahead token */
74457 ){
74458   int i;
74459 #ifdef YYERRORSYMBOL
74460   if( stateno>YY_REDUCE_MAX ){
74461     return yy_default[stateno];
74462   }
74463 #else
74464   assert( stateno<=YY_REDUCE_MAX );
74465 #endif
74466   i = yy_reduce_ofst[stateno];
74467   assert( i!=YY_REDUCE_USE_DFLT );
74468   assert( iLookAhead!=YYNOCODE );
74469   i += iLookAhead;
74470 #ifdef YYERRORSYMBOL
74471   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
74472     return yy_default[stateno];
74473   }
74474 #else
74475   assert( i>=0 && i<YY_SZ_ACTTAB );
74476   assert( yy_lookahead[i]==iLookAhead );
74477 #endif
74478   return yy_action[i];
74479 }
74480
74481 /*
74482 ** The following routine is called if the stack overflows.
74483 */
74484 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
74485    sqlite3ParserARG_FETCH;
74486    yypParser->yyidx--;
74487 #ifndef NDEBUG
74488    if( yyTraceFILE ){
74489      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
74490    }
74491 #endif
74492    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
74493    /* Here code is inserted which will execute if the parser
74494    ** stack every overflows */
74495
74496   sqlite3ErrorMsg(pParse, "parser stack overflow");
74497   pParse->parseError = 1;
74498    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
74499 }
74500
74501 /*
74502 ** Perform a shift action.
74503 */
74504 static void yy_shift(
74505   yyParser *yypParser,          /* The parser to be shifted */
74506   int yyNewState,               /* The new state to shift in */
74507   int yyMajor,                  /* The major token to shift in */
74508   YYMINORTYPE *yypMinor         /* Pointer ot the minor token to shift in */
74509 ){
74510   yyStackEntry *yytos;
74511   yypParser->yyidx++;
74512 #if YYSTACKDEPTH>0 
74513   if( yypParser->yyidx>=YYSTACKDEPTH ){
74514     yyStackOverflow(yypParser, yypMinor);
74515     return;
74516   }
74517 #else
74518   if( yypParser->yyidx>=yypParser->yystksz ){
74519     yyGrowStack(yypParser);
74520     if( yypParser->yyidx>=yypParser->yystksz ){
74521       yyStackOverflow(yypParser, yypMinor);
74522       return;
74523     }
74524   }
74525 #endif
74526   yytos = &yypParser->yystack[yypParser->yyidx];
74527   yytos->stateno = yyNewState;
74528   yytos->major = yyMajor;
74529   yytos->minor = *yypMinor;
74530 #ifndef NDEBUG
74531   if( yyTraceFILE && yypParser->yyidx>0 ){
74532     int i;
74533     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
74534     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
74535     for(i=1; i<=yypParser->yyidx; i++)
74536       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
74537     fprintf(yyTraceFILE,"\n");
74538   }
74539 #endif
74540 }
74541
74542 /* The following table contains information about every rule that
74543 ** is used during the reduce.
74544 */
74545 static const struct {
74546   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
74547   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
74548 } yyRuleInfo[] = {
74549   { 139, 1 },
74550   { 140, 2 },
74551   { 140, 1 },
74552   { 142, 1 },
74553   { 141, 1 },
74554   { 141, 3 },
74555   { 144, 0 },
74556   { 144, 1 },
74557   { 144, 3 },
74558   { 143, 3 },
74559   { 146, 0 },
74560   { 146, 1 },
74561   { 146, 2 },
74562   { 145, 0 },
74563   { 145, 1 },
74564   { 145, 1 },
74565   { 145, 1 },
74566   { 143, 2 },
74567   { 143, 2 },
74568   { 143, 2 },
74569   { 143, 2 },
74570   { 148, 6 },
74571   { 151, 0 },
74572   { 151, 3 },
74573   { 150, 1 },
74574   { 150, 0 },
74575   { 149, 4 },
74576   { 149, 2 },
74577   { 153, 3 },
74578   { 153, 1 },
74579   { 156, 3 },
74580   { 157, 1 },
74581   { 160, 1 },
74582   { 161, 1 },
74583   { 147, 1 },
74584   { 147, 1 },
74585   { 147, 1 },
74586   { 158, 0 },
74587   { 158, 1 },
74588   { 162, 1 },
74589   { 162, 4 },
74590   { 162, 6 },
74591   { 163, 1 },
74592   { 163, 2 },
74593   { 164, 1 },
74594   { 164, 1 },
74595   { 159, 2 },
74596   { 159, 0 },
74597   { 167, 3 },
74598   { 167, 1 },
74599   { 168, 2 },
74600   { 168, 4 },
74601   { 168, 3 },
74602   { 168, 3 },
74603   { 168, 2 },
74604   { 168, 2 },
74605   { 168, 3 },
74606   { 168, 5 },
74607   { 168, 2 },
74608   { 168, 4 },
74609   { 168, 4 },
74610   { 168, 1 },
74611   { 168, 2 },
74612   { 173, 0 },
74613   { 173, 1 },
74614   { 175, 0 },
74615   { 175, 2 },
74616   { 177, 2 },
74617   { 177, 3 },
74618   { 177, 3 },
74619   { 177, 3 },
74620   { 178, 2 },
74621   { 178, 2 },
74622   { 178, 1 },
74623   { 178, 1 },
74624   { 176, 3 },
74625   { 176, 2 },
74626   { 179, 0 },
74627   { 179, 2 },
74628   { 179, 2 },
74629   { 154, 0 },
74630   { 154, 2 },
74631   { 180, 3 },
74632   { 180, 2 },
74633   { 180, 1 },
74634   { 181, 2 },
74635   { 181, 7 },
74636   { 181, 5 },
74637   { 181, 5 },
74638   { 181, 10 },
74639   { 183, 0 },
74640   { 183, 1 },
74641   { 171, 0 },
74642   { 171, 3 },
74643   { 184, 0 },
74644   { 184, 2 },
74645   { 185, 1 },
74646   { 185, 1 },
74647   { 185, 1 },
74648   { 143, 4 },
74649   { 187, 2 },
74650   { 187, 0 },
74651   { 143, 8 },
74652   { 143, 4 },
74653   { 143, 1 },
74654   { 155, 1 },
74655   { 155, 3 },
74656   { 190, 1 },
74657   { 190, 2 },
74658   { 190, 1 },
74659   { 189, 9 },
74660   { 191, 1 },
74661   { 191, 1 },
74662   { 191, 0 },
74663   { 199, 2 },
74664   { 199, 0 },
74665   { 192, 3 },
74666   { 192, 2 },
74667   { 192, 4 },
74668   { 200, 2 },
74669   { 200, 1 },
74670   { 200, 0 },
74671   { 193, 0 },
74672   { 193, 2 },
74673   { 202, 2 },
74674   { 202, 0 },
74675   { 201, 6 },
74676   { 201, 7 },
74677   { 206, 1 },
74678   { 206, 1 },
74679   { 152, 0 },
74680   { 152, 2 },
74681   { 188, 2 },
74682   { 203, 1 },
74683   { 203, 2 },
74684   { 203, 3 },
74685   { 203, 4 },
74686   { 204, 2 },
74687   { 204, 0 },
74688   { 205, 4 },
74689   { 205, 0 },
74690   { 197, 0 },
74691   { 197, 3 },
74692   { 209, 4 },
74693   { 209, 2 },
74694   { 210, 1 },
74695   { 172, 1 },
74696   { 172, 1 },
74697   { 172, 0 },
74698   { 195, 0 },
74699   { 195, 3 },
74700   { 196, 0 },
74701   { 196, 2 },
74702   { 198, 0 },
74703   { 198, 2 },
74704   { 198, 4 },
74705   { 198, 4 },
74706   { 143, 4 },
74707   { 194, 0 },
74708   { 194, 2 },
74709   { 143, 6 },
74710   { 212, 5 },
74711   { 212, 3 },
74712   { 143, 8 },
74713   { 143, 5 },
74714   { 143, 6 },
74715   { 213, 2 },
74716   { 213, 1 },
74717   { 215, 3 },
74718   { 215, 1 },
74719   { 214, 0 },
74720   { 214, 3 },
74721   { 208, 3 },
74722   { 208, 1 },
74723   { 170, 1 },
74724   { 170, 3 },
74725   { 169, 1 },
74726   { 170, 1 },
74727   { 170, 1 },
74728   { 170, 3 },
74729   { 170, 5 },
74730   { 169, 1 },
74731   { 169, 1 },
74732   { 170, 1 },
74733   { 170, 1 },
74734   { 170, 3 },
74735   { 170, 6 },
74736   { 170, 5 },
74737   { 170, 4 },
74738   { 169, 1 },
74739   { 170, 3 },
74740   { 170, 3 },
74741   { 170, 3 },
74742   { 170, 3 },
74743   { 170, 3 },
74744   { 170, 3 },
74745   { 170, 3 },
74746   { 170, 3 },
74747   { 217, 1 },
74748   { 217, 2 },
74749   { 217, 1 },
74750   { 217, 2 },
74751   { 218, 2 },
74752   { 218, 0 },
74753   { 170, 4 },
74754   { 170, 2 },
74755   { 170, 3 },
74756   { 170, 3 },
74757   { 170, 4 },
74758   { 170, 2 },
74759   { 170, 2 },
74760   { 170, 2 },
74761   { 170, 2 },
74762   { 219, 1 },
74763   { 219, 2 },
74764   { 170, 5 },
74765   { 220, 1 },
74766   { 220, 2 },
74767   { 170, 5 },
74768   { 170, 3 },
74769   { 170, 5 },
74770   { 170, 4 },
74771   { 170, 4 },
74772   { 170, 5 },
74773   { 222, 5 },
74774   { 222, 4 },
74775   { 223, 2 },
74776   { 223, 0 },
74777   { 221, 1 },
74778   { 221, 0 },
74779   { 216, 1 },
74780   { 216, 0 },
74781   { 211, 3 },
74782   { 211, 1 },
74783   { 143, 11 },
74784   { 224, 1 },
74785   { 224, 0 },
74786   { 174, 0 },
74787   { 174, 3 },
74788   { 182, 5 },
74789   { 182, 3 },
74790   { 225, 1 },
74791   { 226, 0 },
74792   { 226, 2 },
74793   { 143, 4 },
74794   { 143, 1 },
74795   { 143, 2 },
74796   { 143, 5 },
74797   { 143, 5 },
74798   { 143, 5 },
74799   { 143, 5 },
74800   { 143, 6 },
74801   { 143, 3 },
74802   { 227, 1 },
74803   { 227, 1 },
74804   { 165, 2 },
74805   { 166, 2 },
74806   { 229, 1 },
74807   { 228, 1 },
74808   { 228, 0 },
74809   { 143, 5 },
74810   { 230, 11 },
74811   { 232, 1 },
74812   { 232, 1 },
74813   { 232, 2 },
74814   { 232, 0 },
74815   { 233, 1 },
74816   { 233, 1 },
74817   { 233, 3 },
74818   { 234, 0 },
74819   { 234, 3 },
74820   { 235, 0 },
74821   { 235, 2 },
74822   { 231, 3 },
74823   { 231, 0 },
74824   { 236, 6 },
74825   { 236, 8 },
74826   { 236, 5 },
74827   { 236, 4 },
74828   { 236, 1 },
74829   { 170, 4 },
74830   { 170, 6 },
74831   { 186, 1 },
74832   { 186, 1 },
74833   { 186, 1 },
74834   { 143, 4 },
74835   { 143, 6 },
74836   { 143, 3 },
74837   { 238, 0 },
74838   { 238, 2 },
74839   { 237, 1 },
74840   { 237, 0 },
74841   { 143, 1 },
74842   { 143, 3 },
74843   { 143, 1 },
74844   { 143, 3 },
74845   { 143, 6 },
74846   { 143, 6 },
74847   { 239, 1 },
74848   { 240, 0 },
74849   { 240, 1 },
74850   { 143, 1 },
74851   { 143, 4 },
74852   { 241, 7 },
74853   { 242, 1 },
74854   { 242, 3 },
74855   { 243, 0 },
74856   { 243, 2 },
74857   { 244, 1 },
74858   { 244, 3 },
74859   { 245, 1 },
74860   { 246, 0 },
74861   { 246, 2 },
74862 };
74863
74864 static void yy_accept(yyParser*);  /* Forward Declaration */
74865
74866 /*
74867 ** Perform a reduce action and the shift that must immediately
74868 ** follow the reduce.
74869 */
74870 static void yy_reduce(
74871   yyParser *yypParser,         /* The parser */
74872   int yyruleno                 /* Number of the rule by which to reduce */
74873 ){
74874   int yygoto;                     /* The next state */
74875   int yyact;                      /* The next action */
74876   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
74877   yyStackEntry *yymsp;            /* The top of the parser's stack */
74878   int yysize;                     /* Amount to pop the stack */
74879   sqlite3ParserARG_FETCH;
74880   yymsp = &yypParser->yystack[yypParser->yyidx];
74881 #ifndef NDEBUG
74882   if( yyTraceFILE && yyruleno>=0 
74883         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
74884     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
74885       yyRuleName[yyruleno]);
74886   }
74887 #endif /* NDEBUG */
74888
74889   /* Silence complaints from purify about yygotominor being uninitialized
74890   ** in some cases when it is copied into the stack after the following
74891   ** switch.  yygotominor is uninitialized when a rule reduces that does
74892   ** not set the value of its left-hand side nonterminal.  Leaving the
74893   ** value of the nonterminal uninitialized is utterly harmless as long
74894   ** as the value is never used.  So really the only thing this code
74895   ** accomplishes is to quieten purify.  
74896   **
74897   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
74898   ** without this code, their parser segfaults.  I'm not sure what there
74899   ** parser is doing to make this happen.  This is the second bug report
74900   ** from wireshark this week.  Clearly they are stressing Lemon in ways
74901   ** that it has not been previously stressed...  (SQLite ticket #2172)
74902   */
74903   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
74904   yygotominor = yyzerominor;
74905
74906
74907   switch( yyruleno ){
74908   /* Beginning here are the reduction cases.  A typical example
74909   ** follows:
74910   **   case 0:
74911   **  #line <lineno> <grammarfile>
74912   **     { ... }           // User supplied code
74913   **  #line <lineno> <thisfile>
74914   **     break;
74915   */
74916       case 0: /* input ::= cmdlist */
74917       case 1: /* cmdlist ::= cmdlist ecmd */
74918       case 2: /* cmdlist ::= ecmd */
74919       case 4: /* ecmd ::= SEMI */
74920       case 5: /* ecmd ::= explain cmdx SEMI */
74921       case 10: /* trans_opt ::= */
74922       case 11: /* trans_opt ::= TRANSACTION */
74923       case 12: /* trans_opt ::= TRANSACTION nm */
74924       case 20: /* cmd ::= create_table create_table_args */
74925       case 28: /* columnlist ::= columnlist COMMA column */
74926       case 29: /* columnlist ::= column */
74927       case 37: /* type ::= */
74928       case 44: /* signed ::= plus_num */
74929       case 45: /* signed ::= minus_num */
74930       case 46: /* carglist ::= carglist carg */
74931       case 47: /* carglist ::= */
74932       case 48: /* carg ::= CONSTRAINT nm ccons */
74933       case 49: /* carg ::= ccons */
74934       case 55: /* ccons ::= NULL onconf */
74935       case 82: /* conslist ::= conslist COMMA tcons */
74936       case 83: /* conslist ::= conslist tcons */
74937       case 84: /* conslist ::= tcons */
74938       case 85: /* tcons ::= CONSTRAINT nm */
74939       case 258: /* plus_opt ::= PLUS */
74940       case 259: /* plus_opt ::= */
74941       case 269: /* foreach_clause ::= */
74942       case 270: /* foreach_clause ::= FOR EACH ROW */
74943       case 290: /* database_kw_opt ::= DATABASE */
74944       case 291: /* database_kw_opt ::= */
74945       case 299: /* kwcolumn_opt ::= */
74946       case 300: /* kwcolumn_opt ::= COLUMNKW */
74947       case 304: /* vtabarglist ::= vtabarg */
74948       case 305: /* vtabarglist ::= vtabarglist COMMA vtabarg */
74949       case 307: /* vtabarg ::= vtabarg vtabargtoken */
74950       case 311: /* anylist ::= */
74951 {
74952 }
74953         break;
74954       case 3: /* cmdx ::= cmd */
74955 { sqlite3FinishCoding(pParse); }
74956         break;
74957       case 6: /* explain ::= */
74958 { sqlite3BeginParse(pParse, 0); }
74959         break;
74960       case 7: /* explain ::= EXPLAIN */
74961 { sqlite3BeginParse(pParse, 1); }
74962         break;
74963       case 8: /* explain ::= EXPLAIN QUERY PLAN */
74964 { sqlite3BeginParse(pParse, 2); }
74965         break;
74966       case 9: /* cmd ::= BEGIN transtype trans_opt */
74967 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy46);}
74968         break;
74969       case 13: /* transtype ::= */
74970 {yygotominor.yy46 = TK_DEFERRED;}
74971         break;
74972       case 14: /* transtype ::= DEFERRED */
74973       case 15: /* transtype ::= IMMEDIATE */
74974       case 16: /* transtype ::= EXCLUSIVE */
74975       case 107: /* multiselect_op ::= UNION */
74976       case 109: /* multiselect_op ::= EXCEPT|INTERSECT */
74977 {yygotominor.yy46 = yymsp[0].major;}
74978         break;
74979       case 17: /* cmd ::= COMMIT trans_opt */
74980       case 18: /* cmd ::= END trans_opt */
74981 {sqlite3CommitTransaction(pParse);}
74982         break;
74983       case 19: /* cmd ::= ROLLBACK trans_opt */
74984 {sqlite3RollbackTransaction(pParse);}
74985         break;
74986       case 21: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
74987 {
74988    sqlite3StartTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46);
74989 }
74990         break;
74991       case 22: /* ifnotexists ::= */
74992       case 25: /* temp ::= */
74993       case 63: /* autoinc ::= */
74994       case 77: /* init_deferred_pred_opt ::= */
74995       case 79: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
74996       case 90: /* defer_subclause_opt ::= */
74997       case 101: /* ifexists ::= */
74998       case 112: /* distinct ::= ALL */
74999       case 113: /* distinct ::= */
75000       case 213: /* between_op ::= BETWEEN */
75001       case 216: /* in_op ::= IN */
75002 {yygotominor.yy46 = 0;}
75003         break;
75004       case 23: /* ifnotexists ::= IF NOT EXISTS */
75005       case 24: /* temp ::= TEMP */
75006       case 64: /* autoinc ::= AUTOINCR */
75007       case 78: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
75008       case 100: /* ifexists ::= IF EXISTS */
75009       case 111: /* distinct ::= DISTINCT */
75010       case 214: /* between_op ::= NOT BETWEEN */
75011       case 217: /* in_op ::= NOT IN */
75012 {yygotominor.yy46 = 1;}
75013         break;
75014       case 26: /* create_table_args ::= LP columnlist conslist_opt RP */
75015 {
75016   sqlite3EndTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy0,0);
75017 }
75018         break;
75019       case 27: /* create_table_args ::= AS select */
75020 {
75021   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy219);
75022   sqlite3SelectDelete(yymsp[0].minor.yy219);
75023 }
75024         break;
75025       case 30: /* column ::= columnid type carglist */
75026 {
75027   yygotominor.yy410.z = yymsp[-2].minor.yy410.z;
75028   yygotominor.yy410.n = (pParse->sLastToken.z-yymsp[-2].minor.yy410.z) + pParse->sLastToken.n;
75029 }
75030         break;
75031       case 31: /* columnid ::= nm */
75032 {
75033   sqlite3AddColumn(pParse,&yymsp[0].minor.yy410);
75034   yygotominor.yy410 = yymsp[0].minor.yy410;
75035 }
75036         break;
75037       case 32: /* id ::= ID */
75038       case 33: /* ids ::= ID|STRING */
75039       case 34: /* nm ::= ID */
75040       case 35: /* nm ::= STRING */
75041       case 36: /* nm ::= JOIN_KW */
75042       case 257: /* number ::= INTEGER|FLOAT */
75043 {yygotominor.yy410 = yymsp[0].minor.yy0;}
75044         break;
75045       case 38: /* type ::= typetoken */
75046 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy410);}
75047         break;
75048       case 39: /* typetoken ::= typename */
75049       case 42: /* typename ::= ids */
75050       case 119: /* as ::= AS nm */
75051       case 120: /* as ::= ids */
75052       case 131: /* dbnm ::= DOT nm */
75053       case 241: /* idxitem ::= nm */
75054       case 243: /* collate ::= COLLATE ids */
75055       case 253: /* nmnum ::= plus_num */
75056       case 254: /* nmnum ::= nm */
75057       case 255: /* plus_num ::= plus_opt number */
75058       case 256: /* minus_num ::= MINUS number */
75059 {yygotominor.yy410 = yymsp[0].minor.yy410;}
75060         break;
75061       case 40: /* typetoken ::= typename LP signed RP */
75062 {
75063   yygotominor.yy410.z = yymsp[-3].minor.yy410.z;
75064   yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy410.z;
75065 }
75066         break;
75067       case 41: /* typetoken ::= typename LP signed COMMA signed RP */
75068 {
75069   yygotominor.yy410.z = yymsp[-5].minor.yy410.z;
75070   yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy410.z;
75071 }
75072         break;
75073       case 43: /* typename ::= typename ids */
75074 {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);}
75075         break;
75076       case 50: /* ccons ::= DEFAULT term */
75077       case 52: /* ccons ::= DEFAULT PLUS term */
75078 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy172);}
75079         break;
75080       case 51: /* ccons ::= DEFAULT LP expr RP */
75081 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy172);}
75082         break;
75083       case 53: /* ccons ::= DEFAULT MINUS term */
75084 {
75085   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
75086   sqlite3AddDefaultValue(pParse,p);
75087 }
75088         break;
75089       case 54: /* ccons ::= DEFAULT id */
75090 {
75091   Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy410);
75092   sqlite3AddDefaultValue(pParse,p);
75093 }
75094         break;
75095       case 56: /* ccons ::= NOT NULL onconf */
75096 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy46);}
75097         break;
75098       case 57: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
75099 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);}
75100         break;
75101       case 58: /* ccons ::= UNIQUE onconf */
75102 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy46,0,0,0,0);}
75103         break;
75104       case 59: /* ccons ::= CHECK LP expr RP */
75105 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy172);}
75106         break;
75107       case 60: /* ccons ::= REFERENCES nm idxlist_opt refargs */
75108 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy410,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);}
75109         break;
75110       case 61: /* ccons ::= defer_subclause */
75111 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy46);}
75112         break;
75113       case 62: /* ccons ::= COLLATE ids */
75114 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy410);}
75115         break;
75116       case 65: /* refargs ::= */
75117 { yygotominor.yy46 = OE_Restrict * 0x010101; }
75118         break;
75119       case 66: /* refargs ::= refargs refarg */
75120 { yygotominor.yy46 = (yymsp[-1].minor.yy46 & yymsp[0].minor.yy405.mask) | yymsp[0].minor.yy405.value; }
75121         break;
75122       case 67: /* refarg ::= MATCH nm */
75123 { yygotominor.yy405.value = 0;     yygotominor.yy405.mask = 0x000000; }
75124         break;
75125       case 68: /* refarg ::= ON DELETE refact */
75126 { yygotominor.yy405.value = yymsp[0].minor.yy46;     yygotominor.yy405.mask = 0x0000ff; }
75127         break;
75128       case 69: /* refarg ::= ON UPDATE refact */
75129 { yygotominor.yy405.value = yymsp[0].minor.yy46<<8;  yygotominor.yy405.mask = 0x00ff00; }
75130         break;
75131       case 70: /* refarg ::= ON INSERT refact */
75132 { yygotominor.yy405.value = yymsp[0].minor.yy46<<16; yygotominor.yy405.mask = 0xff0000; }
75133         break;
75134       case 71: /* refact ::= SET NULL */
75135 { yygotominor.yy46 = OE_SetNull; }
75136         break;
75137       case 72: /* refact ::= SET DEFAULT */
75138 { yygotominor.yy46 = OE_SetDflt; }
75139         break;
75140       case 73: /* refact ::= CASCADE */
75141 { yygotominor.yy46 = OE_Cascade; }
75142         break;
75143       case 74: /* refact ::= RESTRICT */
75144 { yygotominor.yy46 = OE_Restrict; }
75145         break;
75146       case 75: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
75147       case 76: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
75148       case 91: /* defer_subclause_opt ::= defer_subclause */
75149       case 93: /* onconf ::= ON CONFLICT resolvetype */
75150       case 95: /* orconf ::= OR resolvetype */
75151       case 96: /* resolvetype ::= raisetype */
75152       case 166: /* insert_cmd ::= INSERT orconf */
75153 {yygotominor.yy46 = yymsp[0].minor.yy46;}
75154         break;
75155       case 80: /* conslist_opt ::= */
75156 {yygotominor.yy410.n = 0; yygotominor.yy410.z = 0;}
75157         break;
75158       case 81: /* conslist_opt ::= COMMA conslist */
75159 {yygotominor.yy410 = yymsp[-1].minor.yy0;}
75160         break;
75161       case 86: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
75162 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy174,yymsp[0].minor.yy46,yymsp[-2].minor.yy46,0);}
75163         break;
75164       case 87: /* tcons ::= UNIQUE LP idxlist RP onconf */
75165 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy174,yymsp[0].minor.yy46,0,0,0,0);}
75166         break;
75167       case 88: /* tcons ::= CHECK LP expr RP onconf */
75168 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy172);}
75169         break;
75170       case 89: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
75171 {
75172     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy174, &yymsp[-3].minor.yy410, yymsp[-2].minor.yy174, yymsp[-1].minor.yy46);
75173     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy46);
75174 }
75175         break;
75176       case 92: /* onconf ::= */
75177       case 94: /* orconf ::= */
75178 {yygotominor.yy46 = OE_Default;}
75179         break;
75180       case 97: /* resolvetype ::= IGNORE */
75181 {yygotominor.yy46 = OE_Ignore;}
75182         break;
75183       case 98: /* resolvetype ::= REPLACE */
75184       case 167: /* insert_cmd ::= REPLACE */
75185 {yygotominor.yy46 = OE_Replace;}
75186         break;
75187       case 99: /* cmd ::= DROP TABLE ifexists fullname */
75188 {
75189   sqlite3DropTable(pParse, yymsp[0].minor.yy373, 0, yymsp[-1].minor.yy46);
75190 }
75191         break;
75192       case 102: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
75193 {
75194   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);
75195 }
75196         break;
75197       case 103: /* cmd ::= DROP VIEW ifexists fullname */
75198 {
75199   sqlite3DropTable(pParse, yymsp[0].minor.yy373, 1, yymsp[-1].minor.yy46);
75200 }
75201         break;
75202       case 104: /* cmd ::= select */
75203 {
75204   SelectDest dest = {SRT_Callback, 0, 0, 0, 0};
75205   sqlite3Select(pParse, yymsp[0].minor.yy219, &dest, 0, 0, 0, 0);
75206   sqlite3SelectDelete(yymsp[0].minor.yy219);
75207 }
75208         break;
75209       case 105: /* select ::= oneselect */
75210       case 128: /* seltablist_paren ::= select */
75211 {yygotominor.yy219 = yymsp[0].minor.yy219;}
75212         break;
75213       case 106: /* select ::= select multiselect_op oneselect */
75214 {
75215   if( yymsp[0].minor.yy219 ){
75216     yymsp[0].minor.yy219->op = yymsp[-1].minor.yy46;
75217     yymsp[0].minor.yy219->pPrior = yymsp[-2].minor.yy219;
75218   }else{
75219     sqlite3SelectDelete(yymsp[-2].minor.yy219);
75220   }
75221   yygotominor.yy219 = yymsp[0].minor.yy219;
75222 }
75223         break;
75224       case 108: /* multiselect_op ::= UNION ALL */
75225 {yygotominor.yy46 = TK_ALL;}
75226         break;
75227       case 110: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
75228 {
75229   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);
75230 }
75231         break;
75232       case 114: /* sclp ::= selcollist COMMA */
75233       case 238: /* idxlist_opt ::= LP idxlist RP */
75234 {yygotominor.yy174 = yymsp[-1].minor.yy174;}
75235         break;
75236       case 115: /* sclp ::= */
75237       case 141: /* orderby_opt ::= */
75238       case 149: /* groupby_opt ::= */
75239       case 231: /* exprlist ::= */
75240       case 237: /* idxlist_opt ::= */
75241 {yygotominor.yy174 = 0;}
75242         break;
75243       case 116: /* selcollist ::= sclp expr as */
75244 {
75245    yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy410.n?&yymsp[0].minor.yy410:0);
75246 }
75247         break;
75248       case 117: /* selcollist ::= sclp STAR */
75249 {
75250   Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
75251   yygotominor.yy174 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy174, p, 0);
75252 }
75253         break;
75254       case 118: /* selcollist ::= sclp nm DOT STAR */
75255 {
75256   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
75257   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
75258   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
75259   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174, pDot, 0);
75260 }
75261         break;
75262       case 121: /* as ::= */
75263 {yygotominor.yy410.n = 0;}
75264         break;
75265       case 122: /* from ::= */
75266 {yygotominor.yy373 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy373));}
75267         break;
75268       case 123: /* from ::= FROM seltablist */
75269 {
75270   yygotominor.yy373 = yymsp[0].minor.yy373;
75271   sqlite3SrcListShiftJoinType(yygotominor.yy373);
75272 }
75273         break;
75274       case 124: /* stl_prefix ::= seltablist joinop */
75275 {
75276    yygotominor.yy373 = yymsp[-1].minor.yy373;
75277    if( yygotominor.yy373 && yygotominor.yy373->nSrc>0 ) yygotominor.yy373->a[yygotominor.yy373->nSrc-1].jointype = yymsp[0].minor.yy46;
75278 }
75279         break;
75280       case 125: /* stl_prefix ::= */
75281 {yygotominor.yy373 = 0;}
75282         break;
75283       case 126: /* seltablist ::= stl_prefix nm dbnm as on_opt using_opt */
75284 {
75285   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);
75286 }
75287         break;
75288       case 127: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */
75289 {
75290     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);
75291   }
75292         break;
75293       case 129: /* seltablist_paren ::= seltablist */
75294 {
75295      sqlite3SrcListShiftJoinType(yymsp[0].minor.yy373);
75296      yygotominor.yy219 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy373,0,0,0,0,0,0,0);
75297   }
75298         break;
75299       case 130: /* dbnm ::= */
75300 {yygotominor.yy410.z=0; yygotominor.yy410.n=0;}
75301         break;
75302       case 132: /* fullname ::= nm dbnm */
75303 {yygotominor.yy373 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);}
75304         break;
75305       case 133: /* joinop ::= COMMA|JOIN */
75306 { yygotominor.yy46 = JT_INNER; }
75307         break;
75308       case 134: /* joinop ::= JOIN_KW JOIN */
75309 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
75310         break;
75311       case 135: /* joinop ::= JOIN_KW nm JOIN */
75312 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy410,0); }
75313         break;
75314       case 136: /* joinop ::= JOIN_KW nm nm JOIN */
75315 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy410,&yymsp[-1].minor.yy410); }
75316         break;
75317       case 137: /* on_opt ::= ON expr */
75318       case 145: /* sortitem ::= expr */
75319       case 152: /* having_opt ::= HAVING expr */
75320       case 159: /* where_opt ::= WHERE expr */
75321       case 174: /* expr ::= term */
75322       case 202: /* escape ::= ESCAPE expr */
75323       case 226: /* case_else ::= ELSE expr */
75324       case 228: /* case_operand ::= expr */
75325 {yygotominor.yy172 = yymsp[0].minor.yy172;}
75326         break;
75327       case 138: /* on_opt ::= */
75328       case 151: /* having_opt ::= */
75329       case 158: /* where_opt ::= */
75330       case 203: /* escape ::= */
75331       case 227: /* case_else ::= */
75332       case 229: /* case_operand ::= */
75333 {yygotominor.yy172 = 0;}
75334         break;
75335       case 139: /* using_opt ::= USING LP inscollist RP */
75336       case 171: /* inscollist_opt ::= LP inscollist RP */
75337 {yygotominor.yy432 = yymsp[-1].minor.yy432;}
75338         break;
75339       case 140: /* using_opt ::= */
75340       case 170: /* inscollist_opt ::= */
75341 {yygotominor.yy432 = 0;}
75342         break;
75343       case 142: /* orderby_opt ::= ORDER BY sortlist */
75344       case 150: /* groupby_opt ::= GROUP BY nexprlist */
75345       case 230: /* exprlist ::= nexprlist */
75346 {yygotominor.yy174 = yymsp[0].minor.yy174;}
75347         break;
75348       case 143: /* sortlist ::= sortlist COMMA sortitem sortorder */
75349 {
75350   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174,yymsp[-1].minor.yy172,0);
75351   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
75352 }
75353         break;
75354       case 144: /* sortlist ::= sortitem sortorder */
75355 {
75356   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy172,0);
75357   if( yygotominor.yy174 && yygotominor.yy174->a ) yygotominor.yy174->a[0].sortOrder = yymsp[0].minor.yy46;
75358 }
75359         break;
75360       case 146: /* sortorder ::= ASC */
75361       case 148: /* sortorder ::= */
75362 {yygotominor.yy46 = SQLITE_SO_ASC;}
75363         break;
75364       case 147: /* sortorder ::= DESC */
75365 {yygotominor.yy46 = SQLITE_SO_DESC;}
75366         break;
75367       case 153: /* limit_opt ::= */
75368 {yygotominor.yy234.pLimit = 0; yygotominor.yy234.pOffset = 0;}
75369         break;
75370       case 154: /* limit_opt ::= LIMIT expr */
75371 {yygotominor.yy234.pLimit = yymsp[0].minor.yy172; yygotominor.yy234.pOffset = 0;}
75372         break;
75373       case 155: /* limit_opt ::= LIMIT expr OFFSET expr */
75374 {yygotominor.yy234.pLimit = yymsp[-2].minor.yy172; yygotominor.yy234.pOffset = yymsp[0].minor.yy172;}
75375         break;
75376       case 156: /* limit_opt ::= LIMIT expr COMMA expr */
75377 {yygotominor.yy234.pOffset = yymsp[-2].minor.yy172; yygotominor.yy234.pLimit = yymsp[0].minor.yy172;}
75378         break;
75379       case 157: /* cmd ::= DELETE FROM fullname where_opt */
75380 {sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy373,yymsp[0].minor.yy172);}
75381         break;
75382       case 160: /* cmd ::= UPDATE orconf fullname SET setlist where_opt */
75383 {
75384   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy174,"set list"); 
75385   sqlite3Update(pParse,yymsp[-3].minor.yy373,yymsp[-1].minor.yy174,yymsp[0].minor.yy172,yymsp[-4].minor.yy46);
75386 }
75387         break;
75388       case 161: /* setlist ::= setlist COMMA nm EQ expr */
75389 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
75390         break;
75391       case 162: /* setlist ::= nm EQ expr */
75392 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
75393         break;
75394       case 163: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
75395 {sqlite3Insert(pParse, yymsp[-5].minor.yy373, yymsp[-1].minor.yy174, 0, yymsp[-4].minor.yy432, yymsp[-7].minor.yy46);}
75396         break;
75397       case 164: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
75398 {sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);}
75399         break;
75400       case 165: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
75401 {sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);}
75402         break;
75403       case 168: /* itemlist ::= itemlist COMMA expr */
75404       case 232: /* nexprlist ::= nexprlist COMMA expr */
75405 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);}
75406         break;
75407       case 169: /* itemlist ::= expr */
75408       case 233: /* nexprlist ::= expr */
75409 {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,0);}
75410         break;
75411       case 172: /* inscollist ::= inscollist COMMA nm */
75412 {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy432,&yymsp[0].minor.yy410);}
75413         break;
75414       case 173: /* inscollist ::= nm */
75415 {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy410);}
75416         break;
75417       case 175: /* expr ::= LP expr RP */
75418 {yygotominor.yy172 = yymsp[-1].minor.yy172; sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
75419         break;
75420       case 176: /* term ::= NULL */
75421       case 181: /* term ::= INTEGER|FLOAT|BLOB */
75422       case 182: /* term ::= STRING */
75423 {yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
75424         break;
75425       case 177: /* expr ::= ID */
75426       case 178: /* expr ::= JOIN_KW */
75427 {yygotominor.yy172 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
75428         break;
75429       case 179: /* expr ::= nm DOT nm */
75430 {
75431   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
75432   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy410);
75433   yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
75434 }
75435         break;
75436       case 180: /* expr ::= nm DOT nm DOT nm */
75437 {
75438   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy410);
75439   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410);
75440   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy410);
75441   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
75442   yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
75443 }
75444         break;
75445       case 183: /* expr ::= REGISTER */
75446 {yygotominor.yy172 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
75447         break;
75448       case 184: /* expr ::= VARIABLE */
75449 {
75450   Token *pToken = &yymsp[0].minor.yy0;
75451   Expr *pExpr = yygotominor.yy172 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
75452   sqlite3ExprAssignVarNumber(pParse, pExpr);
75453 }
75454         break;
75455       case 185: /* expr ::= expr COLLATE ids */
75456 {
75457   yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy410);
75458 }
75459         break;
75460       case 186: /* expr ::= CAST LP expr AS typetoken RP */
75461 {
75462   yygotominor.yy172 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy172, 0, &yymsp[-1].minor.yy410);
75463   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
75464 }
75465         break;
75466       case 187: /* expr ::= ID LP distinct exprlist RP */
75467 {
75468   if( yymsp[-1].minor.yy174 && yymsp[-1].minor.yy174->nExpr>SQLITE_MAX_FUNCTION_ARG ){
75469     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
75470   }
75471   yygotominor.yy172 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy174, &yymsp[-4].minor.yy0);
75472   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
75473   if( yymsp[-2].minor.yy46 && yygotominor.yy172 ){
75474     yygotominor.yy172->flags |= EP_Distinct;
75475   }
75476 }
75477         break;
75478       case 188: /* expr ::= ID LP STAR RP */
75479 {
75480   yygotominor.yy172 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
75481   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
75482 }
75483         break;
75484       case 189: /* term ::= CTIME_KW */
75485 {
75486   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
75487   ** treated as functions that return constants */
75488   yygotominor.yy172 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
75489   if( yygotominor.yy172 ){
75490     yygotominor.yy172->op = TK_CONST_FUNC;  
75491     yygotominor.yy172->span = yymsp[0].minor.yy0;
75492   }
75493 }
75494         break;
75495       case 190: /* expr ::= expr AND expr */
75496       case 191: /* expr ::= expr OR expr */
75497       case 192: /* expr ::= expr LT|GT|GE|LE expr */
75498       case 193: /* expr ::= expr EQ|NE expr */
75499       case 194: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
75500       case 195: /* expr ::= expr PLUS|MINUS expr */
75501       case 196: /* expr ::= expr STAR|SLASH|REM expr */
75502       case 197: /* expr ::= expr CONCAT expr */
75503 {yygotominor.yy172 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy172,yymsp[0].minor.yy172,0);}
75504         break;
75505       case 198: /* likeop ::= LIKE_KW */
75506       case 200: /* likeop ::= MATCH */
75507 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 0;}
75508         break;
75509       case 199: /* likeop ::= NOT LIKE_KW */
75510       case 201: /* likeop ::= NOT MATCH */
75511 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 1;}
75512         break;
75513       case 204: /* expr ::= expr likeop expr escape */
75514 {
75515   ExprList *pList;
75516   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy172, 0);
75517   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy172, 0);
75518   if( yymsp[0].minor.yy172 ){
75519     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0);
75520   }
75521   yygotominor.yy172 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy72.eOperator);
75522   if( yymsp[-2].minor.yy72.not ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
75523   sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy172->span, &yymsp[-1].minor.yy172->span);
75524   if( yygotominor.yy172 ) yygotominor.yy172->flags |= EP_InfixFunc;
75525 }
75526         break;
75527       case 205: /* expr ::= expr ISNULL|NOTNULL */
75528 {
75529   yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy172, 0, 0);
75530   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy172->span,&yymsp[0].minor.yy0);
75531 }
75532         break;
75533       case 206: /* expr ::= expr IS NULL */
75534 {
75535   yygotominor.yy172 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy172, 0, 0);
75536   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
75537 }
75538         break;
75539       case 207: /* expr ::= expr NOT NULL */
75540 {
75541   yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy172, 0, 0);
75542   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
75543 }
75544         break;
75545       case 208: /* expr ::= expr IS NOT NULL */
75546 {
75547   yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy172, 0, 0);
75548   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,&yymsp[0].minor.yy0);
75549 }
75550         break;
75551       case 209: /* expr ::= NOT expr */
75552       case 210: /* expr ::= BITNOT expr */
75553 {
75554   yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy172, 0, 0);
75555   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
75556 }
75557         break;
75558       case 211: /* expr ::= MINUS expr */
75559 {
75560   yygotominor.yy172 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
75561   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
75562 }
75563         break;
75564       case 212: /* expr ::= PLUS expr */
75565 {
75566   yygotominor.yy172 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy172, 0, 0);
75567   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
75568 }
75569         break;
75570       case 215: /* expr ::= expr between_op expr AND expr */
75571 {
75572   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0);
75573   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0);
75574   yygotominor.yy172 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy172, 0, 0);
75575   if( yygotominor.yy172 ){
75576     yygotominor.yy172->pList = pList;
75577   }else{
75578     sqlite3ExprListDelete(pList);
75579   } 
75580   if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
75581   sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy172->span);
75582 }
75583         break;
75584       case 218: /* expr ::= expr in_op LP exprlist RP */
75585 {
75586     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0);
75587     if( yygotominor.yy172 ){
75588       yygotominor.yy172->pList = yymsp[-1].minor.yy174;
75589       sqlite3ExprSetHeight(yygotominor.yy172);
75590     }else{
75591       sqlite3ExprListDelete(yymsp[-1].minor.yy174);
75592     }
75593     if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
75594     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
75595   }
75596         break;
75597       case 219: /* expr ::= LP select RP */
75598 {
75599     yygotominor.yy172 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
75600     if( yygotominor.yy172 ){
75601       yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
75602       sqlite3ExprSetHeight(yygotominor.yy172);
75603     }else{
75604       sqlite3SelectDelete(yymsp[-1].minor.yy219);
75605     }
75606     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
75607   }
75608         break;
75609       case 220: /* expr ::= expr in_op LP select RP */
75610 {
75611     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0);
75612     if( yygotominor.yy172 ){
75613       yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
75614       sqlite3ExprSetHeight(yygotominor.yy172);
75615     }else{
75616       sqlite3SelectDelete(yymsp[-1].minor.yy219);
75617     }
75618     if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
75619     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
75620   }
75621         break;
75622       case 221: /* expr ::= expr in_op nm dbnm */
75623 {
75624     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);
75625     yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy172, 0, 0);
75626     if( yygotominor.yy172 ){
75627       yygotominor.yy172->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
75628       sqlite3ExprSetHeight(yygotominor.yy172);
75629     }else{
75630       sqlite3SrcListDelete(pSrc);
75631     }
75632     if( yymsp[-2].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0);
75633     sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,yymsp[0].minor.yy410.z?&yymsp[0].minor.yy410:&yymsp[-1].minor.yy410);
75634   }
75635         break;
75636       case 222: /* expr ::= EXISTS LP select RP */
75637 {
75638     Expr *p = yygotominor.yy172 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
75639     if( p ){
75640       p->pSelect = yymsp[-1].minor.yy219;
75641       sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
75642       sqlite3ExprSetHeight(yygotominor.yy172);
75643     }else{
75644       sqlite3SelectDelete(yymsp[-1].minor.yy219);
75645     }
75646   }
75647         break;
75648       case 223: /* expr ::= CASE case_operand case_exprlist case_else END */
75649 {
75650   yygotominor.yy172 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, 0);
75651   if( yygotominor.yy172 ){
75652     yygotominor.yy172->pList = yymsp[-2].minor.yy174;
75653     sqlite3ExprSetHeight(yygotominor.yy172);
75654   }else{
75655     sqlite3ExprListDelete(yymsp[-2].minor.yy174);
75656   }
75657   sqlite3ExprSpan(yygotominor.yy172, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
75658 }
75659         break;
75660       case 224: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
75661 {
75662   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, yymsp[-2].minor.yy172, 0);
75663   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0);
75664 }
75665         break;
75666       case 225: /* case_exprlist ::= WHEN expr THEN expr */
75667 {
75668   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0);
75669   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0);
75670 }
75671         break;
75672       case 234: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
75673 {
75674   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy410, &yymsp[-5].minor.yy410, 
75675                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy410,0), yymsp[-1].minor.yy174, yymsp[-9].minor.yy46,
75676                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy46);
75677 }
75678         break;
75679       case 235: /* uniqueflag ::= UNIQUE */
75680       case 283: /* raisetype ::= ABORT */
75681 {yygotominor.yy46 = OE_Abort;}
75682         break;
75683       case 236: /* uniqueflag ::= */
75684 {yygotominor.yy46 = OE_None;}
75685         break;
75686       case 239: /* idxlist ::= idxlist COMMA idxitem collate sortorder */
75687 {
75688   Expr *p = 0;
75689   if( yymsp[-1].minor.yy410.n>0 ){
75690     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
75691     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410);
75692   }
75693   yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, p, &yymsp[-2].minor.yy410);
75694   sqlite3ExprListCheckLength(pParse, yygotominor.yy174, "index");
75695   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
75696 }
75697         break;
75698       case 240: /* idxlist ::= idxitem collate sortorder */
75699 {
75700   Expr *p = 0;
75701   if( yymsp[-1].minor.yy410.n>0 ){
75702     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
75703     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410);
75704   }
75705   yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy410);
75706   sqlite3ExprListCheckLength(pParse, yygotominor.yy174, "index");
75707   if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
75708 }
75709         break;
75710       case 242: /* collate ::= */
75711 {yygotominor.yy410.z = 0; yygotominor.yy410.n = 0;}
75712         break;
75713       case 244: /* cmd ::= DROP INDEX ifexists fullname */
75714 {sqlite3DropIndex(pParse, yymsp[0].minor.yy373, yymsp[-1].minor.yy46);}
75715         break;
75716       case 245: /* cmd ::= VACUUM */
75717       case 246: /* cmd ::= VACUUM nm */
75718 {sqlite3Vacuum(pParse);}
75719         break;
75720       case 247: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
75721 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,0);}
75722         break;
75723       case 248: /* cmd ::= PRAGMA nm dbnm EQ ON */
75724       case 249: /* cmd ::= PRAGMA nm dbnm EQ DELETE */
75725 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy0,0);}
75726         break;
75727       case 250: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
75728 {
75729   sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,1);
75730 }
75731         break;
75732       case 251: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
75733 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-1].minor.yy410,0);}
75734         break;
75735       case 252: /* cmd ::= PRAGMA nm dbnm */
75736 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,0,0);}
75737         break;
75738       case 260: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
75739 {
75740   Token all;
75741   all.z = yymsp[-3].minor.yy410.z;
75742   all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy410.z) + yymsp[0].minor.yy0.n;
75743   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy243, &all);
75744 }
75745         break;
75746       case 261: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
75747 {
75748   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);
75749   yygotominor.yy410 = (yymsp[-6].minor.yy410.n==0?yymsp[-7].minor.yy410:yymsp[-6].minor.yy410);
75750 }
75751         break;
75752       case 262: /* trigger_time ::= BEFORE */
75753       case 265: /* trigger_time ::= */
75754 { yygotominor.yy46 = TK_BEFORE; }
75755         break;
75756       case 263: /* trigger_time ::= AFTER */
75757 { yygotominor.yy46 = TK_AFTER;  }
75758         break;
75759       case 264: /* trigger_time ::= INSTEAD OF */
75760 { yygotominor.yy46 = TK_INSTEAD;}
75761         break;
75762       case 266: /* trigger_event ::= DELETE|INSERT */
75763       case 267: /* trigger_event ::= UPDATE */
75764 {yygotominor.yy370.a = yymsp[0].major; yygotominor.yy370.b = 0;}
75765         break;
75766       case 268: /* trigger_event ::= UPDATE OF inscollist */
75767 {yygotominor.yy370.a = TK_UPDATE; yygotominor.yy370.b = yymsp[0].minor.yy432;}
75768         break;
75769       case 271: /* when_clause ::= */
75770       case 288: /* key_opt ::= */
75771 { yygotominor.yy172 = 0; }
75772         break;
75773       case 272: /* when_clause ::= WHEN expr */
75774       case 289: /* key_opt ::= KEY expr */
75775 { yygotominor.yy172 = yymsp[0].minor.yy172; }
75776         break;
75777       case 273: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
75778 {
75779   if( yymsp[-2].minor.yy243 ){
75780     yymsp[-2].minor.yy243->pLast->pNext = yymsp[-1].minor.yy243;
75781   }else{
75782     yymsp[-2].minor.yy243 = yymsp[-1].minor.yy243;
75783   }
75784   yymsp[-2].minor.yy243->pLast = yymsp[-1].minor.yy243;
75785   yygotominor.yy243 = yymsp[-2].minor.yy243;
75786 }
75787         break;
75788       case 274: /* trigger_cmd_list ::= */
75789 { yygotominor.yy243 = 0; }
75790         break;
75791       case 275: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
75792 { yygotominor.yy243 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy410, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); }
75793         break;
75794       case 276: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
75795 {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy410, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);}
75796         break;
75797       case 277: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
75798 {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy410, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);}
75799         break;
75800       case 278: /* trigger_cmd ::= DELETE FROM nm where_opt */
75801 {yygotominor.yy243 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy410, yymsp[0].minor.yy172);}
75802         break;
75803       case 279: /* trigger_cmd ::= select */
75804 {yygotominor.yy243 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy219); }
75805         break;
75806       case 280: /* expr ::= RAISE LP IGNORE RP */
75807 {
75808   yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
75809   if( yygotominor.yy172 ){
75810     yygotominor.yy172->iColumn = OE_Ignore;
75811     sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
75812   }
75813 }
75814         break;
75815       case 281: /* expr ::= RAISE LP raisetype COMMA nm RP */
75816 {
75817   yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy410); 
75818   if( yygotominor.yy172 ) {
75819     yygotominor.yy172->iColumn = yymsp[-3].minor.yy46;
75820     sqlite3ExprSpan(yygotominor.yy172, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
75821   }
75822 }
75823         break;
75824       case 282: /* raisetype ::= ROLLBACK */
75825 {yygotominor.yy46 = OE_Rollback;}
75826         break;
75827       case 284: /* raisetype ::= FAIL */
75828 {yygotominor.yy46 = OE_Fail;}
75829         break;
75830       case 285: /* cmd ::= DROP TRIGGER ifexists fullname */
75831 {
75832   sqlite3DropTrigger(pParse,yymsp[0].minor.yy373,yymsp[-1].minor.yy46);
75833 }
75834         break;
75835       case 286: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
75836 {
75837   sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy172);
75838 }
75839         break;
75840       case 287: /* cmd ::= DETACH database_kw_opt expr */
75841 {
75842   sqlite3Detach(pParse, yymsp[0].minor.yy172);
75843 }
75844         break;
75845       case 292: /* cmd ::= REINDEX */
75846 {sqlite3Reindex(pParse, 0, 0);}
75847         break;
75848       case 293: /* cmd ::= REINDEX nm dbnm */
75849 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
75850         break;
75851       case 294: /* cmd ::= ANALYZE */
75852 {sqlite3Analyze(pParse, 0, 0);}
75853         break;
75854       case 295: /* cmd ::= ANALYZE nm dbnm */
75855 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
75856         break;
75857       case 296: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
75858 {
75859   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy410);
75860 }
75861         break;
75862       case 297: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
75863 {
75864   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy410);
75865 }
75866         break;
75867       case 298: /* add_column_fullname ::= fullname */
75868 {
75869   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy373);
75870 }
75871         break;
75872       case 301: /* cmd ::= create_vtab */
75873 {sqlite3VtabFinishParse(pParse,0);}
75874         break;
75875       case 302: /* cmd ::= create_vtab LP vtabarglist RP */
75876 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
75877         break;
75878       case 303: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */
75879 {
75880     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, &yymsp[0].minor.yy410);
75881 }
75882         break;
75883       case 306: /* vtabarg ::= */
75884 {sqlite3VtabArgInit(pParse);}
75885         break;
75886       case 308: /* vtabargtoken ::= ANY */
75887       case 309: /* vtabargtoken ::= lp anylist RP */
75888       case 310: /* lp ::= LP */
75889       case 312: /* anylist ::= anylist ANY */
75890 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
75891         break;
75892   };
75893   yygoto = yyRuleInfo[yyruleno].lhs;
75894   yysize = yyRuleInfo[yyruleno].nrhs;
75895   yypParser->yyidx -= yysize;
75896   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
75897   if( yyact < YYNSTATE ){
75898 #ifdef NDEBUG
75899     /* If we are not debugging and the reduce action popped at least
75900     ** one element off the stack, then we can push the new element back
75901     ** onto the stack here, and skip the stack overflow test in yy_shift().
75902     ** That gives a significant speed improvement. */
75903     if( yysize ){
75904       yypParser->yyidx++;
75905       yymsp -= yysize-1;
75906       yymsp->stateno = yyact;
75907       yymsp->major = yygoto;
75908       yymsp->minor = yygotominor;
75909     }else
75910 #endif
75911     {
75912       yy_shift(yypParser,yyact,yygoto,&yygotominor);
75913     }
75914   }else{
75915     assert( yyact == YYNSTATE + YYNRULE + 1 );
75916     yy_accept(yypParser);
75917   }
75918 }
75919
75920 /*
75921 ** The following code executes when the parse fails
75922 */
75923 static void yy_parse_failed(
75924   yyParser *yypParser           /* The parser */
75925 ){
75926   sqlite3ParserARG_FETCH;
75927 #ifndef NDEBUG
75928   if( yyTraceFILE ){
75929     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
75930   }
75931 #endif
75932   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
75933   /* Here code is inserted which will be executed whenever the
75934   ** parser fails */
75935   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
75936 }
75937
75938 /*
75939 ** The following code executes when a syntax error first occurs.
75940 */
75941 static void yy_syntax_error(
75942   yyParser *yypParser,           /* The parser */
75943   int yymajor,                   /* The major type of the error token */
75944   YYMINORTYPE yyminor            /* The minor type of the error token */
75945 ){
75946   sqlite3ParserARG_FETCH;
75947 #define TOKEN (yyminor.yy0)
75948
75949   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
75950   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
75951   pParse->parseError = 1;
75952   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
75953 }
75954
75955 /*
75956 ** The following is executed when the parser accepts
75957 */
75958 static void yy_accept(
75959   yyParser *yypParser           /* The parser */
75960 ){
75961   sqlite3ParserARG_FETCH;
75962 #ifndef NDEBUG
75963   if( yyTraceFILE ){
75964     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
75965   }
75966 #endif
75967   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
75968   /* Here code is inserted which will be executed whenever the
75969   ** parser accepts */
75970   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
75971 }
75972
75973 /* The main parser program.
75974 ** The first argument is a pointer to a structure obtained from
75975 ** "sqlite3ParserAlloc" which describes the current state of the parser.
75976 ** The second argument is the major token number.  The third is
75977 ** the minor token.  The fourth optional argument is whatever the
75978 ** user wants (and specified in the grammar) and is available for
75979 ** use by the action routines.
75980 **
75981 ** Inputs:
75982 ** <ul>
75983 ** <li> A pointer to the parser (an opaque structure.)
75984 ** <li> The major token number.
75985 ** <li> The minor token number.
75986 ** <li> An option argument of a grammar-specified type.
75987 ** </ul>
75988 **
75989 ** Outputs:
75990 ** None.
75991 */
75992 SQLITE_PRIVATE void sqlite3Parser(
75993   void *yyp,                   /* The parser */
75994   int yymajor,                 /* The major token code number */
75995   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
75996   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
75997 ){
75998   YYMINORTYPE yyminorunion;
75999   int yyact;            /* The parser action. */
76000   int yyendofinput;     /* True if we are at the end of input */
76001 #ifdef YYERRORSYMBOL
76002   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
76003 #endif
76004   yyParser *yypParser;  /* The parser */
76005
76006   /* (re)initialize the parser, if necessary */
76007   yypParser = (yyParser*)yyp;
76008   if( yypParser->yyidx<0 ){
76009 #if YYSTACKDEPTH<=0
76010     if( yypParser->yystksz <=0 ){
76011       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
76012       yyminorunion = yyzerominor;
76013       yyStackOverflow(yypParser, &yyminorunion);
76014       return;
76015     }
76016 #endif
76017     yypParser->yyidx = 0;
76018     yypParser->yyerrcnt = -1;
76019     yypParser->yystack[0].stateno = 0;
76020     yypParser->yystack[0].major = 0;
76021   }
76022   yyminorunion.yy0 = yyminor;
76023   yyendofinput = (yymajor==0);
76024   sqlite3ParserARG_STORE;
76025
76026 #ifndef NDEBUG
76027   if( yyTraceFILE ){
76028     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
76029   }
76030 #endif
76031
76032   do{
76033     yyact = yy_find_shift_action(yypParser,yymajor);
76034     if( yyact<YYNSTATE ){
76035       assert( !yyendofinput );  /* Impossible to shift the $ token */
76036       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
76037       yypParser->yyerrcnt--;
76038       yymajor = YYNOCODE;
76039     }else if( yyact < YYNSTATE + YYNRULE ){
76040       yy_reduce(yypParser,yyact-YYNSTATE);
76041     }else{
76042       assert( yyact == YY_ERROR_ACTION );
76043 #ifdef YYERRORSYMBOL
76044       int yymx;
76045 #endif
76046 #ifndef NDEBUG
76047       if( yyTraceFILE ){
76048         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
76049       }
76050 #endif
76051 #ifdef YYERRORSYMBOL
76052       /* A syntax error has occurred.
76053       ** The response to an error depends upon whether or not the
76054       ** grammar defines an error token "ERROR".  
76055       **
76056       ** This is what we do if the grammar does define ERROR:
76057       **
76058       **  * Call the %syntax_error function.
76059       **
76060       **  * Begin popping the stack until we enter a state where
76061       **    it is legal to shift the error symbol, then shift
76062       **    the error symbol.
76063       **
76064       **  * Set the error count to three.
76065       **
76066       **  * Begin accepting and shifting new tokens.  No new error
76067       **    processing will occur until three tokens have been
76068       **    shifted successfully.
76069       **
76070       */
76071       if( yypParser->yyerrcnt<0 ){
76072         yy_syntax_error(yypParser,yymajor,yyminorunion);
76073       }
76074       yymx = yypParser->yystack[yypParser->yyidx].major;
76075       if( yymx==YYERRORSYMBOL || yyerrorhit ){
76076 #ifndef NDEBUG
76077         if( yyTraceFILE ){
76078           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
76079              yyTracePrompt,yyTokenName[yymajor]);
76080         }
76081 #endif
76082         yy_destructor(yymajor,&yyminorunion);
76083         yymajor = YYNOCODE;
76084       }else{
76085          while(
76086           yypParser->yyidx >= 0 &&
76087           yymx != YYERRORSYMBOL &&
76088           (yyact = yy_find_reduce_action(
76089                         yypParser->yystack[yypParser->yyidx].stateno,
76090                         YYERRORSYMBOL)) >= YYNSTATE
76091         ){
76092           yy_pop_parser_stack(yypParser);
76093         }
76094         if( yypParser->yyidx < 0 || yymajor==0 ){
76095           yy_destructor(yymajor,&yyminorunion);
76096           yy_parse_failed(yypParser);
76097           yymajor = YYNOCODE;
76098         }else if( yymx!=YYERRORSYMBOL ){
76099           YYMINORTYPE u2;
76100           u2.YYERRSYMDT = 0;
76101           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
76102         }
76103       }
76104       yypParser->yyerrcnt = 3;
76105       yyerrorhit = 1;
76106 #else  /* YYERRORSYMBOL is not defined */
76107       /* This is what we do if the grammar does not define ERROR:
76108       **
76109       **  * Report an error message, and throw away the input token.
76110       **
76111       **  * If the input token is $, then fail the parse.
76112       **
76113       ** As before, subsequent error messages are suppressed until
76114       ** three input tokens have been successfully shifted.
76115       */
76116       if( yypParser->yyerrcnt<=0 ){
76117         yy_syntax_error(yypParser,yymajor,yyminorunion);
76118       }
76119       yypParser->yyerrcnt = 3;
76120       yy_destructor(yymajor,&yyminorunion);
76121       if( yyendofinput ){
76122         yy_parse_failed(yypParser);
76123       }
76124       yymajor = YYNOCODE;
76125 #endif
76126     }
76127   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
76128   return;
76129 }
76130
76131 /************** End of parse.c ***********************************************/
76132 /************** Begin file tokenize.c ****************************************/
76133 /*
76134 ** 2001 September 15
76135 **
76136 ** The author disclaims copyright to this source code.  In place of
76137 ** a legal notice, here is a blessing:
76138 **
76139 **    May you do good and not evil.
76140 **    May you find forgiveness for yourself and forgive others.
76141 **    May you share freely, never taking more than you give.
76142 **
76143 *************************************************************************
76144 ** An tokenizer for SQL
76145 **
76146 ** This file contains C code that splits an SQL input string up into
76147 ** individual tokens and sends those tokens one-by-one over to the
76148 ** parser for analysis.
76149 **
76150 ** $Id: tokenize.c,v 1.142 2008/04/28 18:46:43 drh Exp $
76151 */
76152
76153 /*
76154 ** The charMap() macro maps alphabetic characters into their
76155 ** lower-case ASCII equivalent.  On ASCII machines, this is just
76156 ** an upper-to-lower case map.  On EBCDIC machines we also need
76157 ** to adjust the encoding.  Only alphabetic characters and underscores
76158 ** need to be translated.
76159 */
76160 #ifdef SQLITE_ASCII
76161 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
76162 #endif
76163 #ifdef SQLITE_EBCDIC
76164 # define charMap(X) ebcdicToAscii[(unsigned char)X]
76165 const unsigned char ebcdicToAscii[] = {
76166 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
76167    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
76168    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
76169    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
76170    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
76171    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
76172    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
76173    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
76174    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
76175    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
76176    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
76177    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
76178    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
76179    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
76180    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
76181    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
76182    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
76183 };
76184 #endif
76185
76186 /*
76187 ** The sqlite3KeywordCode function looks up an identifier to determine if
76188 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
76189 ** returned.  If the input is not a keyword, TK_ID is returned.
76190 **
76191 ** The implementation of this routine was generated by a program,
76192 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
76193 ** The output of the mkkeywordhash.c program is written into a file
76194 ** named keywordhash.h and then included into this source file by
76195 ** the #include below.
76196 */
76197 /************** Include keywordhash.h in the middle of tokenize.c ************/
76198 /************** Begin file keywordhash.h *************************************/
76199 /***** This file contains automatically generated code ******
76200 **
76201 ** The code in this file has been automatically generated by
76202 **
76203 **     $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.31 2007/07/30 18:26:20 rse Exp $
76204 **
76205 ** The code in this file implements a function that determines whether
76206 ** or not a given identifier is really an SQL keyword.  The same thing
76207 ** might be implemented more directly using a hand-written hash table.
76208 ** But by using this automatically generated code, the size of the code
76209 ** is substantially reduced.  This is important for embedded applications
76210 ** on platforms with limited memory.
76211 */
76212 /* Hash score: 165 */
76213 static int keywordCode(const char *z, int n){
76214   /* zText[] encodes 775 bytes of keywords in 526 bytes */
76215   static const char zText[526] =
76216     "BEFOREIGNOREGEXPLAINSTEADDESCAPEACHECKEYCONSTRAINTERSECTABLEFT"
76217     "HENDATABASELECTRANSACTIONATURALTERAISELSEXCEPTRIGGEREFERENCES"
76218     "UNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNEREINDEXCLUSIVEXISTSBETWEEN"
76219     "OTNULLIKECASCADEFERRABLECASECOLLATECREATECURRENT_DATEDELETEDETACH"
76220     "IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN"
76221     "WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICT"
76222     "CROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOB"
76223     "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM"
76224     "VIEWINITIALLY";
76225   static const unsigned char aHash[127] = {
76226       63,  92, 109,  61,   0,  38,   0,   0,  69,   0,  64,   0,   0,
76227      102,   4,  65,   7,   0, 108,  72, 103,  99,   0,  22,   0,   0,
76228      113,   0, 111, 106,   0,  18,  80,   0,   1,   0,   0,  56,  57,
76229        0,  55,  11,   0,  33,  77,  89,   0, 110,  88,   0,   0,  45,
76230        0,  90,  54,   0,  20,   0, 114,  34,  19,   0,  10,  97,  28,
76231       83,   0,   0, 116,  93,  47, 115,  41,  12,  44,   0,  78,   0,
76232       87,  29,   0,  86,   0,   0,   0,  82,  79,  84,  75,  96,   6,
76233       14,  95,   0,  68,   0,  21,  76,  98,  27,   0, 112,  67, 104,
76234       49,  40,  71,   0,   0,  81, 100,   0, 107,   0,  15,   0,   0,
76235       24,   0,  73,  42,  50,   0,  16,  48,   0,  37,
76236   };
76237   static const unsigned char aNext[116] = {
76238        0,   0,   0,   0,   0,   0,   0,   0,   0,   9,   0,   0,   0,
76239        0,   0,   0,   0,   5,   0,   0,   0,   0,   0,   0,   0,   0,
76240        0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  32,   0,   0,
76241       17,   0,   0,   0,  36,  39,   0,   0,  25,   0,   0,  31,   0,
76242        0,   0,  43,  52,   0,   0,   0,  53,   0,   0,   0,   0,   0,
76243        0,   0,   0,   0,  51,   0,   0,   0,   0,  26,   0,   8,  46,
76244        2,   0,   0,   0,   0,   0,   0,   0,   3,  58,  66,   0,  13,
76245        0,  91,  85,   0,  94,   0,  74,   0,   0,  62,   0,  35, 101,
76246        0,   0, 105,  23,  30,  60,  70,   0,   0,  59,   0,   0,
76247   };
76248   static const unsigned char aLen[116] = {
76249        6,   7,   3,   6,   6,   7,   7,   3,   4,   6,   4,   5,   3,
76250       10,   9,   5,   4,   4,   3,   8,   2,   6,  11,   2,   7,   5,
76251        5,   4,   6,   7,  10,   6,   5,   6,   6,   5,   6,   4,   9,
76252        2,   5,   5,   7,   5,   9,   6,   7,   7,   3,   4,   4,   7,
76253        3,  10,   4,   7,   6,  12,   6,   6,   9,   4,   6,   5,   4,
76254        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
76255       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
76256        2,   4,   4,   4,   4,   4,   2,   2,   4,   6,   2,   3,   6,
76257        5,   8,   5,   5,   8,   3,   5,   5,   6,   4,   9,   3,
76258   };
76259   static const unsigned short int aOffset[116] = {
76260        0,   2,   2,   6,  10,  13,  18,  23,  25,  26,  31,  33,  37,
76261       40,  47,  55,  58,  61,  63,  65,  70,  71,  76,  85,  86,  91,
76262       95,  99, 102, 107, 113, 123, 126, 131, 136, 141, 144, 148, 148,
76263      152, 157, 160, 164, 166, 169, 177, 183, 189, 189, 192, 195, 199,
76264      200, 204, 214, 218, 225, 231, 243, 249, 255, 264, 266, 272, 277,
76265      279, 286, 291, 296, 302, 308, 313, 317, 320, 326, 330, 337, 339,
76266      346, 348, 350, 359, 363, 369, 375, 383, 388, 388, 404, 411, 418,
76267      419, 426, 430, 434, 438, 442, 445, 447, 449, 452, 452, 455, 458,
76268      464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521,
76269   };
76270   static const unsigned char aCode[116] = {
76271     TK_BEFORE,     TK_FOREIGN,    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    
76272     TK_EXPLAIN,    TK_INSTEAD,    TK_ADD,        TK_DESC,       TK_ESCAPE,     
76273     TK_EACH,       TK_CHECK,      TK_KEY,        TK_CONSTRAINT, TK_INTERSECT,  
76274     TK_TABLE,      TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DATABASE,   
76275     TK_AS,         TK_SELECT,     TK_TRANSACTION,TK_ON,         TK_JOIN_KW,    
76276     TK_ALTER,      TK_RAISE,      TK_ELSE,       TK_EXCEPT,     TK_TRIGGER,    
76277     TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
76278     TK_GROUP,      TK_UPDATE,     TK_TEMP,       TK_TEMP,       TK_OR,         
76279     TK_BEGIN,      TK_JOIN_KW,    TK_REINDEX,    TK_INDEX,      TK_EXCLUSIVE,  
76280     TK_EXISTS,     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NULL,       
76281     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DEFERRABLE, TK_CASE,       
76282     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DELETE,     TK_DETACH,     
76283     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       
76284     TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    
76285     TK_LIMIT,      TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      
76286     TK_REPLACE,    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         
76287     TK_IN,         TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   
76288     TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   
76289     TK_DISTINCT,   TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       
76290     TK_JOIN_KW,    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_INTO,       
76291     TK_OFFSET,     TK_OF,         TK_SET,        TK_ISNULL,     TK_ORDER,      
76292     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
76293     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
76294     TK_ALL,        
76295   };
76296   int h, i;
76297   if( n<2 ) return TK_ID;
76298   h = ((charMap(z[0])*4) ^
76299       (charMap(z[n-1])*3) ^
76300       n) % 127;
76301   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
76302     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
76303       return aCode[i];
76304     }
76305   }
76306   return TK_ID;
76307 }
76308 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
76309   return keywordCode((char*)z, n);
76310 }
76311
76312 /************** End of keywordhash.h *****************************************/
76313 /************** Continuing where we left off in tokenize.c *******************/
76314
76315
76316 /*
76317 ** If X is a character that can be used in an identifier then
76318 ** IdChar(X) will be true.  Otherwise it is false.
76319 **
76320 ** For ASCII, any character with the high-order bit set is
76321 ** allowed in an identifier.  For 7-bit characters, 
76322 ** sqlite3IsIdChar[X] must be 1.
76323 **
76324 ** For EBCDIC, the rules are more complex but have the same
76325 ** end result.
76326 **
76327 ** Ticket #1066.  the SQL standard does not allow '$' in the
76328 ** middle of identfiers.  But many SQL implementations do. 
76329 ** SQLite will allow '$' in identifiers for compatibility.
76330 ** But the feature is undocumented.
76331 */
76332 #ifdef SQLITE_ASCII
76333 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
76334 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
76335     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
76336     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
76337     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
76338     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
76339     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
76340     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
76341 };
76342 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
76343 #endif
76344 #ifdef SQLITE_EBCDIC
76345 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
76346 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
76347     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
76348     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
76349     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
76350     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
76351     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
76352     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
76353     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
76354     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
76355     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
76356     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
76357     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
76358     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
76359 };
76360 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
76361 #endif
76362
76363
76364 /*
76365 ** Return the length of the token that begins at z[0]. 
76366 ** Store the token type in *tokenType before returning.
76367 */
76368 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
76369   int i, c;
76370   switch( *z ){
76371     case ' ': case '\t': case '\n': case '\f': case '\r': {
76372       for(i=1; isspace(z[i]); i++){}
76373       *tokenType = TK_SPACE;
76374       return i;
76375     }
76376     case '-': {
76377       if( z[1]=='-' ){
76378         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
76379         *tokenType = TK_COMMENT;
76380         return i;
76381       }
76382       *tokenType = TK_MINUS;
76383       return 1;
76384     }
76385     case '(': {
76386       *tokenType = TK_LP;
76387       return 1;
76388     }
76389     case ')': {
76390       *tokenType = TK_RP;
76391       return 1;
76392     }
76393     case ';': {
76394       *tokenType = TK_SEMI;
76395       return 1;
76396     }
76397     case '+': {
76398       *tokenType = TK_PLUS;
76399       return 1;
76400     }
76401     case '*': {
76402       *tokenType = TK_STAR;
76403       return 1;
76404     }
76405     case '/': {
76406       if( z[1]!='*' || z[2]==0 ){
76407         *tokenType = TK_SLASH;
76408         return 1;
76409       }
76410       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
76411       if( c ) i++;
76412       *tokenType = TK_COMMENT;
76413       return i;
76414     }
76415     case '%': {
76416       *tokenType = TK_REM;
76417       return 1;
76418     }
76419     case '=': {
76420       *tokenType = TK_EQ;
76421       return 1 + (z[1]=='=');
76422     }
76423     case '<': {
76424       if( (c=z[1])=='=' ){
76425         *tokenType = TK_LE;
76426         return 2;
76427       }else if( c=='>' ){
76428         *tokenType = TK_NE;
76429         return 2;
76430       }else if( c=='<' ){
76431         *tokenType = TK_LSHIFT;
76432         return 2;
76433       }else{
76434         *tokenType = TK_LT;
76435         return 1;
76436       }
76437     }
76438     case '>': {
76439       if( (c=z[1])=='=' ){
76440         *tokenType = TK_GE;
76441         return 2;
76442       }else if( c=='>' ){
76443         *tokenType = TK_RSHIFT;
76444         return 2;
76445       }else{
76446         *tokenType = TK_GT;
76447         return 1;
76448       }
76449     }
76450     case '!': {
76451       if( z[1]!='=' ){
76452         *tokenType = TK_ILLEGAL;
76453         return 2;
76454       }else{
76455         *tokenType = TK_NE;
76456         return 2;
76457       }
76458     }
76459     case '|': {
76460       if( z[1]!='|' ){
76461         *tokenType = TK_BITOR;
76462         return 1;
76463       }else{
76464         *tokenType = TK_CONCAT;
76465         return 2;
76466       }
76467     }
76468     case ',': {
76469       *tokenType = TK_COMMA;
76470       return 1;
76471     }
76472     case '&': {
76473       *tokenType = TK_BITAND;
76474       return 1;
76475     }
76476     case '~': {
76477       *tokenType = TK_BITNOT;
76478       return 1;
76479     }
76480     case '`':
76481     case '\'':
76482     case '"': {
76483       int delim = z[0];
76484       for(i=1; (c=z[i])!=0; i++){
76485         if( c==delim ){
76486           if( z[i+1]==delim ){
76487             i++;
76488           }else{
76489             break;
76490           }
76491         }
76492       }
76493       if( c ){
76494         *tokenType = TK_STRING;
76495         return i+1;
76496       }else{
76497         *tokenType = TK_ILLEGAL;
76498         return i;
76499       }
76500     }
76501     case '.': {
76502 #ifndef SQLITE_OMIT_FLOATING_POINT
76503       if( !isdigit(z[1]) )
76504 #endif
76505       {
76506         *tokenType = TK_DOT;
76507         return 1;
76508       }
76509       /* If the next character is a digit, this is a floating point
76510       ** number that begins with ".".  Fall thru into the next case */
76511     }
76512     case '0': case '1': case '2': case '3': case '4':
76513     case '5': case '6': case '7': case '8': case '9': {
76514       *tokenType = TK_INTEGER;
76515       for(i=0; isdigit(z[i]); i++){}
76516 #ifndef SQLITE_OMIT_FLOATING_POINT
76517       if( z[i]=='.' ){
76518         i++;
76519         while( isdigit(z[i]) ){ i++; }
76520         *tokenType = TK_FLOAT;
76521       }
76522       if( (z[i]=='e' || z[i]=='E') &&
76523            ( isdigit(z[i+1]) 
76524             || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
76525            )
76526       ){
76527         i += 2;
76528         while( isdigit(z[i]) ){ i++; }
76529         *tokenType = TK_FLOAT;
76530       }
76531 #endif
76532       while( IdChar(z[i]) ){
76533         *tokenType = TK_ILLEGAL;
76534         i++;
76535       }
76536       return i;
76537     }
76538     case '[': {
76539       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
76540       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
76541       return i;
76542     }
76543     case '?': {
76544       *tokenType = TK_VARIABLE;
76545       for(i=1; isdigit(z[i]); i++){}
76546       return i;
76547     }
76548     case '#': {
76549       for(i=1; isdigit(z[i]); i++){}
76550       if( i>1 ){
76551         /* Parameters of the form #NNN (where NNN is a number) are used
76552         ** internally by sqlite3NestedParse.  */
76553         *tokenType = TK_REGISTER;
76554         return i;
76555       }
76556       /* Fall through into the next case if the '#' is not followed by
76557       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
76558     }
76559 #ifndef SQLITE_OMIT_TCL_VARIABLE
76560     case '$':
76561 #endif
76562     case '@':  /* For compatibility with MS SQL Server */
76563     case ':': {
76564       int n = 0;
76565       *tokenType = TK_VARIABLE;
76566       for(i=1; (c=z[i])!=0; i++){
76567         if( IdChar(c) ){
76568           n++;
76569 #ifndef SQLITE_OMIT_TCL_VARIABLE
76570         }else if( c=='(' && n>0 ){
76571           do{
76572             i++;
76573           }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
76574           if( c==')' ){
76575             i++;
76576           }else{
76577             *tokenType = TK_ILLEGAL;
76578           }
76579           break;
76580         }else if( c==':' && z[i+1]==':' ){
76581           i++;
76582 #endif
76583         }else{
76584           break;
76585         }
76586       }
76587       if( n==0 ) *tokenType = TK_ILLEGAL;
76588       return i;
76589     }
76590 #ifndef SQLITE_OMIT_BLOB_LITERAL
76591     case 'x': case 'X': {
76592       if( z[1]=='\'' ){
76593         *tokenType = TK_BLOB;
76594         for(i=2; (c=z[i])!=0 && c!='\''; i++){
76595           if( !isxdigit(c) ){
76596             *tokenType = TK_ILLEGAL;
76597           }
76598         }
76599         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
76600         if( c ) i++;
76601         return i;
76602       }
76603       /* Otherwise fall through to the next case */
76604     }
76605 #endif
76606     default: {
76607       if( !IdChar(*z) ){
76608         break;
76609       }
76610       for(i=1; IdChar(z[i]); i++){}
76611       *tokenType = keywordCode((char*)z, i);
76612       return i;
76613     }
76614   }
76615   *tokenType = TK_ILLEGAL;
76616   return 1;
76617 }
76618
76619 /*
76620 ** Run the parser on the given SQL string.  The parser structure is
76621 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
76622 ** and pzErrMsg!=NULL then an error message might be written into 
76623 ** memory obtained from sqlite3_malloc() and *pzErrMsg made to point to that
76624 ** error message.  Or maybe not.
76625 */
76626 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
76627   int nErr = 0;
76628   int i;
76629   void *pEngine;
76630   int tokenType;
76631   int lastTokenParsed = -1;
76632   sqlite3 *db = pParse->db;
76633   int mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
76634
76635   if( db->activeVdbeCnt==0 ){
76636     db->u1.isInterrupted = 0;
76637   }
76638   pParse->rc = SQLITE_OK;
76639   pParse->zTail = pParse->zSql = zSql;
76640   i = 0;
76641   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3_malloc);
76642   if( pEngine==0 ){
76643     db->mallocFailed = 1;
76644     return SQLITE_NOMEM;
76645   }
76646   assert( pParse->sLastToken.dyn==0 );
76647   assert( pParse->pNewTable==0 );
76648   assert( pParse->pNewTrigger==0 );
76649   assert( pParse->nVar==0 );
76650   assert( pParse->nVarExpr==0 );
76651   assert( pParse->nVarExprAlloc==0 );
76652   assert( pParse->apVarExpr==0 );
76653   while( !db->mallocFailed && zSql[i]!=0 ){
76654     assert( i>=0 );
76655     pParse->sLastToken.z = (u8*)&zSql[i];
76656     assert( pParse->sLastToken.dyn==0 );
76657     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
76658     i += pParse->sLastToken.n;
76659     if( i>mxSqlLen ){
76660       pParse->rc = SQLITE_TOOBIG;
76661       break;
76662     }
76663     switch( tokenType ){
76664       case TK_SPACE:
76665       case TK_COMMENT: {
76666         if( db->u1.isInterrupted ){
76667           pParse->rc = SQLITE_INTERRUPT;
76668           sqlite3SetString(pzErrMsg, "interrupt", (char*)0);
76669           goto abort_parse;
76670         }
76671         break;
76672       }
76673       case TK_ILLEGAL: {
76674         if( pzErrMsg ){
76675           sqlite3_free(*pzErrMsg);
76676           *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
76677                           &pParse->sLastToken);
76678         }
76679         nErr++;
76680         goto abort_parse;
76681       }
76682       case TK_SEMI: {
76683         pParse->zTail = &zSql[i];
76684         /* Fall thru into the default case */
76685       }
76686       default: {
76687         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
76688         lastTokenParsed = tokenType;
76689         if( pParse->rc!=SQLITE_OK ){
76690           goto abort_parse;
76691         }
76692         break;
76693       }
76694     }
76695   }
76696 abort_parse:
76697   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
76698     if( lastTokenParsed!=TK_SEMI ){
76699       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
76700       pParse->zTail = &zSql[i];
76701     }
76702     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
76703   }
76704   sqlite3ParserFree(pEngine, sqlite3_free);
76705   if( db->mallocFailed ){
76706     pParse->rc = SQLITE_NOMEM;
76707   }
76708   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
76709     sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc), (char*)0);
76710   }
76711   if( pParse->zErrMsg ){
76712     if( pzErrMsg && *pzErrMsg==0 ){
76713       *pzErrMsg = pParse->zErrMsg;
76714     }else{
76715       sqlite3_free(pParse->zErrMsg);
76716     }
76717     pParse->zErrMsg = 0;
76718     nErr++;
76719   }
76720   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
76721     sqlite3VdbeDelete(pParse->pVdbe);
76722     pParse->pVdbe = 0;
76723   }
76724 #ifndef SQLITE_OMIT_SHARED_CACHE
76725   if( pParse->nested==0 ){
76726     sqlite3_free(pParse->aTableLock);
76727     pParse->aTableLock = 0;
76728     pParse->nTableLock = 0;
76729   }
76730 #endif
76731 #ifndef SQLITE_OMIT_VIRTUALTABLE
76732   sqlite3_free(pParse->apVtabLock);
76733 #endif
76734
76735   if( !IN_DECLARE_VTAB ){
76736     /* If the pParse->declareVtab flag is set, do not delete any table 
76737     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
76738     ** will take responsibility for freeing the Table structure.
76739     */
76740     sqlite3DeleteTable(pParse->pNewTable);
76741   }
76742
76743   sqlite3DeleteTrigger(pParse->pNewTrigger);
76744   sqlite3_free(pParse->apVarExpr);
76745   if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
76746     pParse->rc = SQLITE_ERROR;
76747   }
76748   return nErr;
76749 }
76750
76751 /************** End of tokenize.c ********************************************/
76752 /************** Begin file complete.c ****************************************/
76753 /*
76754 ** 2001 September 15
76755 **
76756 ** The author disclaims copyright to this source code.  In place of
76757 ** a legal notice, here is a blessing:
76758 **
76759 **    May you do good and not evil.
76760 **    May you find forgiveness for yourself and forgive others.
76761 **    May you share freely, never taking more than you give.
76762 **
76763 *************************************************************************
76764 ** An tokenizer for SQL
76765 **
76766 ** This file contains C code that implements the sqlite3_complete() API.
76767 ** This code used to be part of the tokenizer.c source file.  But by
76768 ** separating it out, the code will be automatically omitted from
76769 ** static links that do not use it.
76770 **
76771 ** $Id: complete.c,v 1.6 2007/08/27 23:26:59 drh Exp $
76772 */
76773 #ifndef SQLITE_OMIT_COMPLETE
76774
76775 /*
76776 ** This is defined in tokenize.c.  We just have to import the definition.
76777 */
76778 #ifndef SQLITE_AMALGAMATION
76779 #ifdef SQLITE_ASCII
76780 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
76781 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
76782 #endif
76783 #ifdef SQLITE_EBCDIC
76784 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
76785 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
76786 #endif
76787 #endif /* SQLITE_AMALGAMATION */
76788
76789
76790 /*
76791 ** Token types used by the sqlite3_complete() routine.  See the header
76792 ** comments on that procedure for additional information.
76793 */
76794 #define tkSEMI    0
76795 #define tkWS      1
76796 #define tkOTHER   2
76797 #define tkEXPLAIN 3
76798 #define tkCREATE  4
76799 #define tkTEMP    5
76800 #define tkTRIGGER 6
76801 #define tkEND     7
76802
76803 /*
76804 ** Return TRUE if the given SQL string ends in a semicolon.
76805 **
76806 ** Special handling is require for CREATE TRIGGER statements.
76807 ** Whenever the CREATE TRIGGER keywords are seen, the statement
76808 ** must end with ";END;".
76809 **
76810 ** This implementation uses a state machine with 7 states:
76811 **
76812 **   (0) START     At the beginning or end of an SQL statement.  This routine
76813 **                 returns 1 if it ends in the START state and 0 if it ends
76814 **                 in any other state.
76815 **
76816 **   (1) NORMAL    We are in the middle of statement which ends with a single
76817 **                 semicolon.
76818 **
76819 **   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
76820 **                 a statement.
76821 **
76822 **   (3) CREATE    The keyword CREATE has been seen at the beginning of a
76823 **                 statement, possibly preceeded by EXPLAIN and/or followed by
76824 **                 TEMP or TEMPORARY
76825 **
76826 **   (4) TRIGGER   We are in the middle of a trigger definition that must be
76827 **                 ended by a semicolon, the keyword END, and another semicolon.
76828 **
76829 **   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
76830 **                 the end of a trigger definition.
76831 **
76832 **   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
76833 **                 of a trigger difinition.
76834 **
76835 ** Transitions between states above are determined by tokens extracted
76836 ** from the input.  The following tokens are significant:
76837 **
76838 **   (0) tkSEMI      A semicolon.
76839 **   (1) tkWS        Whitespace
76840 **   (2) tkOTHER     Any other SQL token.
76841 **   (3) tkEXPLAIN   The "explain" keyword.
76842 **   (4) tkCREATE    The "create" keyword.
76843 **   (5) tkTEMP      The "temp" or "temporary" keyword.
76844 **   (6) tkTRIGGER   The "trigger" keyword.
76845 **   (7) tkEND       The "end" keyword.
76846 **
76847 ** Whitespace never causes a state transition and is always ignored.
76848 **
76849 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
76850 ** to recognize the end of a trigger can be omitted.  All we have to do
76851 ** is look for a semicolon that is not part of an string or comment.
76852 */
76853 SQLITE_API int sqlite3_complete(const char *zSql){
76854   u8 state = 0;   /* Current state, using numbers defined in header comment */
76855   u8 token;       /* Value of the next token */
76856
76857 #ifndef SQLITE_OMIT_TRIGGER
76858   /* A complex statement machine used to detect the end of a CREATE TRIGGER
76859   ** statement.  This is the normal case.
76860   */
76861   static const u8 trans[7][8] = {
76862                      /* Token:                                                */
76863      /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
76864      /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
76865      /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
76866      /* 2 EXPLAIN: */ {    0,  2,     1,      1,      3,    1,       1,   1,  },
76867      /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
76868      /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
76869      /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
76870      /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
76871   };
76872 #else
76873   /* If triggers are not suppored by this compile then the statement machine
76874   ** used to detect the end of a statement is much simplier
76875   */
76876   static const u8 trans[2][3] = {
76877                      /* Token:           */
76878      /* State:       **  SEMI  WS  OTHER */
76879      /* 0   START: */ {    0,  0,     1, },
76880      /* 1  NORMAL: */ {    0,  1,     1, },
76881   };
76882 #endif /* SQLITE_OMIT_TRIGGER */
76883
76884   while( *zSql ){
76885     switch( *zSql ){
76886       case ';': {  /* A semicolon */
76887         token = tkSEMI;
76888         break;
76889       }
76890       case ' ':
76891       case '\r':
76892       case '\t':
76893       case '\n':
76894       case '\f': {  /* White space is ignored */
76895         token = tkWS;
76896         break;
76897       }
76898       case '/': {   /* C-style comments */
76899         if( zSql[1]!='*' ){
76900           token = tkOTHER;
76901           break;
76902         }
76903         zSql += 2;
76904         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
76905         if( zSql[0]==0 ) return 0;
76906         zSql++;
76907         token = tkWS;
76908         break;
76909       }
76910       case '-': {   /* SQL-style comments from "--" to end of line */
76911         if( zSql[1]!='-' ){
76912           token = tkOTHER;
76913           break;
76914         }
76915         while( *zSql && *zSql!='\n' ){ zSql++; }
76916         if( *zSql==0 ) return state==0;
76917         token = tkWS;
76918         break;
76919       }
76920       case '[': {   /* Microsoft-style identifiers in [...] */
76921         zSql++;
76922         while( *zSql && *zSql!=']' ){ zSql++; }
76923         if( *zSql==0 ) return 0;
76924         token = tkOTHER;
76925         break;
76926       }
76927       case '`':     /* Grave-accent quoted symbols used by MySQL */
76928       case '"':     /* single- and double-quoted strings */
76929       case '\'': {
76930         int c = *zSql;
76931         zSql++;
76932         while( *zSql && *zSql!=c ){ zSql++; }
76933         if( *zSql==0 ) return 0;
76934         token = tkOTHER;
76935         break;
76936       }
76937       default: {
76938         int c;
76939         if( IdChar((u8)*zSql) ){
76940           /* Keywords and unquoted identifiers */
76941           int nId;
76942           for(nId=1; IdChar(zSql[nId]); nId++){}
76943 #ifdef SQLITE_OMIT_TRIGGER
76944           token = tkOTHER;
76945 #else
76946           switch( *zSql ){
76947             case 'c': case 'C': {
76948               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
76949                 token = tkCREATE;
76950               }else{
76951                 token = tkOTHER;
76952               }
76953               break;
76954             }
76955             case 't': case 'T': {
76956               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
76957                 token = tkTRIGGER;
76958               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
76959                 token = tkTEMP;
76960               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
76961                 token = tkTEMP;
76962               }else{
76963                 token = tkOTHER;
76964               }
76965               break;
76966             }
76967             case 'e':  case 'E': {
76968               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
76969                 token = tkEND;
76970               }else
76971 #ifndef SQLITE_OMIT_EXPLAIN
76972               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
76973                 token = tkEXPLAIN;
76974               }else
76975 #endif
76976               {
76977                 token = tkOTHER;
76978               }
76979               break;
76980             }
76981             default: {
76982               token = tkOTHER;
76983               break;
76984             }
76985           }
76986 #endif /* SQLITE_OMIT_TRIGGER */
76987           zSql += nId-1;
76988         }else{
76989           /* Operators and special symbols */
76990           token = tkOTHER;
76991         }
76992         break;
76993       }
76994     }
76995     state = trans[state][token];
76996     zSql++;
76997   }
76998   return state==0;
76999 }
77000
77001 #ifndef SQLITE_OMIT_UTF16
77002 /*
77003 ** This routine is the same as the sqlite3_complete() routine described
77004 ** above, except that the parameter is required to be UTF-16 encoded, not
77005 ** UTF-8.
77006 */
77007 SQLITE_API int sqlite3_complete16(const void *zSql){
77008   sqlite3_value *pVal;
77009   char const *zSql8;
77010   int rc = SQLITE_NOMEM;
77011
77012   pVal = sqlite3ValueNew(0);
77013   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
77014   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
77015   if( zSql8 ){
77016     rc = sqlite3_complete(zSql8);
77017   }
77018   sqlite3ValueFree(pVal);
77019   return sqlite3ApiExit(0, rc);
77020 }
77021 #endif /* SQLITE_OMIT_UTF16 */
77022 #endif /* SQLITE_OMIT_COMPLETE */
77023
77024 /************** End of complete.c ********************************************/
77025 /************** Begin file main.c ********************************************/
77026 /*
77027 ** 2001 September 15
77028 **
77029 ** The author disclaims copyright to this source code.  In place of
77030 ** a legal notice, here is a blessing:
77031 **
77032 **    May you do good and not evil.
77033 **    May you find forgiveness for yourself and forgive others.
77034 **    May you share freely, never taking more than you give.
77035 **
77036 *************************************************************************
77037 ** Main file for the SQLite library.  The routines in this file
77038 ** implement the programmer interface to the library.  Routines in
77039 ** other files are for internal use by SQLite and should not be
77040 ** accessed by users of the library.
77041 **
77042 ** $Id: main.c,v 1.439 2008/05/13 13:27:34 drh Exp $
77043 */
77044 #ifdef SQLITE_ENABLE_FTS3
77045 /************** Include fts3.h in the middle of main.c ***********************/
77046 /************** Begin file fts3.h ********************************************/
77047 /*
77048 ** 2006 Oct 10
77049 **
77050 ** The author disclaims copyright to this source code.  In place of
77051 ** a legal notice, here is a blessing:
77052 **
77053 **    May you do good and not evil.
77054 **    May you find forgiveness for yourself and forgive others.
77055 **    May you share freely, never taking more than you give.
77056 **
77057 ******************************************************************************
77058 **
77059 ** This header file is used by programs that want to link against the
77060 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
77061 */
77062
77063 #if 0
77064 extern "C" {
77065 #endif  /* __cplusplus */
77066
77067 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
77068
77069 #if 0
77070 }  /* extern "C" */
77071 #endif  /* __cplusplus */
77072
77073 /************** End of fts3.h ************************************************/
77074 /************** Continuing where we left off in main.c ***********************/
77075 #endif
77076
77077 /*
77078 ** The version of the library
77079 */
77080 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
77081 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
77082 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
77083 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
77084
77085 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
77086 /*
77087 ** If the following function pointer is not NULL and if
77088 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
77089 ** I/O active are written using this function.  These messages
77090 ** are intended for debugging activity only.
77091 */
77092 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
77093 #endif
77094
77095 /*
77096 ** If the following global variable points to a string which is the
77097 ** name of a directory, then that directory will be used to store
77098 ** temporary files.
77099 **
77100 ** See also the "PRAGMA temp_store_directory" SQL command.
77101 */
77102 SQLITE_API char *sqlite3_temp_directory = 0;
77103
77104 /*
77105 ** Routine needed to support the testcase() macro.
77106 */
77107 #ifdef SQLITE_COVERAGE_TEST
77108 SQLITE_PRIVATE void sqlite3Coverage(int x){
77109   static int dummy = 0;
77110   dummy += x;
77111 }
77112 #endif
77113
77114
77115 /*
77116 ** Return true if the buffer z[0..n-1] contains all spaces.
77117 */
77118 static int allSpaces(const char *z, int n){
77119   while( n>0 && z[n-1]==' ' ){ n--; }
77120   return n==0;
77121 }
77122
77123 /*
77124 ** This is the default collating function named "BINARY" which is always
77125 ** available.
77126 **
77127 ** If the padFlag argument is not NULL then space padding at the end
77128 ** of strings is ignored.  This implements the RTRIM collation.
77129 */
77130 static int binCollFunc(
77131   void *padFlag,
77132   int nKey1, const void *pKey1,
77133   int nKey2, const void *pKey2
77134 ){
77135   int rc, n;
77136   n = nKey1<nKey2 ? nKey1 : nKey2;
77137   rc = memcmp(pKey1, pKey2, n);
77138   if( rc==0 ){
77139     if( padFlag
77140      && allSpaces(((char*)pKey1)+n, nKey1-n)
77141      && allSpaces(((char*)pKey2)+n, nKey2-n)
77142     ){
77143       /* Leave rc unchanged at 0 */
77144     }else{
77145       rc = nKey1 - nKey2;
77146     }
77147   }
77148   return rc;
77149 }
77150
77151 /*
77152 ** Another built-in collating sequence: NOCASE. 
77153 **
77154 ** This collating sequence is intended to be used for "case independant
77155 ** comparison". SQLite's knowledge of upper and lower case equivalents
77156 ** extends only to the 26 characters used in the English language.
77157 **
77158 ** At the moment there is only a UTF-8 implementation.
77159 */
77160 static int nocaseCollatingFunc(
77161   void *NotUsed,
77162   int nKey1, const void *pKey1,
77163   int nKey2, const void *pKey2
77164 ){
77165   int r = sqlite3StrNICmp(
77166       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
77167   if( 0==r ){
77168     r = nKey1-nKey2;
77169   }
77170   return r;
77171 }
77172
77173 /*
77174 ** Return the ROWID of the most recent insert
77175 */
77176 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
77177   return db->lastRowid;
77178 }
77179
77180 /*
77181 ** Return the number of changes in the most recent call to sqlite3_exec().
77182 */
77183 SQLITE_API int sqlite3_changes(sqlite3 *db){
77184   return db->nChange;
77185 }
77186
77187 /*
77188 ** Return the number of changes since the database handle was opened.
77189 */
77190 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
77191   return db->nTotalChange;
77192 }
77193
77194 /*
77195 ** Close an existing SQLite database
77196 */
77197 SQLITE_API int sqlite3_close(sqlite3 *db){
77198   HashElem *i;
77199   int j;
77200
77201   if( !db ){
77202     return SQLITE_OK;
77203   }
77204   if( !sqlite3SafetyCheckSickOrOk(db) ){
77205     return SQLITE_MISUSE;
77206   }
77207   sqlite3_mutex_enter(db->mutex);
77208
77209 #ifdef SQLITE_SSE
77210   {
77211     extern void sqlite3SseCleanup(sqlite3*);
77212     sqlite3SseCleanup(db);
77213   }
77214 #endif 
77215
77216   sqlite3ResetInternalSchema(db, 0);
77217
77218   /* If a transaction is open, the ResetInternalSchema() call above
77219   ** will not have called the xDisconnect() method on any virtual
77220   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
77221   ** call will do so. We need to do this before the check for active
77222   ** SQL statements below, as the v-table implementation may be storing
77223   ** some prepared statements internally.
77224   */
77225   sqlite3VtabRollback(db);
77226
77227   /* If there are any outstanding VMs, return SQLITE_BUSY. */
77228   if( db->pVdbe ){
77229     sqlite3Error(db, SQLITE_BUSY, 
77230         "Unable to close due to unfinalised statements");
77231     sqlite3_mutex_leave(db->mutex);
77232     return SQLITE_BUSY;
77233   }
77234   assert( sqlite3SafetyCheckSickOrOk(db) );
77235
77236   for(j=0; j<db->nDb; j++){
77237     struct Db *pDb = &db->aDb[j];
77238     if( pDb->pBt ){
77239       sqlite3BtreeClose(pDb->pBt);
77240       pDb->pBt = 0;
77241       if( j!=1 ){
77242         pDb->pSchema = 0;
77243       }
77244     }
77245   }
77246   sqlite3ResetInternalSchema(db, 0);
77247   assert( db->nDb<=2 );
77248   assert( db->aDb==db->aDbStatic );
77249   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
77250     FuncDef *pFunc, *pNext;
77251     for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
77252       pNext = pFunc->pNext;
77253       sqlite3_free(pFunc);
77254     }
77255   }
77256
77257   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
77258     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
77259     /* Invoke any destructors registered for collation sequence user data. */
77260     for(j=0; j<3; j++){
77261       if( pColl[j].xDel ){
77262         pColl[j].xDel(pColl[j].pUser);
77263       }
77264     }
77265     sqlite3_free(pColl);
77266   }
77267   sqlite3HashClear(&db->aCollSeq);
77268 #ifndef SQLITE_OMIT_VIRTUALTABLE
77269   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
77270     Module *pMod = (Module *)sqliteHashData(i);
77271     if( pMod->xDestroy ){
77272       pMod->xDestroy(pMod->pAux);
77273     }
77274     sqlite3_free(pMod);
77275   }
77276   sqlite3HashClear(&db->aModule);
77277 #endif
77278
77279   sqlite3HashClear(&db->aFunc);
77280   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
77281   if( db->pErr ){
77282     sqlite3ValueFree(db->pErr);
77283   }
77284   sqlite3CloseExtensions(db);
77285
77286   db->magic = SQLITE_MAGIC_ERROR;
77287
77288   /* The temp-database schema is allocated differently from the other schema
77289   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
77290   ** So it needs to be freed here. Todo: Why not roll the temp schema into
77291   ** the same sqliteMalloc() as the one that allocates the database 
77292   ** structure?
77293   */
77294   sqlite3_free(db->aDb[1].pSchema);
77295   sqlite3_mutex_leave(db->mutex);
77296   db->magic = SQLITE_MAGIC_CLOSED;
77297   sqlite3_mutex_free(db->mutex);
77298   sqlite3_free(db);
77299   return SQLITE_OK;
77300 }
77301
77302 /*
77303 ** Rollback all database files.
77304 */
77305 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
77306   int i;
77307   int inTrans = 0;
77308   assert( sqlite3_mutex_held(db->mutex) );
77309   sqlite3FaultBeginBenign(SQLITE_FAULTINJECTOR_MALLOC);
77310   for(i=0; i<db->nDb; i++){
77311     if( db->aDb[i].pBt ){
77312       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
77313         inTrans = 1;
77314       }
77315       sqlite3BtreeRollback(db->aDb[i].pBt);
77316       db->aDb[i].inTrans = 0;
77317     }
77318   }
77319   sqlite3VtabRollback(db);
77320   sqlite3FaultEndBenign(SQLITE_FAULTINJECTOR_MALLOC);
77321
77322   if( db->flags&SQLITE_InternChanges ){
77323     sqlite3ExpirePreparedStatements(db);
77324     sqlite3ResetInternalSchema(db, 0);
77325   }
77326
77327   /* If one has been configured, invoke the rollback-hook callback */
77328   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
77329     db->xRollbackCallback(db->pRollbackArg);
77330   }
77331 }
77332
77333 /*
77334 ** Return a static string that describes the kind of error specified in the
77335 ** argument.
77336 */
77337 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
77338   const char *z;
77339   switch( rc & 0xff ){
77340     case SQLITE_ROW:
77341     case SQLITE_DONE:
77342     case SQLITE_OK:         z = "not an error";                          break;
77343     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
77344     case SQLITE_PERM:       z = "access permission denied";              break;
77345     case SQLITE_ABORT:      z = "callback requested query abort";        break;
77346     case SQLITE_BUSY:       z = "database is locked";                    break;
77347     case SQLITE_LOCKED:     z = "database table is locked";              break;
77348     case SQLITE_NOMEM:      z = "out of memory";                         break;
77349     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
77350     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
77351     case SQLITE_IOERR:      z = "disk I/O error";                        break;
77352     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
77353     case SQLITE_FULL:       z = "database or disk is full";              break;
77354     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
77355     case SQLITE_EMPTY:      z = "table contains no data";                break;
77356     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
77357     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
77358     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
77359     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
77360     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
77361     case SQLITE_NOLFS:      z = "large file support is disabled";        break;
77362     case SQLITE_AUTH:       z = "authorization denied";                  break;
77363     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
77364     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
77365     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
77366     default:                z = "unknown error";                         break;
77367   }
77368   return z;
77369 }
77370
77371 /*
77372 ** This routine implements a busy callback that sleeps and tries
77373 ** again until a timeout value is reached.  The timeout value is
77374 ** an integer number of milliseconds passed in as the first
77375 ** argument.
77376 */
77377 static int sqliteDefaultBusyCallback(
77378  void *ptr,               /* Database connection */
77379  int count                /* Number of times table has been busy */
77380 ){
77381 #if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
77382   static const u8 delays[] =
77383      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
77384   static const u8 totals[] =
77385      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
77386 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
77387   sqlite3 *db = (sqlite3 *)ptr;
77388   int timeout = db->busyTimeout;
77389   int delay, prior;
77390
77391   assert( count>=0 );
77392   if( count < NDELAY ){
77393     delay = delays[count];
77394     prior = totals[count];
77395   }else{
77396     delay = delays[NDELAY-1];
77397     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
77398   }
77399   if( prior + delay > timeout ){
77400     delay = timeout - prior;
77401     if( delay<=0 ) return 0;
77402   }
77403   sqlite3OsSleep(db->pVfs, delay*1000);
77404   return 1;
77405 #else
77406   sqlite3 *db = (sqlite3 *)ptr;
77407   int timeout = ((sqlite3 *)ptr)->busyTimeout;
77408   if( (count+1)*1000 > timeout ){
77409     return 0;
77410   }
77411   sqlite3OsSleep(db->pVfs, 1000000);
77412   return 1;
77413 #endif
77414 }
77415
77416 /*
77417 ** Invoke the given busy handler.
77418 **
77419 ** This routine is called when an operation failed with a lock.
77420 ** If this routine returns non-zero, the lock is retried.  If it
77421 ** returns 0, the operation aborts with an SQLITE_BUSY error.
77422 */
77423 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
77424   int rc;
77425   if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
77426   rc = p->xFunc(p->pArg, p->nBusy);
77427   if( rc==0 ){
77428     p->nBusy = -1;
77429   }else{
77430     p->nBusy++;
77431   }
77432   return rc; 
77433 }
77434
77435 /*
77436 ** This routine sets the busy callback for an Sqlite database to the
77437 ** given callback function with the given argument.
77438 */
77439 SQLITE_API int sqlite3_busy_handler(
77440   sqlite3 *db,
77441   int (*xBusy)(void*,int),
77442   void *pArg
77443 ){
77444   sqlite3_mutex_enter(db->mutex);
77445   db->busyHandler.xFunc = xBusy;
77446   db->busyHandler.pArg = pArg;
77447   db->busyHandler.nBusy = 0;
77448   sqlite3_mutex_leave(db->mutex);
77449   return SQLITE_OK;
77450 }
77451
77452 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77453 /*
77454 ** This routine sets the progress callback for an Sqlite database to the
77455 ** given callback function with the given argument. The progress callback will
77456 ** be invoked every nOps opcodes.
77457 */
77458 SQLITE_API void sqlite3_progress_handler(
77459   sqlite3 *db, 
77460   int nOps,
77461   int (*xProgress)(void*), 
77462   void *pArg
77463 ){
77464   if( sqlite3SafetyCheckOk(db) ){
77465     sqlite3_mutex_enter(db->mutex);
77466     if( nOps>0 ){
77467       db->xProgress = xProgress;
77468       db->nProgressOps = nOps;
77469       db->pProgressArg = pArg;
77470     }else{
77471       db->xProgress = 0;
77472       db->nProgressOps = 0;
77473       db->pProgressArg = 0;
77474     }
77475     sqlite3_mutex_leave(db->mutex);
77476   }
77477 }
77478 #endif
77479
77480
77481 /*
77482 ** This routine installs a default busy handler that waits for the
77483 ** specified number of milliseconds before returning 0.
77484 */
77485 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
77486   if( ms>0 ){
77487     db->busyTimeout = ms;
77488     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
77489   }else{
77490     sqlite3_busy_handler(db, 0, 0);
77491   }
77492   return SQLITE_OK;
77493 }
77494
77495 /*
77496 ** Cause any pending operation to stop at its earliest opportunity.
77497 */
77498 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
77499   if( sqlite3SafetyCheckOk(db) ){
77500     db->u1.isInterrupted = 1;
77501   }
77502 }
77503
77504
77505 /*
77506 ** This function is exactly the same as sqlite3_create_function(), except
77507 ** that it is designed to be called by internal code. The difference is
77508 ** that if a malloc() fails in sqlite3_create_function(), an error code
77509 ** is returned and the mallocFailed flag cleared. 
77510 */
77511 SQLITE_PRIVATE int sqlite3CreateFunc(
77512   sqlite3 *db,
77513   const char *zFunctionName,
77514   int nArg,
77515   int enc,
77516   void *pUserData,
77517   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
77518   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
77519   void (*xFinal)(sqlite3_context*)
77520 ){
77521   FuncDef *p;
77522   int nName;
77523
77524   assert( sqlite3_mutex_held(db->mutex) );
77525   if( zFunctionName==0 ||
77526       (xFunc && (xFinal || xStep)) || 
77527       (!xFunc && (xFinal && !xStep)) ||
77528       (!xFunc && (!xFinal && xStep)) ||
77529       (nArg<-1 || nArg>127) ||
77530       (255<(nName = strlen(zFunctionName))) ){
77531     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
77532     return SQLITE_ERROR;
77533   }
77534   
77535 #ifndef SQLITE_OMIT_UTF16
77536   /* If SQLITE_UTF16 is specified as the encoding type, transform this
77537   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
77538   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
77539   **
77540   ** If SQLITE_ANY is specified, add three versions of the function
77541   ** to the hash table.
77542   */
77543   if( enc==SQLITE_UTF16 ){
77544     enc = SQLITE_UTF16NATIVE;
77545   }else if( enc==SQLITE_ANY ){
77546     int rc;
77547     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
77548          pUserData, xFunc, xStep, xFinal);
77549     if( rc==SQLITE_OK ){
77550       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
77551           pUserData, xFunc, xStep, xFinal);
77552     }
77553     if( rc!=SQLITE_OK ){
77554       return rc;
77555     }
77556     enc = SQLITE_UTF16BE;
77557   }
77558 #else
77559   enc = SQLITE_UTF8;
77560 #endif
77561   
77562   /* Check if an existing function is being overridden or deleted. If so,
77563   ** and there are active VMs, then return SQLITE_BUSY. If a function
77564   ** is being overridden/deleted but there are no active VMs, allow the
77565   ** operation to continue but invalidate all precompiled statements.
77566   */
77567   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
77568   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
77569     if( db->activeVdbeCnt ){
77570       sqlite3Error(db, SQLITE_BUSY, 
77571         "Unable to delete/modify user-function due to active statements");
77572       assert( !db->mallocFailed );
77573       return SQLITE_BUSY;
77574     }else{
77575       sqlite3ExpirePreparedStatements(db);
77576     }
77577   }
77578
77579   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
77580   assert(p || db->mallocFailed);
77581   if( !p ){
77582     return SQLITE_NOMEM;
77583   }
77584   p->flags = 0;
77585   p->xFunc = xFunc;
77586   p->xStep = xStep;
77587   p->xFinalize = xFinal;
77588   p->pUserData = pUserData;
77589   p->nArg = nArg;
77590   return SQLITE_OK;
77591 }
77592
77593 /*
77594 ** Create new user functions.
77595 */
77596 SQLITE_API int sqlite3_create_function(
77597   sqlite3 *db,
77598   const char *zFunctionName,
77599   int nArg,
77600   int enc,
77601   void *p,
77602   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
77603   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
77604   void (*xFinal)(sqlite3_context*)
77605 ){
77606   int rc;
77607   sqlite3_mutex_enter(db->mutex);
77608   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
77609   rc = sqlite3ApiExit(db, rc);
77610   sqlite3_mutex_leave(db->mutex);
77611   return rc;
77612 }
77613
77614 #ifndef SQLITE_OMIT_UTF16
77615 SQLITE_API int sqlite3_create_function16(
77616   sqlite3 *db,
77617   const void *zFunctionName,
77618   int nArg,
77619   int eTextRep,
77620   void *p,
77621   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
77622   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
77623   void (*xFinal)(sqlite3_context*)
77624 ){
77625   int rc;
77626   char *zFunc8;
77627   sqlite3_mutex_enter(db->mutex);
77628   assert( !db->mallocFailed );
77629   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
77630   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
77631   sqlite3_free(zFunc8);
77632   rc = sqlite3ApiExit(db, rc);
77633   sqlite3_mutex_leave(db->mutex);
77634   return rc;
77635 }
77636 #endif
77637
77638
77639 /*
77640 ** Declare that a function has been overloaded by a virtual table.
77641 **
77642 ** If the function already exists as a regular global function, then
77643 ** this routine is a no-op.  If the function does not exist, then create
77644 ** a new one that always throws a run-time error.  
77645 **
77646 ** When virtual tables intend to provide an overloaded function, they
77647 ** should call this routine to make sure the global function exists.
77648 ** A global function must exist in order for name resolution to work
77649 ** properly.
77650 */
77651 SQLITE_API int sqlite3_overload_function(
77652   sqlite3 *db,
77653   const char *zName,
77654   int nArg
77655 ){
77656   int nName = strlen(zName);
77657   int rc;
77658   sqlite3_mutex_enter(db->mutex);
77659   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
77660     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
77661                       0, sqlite3InvalidFunction, 0, 0);
77662   }
77663   rc = sqlite3ApiExit(db, SQLITE_OK);
77664   sqlite3_mutex_leave(db->mutex);
77665   return rc;
77666 }
77667
77668 #ifndef SQLITE_OMIT_TRACE
77669 /*
77670 ** Register a trace function.  The pArg from the previously registered trace
77671 ** is returned.  
77672 **
77673 ** A NULL trace function means that no tracing is executes.  A non-NULL
77674 ** trace is a pointer to a function that is invoked at the start of each
77675 ** SQL statement.
77676 */
77677 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
77678   void *pOld;
77679   sqlite3_mutex_enter(db->mutex);
77680   pOld = db->pTraceArg;
77681   db->xTrace = xTrace;
77682   db->pTraceArg = pArg;
77683   sqlite3_mutex_leave(db->mutex);
77684   return pOld;
77685 }
77686 /*
77687 ** Register a profile function.  The pArg from the previously registered 
77688 ** profile function is returned.  
77689 **
77690 ** A NULL profile function means that no profiling is executes.  A non-NULL
77691 ** profile is a pointer to a function that is invoked at the conclusion of
77692 ** each SQL statement that is run.
77693 */
77694 SQLITE_API void *sqlite3_profile(
77695   sqlite3 *db,
77696   void (*xProfile)(void*,const char*,sqlite_uint64),
77697   void *pArg
77698 ){
77699   void *pOld;
77700   sqlite3_mutex_enter(db->mutex);
77701   pOld = db->pProfileArg;
77702   db->xProfile = xProfile;
77703   db->pProfileArg = pArg;
77704   sqlite3_mutex_leave(db->mutex);
77705   return pOld;
77706 }
77707 #endif /* SQLITE_OMIT_TRACE */
77708
77709 /*** EXPERIMENTAL ***
77710 **
77711 ** Register a function to be invoked when a transaction comments.
77712 ** If the invoked function returns non-zero, then the commit becomes a
77713 ** rollback.
77714 */
77715 SQLITE_API void *sqlite3_commit_hook(
77716   sqlite3 *db,              /* Attach the hook to this database */
77717   int (*xCallback)(void*),  /* Function to invoke on each commit */
77718   void *pArg                /* Argument to the function */
77719 ){
77720   void *pOld;
77721   sqlite3_mutex_enter(db->mutex);
77722   pOld = db->pCommitArg;
77723   db->xCommitCallback = xCallback;
77724   db->pCommitArg = pArg;
77725   sqlite3_mutex_leave(db->mutex);
77726   return pOld;
77727 }
77728
77729 /*
77730 ** Register a callback to be invoked each time a row is updated,
77731 ** inserted or deleted using this database connection.
77732 */
77733 SQLITE_API void *sqlite3_update_hook(
77734   sqlite3 *db,              /* Attach the hook to this database */
77735   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
77736   void *pArg                /* Argument to the function */
77737 ){
77738   void *pRet;
77739   sqlite3_mutex_enter(db->mutex);
77740   pRet = db->pUpdateArg;
77741   db->xUpdateCallback = xCallback;
77742   db->pUpdateArg = pArg;
77743   sqlite3_mutex_leave(db->mutex);
77744   return pRet;
77745 }
77746
77747 /*
77748 ** Register a callback to be invoked each time a transaction is rolled
77749 ** back by this database connection.
77750 */
77751 SQLITE_API void *sqlite3_rollback_hook(
77752   sqlite3 *db,              /* Attach the hook to this database */
77753   void (*xCallback)(void*), /* Callback function */
77754   void *pArg                /* Argument to the function */
77755 ){
77756   void *pRet;
77757   sqlite3_mutex_enter(db->mutex);
77758   pRet = db->pRollbackArg;
77759   db->xRollbackCallback = xCallback;
77760   db->pRollbackArg = pArg;
77761   sqlite3_mutex_leave(db->mutex);
77762   return pRet;
77763 }
77764
77765 /*
77766 ** This routine is called to create a connection to a database BTree
77767 ** driver.  If zFilename is the name of a file, then that file is
77768 ** opened and used.  If zFilename is the magic name ":memory:" then
77769 ** the database is stored in memory (and is thus forgotten as soon as
77770 ** the connection is closed.)  If zFilename is NULL then the database
77771 ** is a "virtual" database for transient use only and is deleted as
77772 ** soon as the connection is closed.
77773 **
77774 ** A virtual database can be either a disk file (that is automatically
77775 ** deleted when the file is closed) or it an be held entirely in memory,
77776 ** depending on the values of the TEMP_STORE compile-time macro and the
77777 ** db->temp_store variable, according to the following chart:
77778 **
77779 **       TEMP_STORE     db->temp_store     Location of temporary database
77780 **       ----------     --------------     ------------------------------
77781 **           0               any             file
77782 **           1                1              file
77783 **           1                2              memory
77784 **           1                0              file
77785 **           2                1              file
77786 **           2                2              memory
77787 **           2                0              memory
77788 **           3               any             memory
77789 */
77790 SQLITE_PRIVATE int sqlite3BtreeFactory(
77791   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
77792   const char *zFilename,    /* Name of the file containing the BTree database */
77793   int omitJournal,          /* if TRUE then do not journal this file */
77794   int nCache,               /* How many pages in the page cache */
77795   int vfsFlags,             /* Flags passed through to vfsOpen */
77796   Btree **ppBtree           /* Pointer to new Btree object written here */
77797 ){
77798   int btFlags = 0;
77799   int rc;
77800   
77801   assert( sqlite3_mutex_held(db->mutex) );
77802   assert( ppBtree != 0);
77803   if( omitJournal ){
77804     btFlags |= BTREE_OMIT_JOURNAL;
77805   }
77806   if( db->flags & SQLITE_NoReadlock ){
77807     btFlags |= BTREE_NO_READLOCK;
77808   }
77809   if( zFilename==0 ){
77810 #if TEMP_STORE==0
77811     /* Do nothing */
77812 #endif
77813 #ifndef SQLITE_OMIT_MEMORYDB
77814 #if TEMP_STORE==1
77815     if( db->temp_store==2 ) zFilename = ":memory:";
77816 #endif
77817 #if TEMP_STORE==2
77818     if( db->temp_store!=1 ) zFilename = ":memory:";
77819 #endif
77820 #if TEMP_STORE==3
77821     zFilename = ":memory:";
77822 #endif
77823 #endif /* SQLITE_OMIT_MEMORYDB */
77824   }
77825
77826   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
77827     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
77828   }
77829   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
77830   if( rc==SQLITE_OK ){
77831     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
77832   }
77833   return rc;
77834 }
77835
77836 /*
77837 ** Return UTF-8 encoded English language explanation of the most recent
77838 ** error.
77839 */
77840 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
77841   const char *z;
77842   if( !db ){
77843     return sqlite3ErrStr(SQLITE_NOMEM);
77844   }
77845   if( !sqlite3SafetyCheckSickOrOk(db) || db->errCode==SQLITE_MISUSE ){
77846     return sqlite3ErrStr(SQLITE_MISUSE);
77847   }
77848   sqlite3_mutex_enter(db->mutex);
77849   assert( !db->mallocFailed );
77850   z = (char*)sqlite3_value_text(db->pErr);
77851   if( z==0 ){
77852     z = sqlite3ErrStr(db->errCode);
77853   }
77854   sqlite3_mutex_leave(db->mutex);
77855   return z;
77856 }
77857
77858 #ifndef SQLITE_OMIT_UTF16
77859 /*
77860 ** Return UTF-16 encoded English language explanation of the most recent
77861 ** error.
77862 */
77863 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
77864   /* Because all the characters in the string are in the unicode
77865   ** range 0x00-0xFF, if we pad the big-endian string with a 
77866   ** zero byte, we can obtain the little-endian string with
77867   ** &big_endian[1].
77868   */
77869   static const char outOfMemBe[] = {
77870     0, 'o', 0, 'u', 0, 't', 0, ' ', 
77871     0, 'o', 0, 'f', 0, ' ', 
77872     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
77873   };
77874   static const char misuseBe [] = {
77875     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
77876     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
77877     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
77878     0, 'o', 0, 'u', 0, 't', 0, ' ', 
77879     0, 'o', 0, 'f', 0, ' ', 
77880     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
77881   };
77882
77883   const void *z;
77884   if( !db ){
77885     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
77886   }
77887   if( !sqlite3SafetyCheckSickOrOk(db) || db->errCode==SQLITE_MISUSE ){
77888     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
77889   }
77890   sqlite3_mutex_enter(db->mutex);
77891   assert( !db->mallocFailed );
77892   z = sqlite3_value_text16(db->pErr);
77893   if( z==0 ){
77894     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
77895          SQLITE_UTF8, SQLITE_STATIC);
77896     z = sqlite3_value_text16(db->pErr);
77897   }
77898   sqlite3ApiExit(0, 0);
77899   sqlite3_mutex_leave(db->mutex);
77900   return z;
77901 }
77902 #endif /* SQLITE_OMIT_UTF16 */
77903
77904 /*
77905 ** Return the most recent error code generated by an SQLite routine. If NULL is
77906 ** passed to this function, we assume a malloc() failed during sqlite3_open().
77907 */
77908 SQLITE_API int sqlite3_errcode(sqlite3 *db){
77909   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
77910     return SQLITE_MISUSE;
77911   }
77912   if( !db || db->mallocFailed ){
77913     return SQLITE_NOMEM;
77914   }
77915   return db->errCode & db->errMask;
77916 }
77917
77918 /*
77919 ** Create a new collating function for database "db".  The name is zName
77920 ** and the encoding is enc.
77921 */
77922 static int createCollation(
77923   sqlite3* db, 
77924   const char *zName, 
77925   int enc, 
77926   void* pCtx,
77927   int(*xCompare)(void*,int,const void*,int,const void*),
77928   void(*xDel)(void*)
77929 ){
77930   CollSeq *pColl;
77931   int enc2;
77932   
77933   assert( sqlite3_mutex_held(db->mutex) );
77934
77935   /* If SQLITE_UTF16 is specified as the encoding type, transform this
77936   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
77937   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
77938   */
77939   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
77940   if( enc2==SQLITE_UTF16 ){
77941     enc2 = SQLITE_UTF16NATIVE;
77942   }
77943
77944   if( (enc2&~3)!=0 ){
77945     sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
77946     return SQLITE_ERROR;
77947   }
77948
77949   /* Check if this call is removing or replacing an existing collation 
77950   ** sequence. If so, and there are active VMs, return busy. If there
77951   ** are no active VMs, invalidate any pre-compiled statements.
77952   */
77953   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
77954   if( pColl && pColl->xCmp ){
77955     if( db->activeVdbeCnt ){
77956       sqlite3Error(db, SQLITE_BUSY, 
77957         "Unable to delete/modify collation sequence due to active statements");
77958       return SQLITE_BUSY;
77959     }
77960     sqlite3ExpirePreparedStatements(db);
77961
77962     /* If collation sequence pColl was created directly by a call to
77963     ** sqlite3_create_collation, and not generated by synthCollSeq(),
77964     ** then any copies made by synthCollSeq() need to be invalidated.
77965     ** Also, collation destructor - CollSeq.xDel() - function may need
77966     ** to be called.
77967     */ 
77968     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
77969       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, strlen(zName));
77970       int j;
77971       for(j=0; j<3; j++){
77972         CollSeq *p = &aColl[j];
77973         if( p->enc==pColl->enc ){
77974           if( p->xDel ){
77975             p->xDel(p->pUser);
77976           }
77977           p->xCmp = 0;
77978         }
77979       }
77980     }
77981   }
77982
77983   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
77984   if( pColl ){
77985     pColl->xCmp = xCompare;
77986     pColl->pUser = pCtx;
77987     pColl->xDel = xDel;
77988     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
77989   }
77990   sqlite3Error(db, SQLITE_OK, 0);
77991   return SQLITE_OK;
77992 }
77993
77994
77995 /*
77996 ** This array defines hard upper bounds on limit values.  The
77997 ** initializer must be kept in sync with the SQLITE_LIMIT_*
77998 ** #defines in sqlite3.h.
77999 */
78000 static const int aHardLimit[] = {
78001   SQLITE_MAX_LENGTH,
78002   SQLITE_MAX_SQL_LENGTH,
78003   SQLITE_MAX_COLUMN,
78004   SQLITE_MAX_EXPR_DEPTH,
78005   SQLITE_MAX_COMPOUND_SELECT,
78006   SQLITE_MAX_VDBE_OP,
78007   SQLITE_MAX_FUNCTION_ARG,
78008   SQLITE_MAX_ATTACHED,
78009   SQLITE_MAX_LIKE_PATTERN_LENGTH,
78010   SQLITE_MAX_VARIABLE_NUMBER,
78011 };
78012
78013 /*
78014 ** Make sure the hard limits are set to reasonable values
78015 */
78016 #if SQLITE_MAX_LENGTH<100
78017 # error SQLITE_MAX_LENGTH must be at least 100
78018 #endif
78019 #if SQLITE_MAX_SQL_LENGTH<100
78020 # error SQLITE_MAX_SQL_LENGTH must be at least 100
78021 #endif
78022 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
78023 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
78024 #endif
78025 #if SQLITE_MAX_COMPOUND_SELECT<2
78026 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
78027 #endif
78028 #if SQLITE_MAX_VDBE_OP<40
78029 # error SQLITE_MAX_VDBE_OP must be at least 40
78030 #endif
78031 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>255
78032 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 255
78033 #endif
78034 #if SQLITE_MAX_ATTACH<0 || SQLITE_MAX_ATTACH>30
78035 # error SQLITE_MAX_ATTACH must be between 0 and 30
78036 #endif
78037 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
78038 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
78039 #endif
78040 #if SQLITE_MAX_VARIABLE_NUMBER<1
78041 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
78042 #endif
78043
78044
78045 /*
78046 ** Change the value of a limit.  Report the old value.
78047 ** If an invalid limit index is supplied, report -1.
78048 ** Make no changes but still report the old value if the
78049 ** new limit is negative.
78050 **
78051 ** A new lower limit does not shrink existing constructs.
78052 ** It merely prevents new constructs that exceed the limit
78053 ** from forming.
78054 */
78055 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
78056   int oldLimit;
78057   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
78058     return -1;
78059   }
78060   oldLimit = db->aLimit[limitId];
78061   if( newLimit>=0 ){
78062     if( newLimit>aHardLimit[limitId] ){
78063       newLimit = aHardLimit[limitId];
78064     }
78065     db->aLimit[limitId] = newLimit;
78066   }
78067   return oldLimit;
78068 }
78069
78070 /*
78071 ** This routine does the work of opening a database on behalf of
78072 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
78073 ** is UTF-8 encoded.
78074 */
78075 static int openDatabase(
78076   const char *zFilename, /* Database filename UTF-8 encoded */
78077   sqlite3 **ppDb,        /* OUT: Returned database handle */
78078   unsigned flags,        /* Operational flags */
78079   const char *zVfs       /* Name of the VFS to use */
78080 ){
78081   sqlite3 *db;
78082   int rc;
78083   CollSeq *pColl;
78084
78085   /* Remove harmful bits from the flags parameter */
78086   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
78087                SQLITE_OPEN_MAIN_DB |
78088                SQLITE_OPEN_TEMP_DB | 
78089                SQLITE_OPEN_TRANSIENT_DB | 
78090                SQLITE_OPEN_MAIN_JOURNAL | 
78091                SQLITE_OPEN_TEMP_JOURNAL | 
78092                SQLITE_OPEN_SUBJOURNAL | 
78093                SQLITE_OPEN_MASTER_JOURNAL
78094              );
78095
78096   /* Allocate the sqlite data structure */
78097   db = sqlite3MallocZero( sizeof(sqlite3) );
78098   if( db==0 ) goto opendb_out;
78099   db->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
78100   if( db->mutex==0 ){
78101     sqlite3_free(db);
78102     db = 0;
78103     goto opendb_out;
78104   }
78105   sqlite3_mutex_enter(db->mutex);
78106   db->errMask = 0xff;
78107   db->priorNewRowid = 0;
78108   db->nDb = 2;
78109   db->magic = SQLITE_MAGIC_BUSY;
78110   db->aDb = db->aDbStatic;
78111   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
78112   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
78113   db->autoCommit = 1;
78114   db->nextAutovac = -1;
78115   db->nextPagesize = 0;
78116   db->flags |= SQLITE_ShortColNames
78117 #if SQLITE_DEFAULT_FILE_FORMAT<4
78118                  | SQLITE_LegacyFileFmt
78119 #endif
78120 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
78121                  | SQLITE_LoadExtension
78122 #endif
78123       ;
78124   sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
78125   sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
78126 #ifndef SQLITE_OMIT_VIRTUALTABLE
78127   sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
78128 #endif
78129
78130   db->pVfs = sqlite3_vfs_find(zVfs);
78131   if( !db->pVfs ){
78132     rc = SQLITE_ERROR;
78133     db->magic = SQLITE_MAGIC_SICK;
78134     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
78135     goto opendb_out;
78136   }
78137
78138   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
78139   ** and UTF-16, so add a version for each to avoid any unnecessary
78140   ** conversions. The only error that can occur here is a malloc() failure.
78141   */
78142   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
78143   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
78144   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
78145   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
78146   if( db->mallocFailed ){
78147     db->magic = SQLITE_MAGIC_SICK;
78148     goto opendb_out;
78149   }
78150   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
78151   assert( db->pDfltColl!=0 );
78152
78153   /* Also add a UTF-8 case-insensitive collation sequence. */
78154   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
78155
78156   /* Set flags on the built-in collating sequences */
78157   db->pDfltColl->type = SQLITE_COLL_BINARY;
78158   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
78159   if( pColl ){
78160     pColl->type = SQLITE_COLL_NOCASE;
78161   }
78162
78163   /* Open the backend database driver */
78164   db->openFlags = flags;
78165   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
78166                            flags | SQLITE_OPEN_MAIN_DB,
78167                            &db->aDb[0].pBt);
78168   if( rc!=SQLITE_OK ){
78169     sqlite3Error(db, rc, 0);
78170     db->magic = SQLITE_MAGIC_SICK;
78171     goto opendb_out;
78172   }
78173   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
78174   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
78175
78176
78177   /* The default safety_level for the main database is 'full'; for the temp
78178   ** database it is 'NONE'. This matches the pager layer defaults.  
78179   */
78180   db->aDb[0].zName = "main";
78181   db->aDb[0].safety_level = 3;
78182 #ifndef SQLITE_OMIT_TEMPDB
78183   db->aDb[1].zName = "temp";
78184   db->aDb[1].safety_level = 1;
78185 #endif
78186
78187   db->magic = SQLITE_MAGIC_OPEN;
78188   if( db->mallocFailed ){
78189     goto opendb_out;
78190   }
78191
78192   /* Register all built-in functions, but do not attempt to read the
78193   ** database schema yet. This is delayed until the first time the database
78194   ** is accessed.
78195   */
78196   sqlite3Error(db, SQLITE_OK, 0);
78197   sqlite3RegisterBuiltinFunctions(db);
78198
78199   /* Load automatic extensions - extensions that have been registered
78200   ** using the sqlite3_automatic_extension() API.
78201   */
78202   (void)sqlite3AutoLoadExtensions(db);
78203   if( sqlite3_errcode(db)!=SQLITE_OK ){
78204     goto opendb_out;
78205   }
78206
78207 #ifdef SQLITE_ENABLE_FTS1
78208   if( !db->mallocFailed ){
78209     extern int sqlite3Fts1Init(sqlite3*);
78210     rc = sqlite3Fts1Init(db);
78211   }
78212 #endif
78213
78214 #ifdef SQLITE_ENABLE_FTS2
78215   if( !db->mallocFailed && rc==SQLITE_OK ){
78216     extern int sqlite3Fts2Init(sqlite3*);
78217     rc = sqlite3Fts2Init(db);
78218   }
78219 #endif
78220
78221 #ifdef SQLITE_ENABLE_FTS3
78222   if( !db->mallocFailed && rc==SQLITE_OK ){
78223     rc = sqlite3Fts3Init(db);
78224   }
78225 #endif
78226
78227 #ifdef SQLITE_ENABLE_ICU
78228   if( !db->mallocFailed && rc==SQLITE_OK ){
78229     extern int sqlite3IcuInit(sqlite3*);
78230     rc = sqlite3IcuInit(db);
78231   }
78232 #endif
78233   sqlite3Error(db, rc, 0);
78234
78235   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
78236   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
78237   ** mode.  Doing nothing at all also makes NORMAL the default.
78238   */
78239 #ifdef SQLITE_DEFAULT_LOCKING_MODE
78240   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
78241   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
78242                           SQLITE_DEFAULT_LOCKING_MODE);
78243 #endif
78244
78245 opendb_out:
78246   if( db ){
78247     assert( db->mutex!=0 );
78248     sqlite3_mutex_leave(db->mutex);
78249   }
78250   if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
78251     sqlite3_close(db);
78252     db = 0;
78253   }
78254   *ppDb = db;
78255   return sqlite3ApiExit(0, rc);
78256 }
78257
78258 /*
78259 ** Open a new database handle.
78260 */
78261 SQLITE_API int sqlite3_open(
78262   const char *zFilename, 
78263   sqlite3 **ppDb 
78264 ){
78265   return openDatabase(zFilename, ppDb,
78266                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
78267 }
78268 SQLITE_API int sqlite3_open_v2(
78269   const char *filename,   /* Database filename (UTF-8) */
78270   sqlite3 **ppDb,         /* OUT: SQLite db handle */
78271   int flags,              /* Flags */
78272   const char *zVfs        /* Name of VFS module to use */
78273 ){
78274   return openDatabase(filename, ppDb, flags, zVfs);
78275 }
78276
78277 #ifndef SQLITE_OMIT_UTF16
78278 /*
78279 ** Open a new database handle.
78280 */
78281 SQLITE_API int sqlite3_open16(
78282   const void *zFilename, 
78283   sqlite3 **ppDb
78284 ){
78285   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
78286   sqlite3_value *pVal;
78287   int rc = SQLITE_NOMEM;
78288
78289   assert( zFilename );
78290   assert( ppDb );
78291   *ppDb = 0;
78292   pVal = sqlite3ValueNew(0);
78293   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
78294   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
78295   if( zFilename8 ){
78296     rc = openDatabase(zFilename8, ppDb,
78297                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
78298     assert( *ppDb || rc==SQLITE_NOMEM );
78299     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
78300       ENC(*ppDb) = SQLITE_UTF16NATIVE;
78301     }
78302   }
78303   sqlite3ValueFree(pVal);
78304
78305   return sqlite3ApiExit(0, rc);
78306 }
78307 #endif /* SQLITE_OMIT_UTF16 */
78308
78309 /*
78310 ** Register a new collation sequence with the database handle db.
78311 */
78312 SQLITE_API int sqlite3_create_collation(
78313   sqlite3* db, 
78314   const char *zName, 
78315   int enc, 
78316   void* pCtx,
78317   int(*xCompare)(void*,int,const void*,int,const void*)
78318 ){
78319   int rc;
78320   sqlite3_mutex_enter(db->mutex);
78321   assert( !db->mallocFailed );
78322   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
78323   rc = sqlite3ApiExit(db, rc);
78324   sqlite3_mutex_leave(db->mutex);
78325   return rc;
78326 }
78327
78328 /*
78329 ** Register a new collation sequence with the database handle db.
78330 */
78331 SQLITE_API int sqlite3_create_collation_v2(
78332   sqlite3* db, 
78333   const char *zName, 
78334   int enc, 
78335   void* pCtx,
78336   int(*xCompare)(void*,int,const void*,int,const void*),
78337   void(*xDel)(void*)
78338 ){
78339   int rc;
78340   sqlite3_mutex_enter(db->mutex);
78341   assert( !db->mallocFailed );
78342   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
78343   rc = sqlite3ApiExit(db, rc);
78344   sqlite3_mutex_leave(db->mutex);
78345   return rc;
78346 }
78347
78348 #ifndef SQLITE_OMIT_UTF16
78349 /*
78350 ** Register a new collation sequence with the database handle db.
78351 */
78352 SQLITE_API int sqlite3_create_collation16(
78353   sqlite3* db, 
78354   const char *zName, 
78355   int enc, 
78356   void* pCtx,
78357   int(*xCompare)(void*,int,const void*,int,const void*)
78358 ){
78359   int rc = SQLITE_OK;
78360   char *zName8;
78361   sqlite3_mutex_enter(db->mutex);
78362   assert( !db->mallocFailed );
78363   zName8 = sqlite3Utf16to8(db, zName, -1);
78364   if( zName8 ){
78365     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
78366     sqlite3_free(zName8);
78367   }
78368   rc = sqlite3ApiExit(db, rc);
78369   sqlite3_mutex_leave(db->mutex);
78370   return rc;
78371 }
78372 #endif /* SQLITE_OMIT_UTF16 */
78373
78374 /*
78375 ** Register a collation sequence factory callback with the database handle
78376 ** db. Replace any previously installed collation sequence factory.
78377 */
78378 SQLITE_API int sqlite3_collation_needed(
78379   sqlite3 *db, 
78380   void *pCollNeededArg, 
78381   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
78382 ){
78383   sqlite3_mutex_enter(db->mutex);
78384   db->xCollNeeded = xCollNeeded;
78385   db->xCollNeeded16 = 0;
78386   db->pCollNeededArg = pCollNeededArg;
78387   sqlite3_mutex_leave(db->mutex);
78388   return SQLITE_OK;
78389 }
78390
78391 #ifndef SQLITE_OMIT_UTF16
78392 /*
78393 ** Register a collation sequence factory callback with the database handle
78394 ** db. Replace any previously installed collation sequence factory.
78395 */
78396 SQLITE_API int sqlite3_collation_needed16(
78397   sqlite3 *db, 
78398   void *pCollNeededArg, 
78399   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
78400 ){
78401   sqlite3_mutex_enter(db->mutex);
78402   db->xCollNeeded = 0;
78403   db->xCollNeeded16 = xCollNeeded16;
78404   db->pCollNeededArg = pCollNeededArg;
78405   sqlite3_mutex_leave(db->mutex);
78406   return SQLITE_OK;
78407 }
78408 #endif /* SQLITE_OMIT_UTF16 */
78409
78410 #ifndef SQLITE_OMIT_GLOBALRECOVER
78411 /*
78412 ** This function is now an anachronism. It used to be used to recover from a
78413 ** malloc() failure, but SQLite now does this automatically.
78414 */
78415 SQLITE_API int sqlite3_global_recover(void){
78416   return SQLITE_OK;
78417 }
78418 #endif
78419
78420 /*
78421 ** Test to see whether or not the database connection is in autocommit
78422 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
78423 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
78424 ** by the next COMMIT or ROLLBACK.
78425 **
78426 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
78427 */
78428 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
78429   return db->autoCommit;
78430 }
78431
78432 #ifdef SQLITE_DEBUG
78433 /*
78434 ** The following routine is subtituted for constant SQLITE_CORRUPT in
78435 ** debugging builds.  This provides a way to set a breakpoint for when
78436 ** corruption is first detected.
78437 */
78438 SQLITE_PRIVATE int sqlite3Corrupt(void){
78439   return SQLITE_CORRUPT;
78440 }
78441 #endif
78442
78443 /*
78444 ** This is a convenience routine that makes sure that all thread-specific
78445 ** data for this thread has been deallocated.
78446 **
78447 ** SQLite no longer uses thread-specific data so this routine is now a
78448 ** no-op.  It is retained for historical compatibility.
78449 */
78450 SQLITE_API void sqlite3_thread_cleanup(void){
78451 }
78452
78453 /*
78454 ** Return meta information about a specific column of a database table.
78455 ** See comment in sqlite3.h (sqlite.h.in) for details.
78456 */
78457 #ifdef SQLITE_ENABLE_COLUMN_METADATA
78458 SQLITE_API int sqlite3_table_column_metadata(
78459   sqlite3 *db,                /* Connection handle */
78460   const char *zDbName,        /* Database name or NULL */
78461   const char *zTableName,     /* Table name */
78462   const char *zColumnName,    /* Column name */
78463   char const **pzDataType,    /* OUTPUT: Declared data type */
78464   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
78465   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
78466   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
78467   int *pAutoinc               /* OUTPUT: True if colums is auto-increment */
78468 ){
78469   int rc;
78470   char *zErrMsg = 0;
78471   Table *pTab = 0;
78472   Column *pCol = 0;
78473   int iCol;
78474
78475   char const *zDataType = 0;
78476   char const *zCollSeq = 0;
78477   int notnull = 0;
78478   int primarykey = 0;
78479   int autoinc = 0;
78480
78481   /* Ensure the database schema has been loaded */
78482   sqlite3_mutex_enter(db->mutex);
78483   (void)sqlite3SafetyOn(db);
78484   sqlite3BtreeEnterAll(db);
78485   rc = sqlite3Init(db, &zErrMsg);
78486   sqlite3BtreeLeaveAll(db);
78487   if( SQLITE_OK!=rc ){
78488     goto error_out;
78489   }
78490
78491   /* Locate the table in question */
78492   pTab = sqlite3FindTable(db, zTableName, zDbName);
78493   if( !pTab || pTab->pSelect ){
78494     pTab = 0;
78495     goto error_out;
78496   }
78497
78498   /* Find the column for which info is requested */
78499   if( sqlite3IsRowid(zColumnName) ){
78500     iCol = pTab->iPKey;
78501     if( iCol>=0 ){
78502       pCol = &pTab->aCol[iCol];
78503     }
78504   }else{
78505     for(iCol=0; iCol<pTab->nCol; iCol++){
78506       pCol = &pTab->aCol[iCol];
78507       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
78508         break;
78509       }
78510     }
78511     if( iCol==pTab->nCol ){
78512       pTab = 0;
78513       goto error_out;
78514     }
78515   }
78516
78517   /* The following block stores the meta information that will be returned
78518   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
78519   ** and autoinc. At this point there are two possibilities:
78520   ** 
78521   **     1. The specified column name was rowid", "oid" or "_rowid_" 
78522   **        and there is no explicitly declared IPK column. 
78523   **
78524   **     2. The table is not a view and the column name identified an 
78525   **        explicitly declared column. Copy meta information from *pCol.
78526   */ 
78527   if( pCol ){
78528     zDataType = pCol->zType;
78529     zCollSeq = pCol->zColl;
78530     notnull = (pCol->notNull?1:0);
78531     primarykey  = (pCol->isPrimKey?1:0);
78532     autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
78533   }else{
78534     zDataType = "INTEGER";
78535     primarykey = 1;
78536   }
78537   if( !zCollSeq ){
78538     zCollSeq = "BINARY";
78539   }
78540
78541 error_out:
78542   (void)sqlite3SafetyOff(db);
78543
78544   /* Whether the function call succeeded or failed, set the output parameters
78545   ** to whatever their local counterparts contain. If an error did occur,
78546   ** this has the effect of zeroing all output parameters.
78547   */
78548   if( pzDataType ) *pzDataType = zDataType;
78549   if( pzCollSeq ) *pzCollSeq = zCollSeq;
78550   if( pNotNull ) *pNotNull = notnull;
78551   if( pPrimaryKey ) *pPrimaryKey = primarykey;
78552   if( pAutoinc ) *pAutoinc = autoinc;
78553
78554   if( SQLITE_OK==rc && !pTab ){
78555     sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".", 
78556         zColumnName, 0);
78557     rc = SQLITE_ERROR;
78558   }
78559   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
78560   sqlite3_free(zErrMsg);
78561   rc = sqlite3ApiExit(db, rc);
78562   sqlite3_mutex_leave(db->mutex);
78563   return rc;
78564 }
78565 #endif
78566
78567 /*
78568 ** Sleep for a little while.  Return the amount of time slept.
78569 */
78570 SQLITE_API int sqlite3_sleep(int ms){
78571   sqlite3_vfs *pVfs;
78572   int rc;
78573   pVfs = sqlite3_vfs_find(0);
78574
78575   /* This function works in milliseconds, but the underlying OsSleep() 
78576   ** API uses microseconds. Hence the 1000's.
78577   */
78578   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
78579   return rc;
78580 }
78581
78582 /*
78583 ** Enable or disable the extended result codes.
78584 */
78585 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
78586   sqlite3_mutex_enter(db->mutex);
78587   db->errMask = onoff ? 0xffffffff : 0xff;
78588   sqlite3_mutex_leave(db->mutex);
78589   return SQLITE_OK;
78590 }
78591
78592 /*
78593 ** Invoke the xFileControl method on a particular database.
78594 */
78595 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
78596   int rc = SQLITE_ERROR;
78597   int iDb;
78598   sqlite3_mutex_enter(db->mutex);
78599   if( zDbName==0 ){
78600     iDb = 0;
78601   }else{
78602     for(iDb=0; iDb<db->nDb; iDb++){
78603       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
78604     }
78605   }
78606   if( iDb<db->nDb ){
78607     Btree *pBtree = db->aDb[iDb].pBt;
78608     if( pBtree ){
78609       Pager *pPager;
78610       sqlite3_file *fd;
78611       sqlite3BtreeEnter(pBtree);
78612       pPager = sqlite3BtreePager(pBtree);
78613       assert( pPager!=0 );
78614       fd = sqlite3PagerFile(pPager);
78615       assert( fd!=0 );
78616       if( fd->pMethods ){
78617         rc = sqlite3OsFileControl(fd, op, pArg);
78618       }
78619       sqlite3BtreeLeave(pBtree);
78620     }
78621   }
78622   sqlite3_mutex_leave(db->mutex);
78623   return rc;   
78624 }
78625
78626 /*
78627 ** Interface to the testing logic.
78628 */
78629 SQLITE_API int sqlite3_test_control(int op, ...){
78630   int rc = 0;
78631 #ifndef SQLITE_OMIT_BUILTIN_TEST
78632   va_list ap;
78633   va_start(ap, op);
78634   switch( op ){
78635     /*
78636     ** sqlite3_test_control(FAULT_CONFIG, fault_id, nDelay, nRepeat)
78637     **
78638     ** Configure a fault injector.  The specific fault injector is
78639     ** identified by the fault_id argument.  (ex: SQLITE_FAULTINJECTOR_MALLOC)
78640     ** The fault will occur after a delay of nDelay calls.  The fault
78641     ** will repeat nRepeat times.
78642     */
78643     case SQLITE_TESTCTRL_FAULT_CONFIG: {
78644       int id = va_arg(ap, int);
78645       int nDelay = va_arg(ap, int);
78646       int nRepeat = va_arg(ap, int);
78647       sqlite3FaultConfig(id, nDelay, nRepeat);
78648       break;
78649     }
78650
78651     /*
78652     ** sqlite3_test_control(FAULT_FAILURES, fault_id)
78653     **
78654     ** Return the number of faults (both hard and benign faults) that have
78655     ** occurred since the injector identified by fault_id) was last configured.
78656     */
78657     case SQLITE_TESTCTRL_FAULT_FAILURES: {
78658       int id = va_arg(ap, int);
78659       rc = sqlite3FaultFailures(id);
78660       break;
78661     }
78662
78663     /*
78664     ** sqlite3_test_control(FAULT_BENIGN_FAILURES, fault_id)
78665     **
78666     ** Return the number of benign faults that have occurred since the
78667     ** injector identified by fault_id was last configured.
78668     */
78669     case SQLITE_TESTCTRL_FAULT_BENIGN_FAILURES: {
78670       int id = va_arg(ap, int);
78671       rc = sqlite3FaultBenignFailures(id);
78672       break;
78673     }
78674
78675     /*
78676     ** sqlite3_test_control(FAULT_PENDING, fault_id)
78677     **
78678     ** Return the number of successes that will occur before the next
78679     ** scheduled failure on fault injector fault_id.
78680     ** If no failures are scheduled, return -1.
78681     */
78682     case SQLITE_TESTCTRL_FAULT_PENDING: {
78683       int id = va_arg(ap, int);
78684       rc = sqlite3FaultPending(id);
78685       break;
78686     }
78687
78688     /*
78689     ** Save the current state of the PRNG.
78690     */
78691     case SQLITE_TESTCTRL_PRNG_SAVE: {
78692       sqlite3PrngSaveState();
78693       break;
78694     }
78695
78696     /*
78697     ** Restore the state of the PRNG to the last state saved using
78698     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
78699     ** this verb acts like PRNG_RESET.
78700     */
78701     case SQLITE_TESTCTRL_PRNG_RESTORE: {
78702       sqlite3PrngRestoreState();
78703       break;
78704     }
78705
78706     /*
78707     ** Reset the PRNG back to its uninitialized state.  The next call
78708     ** to sqlite3_randomness() will reseed the PRNG using a single call
78709     ** to the xRandomness method of the default VFS.
78710     */
78711     case SQLITE_TESTCTRL_PRNG_RESET: {
78712       sqlite3PrngResetState();
78713       break;
78714     }
78715
78716     /*
78717     **  sqlite3_test_control(BITVEC_TEST, size, program)
78718     **
78719     ** Run a test against a Bitvec object of size.  The program argument
78720     ** is an array of integers that defines the test.  Return -1 on a
78721     ** memory allocation error, 0 on success, or non-zero for an error.
78722     ** See the sqlite3BitvecBuiltinTest() for additional information.
78723     */
78724     case SQLITE_TESTCTRL_BITVEC_TEST: {
78725       int sz = va_arg(ap, int);
78726       int *aProg = va_arg(ap, int*);
78727       rc = sqlite3BitvecBuiltinTest(sz, aProg);
78728       break;
78729     }
78730   }
78731   va_end(ap);
78732 #endif /* SQLITE_OMIT_BUILTIN_TEST */
78733   return rc;
78734 }
78735
78736 /************** End of main.c ************************************************/
78737 /************** Begin file fts3.c ********************************************/
78738 /*
78739 ** 2006 Oct 10
78740 **
78741 ** The author disclaims copyright to this source code.  In place of
78742 ** a legal notice, here is a blessing:
78743 **
78744 **    May you do good and not evil.
78745 **    May you find forgiveness for yourself and forgive others.
78746 **    May you share freely, never taking more than you give.
78747 **
78748 ******************************************************************************
78749 **
78750 ** This is an SQLite module implementing full-text search.
78751 */
78752
78753 /*
78754 ** The code in this file is only compiled if:
78755 **
78756 **     * The FTS3 module is being built as an extension
78757 **       (in which case SQLITE_CORE is not defined), or
78758 **
78759 **     * The FTS3 module is being built into the core of
78760 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
78761 */
78762
78763 /* TODO(shess) Consider exporting this comment to an HTML file or the
78764 ** wiki.
78765 */
78766 /* The full-text index is stored in a series of b+tree (-like)
78767 ** structures called segments which map terms to doclists.  The
78768 ** structures are like b+trees in layout, but are constructed from the
78769 ** bottom up in optimal fashion and are not updatable.  Since trees
78770 ** are built from the bottom up, things will be described from the
78771 ** bottom up.
78772 **
78773 **
78774 **** Varints ****
78775 ** The basic unit of encoding is a variable-length integer called a
78776 ** varint.  We encode variable-length integers in little-endian order
78777 ** using seven bits * per byte as follows:
78778 **
78779 ** KEY:
78780 **         A = 0xxxxxxx    7 bits of data and one flag bit
78781 **         B = 1xxxxxxx    7 bits of data and one flag bit
78782 **
78783 **  7 bits - A
78784 ** 14 bits - BA
78785 ** 21 bits - BBA
78786 ** and so on.
78787 **
78788 ** This is identical to how sqlite encodes varints (see util.c).
78789 **
78790 **
78791 **** Document lists ****
78792 ** A doclist (document list) holds a docid-sorted list of hits for a
78793 ** given term.  Doclists hold docids, and can optionally associate
78794 ** token positions and offsets with docids.
78795 **
78796 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
78797 **
78798 ** array {
78799 **   varint docid;
78800 **   array {                (position list for column 0)
78801 **     varint position;     (delta from previous position plus POS_BASE)
78802 **     varint startOffset;  (delta from previous startOffset)
78803 **     varint endOffset;    (delta from startOffset)
78804 **   }
78805 **   array {
78806 **     varint POS_COLUMN;   (marks start of position list for new column)
78807 **     varint column;       (index of new column)
78808 **     array {
78809 **       varint position;   (delta from previous position plus POS_BASE)
78810 **       varint startOffset;(delta from previous startOffset)
78811 **       varint endOffset;  (delta from startOffset)
78812 **     }
78813 **   }
78814 **   varint POS_END;        (marks end of positions for this document.
78815 ** }
78816 **
78817 ** Here, array { X } means zero or more occurrences of X, adjacent in
78818 ** memory.  A "position" is an index of a token in the token stream
78819 ** generated by the tokenizer, while an "offset" is a byte offset,
78820 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
78821 ** same logical place as the position element, and act as sentinals
78822 ** ending a position list array.
78823 **
78824 ** A DL_POSITIONS doclist omits the startOffset and endOffset
78825 ** information.  A DL_DOCIDS doclist omits both the position and
78826 ** offset information, becoming an array of varint-encoded docids.
78827 **
78828 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
78829 ** the type.  Due to how deletion is implemented in the segmentation
78830 ** system, on-disk doclists MUST store at least positions.
78831 **
78832 **
78833 **** Segment leaf nodes ****
78834 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
78835 ** nodes are written using LeafWriter, and read using LeafReader (to
78836 ** iterate through a single leaf node's data) and LeavesReader (to
78837 ** iterate through a segment's entire leaf layer).  Leaf nodes have
78838 ** the format:
78839 **
78840 ** varint iHeight;             (height from leaf level, always 0)
78841 ** varint nTerm;               (length of first term)
78842 ** char pTerm[nTerm];          (content of first term)
78843 ** varint nDoclist;            (length of term's associated doclist)
78844 ** char pDoclist[nDoclist];    (content of doclist)
78845 ** array {
78846 **                             (further terms are delta-encoded)
78847 **   varint nPrefix;           (length of prefix shared with previous term)
78848 **   varint nSuffix;           (length of unshared suffix)
78849 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
78850 **   varint nDoclist;          (length of term's associated doclist)
78851 **   char pDoclist[nDoclist];  (content of doclist)
78852 ** }
78853 **
78854 ** Here, array { X } means zero or more occurrences of X, adjacent in
78855 ** memory.
78856 **
78857 ** Leaf nodes are broken into blocks which are stored contiguously in
78858 ** the %_segments table in sorted order.  This means that when the end
78859 ** of a node is reached, the next term is in the node with the next
78860 ** greater node id.
78861 **
78862 ** New data is spilled to a new leaf node when the current node
78863 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
78864 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
78865 ** node (a leaf node with a single term and doclist).  The goal of
78866 ** these settings is to pack together groups of small doclists while
78867 ** making it efficient to directly access large doclists.  The
78868 ** assumption is that large doclists represent terms which are more
78869 ** likely to be query targets.
78870 **
78871 ** TODO(shess) It may be useful for blocking decisions to be more
78872 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
78873 ** node rather than splitting into 2k and .5k nodes.  My intuition is
78874 ** that this might extend through 2x or 4x the pagesize.
78875 **
78876 **
78877 **** Segment interior nodes ****
78878 ** Segment interior nodes store blockids for subtree nodes and terms
78879 ** to describe what data is stored by the each subtree.  Interior
78880 ** nodes are written using InteriorWriter, and read using
78881 ** InteriorReader.  InteriorWriters are created as needed when
78882 ** SegmentWriter creates new leaf nodes, or when an interior node
78883 ** itself grows too big and must be split.  The format of interior
78884 ** nodes:
78885 **
78886 ** varint iHeight;           (height from leaf level, always >0)
78887 ** varint iBlockid;          (block id of node's leftmost subtree)
78888 ** optional {
78889 **   varint nTerm;           (length of first term)
78890 **   char pTerm[nTerm];      (content of first term)
78891 **   array {
78892 **                                (further terms are delta-encoded)
78893 **     varint nPrefix;            (length of shared prefix with previous term)
78894 **     varint nSuffix;            (length of unshared suffix)
78895 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
78896 **   }
78897 ** }
78898 **
78899 ** Here, optional { X } means an optional element, while array { X }
78900 ** means zero or more occurrences of X, adjacent in memory.
78901 **
78902 ** An interior node encodes n terms separating n+1 subtrees.  The
78903 ** subtree blocks are contiguous, so only the first subtree's blockid
78904 ** is encoded.  The subtree at iBlockid will contain all terms less
78905 ** than the first term encoded (or all terms if no term is encoded).
78906 ** Otherwise, for terms greater than or equal to pTerm[i] but less
78907 ** than pTerm[i+1], the subtree for that term will be rooted at
78908 ** iBlockid+i.  Interior nodes only store enough term data to
78909 ** distinguish adjacent children (if the rightmost term of the left
78910 ** child is "something", and the leftmost term of the right child is
78911 ** "wicked", only "w" is stored).
78912 **
78913 ** New data is spilled to a new interior node at the same height when
78914 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
78915 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
78916 ** interior nodes and making the tree too skinny.  The interior nodes
78917 ** at a given height are naturally tracked by interior nodes at
78918 ** height+1, and so on.
78919 **
78920 **
78921 **** Segment directory ****
78922 ** The segment directory in table %_segdir stores meta-information for
78923 ** merging and deleting segments, and also the root node of the
78924 ** segment's tree.
78925 **
78926 ** The root node is the top node of the segment's tree after encoding
78927 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
78928 ** This could be either a leaf node or an interior node.  If the top
78929 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
78930 ** and a new root interior node is generated (which should always fit
78931 ** within ROOT_MAX because it only needs space for 2 varints, the
78932 ** height and the blockid of the previous root).
78933 **
78934 ** The meta-information in the segment directory is:
78935 **   level               - segment level (see below)
78936 **   idx                 - index within level
78937 **                       - (level,idx uniquely identify a segment)
78938 **   start_block         - first leaf node
78939 **   leaves_end_block    - last leaf node
78940 **   end_block           - last block (including interior nodes)
78941 **   root                - contents of root node
78942 **
78943 ** If the root node is a leaf node, then start_block,
78944 ** leaves_end_block, and end_block are all 0.
78945 **
78946 **
78947 **** Segment merging ****
78948 ** To amortize update costs, segments are groups into levels and
78949 ** merged in matches.  Each increase in level represents exponentially
78950 ** more documents.
78951 **
78952 ** New documents (actually, document updates) are tokenized and
78953 ** written individually (using LeafWriter) to a level 0 segment, with
78954 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
78955 ** level 0 segments are merged into a single level 1 segment.  Level 1
78956 ** is populated like level 0, and eventually MERGE_COUNT level 1
78957 ** segments are merged to a single level 2 segment (representing
78958 ** MERGE_COUNT^2 updates), and so on.
78959 **
78960 ** A segment merge traverses all segments at a given level in
78961 ** parallel, performing a straightforward sorted merge.  Since segment
78962 ** leaf nodes are written in to the %_segments table in order, this
78963 ** merge traverses the underlying sqlite disk structures efficiently.
78964 ** After the merge, all segment blocks from the merged level are
78965 ** deleted.
78966 **
78967 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
78968 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
78969 ** very similar performance numbers to 16 on insertion, though they're
78970 ** a tiny bit slower (perhaps due to more overhead in merge-time
78971 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
78972 ** 16, 2 about 66% slower than 16.
78973 **
78974 ** At query time, high MERGE_COUNT increases the number of segments
78975 ** which need to be scanned and merged.  For instance, with 100k docs
78976 ** inserted:
78977 **
78978 **    MERGE_COUNT   segments
78979 **       16           25
78980 **        8           12
78981 **        4           10
78982 **        2            6
78983 **
78984 ** This appears to have only a moderate impact on queries for very
78985 ** frequent terms (which are somewhat dominated by segment merge
78986 ** costs), and infrequent and non-existent terms still seem to be fast
78987 ** even with many segments.
78988 **
78989 ** TODO(shess) That said, it would be nice to have a better query-side
78990 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
78991 ** optimizations to things like doclist merging will swing the sweet
78992 ** spot around.
78993 **
78994 **
78995 **
78996 **** Handling of deletions and updates ****
78997 ** Since we're using a segmented structure, with no docid-oriented
78998 ** index into the term index, we clearly cannot simply update the term
78999 ** index when a document is deleted or updated.  For deletions, we
79000 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
79001 ** we simply write the new doclist.  Segment merges overwrite older
79002 ** data for a particular docid with newer data, so deletes or updates
79003 ** will eventually overtake the earlier data and knock it out.  The
79004 ** query logic likewise merges doclists so that newer data knocks out
79005 ** older data.
79006 **
79007 ** TODO(shess) Provide a VACUUM type operation to clear out all
79008 ** deletions and duplications.  This would basically be a forced merge
79009 ** into a single segment.
79010 */
79011
79012 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
79013
79014 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
79015 # define SQLITE_CORE 1
79016 #endif
79017
79018
79019 /************** Include fts3_hash.h in the middle of fts3.c ******************/
79020 /************** Begin file fts3_hash.h ***************************************/
79021 /*
79022 ** 2001 September 22
79023 **
79024 ** The author disclaims copyright to this source code.  In place of
79025 ** a legal notice, here is a blessing:
79026 **
79027 **    May you do good and not evil.
79028 **    May you find forgiveness for yourself and forgive others.
79029 **    May you share freely, never taking more than you give.
79030 **
79031 *************************************************************************
79032 ** This is the header file for the generic hash-table implemenation
79033 ** used in SQLite.  We've modified it slightly to serve as a standalone
79034 ** hash table implementation for the full-text indexing module.
79035 **
79036 */
79037 #ifndef _FTS3_HASH_H_
79038 #define _FTS3_HASH_H_
79039
79040 /* Forward declarations of structures. */
79041 typedef struct fts3Hash fts3Hash;
79042 typedef struct fts3HashElem fts3HashElem;
79043
79044 /* A complete hash table is an instance of the following structure.
79045 ** The internals of this structure are intended to be opaque -- client
79046 ** code should not attempt to access or modify the fields of this structure
79047 ** directly.  Change this structure only by using the routines below.
79048 ** However, many of the "procedures" and "functions" for modifying and
79049 ** accessing this structure are really macros, so we can't really make
79050 ** this structure opaque.
79051 */
79052 struct fts3Hash {
79053   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
79054   char copyKey;           /* True if copy of key made on insert */
79055   int count;              /* Number of entries in this table */
79056   fts3HashElem *first;    /* The first element of the array */
79057   int htsize;             /* Number of buckets in the hash table */
79058   struct _fts3ht {        /* the hash table */
79059     int count;               /* Number of entries with this hash */
79060     fts3HashElem *chain;     /* Pointer to first entry with this hash */
79061   } *ht;
79062 };
79063
79064 /* Each element in the hash table is an instance of the following 
79065 ** structure.  All elements are stored on a single doubly-linked list.
79066 **
79067 ** Again, this structure is intended to be opaque, but it can't really
79068 ** be opaque because it is used by macros.
79069 */
79070 struct fts3HashElem {
79071   fts3HashElem *next, *prev; /* Next and previous elements in the table */
79072   void *data;                /* Data associated with this element */
79073   void *pKey; int nKey;      /* Key associated with this element */
79074 };
79075
79076 /*
79077 ** There are 2 different modes of operation for a hash table:
79078 **
79079 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
79080 **                           (including the null-terminator, if any).  Case
79081 **                           is respected in comparisons.
79082 **
79083 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
79084 **                           memcmp() is used to compare keys.
79085 **
79086 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
79087 */
79088 #define FTS3_HASH_STRING    1
79089 #define FTS3_HASH_BINARY    2
79090
79091 /*
79092 ** Access routines.  To delete, insert a NULL pointer.
79093 */
79094 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
79095 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
79096 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
79097 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
79098
79099 /*
79100 ** Shorthand for the functions above
79101 */
79102 #define fts3HashInit   sqlite3Fts3HashInit
79103 #define fts3HashInsert sqlite3Fts3HashInsert
79104 #define fts3HashFind   sqlite3Fts3HashFind
79105 #define fts3HashClear  sqlite3Fts3HashClear
79106
79107 /*
79108 ** Macros for looping over all elements of a hash table.  The idiom is
79109 ** like this:
79110 **
79111 **   fts3Hash h;
79112 **   fts3HashElem *p;
79113 **   ...
79114 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
79115 **     SomeStructure *pData = fts3HashData(p);
79116 **     // do something with pData
79117 **   }
79118 */
79119 #define fts3HashFirst(H)  ((H)->first)
79120 #define fts3HashNext(E)   ((E)->next)
79121 #define fts3HashData(E)   ((E)->data)
79122 #define fts3HashKey(E)    ((E)->pKey)
79123 #define fts3HashKeysize(E) ((E)->nKey)
79124
79125 /*
79126 ** Number of entries in a hash table
79127 */
79128 #define fts3HashCount(H)  ((H)->count)
79129
79130 #endif /* _FTS3_HASH_H_ */
79131
79132 /************** End of fts3_hash.h *******************************************/
79133 /************** Continuing where we left off in fts3.c ***********************/
79134 /************** Include fts3_tokenizer.h in the middle of fts3.c *************/
79135 /************** Begin file fts3_tokenizer.h **********************************/
79136 /*
79137 ** 2006 July 10
79138 **
79139 ** The author disclaims copyright to this source code.
79140 **
79141 *************************************************************************
79142 ** Defines the interface to tokenizers used by fulltext-search.  There
79143 ** are three basic components:
79144 **
79145 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
79146 ** interface functions.  This is essentially the class structure for
79147 ** tokenizers.
79148 **
79149 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
79150 ** including customization information defined at creation time.
79151 **
79152 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
79153 ** tokens from a particular input.
79154 */
79155 #ifndef _FTS3_TOKENIZER_H_
79156 #define _FTS3_TOKENIZER_H_
79157
79158 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
79159 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
79160 ** we will need a way to register the API consistently.
79161 */
79162
79163 /*
79164 ** Structures used by the tokenizer interface. When a new tokenizer
79165 ** implementation is registered, the caller provides a pointer to
79166 ** an sqlite3_tokenizer_module containing pointers to the callback
79167 ** functions that make up an implementation.
79168 **
79169 ** When an fts3 table is created, it passes any arguments passed to
79170 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
79171 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
79172 ** implementation. The xCreate() function in turn returns an 
79173 ** sqlite3_tokenizer structure representing the specific tokenizer to
79174 ** be used for the fts3 table (customized by the tokenizer clause arguments).
79175 **
79176 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
79177 ** method is called. It returns an sqlite3_tokenizer_cursor object
79178 ** that may be used to tokenize a specific input buffer based on
79179 ** the tokenization rules supplied by a specific sqlite3_tokenizer
79180 ** object.
79181 */
79182 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
79183 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
79184 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
79185
79186 struct sqlite3_tokenizer_module {
79187
79188   /*
79189   ** Structure version. Should always be set to 0.
79190   */
79191   int iVersion;
79192
79193   /*
79194   ** Create a new tokenizer. The values in the argv[] array are the
79195   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
79196   ** TABLE statement that created the fts3 table. For example, if
79197   ** the following SQL is executed:
79198   **
79199   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
79200   **
79201   ** then argc is set to 2, and the argv[] array contains pointers
79202   ** to the strings "arg1" and "arg2".
79203   **
79204   ** This method should return either SQLITE_OK (0), or an SQLite error 
79205   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
79206   ** to point at the newly created tokenizer structure. The generic
79207   ** sqlite3_tokenizer.pModule variable should not be initialised by
79208   ** this callback. The caller will do so.
79209   */
79210   int (*xCreate)(
79211     int argc,                           /* Size of argv array */
79212     const char *const*argv,             /* Tokenizer argument strings */
79213     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
79214   );
79215
79216   /*
79217   ** Destroy an existing tokenizer. The fts3 module calls this method
79218   ** exactly once for each successful call to xCreate().
79219   */
79220   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
79221
79222   /*
79223   ** Create a tokenizer cursor to tokenize an input buffer. The caller
79224   ** is responsible for ensuring that the input buffer remains valid
79225   ** until the cursor is closed (using the xClose() method). 
79226   */
79227   int (*xOpen)(
79228     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
79229     const char *pInput, int nBytes,      /* Input buffer */
79230     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
79231   );
79232
79233   /*
79234   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
79235   ** method exactly once for each successful call to xOpen().
79236   */
79237   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
79238
79239   /*
79240   ** Retrieve the next token from the tokenizer cursor pCursor. This
79241   ** method should either return SQLITE_OK and set the values of the
79242   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
79243   ** the end of the buffer has been reached, or an SQLite error code.
79244   **
79245   ** *ppToken should be set to point at a buffer containing the 
79246   ** normalized version of the token (i.e. after any case-folding and/or
79247   ** stemming has been performed). *pnBytes should be set to the length
79248   ** of this buffer in bytes. The input text that generated the token is
79249   ** identified by the byte offsets returned in *piStartOffset and
79250   ** *piEndOffset.
79251   **
79252   ** The buffer *ppToken is set to point at is managed by the tokenizer
79253   ** implementation. It is only required to be valid until the next call
79254   ** to xNext() or xClose(). 
79255   */
79256   /* TODO(shess) current implementation requires pInput to be
79257   ** nul-terminated.  This should either be fixed, or pInput/nBytes
79258   ** should be converted to zInput.
79259   */
79260   int (*xNext)(
79261     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
79262     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
79263     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
79264     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
79265     int *piPosition      /* OUT: Number of tokens returned before this one */
79266   );
79267 };
79268
79269 struct sqlite3_tokenizer {
79270   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
79271   /* Tokenizer implementations will typically add additional fields */
79272 };
79273
79274 struct sqlite3_tokenizer_cursor {
79275   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
79276   /* Tokenizer implementations will typically add additional fields */
79277 };
79278
79279 #endif /* _FTS3_TOKENIZER_H_ */
79280
79281 /************** End of fts3_tokenizer.h **************************************/
79282 /************** Continuing where we left off in fts3.c ***********************/
79283 #ifndef SQLITE_CORE 
79284   SQLITE_EXTENSION_INIT1
79285 #endif
79286
79287
79288 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
79289 ** would be nice to order the file better, perhaps something along the
79290 ** lines of:
79291 **
79292 **  - utility functions
79293 **  - table setup functions
79294 **  - table update functions
79295 **  - table query functions
79296 **
79297 ** Put the query functions last because they're likely to reference
79298 ** typedefs or functions from the table update section.
79299 */
79300
79301 #if 0
79302 # define FTSTRACE(A)  printf A; fflush(stdout)
79303 #else
79304 # define FTSTRACE(A)
79305 #endif
79306
79307 /*
79308 ** Default span for NEAR operators.
79309 */
79310 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
79311
79312 /* It is not safe to call isspace(), tolower(), or isalnum() on
79313 ** hi-bit-set characters.  This is the same solution used in the
79314 ** tokenizer.
79315 */
79316 /* TODO(shess) The snippet-generation code should be using the
79317 ** tokenizer-generated tokens rather than doing its own local
79318 ** tokenization.
79319 */
79320 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
79321 static int safe_isspace(char c){
79322   return (c&0x80)==0 ? isspace(c) : 0;
79323 }
79324 static int safe_tolower(char c){
79325   return (c&0x80)==0 ? tolower(c) : c;
79326 }
79327 static int safe_isalnum(char c){
79328   return (c&0x80)==0 ? isalnum(c) : 0;
79329 }
79330
79331 typedef enum DocListType {
79332   DL_DOCIDS,              /* docids only */
79333   DL_POSITIONS,           /* docids + positions */
79334   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
79335 } DocListType;
79336
79337 /*
79338 ** By default, only positions and not offsets are stored in the doclists.
79339 ** To change this so that offsets are stored too, compile with
79340 **
79341 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
79342 **
79343 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
79344 ** into (no deletes or updates).
79345 */
79346 #ifndef DL_DEFAULT
79347 # define DL_DEFAULT DL_POSITIONS
79348 #endif
79349
79350 enum {
79351   POS_END = 0,        /* end of this position list */
79352   POS_COLUMN,         /* followed by new column number */
79353   POS_BASE
79354 };
79355
79356 /* MERGE_COUNT controls how often we merge segments (see comment at
79357 ** top of file).
79358 */
79359 #define MERGE_COUNT 16
79360
79361 /* utility functions */
79362
79363 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
79364 ** record to prevent errors of the form:
79365 **
79366 ** my_function(SomeType *b){
79367 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
79368 ** }
79369 */
79370 /* TODO(shess) Obvious candidates for a header file. */
79371 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
79372
79373 #ifndef NDEBUG
79374 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
79375 #else
79376 #  define SCRAMBLE(b)
79377 #endif
79378
79379 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
79380 #define VARINT_MAX 10
79381
79382 /* Write a 64-bit variable-length integer to memory starting at p[0].
79383  * The length of data written will be between 1 and VARINT_MAX bytes.
79384  * The number of bytes written is returned. */
79385 static int fts3PutVarint(char *p, sqlite_int64 v){
79386   unsigned char *q = (unsigned char *) p;
79387   sqlite_uint64 vu = v;
79388   do{
79389     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
79390     vu >>= 7;
79391   }while( vu!=0 );
79392   q[-1] &= 0x7f;  /* turn off high bit in final byte */
79393   assert( q - (unsigned char *)p <= VARINT_MAX );
79394   return (int) (q - (unsigned char *)p);
79395 }
79396
79397 /* Read a 64-bit variable-length integer from memory starting at p[0].
79398  * Return the number of bytes read, or 0 on error.
79399  * The value is stored in *v. */
79400 static int fts3GetVarint(const char *p, sqlite_int64 *v){
79401   const unsigned char *q = (const unsigned char *) p;
79402   sqlite_uint64 x = 0, y = 1;
79403   while( (*q & 0x80) == 0x80 ){
79404     x += y * (*q++ & 0x7f);
79405     y <<= 7;
79406     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
79407       assert( 0 );
79408       return 0;
79409     }
79410   }
79411   x += y * (*q++);
79412   *v = (sqlite_int64) x;
79413   return (int) (q - (unsigned char *)p);
79414 }
79415
79416 static int fts3GetVarint32(const char *p, int *pi){
79417  sqlite_int64 i;
79418  int ret = fts3GetVarint(p, &i);
79419  *pi = (int) i;
79420  assert( *pi==i );
79421  return ret;
79422 }
79423
79424 /*******************************************************************/
79425 /* DataBuffer is used to collect data into a buffer in piecemeal
79426 ** fashion.  It implements the usual distinction between amount of
79427 ** data currently stored (nData) and buffer capacity (nCapacity).
79428 **
79429 ** dataBufferInit - create a buffer with given initial capacity.
79430 ** dataBufferReset - forget buffer's data, retaining capacity.
79431 ** dataBufferDestroy - free buffer's data.
79432 ** dataBufferSwap - swap contents of two buffers.
79433 ** dataBufferExpand - expand capacity without adding data.
79434 ** dataBufferAppend - append data.
79435 ** dataBufferAppend2 - append two pieces of data at once.
79436 ** dataBufferReplace - replace buffer's data.
79437 */
79438 typedef struct DataBuffer {
79439   char *pData;          /* Pointer to malloc'ed buffer. */
79440   int nCapacity;        /* Size of pData buffer. */
79441   int nData;            /* End of data loaded into pData. */
79442 } DataBuffer;
79443
79444 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
79445   assert( nCapacity>=0 );
79446   pBuffer->nData = 0;
79447   pBuffer->nCapacity = nCapacity;
79448   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
79449 }
79450 static void dataBufferReset(DataBuffer *pBuffer){
79451   pBuffer->nData = 0;
79452 }
79453 static void dataBufferDestroy(DataBuffer *pBuffer){
79454   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
79455   SCRAMBLE(pBuffer);
79456 }
79457 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
79458   DataBuffer tmp = *pBuffer1;
79459   *pBuffer1 = *pBuffer2;
79460   *pBuffer2 = tmp;
79461 }
79462 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
79463   assert( nAddCapacity>0 );
79464   /* TODO(shess) Consider expanding more aggressively.  Note that the
79465   ** underlying malloc implementation may take care of such things for
79466   ** us already.
79467   */
79468   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
79469     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
79470     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
79471   }
79472 }
79473 static void dataBufferAppend(DataBuffer *pBuffer,
79474                              const char *pSource, int nSource){
79475   assert( nSource>0 && pSource!=NULL );
79476   dataBufferExpand(pBuffer, nSource);
79477   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
79478   pBuffer->nData += nSource;
79479 }
79480 static void dataBufferAppend2(DataBuffer *pBuffer,
79481                               const char *pSource1, int nSource1,
79482                               const char *pSource2, int nSource2){
79483   assert( nSource1>0 && pSource1!=NULL );
79484   assert( nSource2>0 && pSource2!=NULL );
79485   dataBufferExpand(pBuffer, nSource1+nSource2);
79486   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
79487   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
79488   pBuffer->nData += nSource1+nSource2;
79489 }
79490 static void dataBufferReplace(DataBuffer *pBuffer,
79491                               const char *pSource, int nSource){
79492   dataBufferReset(pBuffer);
79493   dataBufferAppend(pBuffer, pSource, nSource);
79494 }
79495
79496 /* StringBuffer is a null-terminated version of DataBuffer. */
79497 typedef struct StringBuffer {
79498   DataBuffer b;            /* Includes null terminator. */
79499 } StringBuffer;
79500
79501 static void initStringBuffer(StringBuffer *sb){
79502   dataBufferInit(&sb->b, 100);
79503   dataBufferReplace(&sb->b, "", 1);
79504 }
79505 static int stringBufferLength(StringBuffer *sb){
79506   return sb->b.nData-1;
79507 }
79508 static char *stringBufferData(StringBuffer *sb){
79509   return sb->b.pData;
79510 }
79511 static void stringBufferDestroy(StringBuffer *sb){
79512   dataBufferDestroy(&sb->b);
79513 }
79514
79515 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
79516   assert( sb->b.nData>0 );
79517   if( nFrom>0 ){
79518     sb->b.nData--;
79519     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
79520   }
79521 }
79522 static void append(StringBuffer *sb, const char *zFrom){
79523   nappend(sb, zFrom, strlen(zFrom));
79524 }
79525
79526 /* Append a list of strings separated by commas. */
79527 static void appendList(StringBuffer *sb, int nString, char **azString){
79528   int i;
79529   for(i=0; i<nString; ++i){
79530     if( i>0 ) append(sb, ", ");
79531     append(sb, azString[i]);
79532   }
79533 }
79534
79535 static int endsInWhiteSpace(StringBuffer *p){
79536   return stringBufferLength(p)>0 &&
79537     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
79538 }
79539
79540 /* If the StringBuffer ends in something other than white space, add a
79541 ** single space character to the end.
79542 */
79543 static void appendWhiteSpace(StringBuffer *p){
79544   if( stringBufferLength(p)==0 ) return;
79545   if( !endsInWhiteSpace(p) ) append(p, " ");
79546 }
79547
79548 /* Remove white space from the end of the StringBuffer */
79549 static void trimWhiteSpace(StringBuffer *p){
79550   while( endsInWhiteSpace(p) ){
79551     p->b.pData[--p->b.nData-1] = '\0';
79552   }
79553 }
79554
79555 /*******************************************************************/
79556 /* DLReader is used to read document elements from a doclist.  The
79557 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
79558 ** own the doclist buffer.
79559 **
79560 ** dlrAtEnd - true if there's no more data to read.
79561 ** dlrDocid - docid of current document.
79562 ** dlrDocData - doclist data for current document (including docid).
79563 ** dlrDocDataBytes - length of same.
79564 ** dlrAllDataBytes - length of all remaining data.
79565 ** dlrPosData - position data for current document.
79566 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
79567 ** dlrStep - step to current document.
79568 ** dlrInit - initial for doclist of given type against given data.
79569 ** dlrDestroy - clean up.
79570 **
79571 ** Expected usage is something like:
79572 **
79573 **   DLReader reader;
79574 **   dlrInit(&reader, pData, nData);
79575 **   while( !dlrAtEnd(&reader) ){
79576 **     // calls to dlrDocid() and kin.
79577 **     dlrStep(&reader);
79578 **   }
79579 **   dlrDestroy(&reader);
79580 */
79581 typedef struct DLReader {
79582   DocListType iType;
79583   const char *pData;
79584   int nData;
79585
79586   sqlite_int64 iDocid;
79587   int nElement;
79588 } DLReader;
79589
79590 static int dlrAtEnd(DLReader *pReader){
79591   assert( pReader->nData>=0 );
79592   return pReader->nData==0;
79593 }
79594 static sqlite_int64 dlrDocid(DLReader *pReader){
79595   assert( !dlrAtEnd(pReader) );
79596   return pReader->iDocid;
79597 }
79598 static const char *dlrDocData(DLReader *pReader){
79599   assert( !dlrAtEnd(pReader) );
79600   return pReader->pData;
79601 }
79602 static int dlrDocDataBytes(DLReader *pReader){
79603   assert( !dlrAtEnd(pReader) );
79604   return pReader->nElement;
79605 }
79606 static int dlrAllDataBytes(DLReader *pReader){
79607   assert( !dlrAtEnd(pReader) );
79608   return pReader->nData;
79609 }
79610 /* TODO(shess) Consider adding a field to track iDocid varint length
79611 ** to make these two functions faster.  This might matter (a tiny bit)
79612 ** for queries.
79613 */
79614 static const char *dlrPosData(DLReader *pReader){
79615   sqlite_int64 iDummy;
79616   int n = fts3GetVarint(pReader->pData, &iDummy);
79617   assert( !dlrAtEnd(pReader) );
79618   return pReader->pData+n;
79619 }
79620 static int dlrPosDataLen(DLReader *pReader){
79621   sqlite_int64 iDummy;
79622   int n = fts3GetVarint(pReader->pData, &iDummy);
79623   assert( !dlrAtEnd(pReader) );
79624   return pReader->nElement-n;
79625 }
79626 static void dlrStep(DLReader *pReader){
79627   assert( !dlrAtEnd(pReader) );
79628
79629   /* Skip past current doclist element. */
79630   assert( pReader->nElement<=pReader->nData );
79631   pReader->pData += pReader->nElement;
79632   pReader->nData -= pReader->nElement;
79633
79634   /* If there is more data, read the next doclist element. */
79635   if( pReader->nData!=0 ){
79636     sqlite_int64 iDocidDelta;
79637     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
79638     pReader->iDocid += iDocidDelta;
79639     if( pReader->iType>=DL_POSITIONS ){
79640       assert( n<pReader->nData );
79641       while( 1 ){
79642         n += fts3GetVarint32(pReader->pData+n, &iDummy);
79643         assert( n<=pReader->nData );
79644         if( iDummy==POS_END ) break;
79645         if( iDummy==POS_COLUMN ){
79646           n += fts3GetVarint32(pReader->pData+n, &iDummy);
79647           assert( n<pReader->nData );
79648         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
79649           n += fts3GetVarint32(pReader->pData+n, &iDummy);
79650           n += fts3GetVarint32(pReader->pData+n, &iDummy);
79651           assert( n<pReader->nData );
79652         }
79653       }
79654     }
79655     pReader->nElement = n;
79656     assert( pReader->nElement<=pReader->nData );
79657   }
79658 }
79659 static void dlrInit(DLReader *pReader, DocListType iType,
79660                     const char *pData, int nData){
79661   assert( pData!=NULL && nData!=0 );
79662   pReader->iType = iType;
79663   pReader->pData = pData;
79664   pReader->nData = nData;
79665   pReader->nElement = 0;
79666   pReader->iDocid = 0;
79667
79668   /* Load the first element's data.  There must be a first element. */
79669   dlrStep(pReader);
79670 }
79671 static void dlrDestroy(DLReader *pReader){
79672   SCRAMBLE(pReader);
79673 }
79674
79675 #ifndef NDEBUG
79676 /* Verify that the doclist can be validly decoded.  Also returns the
79677 ** last docid found because it is convenient in other assertions for
79678 ** DLWriter.
79679 */
79680 static void docListValidate(DocListType iType, const char *pData, int nData,
79681                             sqlite_int64 *pLastDocid){
79682   sqlite_int64 iPrevDocid = 0;
79683   assert( nData>0 );
79684   assert( pData!=0 );
79685   assert( pData+nData>pData );
79686   while( nData!=0 ){
79687     sqlite_int64 iDocidDelta;
79688     int n = fts3GetVarint(pData, &iDocidDelta);
79689     iPrevDocid += iDocidDelta;
79690     if( iType>DL_DOCIDS ){
79691       int iDummy;
79692       while( 1 ){
79693         n += fts3GetVarint32(pData+n, &iDummy);
79694         if( iDummy==POS_END ) break;
79695         if( iDummy==POS_COLUMN ){
79696           n += fts3GetVarint32(pData+n, &iDummy);
79697         }else if( iType>DL_POSITIONS ){
79698           n += fts3GetVarint32(pData+n, &iDummy);
79699           n += fts3GetVarint32(pData+n, &iDummy);
79700         }
79701         assert( n<=nData );
79702       }
79703     }
79704     assert( n<=nData );
79705     pData += n;
79706     nData -= n;
79707   }
79708   if( pLastDocid ) *pLastDocid = iPrevDocid;
79709 }
79710 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
79711 #else
79712 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
79713 #endif
79714
79715 /*******************************************************************/
79716 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
79717 ** always appends to the buffer and does not own it.
79718 **
79719 ** dlwInit - initialize to write a given type doclistto a buffer.
79720 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
79721 ** dlwAppend - append raw doclist data to buffer.
79722 ** dlwCopy - copy next doclist from reader to writer.
79723 ** dlwAdd - construct doclist element and append to buffer.
79724 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
79725 */
79726 typedef struct DLWriter {
79727   DocListType iType;
79728   DataBuffer *b;
79729   sqlite_int64 iPrevDocid;
79730 #ifndef NDEBUG
79731   int has_iPrevDocid;
79732 #endif
79733 } DLWriter;
79734
79735 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
79736   pWriter->b = b;
79737   pWriter->iType = iType;
79738   pWriter->iPrevDocid = 0;
79739 #ifndef NDEBUG
79740   pWriter->has_iPrevDocid = 0;
79741 #endif
79742 }
79743 static void dlwDestroy(DLWriter *pWriter){
79744   SCRAMBLE(pWriter);
79745 }
79746 /* iFirstDocid is the first docid in the doclist in pData.  It is
79747 ** needed because pData may point within a larger doclist, in which
79748 ** case the first item would be delta-encoded.
79749 **
79750 ** iLastDocid is the final docid in the doclist in pData.  It is
79751 ** needed to create the new iPrevDocid for future delta-encoding.  The
79752 ** code could decode the passed doclist to recreate iLastDocid, but
79753 ** the only current user (docListMerge) already has decoded this
79754 ** information.
79755 */
79756 /* TODO(shess) This has become just a helper for docListMerge.
79757 ** Consider a refactor to make this cleaner.
79758 */
79759 static void dlwAppend(DLWriter *pWriter,
79760                       const char *pData, int nData,
79761                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
79762   sqlite_int64 iDocid = 0;
79763   char c[VARINT_MAX];
79764   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
79765 #ifndef NDEBUG
79766   sqlite_int64 iLastDocidDelta;
79767 #endif
79768
79769   /* Recode the initial docid as delta from iPrevDocid. */
79770   nFirstOld = fts3GetVarint(pData, &iDocid);
79771   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
79772   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
79773
79774   /* Verify that the incoming doclist is valid AND that it ends with
79775   ** the expected docid.  This is essential because we'll trust this
79776   ** docid in future delta-encoding.
79777   */
79778   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
79779   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
79780
79781   /* Append recoded initial docid and everything else.  Rest of docids
79782   ** should have been delta-encoded from previous initial docid.
79783   */
79784   if( nFirstOld<nData ){
79785     dataBufferAppend2(pWriter->b, c, nFirstNew,
79786                       pData+nFirstOld, nData-nFirstOld);
79787   }else{
79788     dataBufferAppend(pWriter->b, c, nFirstNew);
79789   }
79790   pWriter->iPrevDocid = iLastDocid;
79791 }
79792 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
79793   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
79794             dlrDocid(pReader), dlrDocid(pReader));
79795 }
79796 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
79797   char c[VARINT_MAX];
79798   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
79799
79800   /* Docids must ascend. */
79801   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
79802   assert( pWriter->iType==DL_DOCIDS );
79803
79804   dataBufferAppend(pWriter->b, c, n);
79805   pWriter->iPrevDocid = iDocid;
79806 #ifndef NDEBUG
79807   pWriter->has_iPrevDocid = 1;
79808 #endif
79809 }
79810
79811 /*******************************************************************/
79812 /* PLReader is used to read data from a document's position list.  As
79813 ** the caller steps through the list, data is cached so that varints
79814 ** only need to be decoded once.
79815 **
79816 ** plrInit, plrDestroy - create/destroy a reader.
79817 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
79818 ** plrAtEnd - at end of stream, only call plrDestroy once true.
79819 ** plrStep - step to the next element.
79820 */
79821 typedef struct PLReader {
79822   /* These refer to the next position's data.  nData will reach 0 when
79823   ** reading the last position, so plrStep() signals EOF by setting
79824   ** pData to NULL.
79825   */
79826   const char *pData;
79827   int nData;
79828
79829   DocListType iType;
79830   int iColumn;         /* the last column read */
79831   int iPosition;       /* the last position read */
79832   int iStartOffset;    /* the last start offset read */
79833   int iEndOffset;      /* the last end offset read */
79834 } PLReader;
79835
79836 static int plrAtEnd(PLReader *pReader){
79837   return pReader->pData==NULL;
79838 }
79839 static int plrColumn(PLReader *pReader){
79840   assert( !plrAtEnd(pReader) );
79841   return pReader->iColumn;
79842 }
79843 static int plrPosition(PLReader *pReader){
79844   assert( !plrAtEnd(pReader) );
79845   return pReader->iPosition;
79846 }
79847 static int plrStartOffset(PLReader *pReader){
79848   assert( !plrAtEnd(pReader) );
79849   return pReader->iStartOffset;
79850 }
79851 static int plrEndOffset(PLReader *pReader){
79852   assert( !plrAtEnd(pReader) );
79853   return pReader->iEndOffset;
79854 }
79855 static void plrStep(PLReader *pReader){
79856   int i, n;
79857
79858   assert( !plrAtEnd(pReader) );
79859
79860   if( pReader->nData==0 ){
79861     pReader->pData = NULL;
79862     return;
79863   }
79864
79865   n = fts3GetVarint32(pReader->pData, &i);
79866   if( i==POS_COLUMN ){
79867     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
79868     pReader->iPosition = 0;
79869     pReader->iStartOffset = 0;
79870     n += fts3GetVarint32(pReader->pData+n, &i);
79871   }
79872   /* Should never see adjacent column changes. */
79873   assert( i!=POS_COLUMN );
79874
79875   if( i==POS_END ){
79876     pReader->nData = 0;
79877     pReader->pData = NULL;
79878     return;
79879   }
79880
79881   pReader->iPosition += i-POS_BASE;
79882   if( pReader->iType==DL_POSITIONS_OFFSETS ){
79883     n += fts3GetVarint32(pReader->pData+n, &i);
79884     pReader->iStartOffset += i;
79885     n += fts3GetVarint32(pReader->pData+n, &i);
79886     pReader->iEndOffset = pReader->iStartOffset+i;
79887   }
79888   assert( n<=pReader->nData );
79889   pReader->pData += n;
79890   pReader->nData -= n;
79891 }
79892
79893 static void plrInit(PLReader *pReader, DLReader *pDLReader){
79894   pReader->pData = dlrPosData(pDLReader);
79895   pReader->nData = dlrPosDataLen(pDLReader);
79896   pReader->iType = pDLReader->iType;
79897   pReader->iColumn = 0;
79898   pReader->iPosition = 0;
79899   pReader->iStartOffset = 0;
79900   pReader->iEndOffset = 0;
79901   plrStep(pReader);
79902 }
79903 static void plrDestroy(PLReader *pReader){
79904   SCRAMBLE(pReader);
79905 }
79906
79907 /*******************************************************************/
79908 /* PLWriter is used in constructing a document's position list.  As a
79909 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
79910 ** PLWriter writes to the associated DLWriter's buffer.
79911 **
79912 ** plwInit - init for writing a document's poslist.
79913 ** plwDestroy - clear a writer.
79914 ** plwAdd - append position and offset information.
79915 ** plwCopy - copy next position's data from reader to writer.
79916 ** plwTerminate - add any necessary doclist terminator.
79917 **
79918 ** Calling plwAdd() after plwTerminate() may result in a corrupt
79919 ** doclist.
79920 */
79921 /* TODO(shess) Until we've written the second item, we can cache the
79922 ** first item's information.  Then we'd have three states:
79923 **
79924 ** - initialized with docid, no positions.
79925 ** - docid and one position.
79926 ** - docid and multiple positions.
79927 **
79928 ** Only the last state needs to actually write to dlw->b, which would
79929 ** be an improvement in the DLCollector case.
79930 */
79931 typedef struct PLWriter {
79932   DLWriter *dlw;
79933
79934   int iColumn;    /* the last column written */
79935   int iPos;       /* the last position written */
79936   int iOffset;    /* the last start offset written */
79937 } PLWriter;
79938
79939 /* TODO(shess) In the case where the parent is reading these values
79940 ** from a PLReader, we could optimize to a copy if that PLReader has
79941 ** the same type as pWriter.
79942 */
79943 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
79944                    int iStartOffset, int iEndOffset){
79945   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
79946   ** iStartOffsetDelta, and iEndOffsetDelta.
79947   */
79948   char c[5*VARINT_MAX];
79949   int n = 0;
79950
79951   /* Ban plwAdd() after plwTerminate(). */
79952   assert( pWriter->iPos!=-1 );
79953
79954   if( pWriter->dlw->iType==DL_DOCIDS ) return;
79955
79956   if( iColumn!=pWriter->iColumn ){
79957     n += fts3PutVarint(c+n, POS_COLUMN);
79958     n += fts3PutVarint(c+n, iColumn);
79959     pWriter->iColumn = iColumn;
79960     pWriter->iPos = 0;
79961     pWriter->iOffset = 0;
79962   }
79963   assert( iPos>=pWriter->iPos );
79964   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
79965   pWriter->iPos = iPos;
79966   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
79967     assert( iStartOffset>=pWriter->iOffset );
79968     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
79969     pWriter->iOffset = iStartOffset;
79970     assert( iEndOffset>=iStartOffset );
79971     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
79972   }
79973   dataBufferAppend(pWriter->dlw->b, c, n);
79974 }
79975 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
79976   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
79977          plrStartOffset(pReader), plrEndOffset(pReader));
79978 }
79979 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
79980   char c[VARINT_MAX];
79981   int n;
79982
79983   pWriter->dlw = dlw;
79984
79985   /* Docids must ascend. */
79986   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
79987   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
79988   dataBufferAppend(pWriter->dlw->b, c, n);
79989   pWriter->dlw->iPrevDocid = iDocid;
79990 #ifndef NDEBUG
79991   pWriter->dlw->has_iPrevDocid = 1;
79992 #endif
79993
79994   pWriter->iColumn = 0;
79995   pWriter->iPos = 0;
79996   pWriter->iOffset = 0;
79997 }
79998 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
79999 ** then plwDestroy() would no longer be just a destructor, it would
80000 ** also be doing work, which isn't consistent with the overall idiom.
80001 ** Another option would be for plwAdd() to always append any necessary
80002 ** terminator, so that the output is always correct.  But that would
80003 ** add incremental work to the common case with the only benefit being
80004 ** API elegance.  Punt for now.
80005 */
80006 static void plwTerminate(PLWriter *pWriter){
80007   if( pWriter->dlw->iType>DL_DOCIDS ){
80008     char c[VARINT_MAX];
80009     int n = fts3PutVarint(c, POS_END);
80010     dataBufferAppend(pWriter->dlw->b, c, n);
80011   }
80012 #ifndef NDEBUG
80013   /* Mark as terminated for assert in plwAdd(). */
80014   pWriter->iPos = -1;
80015 #endif
80016 }
80017 static void plwDestroy(PLWriter *pWriter){
80018   SCRAMBLE(pWriter);
80019 }
80020
80021 /*******************************************************************/
80022 /* DLCollector wraps PLWriter and DLWriter to provide a
80023 ** dynamically-allocated doclist area to use during tokenization.
80024 **
80025 ** dlcNew - malloc up and initialize a collector.
80026 ** dlcDelete - destroy a collector and all contained items.
80027 ** dlcAddPos - append position and offset information.
80028 ** dlcAddDoclist - add the collected doclist to the given buffer.
80029 ** dlcNext - terminate the current document and open another.
80030 */
80031 typedef struct DLCollector {
80032   DataBuffer b;
80033   DLWriter dlw;
80034   PLWriter plw;
80035 } DLCollector;
80036
80037 /* TODO(shess) This could also be done by calling plwTerminate() and
80038 ** dataBufferAppend().  I tried that, expecting nominal performance
80039 ** differences, but it seemed to pretty reliably be worth 1% to code
80040 ** it this way.  I suspect it is the incremental malloc overhead (some
80041 ** percentage of the plwTerminate() calls will cause a realloc), so
80042 ** this might be worth revisiting if the DataBuffer implementation
80043 ** changes.
80044 */
80045 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
80046   if( pCollector->dlw.iType>DL_DOCIDS ){
80047     char c[VARINT_MAX];
80048     int n = fts3PutVarint(c, POS_END);
80049     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
80050   }else{
80051     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
80052   }
80053 }
80054 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
80055   plwTerminate(&pCollector->plw);
80056   plwDestroy(&pCollector->plw);
80057   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
80058 }
80059 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
80060                       int iStartOffset, int iEndOffset){
80061   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
80062 }
80063
80064 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
80065   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
80066   dataBufferInit(&pCollector->b, 0);
80067   dlwInit(&pCollector->dlw, iType, &pCollector->b);
80068   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
80069   return pCollector;
80070 }
80071 static void dlcDelete(DLCollector *pCollector){
80072   plwDestroy(&pCollector->plw);
80073   dlwDestroy(&pCollector->dlw);
80074   dataBufferDestroy(&pCollector->b);
80075   SCRAMBLE(pCollector);
80076   sqlite3_free(pCollector);
80077 }
80078
80079
80080 /* Copy the doclist data of iType in pData/nData into *out, trimming
80081 ** unnecessary data as we go.  Only columns matching iColumn are
80082 ** copied, all columns copied if iColumn is -1.  Elements with no
80083 ** matching columns are dropped.  The output is an iOutType doclist.
80084 */
80085 /* NOTE(shess) This code is only valid after all doclists are merged.
80086 ** If this is run before merges, then doclist items which represent
80087 ** deletion will be trimmed, and will thus not effect a deletion
80088 ** during the merge.
80089 */
80090 static void docListTrim(DocListType iType, const char *pData, int nData,
80091                         int iColumn, DocListType iOutType, DataBuffer *out){
80092   DLReader dlReader;
80093   DLWriter dlWriter;
80094
80095   assert( iOutType<=iType );
80096
80097   dlrInit(&dlReader, iType, pData, nData);
80098   dlwInit(&dlWriter, iOutType, out);
80099
80100   while( !dlrAtEnd(&dlReader) ){
80101     PLReader plReader;
80102     PLWriter plWriter;
80103     int match = 0;
80104
80105     plrInit(&plReader, &dlReader);
80106
80107     while( !plrAtEnd(&plReader) ){
80108       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
80109         if( !match ){
80110           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
80111           match = 1;
80112         }
80113         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
80114                plrStartOffset(&plReader), plrEndOffset(&plReader));
80115       }
80116       plrStep(&plReader);
80117     }
80118     if( match ){
80119       plwTerminate(&plWriter);
80120       plwDestroy(&plWriter);
80121     }
80122
80123     plrDestroy(&plReader);
80124     dlrStep(&dlReader);
80125   }
80126   dlwDestroy(&dlWriter);
80127   dlrDestroy(&dlReader);
80128 }
80129
80130 /* Used by docListMerge() to keep doclists in the ascending order by
80131 ** docid, then ascending order by age (so the newest comes first).
80132 */
80133 typedef struct OrderedDLReader {
80134   DLReader *pReader;
80135
80136   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
80137   ** age (which we do), then we could use pReader comparisons to break
80138   ** ties.
80139   */
80140   int idx;
80141 } OrderedDLReader;
80142
80143 /* Order eof to end, then by docid asc, idx desc. */
80144 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
80145   if( dlrAtEnd(r1->pReader) ){
80146     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
80147     return 1;                              /* Only r1 atEnd(). */
80148   }
80149   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
80150
80151   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
80152   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
80153
80154   /* Descending on idx. */
80155   return r2->idx-r1->idx;
80156 }
80157
80158 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
80159 ** p[1..n-1] is already sorted.
80160 */
80161 /* TODO(shess) Is this frequent enough to warrant a binary search?
80162 ** Before implementing that, instrument the code to check.  In most
80163 ** current usage, I expect that p[0] will be less than p[1] a very
80164 ** high proportion of the time.
80165 */
80166 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
80167   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
80168     OrderedDLReader tmp = p[0];
80169     p[0] = p[1];
80170     p[1] = tmp;
80171     n--;
80172     p++;
80173   }
80174 }
80175
80176 /* Given an array of doclist readers, merge their doclist elements
80177 ** into out in sorted order (by docid), dropping elements from older
80178 ** readers when there is a duplicate docid.  pReaders is assumed to be
80179 ** ordered by age, oldest first.
80180 */
80181 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
80182 ** be fixed.
80183 */
80184 static void docListMerge(DataBuffer *out,
80185                          DLReader *pReaders, int nReaders){
80186   OrderedDLReader readers[MERGE_COUNT];
80187   DLWriter writer;
80188   int i, n;
80189   const char *pStart = 0;
80190   int nStart = 0;
80191   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
80192
80193   assert( nReaders>0 );
80194   if( nReaders==1 ){
80195     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
80196     return;
80197   }
80198
80199   assert( nReaders<=MERGE_COUNT );
80200   n = 0;
80201   for(i=0; i<nReaders; i++){
80202     assert( pReaders[i].iType==pReaders[0].iType );
80203     readers[i].pReader = pReaders+i;
80204     readers[i].idx = i;
80205     n += dlrAllDataBytes(&pReaders[i]);
80206   }
80207   /* Conservatively size output to sum of inputs.  Output should end
80208   ** up strictly smaller than input.
80209   */
80210   dataBufferExpand(out, n);
80211
80212   /* Get the readers into sorted order. */
80213   while( i-->0 ){
80214     orderedDLReaderReorder(readers+i, nReaders-i);
80215   }
80216
80217   dlwInit(&writer, pReaders[0].iType, out);
80218   while( !dlrAtEnd(readers[0].pReader) ){
80219     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
80220
80221     /* If this is a continuation of the current buffer to copy, extend
80222     ** that buffer.  memcpy() seems to be more efficient if it has a
80223     ** lots of data to copy.
80224     */
80225     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
80226       nStart += dlrDocDataBytes(readers[0].pReader);
80227     }else{
80228       if( pStart!=0 ){
80229         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
80230       }
80231       pStart = dlrDocData(readers[0].pReader);
80232       nStart = dlrDocDataBytes(readers[0].pReader);
80233       iFirstDocid = iDocid;
80234     }
80235     iLastDocid = iDocid;
80236     dlrStep(readers[0].pReader);
80237
80238     /* Drop all of the older elements with the same docid. */
80239     for(i=1; i<nReaders &&
80240              !dlrAtEnd(readers[i].pReader) &&
80241              dlrDocid(readers[i].pReader)==iDocid; i++){
80242       dlrStep(readers[i].pReader);
80243     }
80244
80245     /* Get the readers back into order. */
80246     while( i-->0 ){
80247       orderedDLReaderReorder(readers+i, nReaders-i);
80248     }
80249   }
80250
80251   /* Copy over any remaining elements. */
80252   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
80253   dlwDestroy(&writer);
80254 }
80255
80256 /* Helper function for posListUnion().  Compares the current position
80257 ** between left and right, returning as standard C idiom of <0 if
80258 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
80259 ** compares greater.
80260 */
80261 static int posListCmp(PLReader *pLeft, PLReader *pRight){
80262   assert( pLeft->iType==pRight->iType );
80263   if( pLeft->iType==DL_DOCIDS ) return 0;
80264
80265   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
80266   if( plrAtEnd(pRight) ) return -1;
80267
80268   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
80269   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
80270
80271   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
80272   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
80273   if( pLeft->iType==DL_POSITIONS ) return 0;
80274
80275   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
80276   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
80277
80278   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
80279   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
80280
80281   return 0;
80282 }
80283
80284 /* Write the union of position lists in pLeft and pRight to pOut.
80285 ** "Union" in this case meaning "All unique position tuples".  Should
80286 ** work with any doclist type, though both inputs and the output
80287 ** should be the same type.
80288 */
80289 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
80290   PLReader left, right;
80291   PLWriter writer;
80292
80293   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
80294   assert( pLeft->iType==pRight->iType );
80295   assert( pLeft->iType==pOut->iType );
80296
80297   plrInit(&left, pLeft);
80298   plrInit(&right, pRight);
80299   plwInit(&writer, pOut, dlrDocid(pLeft));
80300
80301   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
80302     int c = posListCmp(&left, &right);
80303     if( c<0 ){
80304       plwCopy(&writer, &left);
80305       plrStep(&left);
80306     }else if( c>0 ){
80307       plwCopy(&writer, &right);
80308       plrStep(&right);
80309     }else{
80310       plwCopy(&writer, &left);
80311       plrStep(&left);
80312       plrStep(&right);
80313     }
80314   }
80315
80316   plwTerminate(&writer);
80317   plwDestroy(&writer);
80318   plrDestroy(&left);
80319   plrDestroy(&right);
80320 }
80321
80322 /* Write the union of doclists in pLeft and pRight to pOut.  For
80323 ** docids in common between the inputs, the union of the position
80324 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
80325 */
80326 static void docListUnion(
80327   const char *pLeft, int nLeft,
80328   const char *pRight, int nRight,
80329   DataBuffer *pOut      /* Write the combined doclist here */
80330 ){
80331   DLReader left, right;
80332   DLWriter writer;
80333
80334   if( nLeft==0 ){
80335     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
80336     return;
80337   }
80338   if( nRight==0 ){
80339     dataBufferAppend(pOut, pLeft, nLeft);
80340     return;
80341   }
80342
80343   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
80344   dlrInit(&right, DL_DEFAULT, pRight, nRight);
80345   dlwInit(&writer, DL_DEFAULT, pOut);
80346
80347   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
80348     if( dlrAtEnd(&right) ){
80349       dlwCopy(&writer, &left);
80350       dlrStep(&left);
80351     }else if( dlrAtEnd(&left) ){
80352       dlwCopy(&writer, &right);
80353       dlrStep(&right);
80354     }else if( dlrDocid(&left)<dlrDocid(&right) ){
80355       dlwCopy(&writer, &left);
80356       dlrStep(&left);
80357     }else if( dlrDocid(&left)>dlrDocid(&right) ){
80358       dlwCopy(&writer, &right);
80359       dlrStep(&right);
80360     }else{
80361       posListUnion(&left, &right, &writer);
80362       dlrStep(&left);
80363       dlrStep(&right);
80364     }
80365   }
80366
80367   dlrDestroy(&left);
80368   dlrDestroy(&right);
80369   dlwDestroy(&writer);
80370 }
80371
80372 /* 
80373 ** This function is used as part of the implementation of phrase and
80374 ** NEAR matching.
80375 **
80376 ** pLeft and pRight are DLReaders positioned to the same docid in
80377 ** lists of type DL_POSITION. This function writes an entry to the
80378 ** DLWriter pOut for each position in pRight that is less than
80379 ** (nNear+1) greater (but not equal to or smaller) than a position 
80380 ** in pLeft. For example, if nNear is 0, and the positions contained
80381 ** by pLeft and pRight are:
80382 **
80383 **    pLeft:  5 10 15 20
80384 **    pRight: 6  9 17 21
80385 **
80386 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
80387 ** then a positionids "6" and "21" are also added to pOut.
80388 **
80389 ** If boolean argument isSaveLeft is true, then positionids are copied
80390 ** from pLeft instead of pRight. In the example above, the positions "5"
80391 ** and "20" would be added instead of "6" and "21".
80392 */
80393 static void posListPhraseMerge(
80394   DLReader *pLeft, 
80395   DLReader *pRight,
80396   int nNear,
80397   int isSaveLeft,
80398   DLWriter *pOut
80399 ){
80400   PLReader left, right;
80401   PLWriter writer;
80402   int match = 0;
80403
80404   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
80405   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
80406
80407   plrInit(&left, pLeft);
80408   plrInit(&right, pRight);
80409
80410   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
80411     if( plrColumn(&left)<plrColumn(&right) ){
80412       plrStep(&left);
80413     }else if( plrColumn(&left)>plrColumn(&right) ){
80414       plrStep(&right);
80415     }else if( plrPosition(&left)>=plrPosition(&right) ){
80416       plrStep(&right);
80417     }else{
80418       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
80419         if( !match ){
80420           plwInit(&writer, pOut, dlrDocid(pLeft));
80421           match = 1;
80422         }
80423         if( !isSaveLeft ){
80424           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
80425         }else{
80426           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
80427         }
80428         plrStep(&right);
80429       }else{
80430         plrStep(&left);
80431       }
80432     }
80433   }
80434
80435   if( match ){
80436     plwTerminate(&writer);
80437     plwDestroy(&writer);
80438   }
80439
80440   plrDestroy(&left);
80441   plrDestroy(&right);
80442 }
80443
80444 /*
80445 ** Compare the values pointed to by the PLReaders passed as arguments. 
80446 ** Return -1 if the value pointed to by pLeft is considered less than
80447 ** the value pointed to by pRight, +1 if it is considered greater
80448 ** than it, or 0 if it is equal. i.e.
80449 **
80450 **     (*pLeft - *pRight)
80451 **
80452 ** A PLReader that is in the EOF condition is considered greater than
80453 ** any other. If neither argument is in EOF state, the return value of
80454 ** plrColumn() is used. If the plrColumn() values are equal, the
80455 ** comparison is on the basis of plrPosition().
80456 */
80457 static int plrCompare(PLReader *pLeft, PLReader *pRight){
80458   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
80459
80460   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
80461     return (plrAtEnd(pRight) ? -1 : 1);
80462   }
80463   if( plrColumn(pLeft)!=plrColumn(pRight) ){
80464     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
80465   }
80466   if( plrPosition(pLeft)!=plrPosition(pRight) ){
80467     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
80468   }
80469   return 0;
80470 }
80471
80472 /* We have two doclists with positions:  pLeft and pRight. Depending
80473 ** on the value of the nNear parameter, perform either a phrase
80474 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
80475 ** and write the results into pOut.
80476 **
80477 ** A phrase intersection means that two documents only match
80478 ** if pLeft.iPos+1==pRight.iPos.
80479 **
80480 ** A NEAR intersection means that two documents only match if 
80481 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
80482 **
80483 ** If a NEAR intersection is requested, then the nPhrase argument should
80484 ** be passed the number of tokens in the two operands to the NEAR operator
80485 ** combined. For example:
80486 **
80487 **       Query syntax               nPhrase
80488 **      ------------------------------------
80489 **       "A B C" NEAR "D E"         5
80490 **       A NEAR B                   2
80491 **
80492 ** iType controls the type of data written to pOut.  If iType is
80493 ** DL_POSITIONS, the positions are those from pRight.
80494 */
80495 static void docListPhraseMerge(
80496   const char *pLeft, int nLeft,
80497   const char *pRight, int nRight,
80498   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
80499   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
80500   DocListType iType,    /* Type of doclist to write to pOut */
80501   DataBuffer *pOut      /* Write the combined doclist here */
80502 ){
80503   DLReader left, right;
80504   DLWriter writer;
80505
80506   if( nLeft==0 || nRight==0 ) return;
80507
80508   assert( iType!=DL_POSITIONS_OFFSETS );
80509
80510   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
80511   dlrInit(&right, DL_POSITIONS, pRight, nRight);
80512   dlwInit(&writer, iType, pOut);
80513
80514   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
80515     if( dlrDocid(&left)<dlrDocid(&right) ){
80516       dlrStep(&left);
80517     }else if( dlrDocid(&right)<dlrDocid(&left) ){
80518       dlrStep(&right);
80519     }else{
80520       if( nNear==0 ){
80521         posListPhraseMerge(&left, &right, 0, 0, &writer);
80522       }else{
80523         /* This case occurs when two terms (simple terms or phrases) are
80524          * connected by a NEAR operator, span (nNear+1). i.e.
80525          *
80526          *     '"terrible company" NEAR widget'
80527          */
80528         DataBuffer one = {0, 0, 0};
80529         DataBuffer two = {0, 0, 0};
80530
80531         DLWriter dlwriter2;
80532         DLReader dr1 = {0, 0, 0, 0, 0}; 
80533         DLReader dr2 = {0, 0, 0, 0, 0};
80534
80535         dlwInit(&dlwriter2, iType, &one);
80536         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
80537         dlwInit(&dlwriter2, iType, &two);
80538         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
80539
80540         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
80541         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
80542
80543         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
80544           PLReader pr1 = {0};
80545           PLReader pr2 = {0};
80546
80547           PLWriter plwriter;
80548           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
80549
80550           if( one.nData ) plrInit(&pr1, &dr1);
80551           if( two.nData ) plrInit(&pr2, &dr2);
80552           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
80553             int iCompare = plrCompare(&pr1, &pr2);
80554             switch( iCompare ){
80555               case -1:
80556                 plwCopy(&plwriter, &pr1);
80557                 plrStep(&pr1);
80558                 break;
80559               case 1:
80560                 plwCopy(&plwriter, &pr2);
80561                 plrStep(&pr2);
80562                 break;
80563               case 0:
80564                 plwCopy(&plwriter, &pr1);
80565                 plrStep(&pr1);
80566                 plrStep(&pr2);
80567                 break;
80568             }
80569           }
80570           plwTerminate(&plwriter);
80571         }
80572         dataBufferDestroy(&one);
80573         dataBufferDestroy(&two);
80574       }
80575       dlrStep(&left);
80576       dlrStep(&right);
80577     }
80578   }
80579
80580   dlrDestroy(&left);
80581   dlrDestroy(&right);
80582   dlwDestroy(&writer);
80583 }
80584
80585 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
80586 ** Write the intersection of these two doclists into pOut as a
80587 ** DL_DOCIDS doclist.
80588 */
80589 static void docListAndMerge(
80590   const char *pLeft, int nLeft,
80591   const char *pRight, int nRight,
80592   DataBuffer *pOut      /* Write the combined doclist here */
80593 ){
80594   DLReader left, right;
80595   DLWriter writer;
80596
80597   if( nLeft==0 || nRight==0 ) return;
80598
80599   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
80600   dlrInit(&right, DL_DOCIDS, pRight, nRight);
80601   dlwInit(&writer, DL_DOCIDS, pOut);
80602
80603   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
80604     if( dlrDocid(&left)<dlrDocid(&right) ){
80605       dlrStep(&left);
80606     }else if( dlrDocid(&right)<dlrDocid(&left) ){
80607       dlrStep(&right);
80608     }else{
80609       dlwAdd(&writer, dlrDocid(&left));
80610       dlrStep(&left);
80611       dlrStep(&right);
80612     }
80613   }
80614
80615   dlrDestroy(&left);
80616   dlrDestroy(&right);
80617   dlwDestroy(&writer);
80618 }
80619
80620 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
80621 ** Write the union of these two doclists into pOut as a
80622 ** DL_DOCIDS doclist.
80623 */
80624 static void docListOrMerge(
80625   const char *pLeft, int nLeft,
80626   const char *pRight, int nRight,
80627   DataBuffer *pOut      /* Write the combined doclist here */
80628 ){
80629   DLReader left, right;
80630   DLWriter writer;
80631
80632   if( nLeft==0 ){
80633     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
80634     return;
80635   }
80636   if( nRight==0 ){
80637     dataBufferAppend(pOut, pLeft, nLeft);
80638     return;
80639   }
80640
80641   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
80642   dlrInit(&right, DL_DOCIDS, pRight, nRight);
80643   dlwInit(&writer, DL_DOCIDS, pOut);
80644
80645   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
80646     if( dlrAtEnd(&right) ){
80647       dlwAdd(&writer, dlrDocid(&left));
80648       dlrStep(&left);
80649     }else if( dlrAtEnd(&left) ){
80650       dlwAdd(&writer, dlrDocid(&right));
80651       dlrStep(&right);
80652     }else if( dlrDocid(&left)<dlrDocid(&right) ){
80653       dlwAdd(&writer, dlrDocid(&left));
80654       dlrStep(&left);
80655     }else if( dlrDocid(&right)<dlrDocid(&left) ){
80656       dlwAdd(&writer, dlrDocid(&right));
80657       dlrStep(&right);
80658     }else{
80659       dlwAdd(&writer, dlrDocid(&left));
80660       dlrStep(&left);
80661       dlrStep(&right);
80662     }
80663   }
80664
80665   dlrDestroy(&left);
80666   dlrDestroy(&right);
80667   dlwDestroy(&writer);
80668 }
80669
80670 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
80671 ** Write into pOut as DL_DOCIDS doclist containing all documents that
80672 ** occur in pLeft but not in pRight.
80673 */
80674 static void docListExceptMerge(
80675   const char *pLeft, int nLeft,
80676   const char *pRight, int nRight,
80677   DataBuffer *pOut      /* Write the combined doclist here */
80678 ){
80679   DLReader left, right;
80680   DLWriter writer;
80681
80682   if( nLeft==0 ) return;
80683   if( nRight==0 ){
80684     dataBufferAppend(pOut, pLeft, nLeft);
80685     return;
80686   }
80687
80688   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
80689   dlrInit(&right, DL_DOCIDS, pRight, nRight);
80690   dlwInit(&writer, DL_DOCIDS, pOut);
80691
80692   while( !dlrAtEnd(&left) ){
80693     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
80694       dlrStep(&right);
80695     }
80696     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
80697       dlwAdd(&writer, dlrDocid(&left));
80698     }
80699     dlrStep(&left);
80700   }
80701
80702   dlrDestroy(&left);
80703   dlrDestroy(&right);
80704   dlwDestroy(&writer);
80705 }
80706
80707 static char *string_dup_n(const char *s, int n){
80708   char *str = sqlite3_malloc(n + 1);
80709   memcpy(str, s, n);
80710   str[n] = '\0';
80711   return str;
80712 }
80713
80714 /* Duplicate a string; the caller must free() the returned string.
80715  * (We don't use strdup() since it is not part of the standard C library and
80716  * may not be available everywhere.) */
80717 static char *string_dup(const char *s){
80718   return string_dup_n(s, strlen(s));
80719 }
80720
80721 /* Format a string, replacing each occurrence of the % character with
80722  * zDb.zName.  This may be more convenient than sqlite_mprintf()
80723  * when one string is used repeatedly in a format string.
80724  * The caller must free() the returned string. */
80725 static char *string_format(const char *zFormat,
80726                            const char *zDb, const char *zName){
80727   const char *p;
80728   size_t len = 0;
80729   size_t nDb = strlen(zDb);
80730   size_t nName = strlen(zName);
80731   size_t nFullTableName = nDb+1+nName;
80732   char *result;
80733   char *r;
80734
80735   /* first compute length needed */
80736   for(p = zFormat ; *p ; ++p){
80737     len += (*p=='%' ? nFullTableName : 1);
80738   }
80739   len += 1;  /* for null terminator */
80740
80741   r = result = sqlite3_malloc(len);
80742   for(p = zFormat; *p; ++p){
80743     if( *p=='%' ){
80744       memcpy(r, zDb, nDb);
80745       r += nDb;
80746       *r++ = '.';
80747       memcpy(r, zName, nName);
80748       r += nName;
80749     } else {
80750       *r++ = *p;
80751     }
80752   }
80753   *r++ = '\0';
80754   assert( r == result + len );
80755   return result;
80756 }
80757
80758 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
80759                     const char *zFormat){
80760   char *zCommand = string_format(zFormat, zDb, zName);
80761   int rc;
80762   FTSTRACE(("FTS3 sql: %s\n", zCommand));
80763   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
80764   sqlite3_free(zCommand);
80765   return rc;
80766 }
80767
80768 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
80769                        sqlite3_stmt **ppStmt, const char *zFormat){
80770   char *zCommand = string_format(zFormat, zDb, zName);
80771   int rc;
80772   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
80773   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
80774   sqlite3_free(zCommand);
80775   return rc;
80776 }
80777
80778 /* end utility functions */
80779
80780 /* Forward reference */
80781 typedef struct fulltext_vtab fulltext_vtab;
80782
80783 /* A single term in a query is represented by an instances of
80784 ** the following structure. Each word which may match against
80785 ** document content is a term. Operators, like NEAR or OR, are
80786 ** not terms. Query terms are organized as a flat list stored
80787 ** in the Query.pTerms array.
80788 **
80789 ** If the QueryTerm.nPhrase variable is non-zero, then the QueryTerm
80790 ** is the first in a contiguous string of terms that are either part
80791 ** of the same phrase, or connected by the NEAR operator.
80792 **
80793 ** If the QueryTerm.nNear variable is non-zero, then the token is followed 
80794 ** by a NEAR operator with span set to (nNear-1). For example, the 
80795 ** following query:
80796 **
80797 ** The QueryTerm.iPhrase variable stores the index of the token within
80798 ** its phrase, indexed starting at 1, or 1 if the token is not part 
80799 ** of any phrase.
80800 **
80801 ** For example, the data structure used to represent the following query:
80802 **
80803 **     ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"'
80804 **
80805 ** is:
80806 **
80807 **     {nPhrase=4, iPhrase=1, nNear=6, pTerm="sqlite"},
80808 **     {nPhrase=0, iPhrase=1, nNear=3, pTerm="google"},
80809 **     {nPhrase=0, iPhrase=1, nNear=0, pTerm="search"},
80810 **     {nPhrase=0, iPhrase=2, nNear=0, pTerm="engine"},
80811 **
80812 ** compiling the FTS3 syntax to Query structures is done by the parseQuery()
80813 ** function.
80814 */
80815 typedef struct QueryTerm {
80816   short int nPhrase; /* How many following terms are part of the same phrase */
80817   short int iPhrase; /* This is the i-th term of a phrase. */
80818   short int iColumn; /* Column of the index that must match this term */
80819   signed char nNear; /* term followed by a NEAR operator with span=(nNear-1) */
80820   signed char isOr;  /* this term is preceded by "OR" */
80821   signed char isNot; /* this term is preceded by "-" */
80822   signed char isPrefix; /* this term is followed by "*" */
80823   char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
80824   int nTerm;         /* Number of bytes in pTerm[] */
80825 } QueryTerm;
80826
80827
80828 /* A query string is parsed into a Query structure.
80829  *
80830  * We could, in theory, allow query strings to be complicated
80831  * nested expressions with precedence determined by parentheses.
80832  * But none of the major search engines do this.  (Perhaps the
80833  * feeling is that an parenthesized expression is two complex of
80834  * an idea for the average user to grasp.)  Taking our lead from
80835  * the major search engines, we will allow queries to be a list
80836  * of terms (with an implied AND operator) or phrases in double-quotes,
80837  * with a single optional "-" before each non-phrase term to designate
80838  * negation and an optional OR connector.
80839  *
80840  * OR binds more tightly than the implied AND, which is what the
80841  * major search engines seem to do.  So, for example:
80842  * 
80843  *    [one two OR three]     ==>    one AND (two OR three)
80844  *    [one OR two three]     ==>    (one OR two) AND three
80845  *
80846  * A "-" before a term matches all entries that lack that term.
80847  * The "-" must occur immediately before the term with in intervening
80848  * space.  This is how the search engines do it.
80849  *
80850  * A NOT term cannot be the right-hand operand of an OR.  If this
80851  * occurs in the query string, the NOT is ignored:
80852  *
80853  *    [one OR -two]          ==>    one OR two
80854  *
80855  */
80856 typedef struct Query {
80857   fulltext_vtab *pFts;  /* The full text index */
80858   int nTerms;           /* Number of terms in the query */
80859   QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
80860   int nextIsOr;         /* Set the isOr flag on the next inserted term */
80861   int nextIsNear;       /* Set the isOr flag on the next inserted term */
80862   int nextColumn;       /* Next word parsed must be in this column */
80863   int dfltColumn;       /* The default column */
80864 } Query;
80865
80866
80867 /*
80868 ** An instance of the following structure keeps track of generated
80869 ** matching-word offset information and snippets.
80870 */
80871 typedef struct Snippet {
80872   int nMatch;     /* Total number of matches */
80873   int nAlloc;     /* Space allocated for aMatch[] */
80874   struct snippetMatch { /* One entry for each matching term */
80875     char snStatus;       /* Status flag for use while constructing snippets */
80876     short int iCol;      /* The column that contains the match */
80877     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
80878     int iToken;          /* The index of the matching document token */
80879     short int nByte;     /* Number of bytes in the term */
80880     int iStart;          /* The offset to the first character of the term */
80881   } *aMatch;      /* Points to space obtained from malloc */
80882   char *zOffset;  /* Text rendering of aMatch[] */
80883   int nOffset;    /* strlen(zOffset) */
80884   char *zSnippet; /* Snippet text */
80885   int nSnippet;   /* strlen(zSnippet) */
80886 } Snippet;
80887
80888
80889 typedef enum QueryType {
80890   QUERY_GENERIC,   /* table scan */
80891   QUERY_DOCID,     /* lookup by docid */
80892   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
80893 } QueryType;
80894
80895 typedef enum fulltext_statement {
80896   CONTENT_INSERT_STMT,
80897   CONTENT_SELECT_STMT,
80898   CONTENT_UPDATE_STMT,
80899   CONTENT_DELETE_STMT,
80900
80901   BLOCK_INSERT_STMT,
80902   BLOCK_SELECT_STMT,
80903   BLOCK_DELETE_STMT,
80904
80905   SEGDIR_MAX_INDEX_STMT,
80906   SEGDIR_SET_STMT,
80907   SEGDIR_SELECT_STMT,
80908   SEGDIR_SPAN_STMT,
80909   SEGDIR_DELETE_STMT,
80910   SEGDIR_SELECT_ALL_STMT,
80911
80912   MAX_STMT                     /* Always at end! */
80913 } fulltext_statement;
80914
80915 /* These must exactly match the enum above. */
80916 /* TODO(shess): Is there some risk that a statement will be used in two
80917 ** cursors at once, e.g.  if a query joins a virtual table to itself?
80918 ** If so perhaps we should move some of these to the cursor object.
80919 */
80920 static const char *const fulltext_zStatement[MAX_STMT] = {
80921   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
80922   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
80923   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
80924   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
80925
80926   /* BLOCK_INSERT */
80927   "insert into %_segments (blockid, block) values (null, ?)",
80928   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
80929   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
80930
80931   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
80932   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
80933   /* SEGDIR_SELECT */
80934   "select start_block, leaves_end_block, root from %_segdir "
80935   " where level = ? order by idx",
80936   /* SEGDIR_SPAN */
80937   "select min(start_block), max(end_block) from %_segdir "
80938   " where level = ? and start_block <> 0",
80939   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
80940   /* SEGDIR_SELECT_ALL */
80941   "select root, leaves_end_block from %_segdir order by level desc, idx",
80942 };
80943
80944 /*
80945 ** A connection to a fulltext index is an instance of the following
80946 ** structure.  The xCreate and xConnect methods create an instance
80947 ** of this structure and xDestroy and xDisconnect free that instance.
80948 ** All other methods receive a pointer to the structure as one of their
80949 ** arguments.
80950 */
80951 struct fulltext_vtab {
80952   sqlite3_vtab base;               /* Base class used by SQLite core */
80953   sqlite3 *db;                     /* The database connection */
80954   const char *zDb;                 /* logical database name */
80955   const char *zName;               /* virtual table name */
80956   int nColumn;                     /* number of columns in virtual table */
80957   char **azColumn;                 /* column names.  malloced */
80958   char **azContentColumn;          /* column names in content table; malloced */
80959   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
80960
80961   /* Precompiled statements which we keep as long as the table is
80962   ** open.
80963   */
80964   sqlite3_stmt *pFulltextStatements[MAX_STMT];
80965
80966   /* Precompiled statements used for segment merges.  We run a
80967   ** separate select across the leaf level of each tree being merged.
80968   */
80969   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
80970   /* The statement used to prepare pLeafSelectStmts. */
80971 #define LEAF_SELECT \
80972   "select block from %_segments where blockid between ? and ? order by blockid"
80973
80974   /* These buffer pending index updates during transactions.
80975   ** nPendingData estimates the memory size of the pending data.  It
80976   ** doesn't include the hash-bucket overhead, nor any malloc
80977   ** overhead.  When nPendingData exceeds kPendingThreshold, the
80978   ** buffer is flushed even before the transaction closes.
80979   ** pendingTerms stores the data, and is only valid when nPendingData
80980   ** is >=0 (nPendingData<0 means pendingTerms has not been
80981   ** initialized).  iPrevDocid is the last docid written, used to make
80982   ** certain we're inserting in sorted order.
80983   */
80984   int nPendingData;
80985 #define kPendingThreshold (1*1024*1024)
80986   sqlite_int64 iPrevDocid;
80987   fts3Hash pendingTerms;
80988 };
80989
80990 /*
80991 ** When the core wants to do a query, it create a cursor using a
80992 ** call to xOpen.  This structure is an instance of a cursor.  It
80993 ** is destroyed by xClose.
80994 */
80995 typedef struct fulltext_cursor {
80996   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
80997   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
80998   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
80999   int eof;                         /* True if at End Of Results */
81000   Query q;                         /* Parsed query string */
81001   Snippet snippet;                 /* Cached snippet for the current row */
81002   int iColumn;                     /* Column being searched */
81003   DataBuffer result;               /* Doclist results from fulltextQuery */
81004   DLReader reader;                 /* Result reader if result not empty */
81005 } fulltext_cursor;
81006
81007 static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
81008   return (fulltext_vtab *) c->base.pVtab;
81009 }
81010
81011 static const sqlite3_module fts3Module;   /* forward declaration */
81012
81013 /* Return a dynamically generated statement of the form
81014  *   insert into %_content (docid, ...) values (?, ...)
81015  */
81016 static const char *contentInsertStatement(fulltext_vtab *v){
81017   StringBuffer sb;
81018   int i;
81019
81020   initStringBuffer(&sb);
81021   append(&sb, "insert into %_content (docid, ");
81022   appendList(&sb, v->nColumn, v->azContentColumn);
81023   append(&sb, ") values (?");
81024   for(i=0; i<v->nColumn; ++i)
81025     append(&sb, ", ?");
81026   append(&sb, ")");
81027   return stringBufferData(&sb);
81028 }
81029
81030 /* Return a dynamically generated statement of the form
81031  *   select <content columns> from %_content where docid = ?
81032  */
81033 static const char *contentSelectStatement(fulltext_vtab *v){
81034   StringBuffer sb;
81035   initStringBuffer(&sb);
81036   append(&sb, "SELECT ");
81037   appendList(&sb, v->nColumn, v->azContentColumn);
81038   append(&sb, " FROM %_content WHERE docid = ?");
81039   return stringBufferData(&sb);
81040 }
81041
81042 /* Return a dynamically generated statement of the form
81043  *   update %_content set [col_0] = ?, [col_1] = ?, ...
81044  *                    where docid = ?
81045  */
81046 static const char *contentUpdateStatement(fulltext_vtab *v){
81047   StringBuffer sb;
81048   int i;
81049
81050   initStringBuffer(&sb);
81051   append(&sb, "update %_content set ");
81052   for(i=0; i<v->nColumn; ++i) {
81053     if( i>0 ){
81054       append(&sb, ", ");
81055     }
81056     append(&sb, v->azContentColumn[i]);
81057     append(&sb, " = ?");
81058   }
81059   append(&sb, " where docid = ?");
81060   return stringBufferData(&sb);
81061 }
81062
81063 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
81064 ** If the indicated statement has never been prepared, it is prepared
81065 ** and cached, otherwise the cached version is reset.
81066 */
81067 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
81068                              sqlite3_stmt **ppStmt){
81069   assert( iStmt<MAX_STMT );
81070   if( v->pFulltextStatements[iStmt]==NULL ){
81071     const char *zStmt;
81072     int rc;
81073     switch( iStmt ){
81074       case CONTENT_INSERT_STMT:
81075         zStmt = contentInsertStatement(v); break;
81076       case CONTENT_SELECT_STMT:
81077         zStmt = contentSelectStatement(v); break;
81078       case CONTENT_UPDATE_STMT:
81079         zStmt = contentUpdateStatement(v); break;
81080       default:
81081         zStmt = fulltext_zStatement[iStmt];
81082     }
81083     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
81084                          zStmt);
81085     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
81086     if( rc!=SQLITE_OK ) return rc;
81087   } else {
81088     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
81089     if( rc!=SQLITE_OK ) return rc;
81090   }
81091
81092   *ppStmt = v->pFulltextStatements[iStmt];
81093   return SQLITE_OK;
81094 }
81095
81096 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
81097 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
81098 ** where we expect no results.
81099 */
81100 static int sql_single_step(sqlite3_stmt *s){
81101   int rc = sqlite3_step(s);
81102   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
81103 }
81104
81105 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
81106 ** statements.
81107 */
81108 /* TODO(shess) Write version for generic statements and then share
81109 ** that between the cached-statement functions.
81110 */
81111 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
81112                                   sqlite3_stmt **ppStmt){
81113   assert( idx>=0 && idx<MERGE_COUNT );
81114   if( v->pLeafSelectStmts[idx]==NULL ){
81115     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
81116                          LEAF_SELECT);
81117     if( rc!=SQLITE_OK ) return rc;
81118   }else{
81119     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
81120     if( rc!=SQLITE_OK ) return rc;
81121   }
81122
81123   *ppStmt = v->pLeafSelectStmts[idx];
81124   return SQLITE_OK;
81125 }
81126
81127 /* insert into %_content (docid, ...) values ([docid], [pValues])
81128 ** If the docid contains SQL NULL, then a unique docid will be
81129 ** generated.
81130 */
81131 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
81132                           sqlite3_value **pValues){
81133   sqlite3_stmt *s;
81134   int i;
81135   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
81136   if( rc!=SQLITE_OK ) return rc;
81137
81138   rc = sqlite3_bind_value(s, 1, docid);
81139   if( rc!=SQLITE_OK ) return rc;
81140
81141   for(i=0; i<v->nColumn; ++i){
81142     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
81143     if( rc!=SQLITE_OK ) return rc;
81144   }
81145
81146   return sql_single_step(s);
81147 }
81148
81149 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
81150  *                  where docid = [iDocid] */
81151 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
81152                           sqlite_int64 iDocid){
81153   sqlite3_stmt *s;
81154   int i;
81155   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
81156   if( rc!=SQLITE_OK ) return rc;
81157
81158   for(i=0; i<v->nColumn; ++i){
81159     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
81160     if( rc!=SQLITE_OK ) return rc;
81161   }
81162
81163   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
81164   if( rc!=SQLITE_OK ) return rc;
81165
81166   return sql_single_step(s);
81167 }
81168
81169 static void freeStringArray(int nString, const char **pString){
81170   int i;
81171
81172   for (i=0 ; i < nString ; ++i) {
81173     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
81174   }
81175   sqlite3_free((void *) pString);
81176 }
81177
81178 /* select * from %_content where docid = [iDocid]
81179  * The caller must delete the returned array and all strings in it.
81180  * null fields will be NULL in the returned array.
81181  *
81182  * TODO: Perhaps we should return pointer/length strings here for consistency
81183  * with other code which uses pointer/length. */
81184 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
81185                           const char ***pValues){
81186   sqlite3_stmt *s;
81187   const char **values;
81188   int i;
81189   int rc;
81190
81191   *pValues = NULL;
81192
81193   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
81194   if( rc!=SQLITE_OK ) return rc;
81195
81196   rc = sqlite3_bind_int64(s, 1, iDocid);
81197   if( rc!=SQLITE_OK ) return rc;
81198
81199   rc = sqlite3_step(s);
81200   if( rc!=SQLITE_ROW ) return rc;
81201
81202   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
81203   for(i=0; i<v->nColumn; ++i){
81204     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
81205       values[i] = NULL;
81206     }else{
81207       values[i] = string_dup((char*)sqlite3_column_text(s, i));
81208     }
81209   }
81210
81211   /* We expect only one row.  We must execute another sqlite3_step()
81212    * to complete the iteration; otherwise the table will remain locked. */
81213   rc = sqlite3_step(s);
81214   if( rc==SQLITE_DONE ){
81215     *pValues = values;
81216     return SQLITE_OK;
81217   }
81218
81219   freeStringArray(v->nColumn, values);
81220   return rc;
81221 }
81222
81223 /* delete from %_content where docid = [iDocid ] */
81224 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
81225   sqlite3_stmt *s;
81226   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
81227   if( rc!=SQLITE_OK ) return rc;
81228
81229   rc = sqlite3_bind_int64(s, 1, iDocid);
81230   if( rc!=SQLITE_OK ) return rc;
81231
81232   return sql_single_step(s);
81233 }
81234
81235 /* insert into %_segments values ([pData])
81236 **   returns assigned blockid in *piBlockid
81237 */
81238 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
81239                         sqlite_int64 *piBlockid){
81240   sqlite3_stmt *s;
81241   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
81242   if( rc!=SQLITE_OK ) return rc;
81243
81244   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
81245   if( rc!=SQLITE_OK ) return rc;
81246
81247   rc = sqlite3_step(s);
81248   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
81249   if( rc!=SQLITE_DONE ) return rc;
81250
81251   /* blockid column is an alias for rowid. */
81252   *piBlockid = sqlite3_last_insert_rowid(v->db);
81253   return SQLITE_OK;
81254 }
81255
81256 /* delete from %_segments
81257 **   where blockid between [iStartBlockid] and [iEndBlockid]
81258 **
81259 ** Deletes the range of blocks, inclusive, used to delete the blocks
81260 ** which form a segment.
81261 */
81262 static int block_delete(fulltext_vtab *v,
81263                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
81264   sqlite3_stmt *s;
81265   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
81266   if( rc!=SQLITE_OK ) return rc;
81267
81268   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
81269   if( rc!=SQLITE_OK ) return rc;
81270
81271   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
81272   if( rc!=SQLITE_OK ) return rc;
81273
81274   return sql_single_step(s);
81275 }
81276
81277 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
81278 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
81279 ** iLevel.  Otherwise returns an error.
81280 */
81281 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
81282   sqlite3_stmt *s;
81283   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
81284   if( rc!=SQLITE_OK ) return rc;
81285
81286   rc = sqlite3_bind_int(s, 1, iLevel);
81287   if( rc!=SQLITE_OK ) return rc;
81288
81289   rc = sqlite3_step(s);
81290   /* Should always get at least one row due to how max() works. */
81291   if( rc==SQLITE_DONE ) return SQLITE_DONE;
81292   if( rc!=SQLITE_ROW ) return rc;
81293
81294   /* NULL means that there were no inputs to max(). */
81295   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
81296     rc = sqlite3_step(s);
81297     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
81298     return rc;
81299   }
81300
81301   *pidx = sqlite3_column_int(s, 0);
81302
81303   /* We expect only one row.  We must execute another sqlite3_step()
81304    * to complete the iteration; otherwise the table will remain locked. */
81305   rc = sqlite3_step(s);
81306   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
81307   if( rc!=SQLITE_DONE ) return rc;
81308   return SQLITE_ROW;
81309 }
81310
81311 /* insert into %_segdir values (
81312 **   [iLevel], [idx],
81313 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
81314 **   [pRootData]
81315 ** )
81316 */
81317 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
81318                       sqlite_int64 iStartBlockid,
81319                       sqlite_int64 iLeavesEndBlockid,
81320                       sqlite_int64 iEndBlockid,
81321                       const char *pRootData, int nRootData){
81322   sqlite3_stmt *s;
81323   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
81324   if( rc!=SQLITE_OK ) return rc;
81325
81326   rc = sqlite3_bind_int(s, 1, iLevel);
81327   if( rc!=SQLITE_OK ) return rc;
81328
81329   rc = sqlite3_bind_int(s, 2, idx);
81330   if( rc!=SQLITE_OK ) return rc;
81331
81332   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
81333   if( rc!=SQLITE_OK ) return rc;
81334
81335   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
81336   if( rc!=SQLITE_OK ) return rc;
81337
81338   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
81339   if( rc!=SQLITE_OK ) return rc;
81340
81341   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
81342   if( rc!=SQLITE_OK ) return rc;
81343
81344   return sql_single_step(s);
81345 }
81346
81347 /* Queries %_segdir for the block span of the segments in level
81348 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
81349 ** SQLITE_ROW if there are blocks, else an error.
81350 */
81351 static int segdir_span(fulltext_vtab *v, int iLevel,
81352                        sqlite_int64 *piStartBlockid,
81353                        sqlite_int64 *piEndBlockid){
81354   sqlite3_stmt *s;
81355   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
81356   if( rc!=SQLITE_OK ) return rc;
81357
81358   rc = sqlite3_bind_int(s, 1, iLevel);
81359   if( rc!=SQLITE_OK ) return rc;
81360
81361   rc = sqlite3_step(s);
81362   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
81363   if( rc!=SQLITE_ROW ) return rc;
81364
81365   /* This happens if all segments at this level are entirely inline. */
81366   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
81367     /* We expect only one row.  We must execute another sqlite3_step()
81368      * to complete the iteration; otherwise the table will remain locked. */
81369     int rc2 = sqlite3_step(s);
81370     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
81371     return rc2;
81372   }
81373
81374   *piStartBlockid = sqlite3_column_int64(s, 0);
81375   *piEndBlockid = sqlite3_column_int64(s, 1);
81376
81377   /* We expect only one row.  We must execute another sqlite3_step()
81378    * to complete the iteration; otherwise the table will remain locked. */
81379   rc = sqlite3_step(s);
81380   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
81381   if( rc!=SQLITE_DONE ) return rc;
81382   return SQLITE_ROW;
81383 }
81384
81385 /* Delete the segment blocks and segment directory records for all
81386 ** segments at iLevel.
81387 */
81388 static int segdir_delete(fulltext_vtab *v, int iLevel){
81389   sqlite3_stmt *s;
81390   sqlite_int64 iStartBlockid, iEndBlockid;
81391   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
81392   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
81393
81394   if( rc==SQLITE_ROW ){
81395     rc = block_delete(v, iStartBlockid, iEndBlockid);
81396     if( rc!=SQLITE_OK ) return rc;
81397   }
81398
81399   /* Delete the segment directory itself. */
81400   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
81401   if( rc!=SQLITE_OK ) return rc;
81402
81403   rc = sqlite3_bind_int64(s, 1, iLevel);
81404   if( rc!=SQLITE_OK ) return rc;
81405
81406   return sql_single_step(s);
81407 }
81408
81409 /* TODO(shess) clearPendingTerms() is far down the file because
81410 ** writeZeroSegment() is far down the file because LeafWriter is far
81411 ** down the file.  Consider refactoring the code to move the non-vtab
81412 ** code above the vtab code so that we don't need this forward
81413 ** reference.
81414 */
81415 static int clearPendingTerms(fulltext_vtab *v);
81416
81417 /*
81418 ** Free the memory used to contain a fulltext_vtab structure.
81419 */
81420 static void fulltext_vtab_destroy(fulltext_vtab *v){
81421   int iStmt, i;
81422
81423   FTSTRACE(("FTS3 Destroy %p\n", v));
81424   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
81425     if( v->pFulltextStatements[iStmt]!=NULL ){
81426       sqlite3_finalize(v->pFulltextStatements[iStmt]);
81427       v->pFulltextStatements[iStmt] = NULL;
81428     }
81429   }
81430
81431   for( i=0; i<MERGE_COUNT; i++ ){
81432     if( v->pLeafSelectStmts[i]!=NULL ){
81433       sqlite3_finalize(v->pLeafSelectStmts[i]);
81434       v->pLeafSelectStmts[i] = NULL;
81435     }
81436   }
81437
81438   if( v->pTokenizer!=NULL ){
81439     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
81440     v->pTokenizer = NULL;
81441   }
81442
81443   clearPendingTerms(v);
81444
81445   sqlite3_free(v->azColumn);
81446   for(i = 0; i < v->nColumn; ++i) {
81447     sqlite3_free(v->azContentColumn[i]);
81448   }
81449   sqlite3_free(v->azContentColumn);
81450   sqlite3_free(v);
81451 }
81452
81453 /*
81454 ** Token types for parsing the arguments to xConnect or xCreate.
81455 */
81456 #define TOKEN_EOF         0    /* End of file */
81457 #define TOKEN_SPACE       1    /* Any kind of whitespace */
81458 #define TOKEN_ID          2    /* An identifier */
81459 #define TOKEN_STRING      3    /* A string literal */
81460 #define TOKEN_PUNCT       4    /* A single punctuation character */
81461
81462 /*
81463 ** If X is a character that can be used in an identifier then
81464 ** ftsIdChar(X) will be true.  Otherwise it is false.
81465 **
81466 ** For ASCII, any character with the high-order bit set is
81467 ** allowed in an identifier.  For 7-bit characters, 
81468 ** isFtsIdChar[X] must be 1.
81469 **
81470 ** Ticket #1066.  the SQL standard does not allow '$' in the
81471 ** middle of identfiers.  But many SQL implementations do. 
81472 ** SQLite will allow '$' in identifiers for compatibility.
81473 ** But the feature is undocumented.
81474 */
81475 static const char isFtsIdChar[] = {
81476 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
81477     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
81478     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
81479     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
81480     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
81481     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
81482     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
81483 };
81484 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
81485
81486
81487 /*
81488 ** Return the length of the token that begins at z[0]. 
81489 ** Store the token type in *tokenType before returning.
81490 */
81491 static int ftsGetToken(const char *z, int *tokenType){
81492   int i, c;
81493   switch( *z ){
81494     case 0: {
81495       *tokenType = TOKEN_EOF;
81496       return 0;
81497     }
81498     case ' ': case '\t': case '\n': case '\f': case '\r': {
81499       for(i=1; safe_isspace(z[i]); i++){}
81500       *tokenType = TOKEN_SPACE;
81501       return i;
81502     }
81503     case '`':
81504     case '\'':
81505     case '"': {
81506       int delim = z[0];
81507       for(i=1; (c=z[i])!=0; i++){
81508         if( c==delim ){
81509           if( z[i+1]==delim ){
81510             i++;
81511           }else{
81512             break;
81513           }
81514         }
81515       }
81516       *tokenType = TOKEN_STRING;
81517       return i + (c!=0);
81518     }
81519     case '[': {
81520       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
81521       *tokenType = TOKEN_ID;
81522       return i;
81523     }
81524     default: {
81525       if( !ftsIdChar(*z) ){
81526         break;
81527       }
81528       for(i=1; ftsIdChar(z[i]); i++){}
81529       *tokenType = TOKEN_ID;
81530       return i;
81531     }
81532   }
81533   *tokenType = TOKEN_PUNCT;
81534   return 1;
81535 }
81536
81537 /*
81538 ** A token extracted from a string is an instance of the following
81539 ** structure.
81540 */
81541 typedef struct FtsToken {
81542   const char *z;       /* Pointer to token text.  Not '\000' terminated */
81543   short int n;         /* Length of the token text in bytes. */
81544 } FtsToken;
81545
81546 /*
81547 ** Given a input string (which is really one of the argv[] parameters
81548 ** passed into xConnect or xCreate) split the string up into tokens.
81549 ** Return an array of pointers to '\000' terminated strings, one string
81550 ** for each non-whitespace token.
81551 **
81552 ** The returned array is terminated by a single NULL pointer.
81553 **
81554 ** Space to hold the returned array is obtained from a single
81555 ** malloc and should be freed by passing the return value to free().
81556 ** The individual strings within the token list are all a part of
81557 ** the single memory allocation and will all be freed at once.
81558 */
81559 static char **tokenizeString(const char *z, int *pnToken){
81560   int nToken = 0;
81561   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
81562   int n = 1;
81563   int e, i;
81564   int totalSize = 0;
81565   char **azToken;
81566   char *zCopy;
81567   while( n>0 ){
81568     n = ftsGetToken(z, &e);
81569     if( e!=TOKEN_SPACE ){
81570       aToken[nToken].z = z;
81571       aToken[nToken].n = n;
81572       nToken++;
81573       totalSize += n+1;
81574     }
81575     z += n;
81576   }
81577   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
81578   zCopy = (char*)&azToken[nToken];
81579   nToken--;
81580   for(i=0; i<nToken; i++){
81581     azToken[i] = zCopy;
81582     n = aToken[i].n;
81583     memcpy(zCopy, aToken[i].z, n);
81584     zCopy[n] = 0;
81585     zCopy += n+1;
81586   }
81587   azToken[nToken] = 0;
81588   sqlite3_free(aToken);
81589   *pnToken = nToken;
81590   return azToken;
81591 }
81592
81593 /*
81594 ** Convert an SQL-style quoted string into a normal string by removing
81595 ** the quote characters.  The conversion is done in-place.  If the
81596 ** input does not begin with a quote character, then this routine
81597 ** is a no-op.
81598 **
81599 ** Examples:
81600 **
81601 **     "abc"   becomes   abc
81602 **     'xyz'   becomes   xyz
81603 **     [pqr]   becomes   pqr
81604 **     `mno`   becomes   mno
81605 */
81606 static void dequoteString(char *z){
81607   int quote;
81608   int i, j;
81609   if( z==0 ) return;
81610   quote = z[0];
81611   switch( quote ){
81612     case '\'':  break;
81613     case '"':   break;
81614     case '`':   break;                /* For MySQL compatibility */
81615     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
81616     default:    return;
81617   }
81618   for(i=1, j=0; z[i]; i++){
81619     if( z[i]==quote ){
81620       if( z[i+1]==quote ){
81621         z[j++] = quote;
81622         i++;
81623       }else{
81624         z[j++] = 0;
81625         break;
81626       }
81627     }else{
81628       z[j++] = z[i];
81629     }
81630   }
81631 }
81632
81633 /*
81634 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
81635 ** token and all punctuation tokens.  Remove the quotes from
81636 ** around string literal tokens.
81637 **
81638 ** Example:
81639 **
81640 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
81641 **     output:     chinese simplifed mixed
81642 **
81643 ** Another example:
81644 **
81645 **     input:      delimiters ( '[' , ']' , '...' )
81646 **     output:     [ ] ...
81647 */
81648 static void tokenListToIdList(char **azIn){
81649   int i, j;
81650   if( azIn ){
81651     for(i=0, j=-1; azIn[i]; i++){
81652       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
81653         dequoteString(azIn[i]);
81654         if( j>=0 ){
81655           azIn[j] = azIn[i];
81656         }
81657         j++;
81658       }
81659     }
81660     azIn[j] = 0;
81661   }
81662 }
81663
81664
81665 /*
81666 ** Find the first alphanumeric token in the string zIn.  Null-terminate
81667 ** this token.  Remove any quotation marks.  And return a pointer to
81668 ** the result.
81669 */
81670 static char *firstToken(char *zIn, char **pzTail){
81671   int n, ttype;
81672   while(1){
81673     n = ftsGetToken(zIn, &ttype);
81674     if( ttype==TOKEN_SPACE ){
81675       zIn += n;
81676     }else if( ttype==TOKEN_EOF ){
81677       *pzTail = zIn;
81678       return 0;
81679     }else{
81680       zIn[n] = 0;
81681       *pzTail = &zIn[1];
81682       dequoteString(zIn);
81683       return zIn;
81684     }
81685   }
81686   /*NOTREACHED*/
81687 }
81688
81689 /* Return true if...
81690 **
81691 **   *  s begins with the string t, ignoring case
81692 **   *  s is longer than t
81693 **   *  The first character of s beyond t is not a alphanumeric
81694 ** 
81695 ** Ignore leading space in *s.
81696 **
81697 ** To put it another way, return true if the first token of
81698 ** s[] is t[].
81699 */
81700 static int startsWith(const char *s, const char *t){
81701   while( safe_isspace(*s) ){ s++; }
81702   while( *t ){
81703     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
81704   }
81705   return *s!='_' && !safe_isalnum(*s);
81706 }
81707
81708 /*
81709 ** An instance of this structure defines the "spec" of a
81710 ** full text index.  This structure is populated by parseSpec
81711 ** and use by fulltextConnect and fulltextCreate.
81712 */
81713 typedef struct TableSpec {
81714   const char *zDb;         /* Logical database name */
81715   const char *zName;       /* Name of the full-text index */
81716   int nColumn;             /* Number of columns to be indexed */
81717   char **azColumn;         /* Original names of columns to be indexed */
81718   char **azContentColumn;  /* Column names for %_content */
81719   char **azTokenizer;      /* Name of tokenizer and its arguments */
81720 } TableSpec;
81721
81722 /*
81723 ** Reclaim all of the memory used by a TableSpec
81724 */
81725 static void clearTableSpec(TableSpec *p) {
81726   sqlite3_free(p->azColumn);
81727   sqlite3_free(p->azContentColumn);
81728   sqlite3_free(p->azTokenizer);
81729 }
81730
81731 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
81732  *
81733  * CREATE VIRTUAL TABLE email
81734  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
81735  *
81736  * We return parsed information in a TableSpec structure.
81737  * 
81738  */
81739 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
81740                      char**pzErr){
81741   int i, n;
81742   char *z, *zDummy;
81743   char **azArg;
81744   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
81745
81746   assert( argc>=3 );
81747   /* Current interface:
81748   ** argv[0] - module name
81749   ** argv[1] - database name
81750   ** argv[2] - table name
81751   ** argv[3..] - columns, optionally followed by tokenizer specification
81752   **             and snippet delimiters specification.
81753   */
81754
81755   /* Make a copy of the complete argv[][] array in a single allocation.
81756   ** The argv[][] array is read-only and transient.  We can write to the
81757   ** copy in order to modify things and the copy is persistent.
81758   */
81759   CLEAR(pSpec);
81760   for(i=n=0; i<argc; i++){
81761     n += strlen(argv[i]) + 1;
81762   }
81763   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
81764   if( azArg==0 ){
81765     return SQLITE_NOMEM;
81766   }
81767   z = (char*)&azArg[argc];
81768   for(i=0; i<argc; i++){
81769     azArg[i] = z;
81770     strcpy(z, argv[i]);
81771     z += strlen(z)+1;
81772   }
81773
81774   /* Identify the column names and the tokenizer and delimiter arguments
81775   ** in the argv[][] array.
81776   */
81777   pSpec->zDb = azArg[1];
81778   pSpec->zName = azArg[2];
81779   pSpec->nColumn = 0;
81780   pSpec->azColumn = azArg;
81781   zTokenizer = "tokenize simple";
81782   for(i=3; i<argc; ++i){
81783     if( startsWith(azArg[i],"tokenize") ){
81784       zTokenizer = azArg[i];
81785     }else{
81786       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
81787       pSpec->nColumn++;
81788     }
81789   }
81790   if( pSpec->nColumn==0 ){
81791     azArg[0] = "content";
81792     pSpec->nColumn = 1;
81793   }
81794
81795   /*
81796   ** Construct the list of content column names.
81797   **
81798   ** Each content column name will be of the form cNNAAAA
81799   ** where NN is the column number and AAAA is the sanitized
81800   ** column name.  "sanitized" means that special characters are
81801   ** converted to "_".  The cNN prefix guarantees that all column
81802   ** names are unique.
81803   **
81804   ** The AAAA suffix is not strictly necessary.  It is included
81805   ** for the convenience of people who might examine the generated
81806   ** %_content table and wonder what the columns are used for.
81807   */
81808   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
81809   if( pSpec->azContentColumn==0 ){
81810     clearTableSpec(pSpec);
81811     return SQLITE_NOMEM;
81812   }
81813   for(i=0; i<pSpec->nColumn; i++){
81814     char *p;
81815     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
81816     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
81817       if( !safe_isalnum(*p) ) *p = '_';
81818     }
81819   }
81820
81821   /*
81822   ** Parse the tokenizer specification string.
81823   */
81824   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
81825   tokenListToIdList(pSpec->azTokenizer);
81826
81827   return SQLITE_OK;
81828 }
81829
81830 /*
81831 ** Generate a CREATE TABLE statement that describes the schema of
81832 ** the virtual table.  Return a pointer to this schema string.
81833 **
81834 ** Space is obtained from sqlite3_mprintf() and should be freed
81835 ** using sqlite3_free().
81836 */
81837 static char *fulltextSchema(
81838   int nColumn,                  /* Number of columns */
81839   const char *const* azColumn,  /* List of columns */
81840   const char *zTableName        /* Name of the table */
81841 ){
81842   int i;
81843   char *zSchema, *zNext;
81844   const char *zSep = "(";
81845   zSchema = sqlite3_mprintf("CREATE TABLE x");
81846   for(i=0; i<nColumn; i++){
81847     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
81848     sqlite3_free(zSchema);
81849     zSchema = zNext;
81850     zSep = ",";
81851   }
81852   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
81853   sqlite3_free(zSchema);
81854   zSchema = zNext;
81855   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
81856   sqlite3_free(zSchema);
81857   return zNext;
81858 }
81859
81860 /*
81861 ** Build a new sqlite3_vtab structure that will describe the
81862 ** fulltext index defined by spec.
81863 */
81864 static int constructVtab(
81865   sqlite3 *db,              /* The SQLite database connection */
81866   fts3Hash *pHash,          /* Hash table containing tokenizers */
81867   TableSpec *spec,          /* Parsed spec information from parseSpec() */
81868   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
81869   char **pzErr              /* Write any error message here */
81870 ){
81871   int rc;
81872   int n;
81873   fulltext_vtab *v = 0;
81874   const sqlite3_tokenizer_module *m = NULL;
81875   char *schema;
81876
81877   char const *zTok;         /* Name of tokenizer to use for this fts table */
81878   int nTok;                 /* Length of zTok, including nul terminator */
81879
81880   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
81881   if( v==0 ) return SQLITE_NOMEM;
81882   CLEAR(v);
81883   /* sqlite will initialize v->base */
81884   v->db = db;
81885   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
81886   v->zName = spec->zName;   /* Freed when azColumn is freed */
81887   v->nColumn = spec->nColumn;
81888   v->azContentColumn = spec->azContentColumn;
81889   spec->azContentColumn = 0;
81890   v->azColumn = spec->azColumn;
81891   spec->azColumn = 0;
81892
81893   if( spec->azTokenizer==0 ){
81894     return SQLITE_NOMEM;
81895   }
81896
81897   zTok = spec->azTokenizer[0]; 
81898   if( !zTok ){
81899     zTok = "simple";
81900   }
81901   nTok = strlen(zTok)+1;
81902
81903   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
81904   if( !m ){
81905     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
81906     rc = SQLITE_ERROR;
81907     goto err;
81908   }
81909
81910   for(n=0; spec->azTokenizer[n]; n++){}
81911   if( n ){
81912     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
81913                     &v->pTokenizer);
81914   }else{
81915     rc = m->xCreate(0, 0, &v->pTokenizer);
81916   }
81917   if( rc!=SQLITE_OK ) goto err;
81918   v->pTokenizer->pModule = m;
81919
81920   /* TODO: verify the existence of backing tables foo_content, foo_term */
81921
81922   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
81923                           spec->zName);
81924   rc = sqlite3_declare_vtab(db, schema);
81925   sqlite3_free(schema);
81926   if( rc!=SQLITE_OK ) goto err;
81927
81928   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
81929
81930   /* Indicate that the buffer is not live. */
81931   v->nPendingData = -1;
81932
81933   *ppVTab = &v->base;
81934   FTSTRACE(("FTS3 Connect %p\n", v));
81935
81936   return rc;
81937
81938 err:
81939   fulltext_vtab_destroy(v);
81940   return rc;
81941 }
81942
81943 static int fulltextConnect(
81944   sqlite3 *db,
81945   void *pAux,
81946   int argc, const char *const*argv,
81947   sqlite3_vtab **ppVTab,
81948   char **pzErr
81949 ){
81950   TableSpec spec;
81951   int rc = parseSpec(&spec, argc, argv, pzErr);
81952   if( rc!=SQLITE_OK ) return rc;
81953
81954   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
81955   clearTableSpec(&spec);
81956   return rc;
81957 }
81958
81959 /* The %_content table holds the text of each document, with
81960 ** the docid column exposed as the SQLite rowid for the table.
81961 */
81962 /* TODO(shess) This comment needs elaboration to match the updated
81963 ** code.  Work it into the top-of-file comment at that time.
81964 */
81965 static int fulltextCreate(sqlite3 *db, void *pAux,
81966                           int argc, const char * const *argv,
81967                           sqlite3_vtab **ppVTab, char **pzErr){
81968   int rc;
81969   TableSpec spec;
81970   StringBuffer schema;
81971   FTSTRACE(("FTS3 Create\n"));
81972
81973   rc = parseSpec(&spec, argc, argv, pzErr);
81974   if( rc!=SQLITE_OK ) return rc;
81975
81976   initStringBuffer(&schema);
81977   append(&schema, "CREATE TABLE %_content(");
81978   append(&schema, "  docid INTEGER PRIMARY KEY,");
81979   appendList(&schema, spec.nColumn, spec.azContentColumn);
81980   append(&schema, ")");
81981   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
81982   stringBufferDestroy(&schema);
81983   if( rc!=SQLITE_OK ) goto out;
81984
81985   rc = sql_exec(db, spec.zDb, spec.zName,
81986                 "create table %_segments("
81987                 "  blockid INTEGER PRIMARY KEY,"
81988                 "  block blob"
81989                 ");"
81990                 );
81991   if( rc!=SQLITE_OK ) goto out;
81992
81993   rc = sql_exec(db, spec.zDb, spec.zName,
81994                 "create table %_segdir("
81995                 "  level integer,"
81996                 "  idx integer,"
81997                 "  start_block integer,"
81998                 "  leaves_end_block integer,"
81999                 "  end_block integer,"
82000                 "  root blob,"
82001                 "  primary key(level, idx)"
82002                 ");");
82003   if( rc!=SQLITE_OK ) goto out;
82004
82005   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
82006
82007 out:
82008   clearTableSpec(&spec);
82009   return rc;
82010 }
82011
82012 /* Decide how to handle an SQL query. */
82013 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
82014   fulltext_vtab *v = (fulltext_vtab *)pVTab;
82015   int i;
82016   FTSTRACE(("FTS3 BestIndex\n"));
82017
82018   for(i=0; i<pInfo->nConstraint; ++i){
82019     const struct sqlite3_index_constraint *pConstraint;
82020     pConstraint = &pInfo->aConstraint[i];
82021     if( pConstraint->usable ) {
82022       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
82023           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
82024         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
82025         FTSTRACE(("FTS3 QUERY_DOCID\n"));
82026       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
82027                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
82028         /* full-text search */
82029         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
82030         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
82031       } else continue;
82032
82033       pInfo->aConstraintUsage[i].argvIndex = 1;
82034       pInfo->aConstraintUsage[i].omit = 1;
82035
82036       /* An arbitrary value for now.
82037        * TODO: Perhaps docid matches should be considered cheaper than
82038        * full-text searches. */
82039       pInfo->estimatedCost = 1.0;   
82040
82041       return SQLITE_OK;
82042     }
82043   }
82044   pInfo->idxNum = QUERY_GENERIC;
82045   return SQLITE_OK;
82046 }
82047
82048 static int fulltextDisconnect(sqlite3_vtab *pVTab){
82049   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
82050   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
82051   return SQLITE_OK;
82052 }
82053
82054 static int fulltextDestroy(sqlite3_vtab *pVTab){
82055   fulltext_vtab *v = (fulltext_vtab *)pVTab;
82056   int rc;
82057
82058   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
82059   rc = sql_exec(v->db, v->zDb, v->zName,
82060                 "drop table if exists %_content;"
82061                 "drop table if exists %_segments;"
82062                 "drop table if exists %_segdir;"
82063                 );
82064   if( rc!=SQLITE_OK ) return rc;
82065
82066   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
82067   return SQLITE_OK;
82068 }
82069
82070 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
82071   fulltext_cursor *c;
82072
82073   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
82074   if( c ){
82075     memset(c, 0, sizeof(fulltext_cursor));
82076     /* sqlite will initialize c->base */
82077     *ppCursor = &c->base;
82078     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
82079     return SQLITE_OK;
82080   }else{
82081     return SQLITE_NOMEM;
82082   }
82083 }
82084
82085
82086 /* Free all of the dynamically allocated memory held by *q
82087 */
82088 static void queryClear(Query *q){
82089   int i;
82090   for(i = 0; i < q->nTerms; ++i){
82091     sqlite3_free(q->pTerms[i].pTerm);
82092   }
82093   sqlite3_free(q->pTerms);
82094   CLEAR(q);
82095 }
82096
82097 /* Free all of the dynamically allocated memory held by the
82098 ** Snippet
82099 */
82100 static void snippetClear(Snippet *p){
82101   sqlite3_free(p->aMatch);
82102   sqlite3_free(p->zOffset);
82103   sqlite3_free(p->zSnippet);
82104   CLEAR(p);
82105 }
82106 /*
82107 ** Append a single entry to the p->aMatch[] log.
82108 */
82109 static void snippetAppendMatch(
82110   Snippet *p,               /* Append the entry to this snippet */
82111   int iCol, int iTerm,      /* The column and query term */
82112   int iToken,               /* Matching token in document */
82113   int iStart, int nByte     /* Offset and size of the match */
82114 ){
82115   int i;
82116   struct snippetMatch *pMatch;
82117   if( p->nMatch+1>=p->nAlloc ){
82118     p->nAlloc = p->nAlloc*2 + 10;
82119     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
82120     if( p->aMatch==0 ){
82121       p->nMatch = 0;
82122       p->nAlloc = 0;
82123       return;
82124     }
82125   }
82126   i = p->nMatch++;
82127   pMatch = &p->aMatch[i];
82128   pMatch->iCol = iCol;
82129   pMatch->iTerm = iTerm;
82130   pMatch->iToken = iToken;
82131   pMatch->iStart = iStart;
82132   pMatch->nByte = nByte;
82133 }
82134
82135 /*
82136 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
82137 */
82138 #define FTS3_ROTOR_SZ   (32)
82139 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
82140
82141 /*
82142 ** Add entries to pSnippet->aMatch[] for every match that occurs against
82143 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
82144 */
82145 static void snippetOffsetsOfColumn(
82146   Query *pQuery,
82147   Snippet *pSnippet,
82148   int iColumn,
82149   const char *zDoc,
82150   int nDoc
82151 ){
82152   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
82153   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
82154   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
82155   fulltext_vtab *pVtab;                /* The full text index */
82156   int nColumn;                         /* Number of columns in the index */
82157   const QueryTerm *aTerm;              /* Query string terms */
82158   int nTerm;                           /* Number of query string terms */  
82159   int i, j;                            /* Loop counters */
82160   int rc;                              /* Return code */
82161   unsigned int match, prevMatch;       /* Phrase search bitmasks */
82162   const char *zToken;                  /* Next token from the tokenizer */
82163   int nToken;                          /* Size of zToken */
82164   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
82165
82166   /* The following variables keep a circular buffer of the last
82167   ** few tokens */
82168   unsigned int iRotor = 0;             /* Index of current token */
82169   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
82170   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
82171
82172   pVtab = pQuery->pFts;
82173   nColumn = pVtab->nColumn;
82174   pTokenizer = pVtab->pTokenizer;
82175   pTModule = pTokenizer->pModule;
82176   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
82177   if( rc ) return;
82178   pTCursor->pTokenizer = pTokenizer;
82179   aTerm = pQuery->pTerms;
82180   nTerm = pQuery->nTerms;
82181   if( nTerm>=FTS3_ROTOR_SZ ){
82182     nTerm = FTS3_ROTOR_SZ - 1;
82183   }
82184   prevMatch = 0;
82185   while(1){
82186     rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
82187     if( rc ) break;
82188     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
82189     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
82190     match = 0;
82191     for(i=0; i<nTerm; i++){
82192       int iCol;
82193       iCol = aTerm[i].iColumn;
82194       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
82195       if( aTerm[i].nTerm>nToken ) continue;
82196       if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
82197       assert( aTerm[i].nTerm<=nToken );
82198       if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
82199       if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
82200       match |= 1<<i;
82201       if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
82202         for(j=aTerm[i].iPhrase-1; j>=0; j--){
82203           int k = (iRotor-j) & FTS3_ROTOR_MASK;
82204           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
82205                 iRotorBegin[k], iRotorLen[k]);
82206         }
82207       }
82208     }
82209     prevMatch = match<<1;
82210     iRotor++;
82211   }
82212   pTModule->xClose(pTCursor);  
82213 }
82214
82215 /*
82216 ** Remove entries from the pSnippet structure to account for the NEAR
82217 ** operator. When this is called, pSnippet contains the list of token 
82218 ** offsets produced by treating all NEAR operators as AND operators.
82219 ** This function removes any entries that should not be present after
82220 ** accounting for the NEAR restriction. For example, if the queried
82221 ** document is:
82222 **
82223 **     "A B C D E A"
82224 **
82225 ** and the query is:
82226 ** 
82227 **     A NEAR/0 E
82228 **
82229 ** then when this function is called the Snippet contains token offsets
82230 ** 0, 4 and 5. This function removes the "0" entry (because the first A
82231 ** is not near enough to an E).
82232 */
82233 static void trimSnippetOffsetsForNear(Query *pQuery, Snippet *pSnippet){
82234   int ii;
82235   int iDir = 1;
82236
82237   while(iDir>-2) {
82238     assert( iDir==1 || iDir==-1 );
82239     for(ii=0; ii<pSnippet->nMatch; ii++){
82240       int jj;
82241       int nNear;
82242       struct snippetMatch *pMatch = &pSnippet->aMatch[ii];
82243       QueryTerm *pQueryTerm = &pQuery->pTerms[pMatch->iTerm];
82244
82245       if( (pMatch->iTerm+iDir)<0 
82246        || (pMatch->iTerm+iDir)>=pQuery->nTerms
82247       ){
82248         continue;
82249       }
82250      
82251       nNear = pQueryTerm->nNear;
82252       if( iDir<0 ){
82253         nNear = pQueryTerm[-1].nNear;
82254       }
82255   
82256       if( pMatch->iTerm>=0 && nNear ){
82257         int isOk = 0;
82258         int iNextTerm = pMatch->iTerm+iDir;
82259         int iPrevTerm = iNextTerm;
82260
82261         int iEndToken;
82262         int iStartToken;
82263
82264         if( iDir<0 ){
82265           int nPhrase = 1;
82266           iStartToken = pMatch->iToken;
82267           while( (pMatch->iTerm+nPhrase)<pQuery->nTerms 
82268               && pQuery->pTerms[pMatch->iTerm+nPhrase].iPhrase>1 
82269           ){
82270             nPhrase++;
82271           }
82272           iEndToken = iStartToken + nPhrase - 1;
82273         }else{
82274           iEndToken   = pMatch->iToken;
82275           iStartToken = pMatch->iToken+1-pQueryTerm->iPhrase;
82276         }
82277
82278         while( pQuery->pTerms[iNextTerm].iPhrase>1 ){
82279           iNextTerm--;
82280         }
82281         while( (iPrevTerm+1)<pQuery->nTerms && 
82282                pQuery->pTerms[iPrevTerm+1].iPhrase>1 
82283         ){
82284           iPrevTerm++;
82285         }
82286   
82287         for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
82288           struct snippetMatch *p = &pSnippet->aMatch[jj];
82289           if( p->iCol==pMatch->iCol && ((
82290                p->iTerm==iNextTerm && 
82291                p->iToken>iEndToken && 
82292                p->iToken<=iEndToken+nNear
82293           ) || (
82294                p->iTerm==iPrevTerm && 
82295                p->iToken<iStartToken && 
82296                p->iToken>=iStartToken-nNear
82297           ))){
82298             isOk = 1;
82299           }
82300         }
82301         if( !isOk ){
82302           for(jj=1-pQueryTerm->iPhrase; jj<=0; jj++){
82303             pMatch[jj].iTerm = -1;
82304           }
82305           ii = -1;
82306           iDir = 1;
82307         }
82308       }
82309     }
82310     iDir -= 2;
82311   }
82312 }
82313
82314 /*
82315 ** Compute all offsets for the current row of the query.  
82316 ** If the offsets have already been computed, this routine is a no-op.
82317 */
82318 static void snippetAllOffsets(fulltext_cursor *p){
82319   int nColumn;
82320   int iColumn, i;
82321   int iFirst, iLast;
82322   fulltext_vtab *pFts;
82323
82324   if( p->snippet.nMatch ) return;
82325   if( p->q.nTerms==0 ) return;
82326   pFts = p->q.pFts;
82327   nColumn = pFts->nColumn;
82328   iColumn = (p->iCursorType - QUERY_FULLTEXT);
82329   if( iColumn<0 || iColumn>=nColumn ){
82330     iFirst = 0;
82331     iLast = nColumn-1;
82332   }else{
82333     iFirst = iColumn;
82334     iLast = iColumn;
82335   }
82336   for(i=iFirst; i<=iLast; i++){
82337     const char *zDoc;
82338     int nDoc;
82339     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
82340     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
82341     snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
82342   }
82343
82344   trimSnippetOffsetsForNear(&p->q, &p->snippet);
82345 }
82346
82347 /*
82348 ** Convert the information in the aMatch[] array of the snippet
82349 ** into the string zOffset[0..nOffset-1].
82350 */
82351 static void snippetOffsetText(Snippet *p){
82352   int i;
82353   int cnt = 0;
82354   StringBuffer sb;
82355   char zBuf[200];
82356   if( p->zOffset ) return;
82357   initStringBuffer(&sb);
82358   for(i=0; i<p->nMatch; i++){
82359     struct snippetMatch *pMatch = &p->aMatch[i];
82360     if( pMatch->iTerm>=0 ){
82361       /* If snippetMatch.iTerm is less than 0, then the match was 
82362       ** discarded as part of processing the NEAR operator (see the 
82363       ** trimSnippetOffsetsForNear() function for details). Ignore 
82364       ** it in this case
82365       */
82366       zBuf[0] = ' ';
82367       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
82368           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
82369       append(&sb, zBuf);
82370       cnt++;
82371     }
82372   }
82373   p->zOffset = stringBufferData(&sb);
82374   p->nOffset = stringBufferLength(&sb);
82375 }
82376
82377 /*
82378 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
82379 ** of matching words some of which might be in zDoc.  zDoc is column
82380 ** number iCol.
82381 **
82382 ** iBreak is suggested spot in zDoc where we could begin or end an
82383 ** excerpt.  Return a value similar to iBreak but possibly adjusted
82384 ** to be a little left or right so that the break point is better.
82385 */
82386 static int wordBoundary(
82387   int iBreak,                   /* The suggested break point */
82388   const char *zDoc,             /* Document text */
82389   int nDoc,                     /* Number of bytes in zDoc[] */
82390   struct snippetMatch *aMatch,  /* Matching words */
82391   int nMatch,                   /* Number of entries in aMatch[] */
82392   int iCol                      /* The column number for zDoc[] */
82393 ){
82394   int i;
82395   if( iBreak<=10 ){
82396     return 0;
82397   }
82398   if( iBreak>=nDoc-10 ){
82399     return nDoc;
82400   }
82401   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
82402   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
82403   if( i<nMatch ){
82404     if( aMatch[i].iStart<iBreak+10 ){
82405       return aMatch[i].iStart;
82406     }
82407     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
82408       return aMatch[i-1].iStart;
82409     }
82410   }
82411   for(i=1; i<=10; i++){
82412     if( safe_isspace(zDoc[iBreak-i]) ){
82413       return iBreak - i + 1;
82414     }
82415     if( safe_isspace(zDoc[iBreak+i]) ){
82416       return iBreak + i + 1;
82417     }
82418   }
82419   return iBreak;
82420 }
82421
82422
82423
82424 /*
82425 ** Allowed values for Snippet.aMatch[].snStatus
82426 */
82427 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
82428 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
82429
82430 /*
82431 ** Generate the text of a snippet.
82432 */
82433 static void snippetText(
82434   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
82435   const char *zStartMark,     /* Markup to appear before each match */
82436   const char *zEndMark,       /* Markup to appear after each match */
82437   const char *zEllipsis       /* Ellipsis mark */
82438 ){
82439   int i, j;
82440   struct snippetMatch *aMatch;
82441   int nMatch;
82442   int nDesired;
82443   StringBuffer sb;
82444   int tailCol;
82445   int tailOffset;
82446   int iCol;
82447   int nDoc;
82448   const char *zDoc;
82449   int iStart, iEnd;
82450   int tailEllipsis = 0;
82451   int iMatch;
82452   
82453
82454   sqlite3_free(pCursor->snippet.zSnippet);
82455   pCursor->snippet.zSnippet = 0;
82456   aMatch = pCursor->snippet.aMatch;
82457   nMatch = pCursor->snippet.nMatch;
82458   initStringBuffer(&sb);
82459
82460   for(i=0; i<nMatch; i++){
82461     aMatch[i].snStatus = SNIPPET_IGNORE;
82462   }
82463   nDesired = 0;
82464   for(i=0; i<pCursor->q.nTerms; i++){
82465     for(j=0; j<nMatch; j++){
82466       if( aMatch[j].iTerm==i ){
82467         aMatch[j].snStatus = SNIPPET_DESIRED;
82468         nDesired++;
82469         break;
82470       }
82471     }
82472   }
82473
82474   iMatch = 0;
82475   tailCol = -1;
82476   tailOffset = 0;
82477   for(i=0; i<nMatch && nDesired>0; i++){
82478     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
82479     nDesired--;
82480     iCol = aMatch[i].iCol;
82481     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
82482     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
82483     iStart = aMatch[i].iStart - 40;
82484     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
82485     if( iStart<=10 ){
82486       iStart = 0;
82487     }
82488     if( iCol==tailCol && iStart<=tailOffset+20 ){
82489       iStart = tailOffset;
82490     }
82491     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
82492       trimWhiteSpace(&sb);
82493       appendWhiteSpace(&sb);
82494       append(&sb, zEllipsis);
82495       appendWhiteSpace(&sb);
82496     }
82497     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
82498     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
82499     if( iEnd>=nDoc-10 ){
82500       iEnd = nDoc;
82501       tailEllipsis = 0;
82502     }else{
82503       tailEllipsis = 1;
82504     }
82505     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
82506     while( iStart<iEnd ){
82507       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
82508              && aMatch[iMatch].iCol<=iCol ){
82509         iMatch++;
82510       }
82511       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
82512              && aMatch[iMatch].iCol==iCol ){
82513         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
82514         iStart = aMatch[iMatch].iStart;
82515         append(&sb, zStartMark);
82516         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
82517         append(&sb, zEndMark);
82518         iStart += aMatch[iMatch].nByte;
82519         for(j=iMatch+1; j<nMatch; j++){
82520           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
82521               && aMatch[j].snStatus==SNIPPET_DESIRED ){
82522             nDesired--;
82523             aMatch[j].snStatus = SNIPPET_IGNORE;
82524           }
82525         }
82526       }else{
82527         nappend(&sb, &zDoc[iStart], iEnd - iStart);
82528         iStart = iEnd;
82529       }
82530     }
82531     tailCol = iCol;
82532     tailOffset = iEnd;
82533   }
82534   trimWhiteSpace(&sb);
82535   if( tailEllipsis ){
82536     appendWhiteSpace(&sb);
82537     append(&sb, zEllipsis);
82538   }
82539   pCursor->snippet.zSnippet = stringBufferData(&sb);
82540   pCursor->snippet.nSnippet = stringBufferLength(&sb);
82541 }
82542
82543
82544 /*
82545 ** Close the cursor.  For additional information see the documentation
82546 ** on the xClose method of the virtual table interface.
82547 */
82548 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
82549   fulltext_cursor *c = (fulltext_cursor *) pCursor;
82550   FTSTRACE(("FTS3 Close %p\n", c));
82551   sqlite3_finalize(c->pStmt);
82552   queryClear(&c->q);
82553   snippetClear(&c->snippet);
82554   if( c->result.nData!=0 ) dlrDestroy(&c->reader);
82555   dataBufferDestroy(&c->result);
82556   sqlite3_free(c);
82557   return SQLITE_OK;
82558 }
82559
82560 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
82561   fulltext_cursor *c = (fulltext_cursor *) pCursor;
82562   int rc;
82563
82564   FTSTRACE(("FTS3 Next %p\n", pCursor));
82565   snippetClear(&c->snippet);
82566   if( c->iCursorType < QUERY_FULLTEXT ){
82567     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
82568     rc = sqlite3_step(c->pStmt);
82569     switch( rc ){
82570       case SQLITE_ROW:
82571         c->eof = 0;
82572         return SQLITE_OK;
82573       case SQLITE_DONE:
82574         c->eof = 1;
82575         return SQLITE_OK;
82576       default:
82577         c->eof = 1;
82578         return rc;
82579     }
82580   } else {  /* full-text query */
82581     rc = sqlite3_reset(c->pStmt);
82582     if( rc!=SQLITE_OK ) return rc;
82583
82584     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
82585       c->eof = 1;
82586       return SQLITE_OK;
82587     }
82588     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
82589     dlrStep(&c->reader);
82590     if( rc!=SQLITE_OK ) return rc;
82591     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
82592     rc = sqlite3_step(c->pStmt);
82593     if( rc==SQLITE_ROW ){   /* the case we expect */
82594       c->eof = 0;
82595       return SQLITE_OK;
82596     }
82597     /* an error occurred; abort */
82598     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
82599   }
82600 }
82601
82602
82603 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
82604 ** another file, term_select() could be pushed above
82605 ** docListOfTerm().
82606 */
82607 static int termSelect(fulltext_vtab *v, int iColumn,
82608                       const char *pTerm, int nTerm, int isPrefix,
82609                       DocListType iType, DataBuffer *out);
82610
82611 /* Return a DocList corresponding to the query term *pTerm.  If *pTerm
82612 ** is the first term of a phrase query, go ahead and evaluate the phrase
82613 ** query and return the doclist for the entire phrase query.
82614 **
82615 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
82616 ** overwritten.
82617 */
82618 static int docListOfTerm(
82619   fulltext_vtab *v,    /* The full text index */
82620   int iColumn,         /* column to restrict to.  No restriction if >=nColumn */
82621   QueryTerm *pQTerm,   /* Term we are looking for, or 1st term of a phrase */
82622   DataBuffer *pResult  /* Write the result here */
82623 ){
82624   DataBuffer left, right, new;
82625   int i, rc;
82626
82627   /* No phrase search if no position info. */
82628   assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
82629
82630   /* This code should never be called with buffered updates. */
82631   assert( v->nPendingData<0 );
82632
82633   dataBufferInit(&left, 0);
82634   rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
82635                   (0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS), &left);
82636   if( rc ) return rc;
82637   for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
82638     /* If this token is connected to the next by a NEAR operator, and
82639     ** the next token is the start of a phrase, then set nPhraseRight
82640     ** to the number of tokens in the phrase. Otherwise leave it at 1.
82641     */
82642     int nPhraseRight = 1;
82643     while( (i+nPhraseRight)<=pQTerm->nPhrase 
82644         && pQTerm[i+nPhraseRight].nNear==0 
82645     ){
82646       nPhraseRight++;
82647     }
82648
82649     dataBufferInit(&right, 0);
82650     rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
82651                     pQTerm[i].isPrefix, DL_POSITIONS, &right);
82652     if( rc ){
82653       dataBufferDestroy(&left);
82654       return rc;
82655     }
82656     dataBufferInit(&new, 0);
82657     docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
82658                        pQTerm[i-1].nNear, pQTerm[i-1].iPhrase + nPhraseRight,
82659                        ((i<pQTerm->nPhrase) ? DL_POSITIONS : DL_DOCIDS),
82660                        &new);
82661     dataBufferDestroy(&left);
82662     dataBufferDestroy(&right);
82663     left = new;
82664   }
82665   *pResult = left;
82666   return SQLITE_OK;
82667 }
82668
82669 /* Add a new term pTerm[0..nTerm-1] to the query *q.
82670 */
82671 static void queryAdd(Query *q, const char *pTerm, int nTerm){
82672   QueryTerm *t;
82673   ++q->nTerms;
82674   q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
82675   if( q->pTerms==0 ){
82676     q->nTerms = 0;
82677     return;
82678   }
82679   t = &q->pTerms[q->nTerms - 1];
82680   CLEAR(t);
82681   t->pTerm = sqlite3_malloc(nTerm+1);
82682   memcpy(t->pTerm, pTerm, nTerm);
82683   t->pTerm[nTerm] = 0;
82684   t->nTerm = nTerm;
82685   t->isOr = q->nextIsOr;
82686   t->isPrefix = 0;
82687   q->nextIsOr = 0;
82688   t->iColumn = q->nextColumn;
82689   q->nextColumn = q->dfltColumn;
82690 }
82691
82692 /*
82693 ** Check to see if the string zToken[0...nToken-1] matches any
82694 ** column name in the virtual table.   If it does,
82695 ** return the zero-indexed column number.  If not, return -1.
82696 */
82697 static int checkColumnSpecifier(
82698   fulltext_vtab *pVtab,    /* The virtual table */
82699   const char *zToken,      /* Text of the token */
82700   int nToken               /* Number of characters in the token */
82701 ){
82702   int i;
82703   for(i=0; i<pVtab->nColumn; i++){
82704     if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
82705         && pVtab->azColumn[i][nToken]==0 ){
82706       return i;
82707     }
82708   }
82709   return -1;
82710 }
82711
82712 /*
82713 ** Parse the text at pSegment[0..nSegment-1].  Add additional terms
82714 ** to the query being assemblied in pQuery.
82715 **
82716 ** inPhrase is true if pSegment[0..nSegement-1] is contained within
82717 ** double-quotes.  If inPhrase is true, then the first term
82718 ** is marked with the number of terms in the phrase less one and
82719 ** OR and "-" syntax is ignored.  If inPhrase is false, then every
82720 ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
82721 */
82722 static int tokenizeSegment(
82723   sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
82724   const char *pSegment, int nSegment,     /* Query expression being parsed */
82725   int inPhrase,                           /* True if within "..." */
82726   Query *pQuery                           /* Append results here */
82727 ){
82728   const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
82729   sqlite3_tokenizer_cursor *pCursor;
82730   int firstIndex = pQuery->nTerms;
82731   int iCol;
82732   int nTerm = 1;
82733   
82734   int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
82735   if( rc!=SQLITE_OK ) return rc;
82736   pCursor->pTokenizer = pTokenizer;
82737
82738   while( 1 ){
82739     const char *pToken;
82740     int nToken, iBegin, iEnd, iPos;
82741
82742     rc = pModule->xNext(pCursor,
82743                         &pToken, &nToken,
82744                         &iBegin, &iEnd, &iPos);
82745     if( rc!=SQLITE_OK ) break;
82746     if( !inPhrase &&
82747         pSegment[iEnd]==':' &&
82748          (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){
82749       pQuery->nextColumn = iCol;
82750       continue;
82751     }
82752     if( !inPhrase && pQuery->nTerms>0 && nToken==2 
82753      && pSegment[iBegin+0]=='O'
82754      && pSegment[iBegin+1]=='R' 
82755     ){
82756       pQuery->nextIsOr = 1;
82757       continue;
82758     }
82759     if( !inPhrase && pQuery->nTerms>0 && !pQuery->nextIsOr && nToken==4 
82760       && pSegment[iBegin+0]=='N' 
82761       && pSegment[iBegin+1]=='E' 
82762       && pSegment[iBegin+2]=='A' 
82763       && pSegment[iBegin+3]=='R' 
82764     ){
82765       QueryTerm *pTerm = &pQuery->pTerms[pQuery->nTerms-1];
82766       if( (iBegin+6)<nSegment 
82767        && pSegment[iBegin+4] == '/'
82768        && pSegment[iBegin+5]>='0' && pSegment[iBegin+5]<='9'
82769       ){
82770         pTerm->nNear = (pSegment[iBegin+5] - '0');
82771         nToken += 2;
82772         if( pSegment[iBegin+6]>='0' && pSegment[iBegin+6]<=9 ){
82773           pTerm->nNear = pTerm->nNear * 10 + (pSegment[iBegin+6] - '0');
82774           iEnd++;
82775         }
82776         pModule->xNext(pCursor, &pToken, &nToken, &iBegin, &iEnd, &iPos);
82777       } else {
82778         pTerm->nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
82779       }
82780       pTerm->nNear++;
82781       continue;
82782     }
82783
82784     queryAdd(pQuery, pToken, nToken);
82785     if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){
82786       pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
82787     }
82788     if( iEnd<nSegment && pSegment[iEnd]=='*' ){
82789       pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
82790     }
82791     pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
82792     if( inPhrase ){
82793       nTerm++;
82794     }
82795   }
82796
82797   if( inPhrase && pQuery->nTerms>firstIndex ){
82798     pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
82799   }
82800
82801   return pModule->xClose(pCursor);
82802 }
82803
82804 /* Parse a query string, yielding a Query object pQuery.
82805 **
82806 ** The calling function will need to queryClear() to clean up
82807 ** the dynamically allocated memory held by pQuery.
82808 */
82809 static int parseQuery(
82810   fulltext_vtab *v,        /* The fulltext index */
82811   const char *zInput,      /* Input text of the query string */
82812   int nInput,              /* Size of the input text */
82813   int dfltColumn,          /* Default column of the index to match against */
82814   Query *pQuery            /* Write the parse results here. */
82815 ){
82816   int iInput, inPhrase = 0;
82817   int ii;
82818   QueryTerm *aTerm;
82819
82820   if( zInput==0 ) nInput = 0;
82821   if( nInput<0 ) nInput = strlen(zInput);
82822   pQuery->nTerms = 0;
82823   pQuery->pTerms = NULL;
82824   pQuery->nextIsOr = 0;
82825   pQuery->nextColumn = dfltColumn;
82826   pQuery->dfltColumn = dfltColumn;
82827   pQuery->pFts = v;
82828
82829   for(iInput=0; iInput<nInput; ++iInput){
82830     int i;
82831     for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
82832     if( i>iInput ){
82833       tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
82834                        pQuery);
82835     }
82836     iInput = i;
82837     if( i<nInput ){
82838       assert( zInput[i]=='"' );
82839       inPhrase = !inPhrase;
82840     }
82841   }
82842
82843   if( inPhrase ){
82844     /* unmatched quote */
82845     queryClear(pQuery);
82846     return SQLITE_ERROR;
82847   }
82848
82849   /* Modify the values of the QueryTerm.nPhrase variables to account for
82850   ** the NEAR operator. For the purposes of QueryTerm.nPhrase, phrases
82851   ** and tokens connected by the NEAR operator are handled as a single
82852   ** phrase. See comments above the QueryTerm structure for details.
82853   */
82854   aTerm = pQuery->pTerms;
82855   for(ii=0; ii<pQuery->nTerms; ii++){
82856     if( aTerm[ii].nNear || aTerm[ii].nPhrase ){
82857       while (aTerm[ii+aTerm[ii].nPhrase].nNear) {
82858         aTerm[ii].nPhrase += (1 + aTerm[ii+aTerm[ii].nPhrase+1].nPhrase);
82859       }
82860     }
82861   }
82862
82863   return SQLITE_OK;
82864 }
82865
82866 /* TODO(shess) Refactor the code to remove this forward decl. */
82867 static int flushPendingTerms(fulltext_vtab *v);
82868
82869 /* Perform a full-text query using the search expression in
82870 ** zInput[0..nInput-1].  Return a list of matching documents
82871 ** in pResult.
82872 **
82873 ** Queries must match column iColumn.  Or if iColumn>=nColumn
82874 ** they are allowed to match against any column.
82875 */
82876 static int fulltextQuery(
82877   fulltext_vtab *v,      /* The full text index */
82878   int iColumn,           /* Match against this column by default */
82879   const char *zInput,    /* The query string */
82880   int nInput,            /* Number of bytes in zInput[] */
82881   DataBuffer *pResult,   /* Write the result doclist here */
82882   Query *pQuery          /* Put parsed query string here */
82883 ){
82884   int i, iNext, rc;
82885   DataBuffer left, right, or, new;
82886   int nNot = 0;
82887   QueryTerm *aTerm;
82888
82889   /* TODO(shess) Instead of flushing pendingTerms, we could query for
82890   ** the relevant term and merge the doclist into what we receive from
82891   ** the database.  Wait and see if this is a common issue, first.
82892   **
82893   ** A good reason not to flush is to not generate update-related
82894   ** error codes from here.
82895   */
82896
82897   /* Flush any buffered updates before executing the query. */
82898   rc = flushPendingTerms(v);
82899   if( rc!=SQLITE_OK ) return rc;
82900
82901   /* TODO(shess) I think that the queryClear() calls below are not
82902   ** necessary, because fulltextClose() already clears the query.
82903   */
82904   rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
82905   if( rc!=SQLITE_OK ) return rc;
82906
82907   /* Empty or NULL queries return no results. */
82908   if( pQuery->nTerms==0 ){
82909     dataBufferInit(pResult, 0);
82910     return SQLITE_OK;
82911   }
82912
82913   /* Merge AND terms. */
82914   /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
82915   aTerm = pQuery->pTerms;
82916   for(i = 0; i<pQuery->nTerms; i=iNext){
82917     if( aTerm[i].isNot ){
82918       /* Handle all NOT terms in a separate pass */
82919       nNot++;
82920       iNext = i + aTerm[i].nPhrase+1;
82921       continue;
82922     }
82923     iNext = i + aTerm[i].nPhrase + 1;
82924     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
82925     if( rc ){
82926       if( i!=nNot ) dataBufferDestroy(&left);
82927       queryClear(pQuery);
82928       return rc;
82929     }
82930     while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
82931       rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
82932       iNext += aTerm[iNext].nPhrase + 1;
82933       if( rc ){
82934         if( i!=nNot ) dataBufferDestroy(&left);
82935         dataBufferDestroy(&right);
82936         queryClear(pQuery);
82937         return rc;
82938       }
82939       dataBufferInit(&new, 0);
82940       docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
82941       dataBufferDestroy(&right);
82942       dataBufferDestroy(&or);
82943       right = new;
82944     }
82945     if( i==nNot ){           /* first term processed. */
82946       left = right;
82947     }else{
82948       dataBufferInit(&new, 0);
82949       docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
82950       dataBufferDestroy(&right);
82951       dataBufferDestroy(&left);
82952       left = new;
82953     }
82954   }
82955
82956   if( nNot==pQuery->nTerms ){
82957     /* We do not yet know how to handle a query of only NOT terms */
82958     return SQLITE_ERROR;
82959   }
82960
82961   /* Do the EXCEPT terms */
82962   for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
82963     if( !aTerm[i].isNot ) continue;
82964     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
82965     if( rc ){
82966       queryClear(pQuery);
82967       dataBufferDestroy(&left);
82968       return rc;
82969     }
82970     dataBufferInit(&new, 0);
82971     docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
82972     dataBufferDestroy(&right);
82973     dataBufferDestroy(&left);
82974     left = new;
82975   }
82976
82977   *pResult = left;
82978   return rc;
82979 }
82980
82981 /*
82982 ** This is the xFilter interface for the virtual table.  See
82983 ** the virtual table xFilter method documentation for additional
82984 ** information.
82985 **
82986 ** If idxNum==QUERY_GENERIC then do a full table scan against
82987 ** the %_content table.
82988 **
82989 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
82990 ** in the %_content table.
82991 **
82992 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
82993 ** column on the left-hand side of the MATCH operator is column
82994 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
82995 ** side of the MATCH operator.
82996 */
82997 /* TODO(shess) Upgrade the cursor initialization and destruction to
82998 ** account for fulltextFilter() being called multiple times on the
82999 ** same cursor.  The current solution is very fragile.  Apply fix to
83000 ** fts3 as appropriate.
83001 */
83002 static int fulltextFilter(
83003   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
83004   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
83005   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
83006 ){
83007   fulltext_cursor *c = (fulltext_cursor *) pCursor;
83008   fulltext_vtab *v = cursor_vtab(c);
83009   int rc;
83010   StringBuffer sb;
83011
83012   FTSTRACE(("FTS3 Filter %p\n",pCursor));
83013
83014   initStringBuffer(&sb);
83015   append(&sb, "SELECT docid, ");
83016   appendList(&sb, v->nColumn, v->azContentColumn);
83017   append(&sb, " FROM %_content");
83018   if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
83019   sqlite3_finalize(c->pStmt);
83020   rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, stringBufferData(&sb));
83021   stringBufferDestroy(&sb);
83022   if( rc!=SQLITE_OK ) return rc;
83023
83024   c->iCursorType = idxNum;
83025   switch( idxNum ){
83026     case QUERY_GENERIC:
83027       break;
83028
83029     case QUERY_DOCID:
83030       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
83031       if( rc!=SQLITE_OK ) return rc;
83032       break;
83033
83034     default:   /* full-text search */
83035     {
83036       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
83037       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
83038       assert( argc==1 );
83039       queryClear(&c->q);
83040       if( c->result.nData!=0 ){
83041         /* This case happens if the same cursor is used repeatedly. */
83042         dlrDestroy(&c->reader);
83043         dataBufferReset(&c->result);
83044       }else{
83045         dataBufferInit(&c->result, 0);
83046       }
83047       rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
83048       if( rc!=SQLITE_OK ) return rc;
83049       if( c->result.nData!=0 ){
83050         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
83051       }
83052       break;
83053     }
83054   }
83055
83056   return fulltextNext(pCursor);
83057 }
83058
83059 /* This is the xEof method of the virtual table.  The SQLite core
83060 ** calls this routine to find out if it has reached the end of
83061 ** a query's results set.
83062 */
83063 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
83064   fulltext_cursor *c = (fulltext_cursor *) pCursor;
83065   return c->eof;
83066 }
83067
83068 /* This is the xColumn method of the virtual table.  The SQLite
83069 ** core calls this method during a query when it needs the value
83070 ** of a column from the virtual table.  This method needs to use
83071 ** one of the sqlite3_result_*() routines to store the requested
83072 ** value back in the pContext.
83073 */
83074 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
83075                           sqlite3_context *pContext, int idxCol){
83076   fulltext_cursor *c = (fulltext_cursor *) pCursor;
83077   fulltext_vtab *v = cursor_vtab(c);
83078
83079   if( idxCol<v->nColumn ){
83080     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
83081     sqlite3_result_value(pContext, pVal);
83082   }else if( idxCol==v->nColumn ){
83083     /* The extra column whose name is the same as the table.
83084     ** Return a blob which is a pointer to the cursor
83085     */
83086     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
83087   }else if( idxCol==v->nColumn+1 ){
83088     /* The docid column, which is an alias for rowid. */
83089     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
83090     sqlite3_result_value(pContext, pVal);
83091   }
83092   return SQLITE_OK;
83093 }
83094
83095 /* This is the xRowid method.  The SQLite core calls this routine to
83096 ** retrieve the rowid for the current row of the result set.  fts3
83097 ** exposes %_content.docid as the rowid for the virtual table.  The
83098 ** rowid should be written to *pRowid.
83099 */
83100 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
83101   fulltext_cursor *c = (fulltext_cursor *) pCursor;
83102
83103   *pRowid = sqlite3_column_int64(c->pStmt, 0);
83104   return SQLITE_OK;
83105 }
83106
83107 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
83108 ** we also store positions and offsets in the hash table using that
83109 ** column number.
83110 */
83111 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
83112                       const char *zText, int iColumn){
83113   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
83114   sqlite3_tokenizer_cursor *pCursor;
83115   const char *pToken;
83116   int nTokenBytes;
83117   int iStartOffset, iEndOffset, iPosition;
83118   int rc;
83119
83120   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
83121   if( rc!=SQLITE_OK ) return rc;
83122
83123   pCursor->pTokenizer = pTokenizer;
83124   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
83125                                                    &pToken, &nTokenBytes,
83126                                                    &iStartOffset, &iEndOffset,
83127                                                    &iPosition)) ){
83128     DLCollector *p;
83129     int nData;                   /* Size of doclist before our update. */
83130
83131     /* Positions can't be negative; we use -1 as a terminator
83132      * internally.  Token can't be NULL or empty. */
83133     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
83134       rc = SQLITE_ERROR;
83135       break;
83136     }
83137
83138     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
83139     if( p==NULL ){
83140       nData = 0;
83141       p = dlcNew(iDocid, DL_DEFAULT);
83142       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
83143
83144       /* Overhead for our hash table entry, the key, and the value. */
83145       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
83146     }else{
83147       nData = p->b.nData;
83148       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
83149     }
83150     if( iColumn>=0 ){
83151       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
83152     }
83153
83154     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
83155     v->nPendingData += p->b.nData-nData;
83156   }
83157
83158   /* TODO(shess) Check return?  Should this be able to cause errors at
83159   ** this point?  Actually, same question about sqlite3_finalize(),
83160   ** though one could argue that failure there means that the data is
83161   ** not durable.  *ponder*
83162   */
83163   pTokenizer->pModule->xClose(pCursor);
83164   if( SQLITE_DONE == rc ) return SQLITE_OK;
83165   return rc;
83166 }
83167
83168 /* Add doclists for all terms in [pValues] to pendingTerms table. */
83169 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
83170                        sqlite3_value **pValues){
83171   int i;
83172   for(i = 0; i < v->nColumn ; ++i){
83173     char *zText = (char*)sqlite3_value_text(pValues[i]);
83174     int rc = buildTerms(v, iDocid, zText, i);
83175     if( rc!=SQLITE_OK ) return rc;
83176   }
83177   return SQLITE_OK;
83178 }
83179
83180 /* Add empty doclists for all terms in the given row's content to
83181 ** pendingTerms.
83182 */
83183 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
83184   const char **pValues;
83185   int i, rc;
83186
83187   /* TODO(shess) Should we allow such tables at all? */
83188   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
83189
83190   rc = content_select(v, iDocid, &pValues);
83191   if( rc!=SQLITE_OK ) return rc;
83192
83193   for(i = 0 ; i < v->nColumn; ++i) {
83194     rc = buildTerms(v, iDocid, pValues[i], -1);
83195     if( rc!=SQLITE_OK ) break;
83196   }
83197
83198   freeStringArray(v->nColumn, pValues);
83199   return SQLITE_OK;
83200 }
83201
83202 /* TODO(shess) Refactor the code to remove this forward decl. */
83203 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
83204
83205 /* Insert a row into the %_content table; set *piDocid to be the ID of the
83206 ** new row.  Add doclists for terms to pendingTerms.
83207 */
83208 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
83209                         sqlite3_value **pValues, sqlite_int64 *piDocid){
83210   int rc;
83211
83212   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
83213   if( rc!=SQLITE_OK ) return rc;
83214
83215   /* docid column is an alias for rowid. */
83216   *piDocid = sqlite3_last_insert_rowid(v->db);
83217   rc = initPendingTerms(v, *piDocid);
83218   if( rc!=SQLITE_OK ) return rc;
83219
83220   return insertTerms(v, *piDocid, pValues);
83221 }
83222
83223 /* Delete a row from the %_content table; add empty doclists for terms
83224 ** to pendingTerms.
83225 */
83226 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
83227   int rc = initPendingTerms(v, iRow);
83228   if( rc!=SQLITE_OK ) return rc;
83229
83230   rc = deleteTerms(v, iRow);
83231   if( rc!=SQLITE_OK ) return rc;
83232
83233   return content_delete(v, iRow);  /* execute an SQL DELETE */
83234 }
83235
83236 /* Update a row in the %_content table; add delete doclists to
83237 ** pendingTerms for old terms not in the new data, add insert doclists
83238 ** to pendingTerms for terms in the new data.
83239 */
83240 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
83241                         sqlite3_value **pValues){
83242   int rc = initPendingTerms(v, iRow);
83243   if( rc!=SQLITE_OK ) return rc;
83244
83245   /* Generate an empty doclist for each term that previously appeared in this
83246    * row. */
83247   rc = deleteTerms(v, iRow);
83248   if( rc!=SQLITE_OK ) return rc;
83249
83250   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
83251   if( rc!=SQLITE_OK ) return rc;
83252
83253   /* Now add positions for terms which appear in the updated row. */
83254   return insertTerms(v, iRow, pValues);
83255 }
83256
83257 /*******************************************************************/
83258 /* InteriorWriter is used to collect terms and block references into
83259 ** interior nodes in %_segments.  See commentary at top of file for
83260 ** format.
83261 */
83262
83263 /* How large interior nodes can grow. */
83264 #define INTERIOR_MAX 2048
83265
83266 /* Minimum number of terms per interior node (except the root). This
83267 ** prevents large terms from making the tree too skinny - must be >0
83268 ** so that the tree always makes progress.  Note that the min tree
83269 ** fanout will be INTERIOR_MIN_TERMS+1.
83270 */
83271 #define INTERIOR_MIN_TERMS 7
83272 #if INTERIOR_MIN_TERMS<1
83273 # error INTERIOR_MIN_TERMS must be greater than 0.
83274 #endif
83275
83276 /* ROOT_MAX controls how much data is stored inline in the segment
83277 ** directory.
83278 */
83279 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
83280 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
83281 ** can both see it, but if the caller passed it in, we wouldn't even
83282 ** need a define.
83283 */
83284 #define ROOT_MAX 1024
83285 #if ROOT_MAX<VARINT_MAX*2
83286 # error ROOT_MAX must have enough space for a header.
83287 #endif
83288
83289 /* InteriorBlock stores a linked-list of interior blocks while a lower
83290 ** layer is being constructed.
83291 */
83292 typedef struct InteriorBlock {
83293   DataBuffer term;           /* Leftmost term in block's subtree. */
83294   DataBuffer data;           /* Accumulated data for the block. */
83295   struct InteriorBlock *next;
83296 } InteriorBlock;
83297
83298 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
83299                                        const char *pTerm, int nTerm){
83300   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
83301   char c[VARINT_MAX+VARINT_MAX];
83302   int n;
83303
83304   if( block ){
83305     memset(block, 0, sizeof(*block));
83306     dataBufferInit(&block->term, 0);
83307     dataBufferReplace(&block->term, pTerm, nTerm);
83308
83309     n = fts3PutVarint(c, iHeight);
83310     n += fts3PutVarint(c+n, iChildBlock);
83311     dataBufferInit(&block->data, INTERIOR_MAX);
83312     dataBufferReplace(&block->data, c, n);
83313   }
83314   return block;
83315 }
83316
83317 #ifndef NDEBUG
83318 /* Verify that the data is readable as an interior node. */
83319 static void interiorBlockValidate(InteriorBlock *pBlock){
83320   const char *pData = pBlock->data.pData;
83321   int nData = pBlock->data.nData;
83322   int n, iDummy;
83323   sqlite_int64 iBlockid;
83324
83325   assert( nData>0 );
83326   assert( pData!=0 );
83327   assert( pData+nData>pData );
83328
83329   /* Must lead with height of node as a varint(n), n>0 */
83330   n = fts3GetVarint32(pData, &iDummy);
83331   assert( n>0 );
83332   assert( iDummy>0 );
83333   assert( n<nData );
83334   pData += n;
83335   nData -= n;
83336
83337   /* Must contain iBlockid. */
83338   n = fts3GetVarint(pData, &iBlockid);
83339   assert( n>0 );
83340   assert( n<=nData );
83341   pData += n;
83342   nData -= n;
83343
83344   /* Zero or more terms of positive length */
83345   if( nData!=0 ){
83346     /* First term is not delta-encoded. */
83347     n = fts3GetVarint32(pData, &iDummy);
83348     assert( n>0 );
83349     assert( iDummy>0 );
83350     assert( n+iDummy>0);
83351     assert( n+iDummy<=nData );
83352     pData += n+iDummy;
83353     nData -= n+iDummy;
83354
83355     /* Following terms delta-encoded. */
83356     while( nData!=0 ){
83357       /* Length of shared prefix. */
83358       n = fts3GetVarint32(pData, &iDummy);
83359       assert( n>0 );
83360       assert( iDummy>=0 );
83361       assert( n<nData );
83362       pData += n;
83363       nData -= n;
83364
83365       /* Length and data of distinct suffix. */
83366       n = fts3GetVarint32(pData, &iDummy);
83367       assert( n>0 );
83368       assert( iDummy>0 );
83369       assert( n+iDummy>0);
83370       assert( n+iDummy<=nData );
83371       pData += n+iDummy;
83372       nData -= n+iDummy;
83373     }
83374   }
83375 }
83376 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
83377 #else
83378 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
83379 #endif
83380
83381 typedef struct InteriorWriter {
83382   int iHeight;                   /* from 0 at leaves. */
83383   InteriorBlock *first, *last;
83384   struct InteriorWriter *parentWriter;
83385
83386   DataBuffer term;               /* Last term written to block "last". */
83387   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
83388 #ifndef NDEBUG
83389   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
83390 #endif
83391 } InteriorWriter;
83392
83393 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
83394 ** term in the tree.  iChildBlock is the leftmost child block at the
83395 ** next level down the tree.
83396 */
83397 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
83398                                sqlite_int64 iChildBlock,
83399                                InteriorWriter *pWriter){
83400   InteriorBlock *block;
83401   assert( iHeight>0 );
83402   CLEAR(pWriter);
83403
83404   pWriter->iHeight = iHeight;
83405   pWriter->iOpeningChildBlock = iChildBlock;
83406 #ifndef NDEBUG
83407   pWriter->iLastChildBlock = iChildBlock;
83408 #endif
83409   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
83410   pWriter->last = pWriter->first = block;
83411   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
83412   dataBufferInit(&pWriter->term, 0);
83413 }
83414
83415 /* Append the child node rooted at iChildBlock to the interior node,
83416 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
83417 */
83418 static void interiorWriterAppend(InteriorWriter *pWriter,
83419                                  const char *pTerm, int nTerm,
83420                                  sqlite_int64 iChildBlock){
83421   char c[VARINT_MAX+VARINT_MAX];
83422   int n, nPrefix = 0;
83423
83424   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
83425
83426   /* The first term written into an interior node is actually
83427   ** associated with the second child added (the first child was added
83428   ** in interiorWriterInit, or in the if clause at the bottom of this
83429   ** function).  That term gets encoded straight up, with nPrefix left
83430   ** at 0.
83431   */
83432   if( pWriter->term.nData==0 ){
83433     n = fts3PutVarint(c, nTerm);
83434   }else{
83435     while( nPrefix<pWriter->term.nData &&
83436            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
83437       nPrefix++;
83438     }
83439
83440     n = fts3PutVarint(c, nPrefix);
83441     n += fts3PutVarint(c+n, nTerm-nPrefix);
83442   }
83443
83444 #ifndef NDEBUG
83445   pWriter->iLastChildBlock++;
83446 #endif
83447   assert( pWriter->iLastChildBlock==iChildBlock );
83448
83449   /* Overflow to a new block if the new term makes the current block
83450   ** too big, and the current block already has enough terms.
83451   */
83452   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
83453       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
83454     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
83455                                            pTerm, nTerm);
83456     pWriter->last = pWriter->last->next;
83457     pWriter->iOpeningChildBlock = iChildBlock;
83458     dataBufferReset(&pWriter->term);
83459   }else{
83460     dataBufferAppend2(&pWriter->last->data, c, n,
83461                       pTerm+nPrefix, nTerm-nPrefix);
83462     dataBufferReplace(&pWriter->term, pTerm, nTerm);
83463   }
83464   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
83465 }
83466
83467 /* Free the space used by pWriter, including the linked-list of
83468 ** InteriorBlocks, and parentWriter, if present.
83469 */
83470 static int interiorWriterDestroy(InteriorWriter *pWriter){
83471   InteriorBlock *block = pWriter->first;
83472
83473   while( block!=NULL ){
83474     InteriorBlock *b = block;
83475     block = block->next;
83476     dataBufferDestroy(&b->term);
83477     dataBufferDestroy(&b->data);
83478     sqlite3_free(b);
83479   }
83480   if( pWriter->parentWriter!=NULL ){
83481     interiorWriterDestroy(pWriter->parentWriter);
83482     sqlite3_free(pWriter->parentWriter);
83483   }
83484   dataBufferDestroy(&pWriter->term);
83485   SCRAMBLE(pWriter);
83486   return SQLITE_OK;
83487 }
83488
83489 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
83490 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
83491 ** pWriter to %_segments, building a new layer of interior nodes, and
83492 ** recursively ask for their root into.
83493 */
83494 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
83495                                   char **ppRootInfo, int *pnRootInfo,
83496                                   sqlite_int64 *piEndBlockid){
83497   InteriorBlock *block = pWriter->first;
83498   sqlite_int64 iBlockid = 0;
83499   int rc;
83500
83501   /* If we can fit the segment inline */
83502   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
83503     *ppRootInfo = block->data.pData;
83504     *pnRootInfo = block->data.nData;
83505     return SQLITE_OK;
83506   }
83507
83508   /* Flush the first block to %_segments, and create a new level of
83509   ** interior node.
83510   */
83511   ASSERT_VALID_INTERIOR_BLOCK(block);
83512   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
83513   if( rc!=SQLITE_OK ) return rc;
83514   *piEndBlockid = iBlockid;
83515
83516   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
83517   interiorWriterInit(pWriter->iHeight+1,
83518                      block->term.pData, block->term.nData,
83519                      iBlockid, pWriter->parentWriter);
83520
83521   /* Flush additional blocks and append to the higher interior
83522   ** node.
83523   */
83524   for(block=block->next; block!=NULL; block=block->next){
83525     ASSERT_VALID_INTERIOR_BLOCK(block);
83526     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
83527     if( rc!=SQLITE_OK ) return rc;
83528     *piEndBlockid = iBlockid;
83529
83530     interiorWriterAppend(pWriter->parentWriter,
83531                          block->term.pData, block->term.nData, iBlockid);
83532   }
83533
83534   /* Parent node gets the chance to be the root. */
83535   return interiorWriterRootInfo(v, pWriter->parentWriter,
83536                                 ppRootInfo, pnRootInfo, piEndBlockid);
83537 }
83538
83539 /****************************************************************/
83540 /* InteriorReader is used to read off the data from an interior node
83541 ** (see comment at top of file for the format).
83542 */
83543 typedef struct InteriorReader {
83544   const char *pData;
83545   int nData;
83546
83547   DataBuffer term;          /* previous term, for decoding term delta. */
83548
83549   sqlite_int64 iBlockid;
83550 } InteriorReader;
83551
83552 static void interiorReaderDestroy(InteriorReader *pReader){
83553   dataBufferDestroy(&pReader->term);
83554   SCRAMBLE(pReader);
83555 }
83556
83557 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
83558 ** and the blob is empty or otherwise contains suspect data?
83559 */
83560 static void interiorReaderInit(const char *pData, int nData,
83561                                InteriorReader *pReader){
83562   int n, nTerm;
83563
83564   /* Require at least the leading flag byte */
83565   assert( nData>0 );
83566   assert( pData[0]!='\0' );
83567
83568   CLEAR(pReader);
83569
83570   /* Decode the base blockid, and set the cursor to the first term. */
83571   n = fts3GetVarint(pData+1, &pReader->iBlockid);
83572   assert( 1+n<=nData );
83573   pReader->pData = pData+1+n;
83574   pReader->nData = nData-(1+n);
83575
83576   /* A single-child interior node (such as when a leaf node was too
83577   ** large for the segment directory) won't have any terms.
83578   ** Otherwise, decode the first term.
83579   */
83580   if( pReader->nData==0 ){
83581     dataBufferInit(&pReader->term, 0);
83582   }else{
83583     n = fts3GetVarint32(pReader->pData, &nTerm);
83584     dataBufferInit(&pReader->term, nTerm);
83585     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
83586     assert( n+nTerm<=pReader->nData );
83587     pReader->pData += n+nTerm;
83588     pReader->nData -= n+nTerm;
83589   }
83590 }
83591
83592 static int interiorReaderAtEnd(InteriorReader *pReader){
83593   return pReader->term.nData==0;
83594 }
83595
83596 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
83597   return pReader->iBlockid;
83598 }
83599
83600 static int interiorReaderTermBytes(InteriorReader *pReader){
83601   assert( !interiorReaderAtEnd(pReader) );
83602   return pReader->term.nData;
83603 }
83604 static const char *interiorReaderTerm(InteriorReader *pReader){
83605   assert( !interiorReaderAtEnd(pReader) );
83606   return pReader->term.pData;
83607 }
83608
83609 /* Step forward to the next term in the node. */
83610 static void interiorReaderStep(InteriorReader *pReader){
83611   assert( !interiorReaderAtEnd(pReader) );
83612
83613   /* If the last term has been read, signal eof, else construct the
83614   ** next term.
83615   */
83616   if( pReader->nData==0 ){
83617     dataBufferReset(&pReader->term);
83618   }else{
83619     int n, nPrefix, nSuffix;
83620
83621     n = fts3GetVarint32(pReader->pData, &nPrefix);
83622     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
83623
83624     /* Truncate the current term and append suffix data. */
83625     pReader->term.nData = nPrefix;
83626     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
83627
83628     assert( n+nSuffix<=pReader->nData );
83629     pReader->pData += n+nSuffix;
83630     pReader->nData -= n+nSuffix;
83631   }
83632   pReader->iBlockid++;
83633 }
83634
83635 /* Compare the current term to pTerm[nTerm], returning strcmp-style
83636 ** results.  If isPrefix, equality means equal through nTerm bytes.
83637 */
83638 static int interiorReaderTermCmp(InteriorReader *pReader,
83639                                  const char *pTerm, int nTerm, int isPrefix){
83640   const char *pReaderTerm = interiorReaderTerm(pReader);
83641   int nReaderTerm = interiorReaderTermBytes(pReader);
83642   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
83643
83644   if( n==0 ){
83645     if( nReaderTerm>0 ) return -1;
83646     if( nTerm>0 ) return 1;
83647     return 0;
83648   }
83649
83650   c = memcmp(pReaderTerm, pTerm, n);
83651   if( c!=0 ) return c;
83652   if( isPrefix && n==nTerm ) return 0;
83653   return nReaderTerm - nTerm;
83654 }
83655
83656 /****************************************************************/
83657 /* LeafWriter is used to collect terms and associated doclist data
83658 ** into leaf blocks in %_segments (see top of file for format info).
83659 ** Expected usage is:
83660 **
83661 ** LeafWriter writer;
83662 ** leafWriterInit(0, 0, &writer);
83663 ** while( sorted_terms_left_to_process ){
83664 **   // data is doclist data for that term.
83665 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
83666 **   if( rc!=SQLITE_OK ) goto err;
83667 ** }
83668 ** rc = leafWriterFinalize(v, &writer);
83669 **err:
83670 ** leafWriterDestroy(&writer);
83671 ** return rc;
83672 **
83673 ** leafWriterStep() may write a collected leaf out to %_segments.
83674 ** leafWriterFinalize() finishes writing any buffered data and stores
83675 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
83676 ** InteriorWriters allocated as part of writing this segment.
83677 **
83678 ** TODO(shess) Document leafWriterStepMerge().
83679 */
83680
83681 /* Put terms with data this big in their own block. */
83682 #define STANDALONE_MIN 1024
83683
83684 /* Keep leaf blocks below this size. */
83685 #define LEAF_MAX 2048
83686
83687 typedef struct LeafWriter {
83688   int iLevel;
83689   int idx;
83690   sqlite_int64 iStartBlockid;     /* needed to create the root info */
83691   sqlite_int64 iEndBlockid;       /* when we're done writing. */
83692
83693   DataBuffer term;                /* previous encoded term */
83694   DataBuffer data;                /* encoding buffer */
83695
83696   /* bytes of first term in the current node which distinguishes that
83697   ** term from the last term of the previous node.
83698   */
83699   int nTermDistinct;
83700
83701   InteriorWriter parentWriter;    /* if we overflow */
83702   int has_parent;
83703 } LeafWriter;
83704
83705 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
83706   CLEAR(pWriter);
83707   pWriter->iLevel = iLevel;
83708   pWriter->idx = idx;
83709
83710   dataBufferInit(&pWriter->term, 32);
83711
83712   /* Start out with a reasonably sized block, though it can grow. */
83713   dataBufferInit(&pWriter->data, LEAF_MAX);
83714 }
83715
83716 #ifndef NDEBUG
83717 /* Verify that the data is readable as a leaf node. */
83718 static void leafNodeValidate(const char *pData, int nData){
83719   int n, iDummy;
83720
83721   if( nData==0 ) return;
83722   assert( nData>0 );
83723   assert( pData!=0 );
83724   assert( pData+nData>pData );
83725
83726   /* Must lead with a varint(0) */
83727   n = fts3GetVarint32(pData, &iDummy);
83728   assert( iDummy==0 );
83729   assert( n>0 );
83730   assert( n<nData );
83731   pData += n;
83732   nData -= n;
83733
83734   /* Leading term length and data must fit in buffer. */
83735   n = fts3GetVarint32(pData, &iDummy);
83736   assert( n>0 );
83737   assert( iDummy>0 );
83738   assert( n+iDummy>0 );
83739   assert( n+iDummy<nData );
83740   pData += n+iDummy;
83741   nData -= n+iDummy;
83742
83743   /* Leading term's doclist length and data must fit. */
83744   n = fts3GetVarint32(pData, &iDummy);
83745   assert( n>0 );
83746   assert( iDummy>0 );
83747   assert( n+iDummy>0 );
83748   assert( n+iDummy<=nData );
83749   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
83750   pData += n+iDummy;
83751   nData -= n+iDummy;
83752
83753   /* Verify that trailing terms and doclists also are readable. */
83754   while( nData!=0 ){
83755     n = fts3GetVarint32(pData, &iDummy);
83756     assert( n>0 );
83757     assert( iDummy>=0 );
83758     assert( n<nData );
83759     pData += n;
83760     nData -= n;
83761     n = fts3GetVarint32(pData, &iDummy);
83762     assert( n>0 );
83763     assert( iDummy>0 );
83764     assert( n+iDummy>0 );
83765     assert( n+iDummy<nData );
83766     pData += n+iDummy;
83767     nData -= n+iDummy;
83768
83769     n = fts3GetVarint32(pData, &iDummy);
83770     assert( n>0 );
83771     assert( iDummy>0 );
83772     assert( n+iDummy>0 );
83773     assert( n+iDummy<=nData );
83774     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
83775     pData += n+iDummy;
83776     nData -= n+iDummy;
83777   }
83778 }
83779 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
83780 #else
83781 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
83782 #endif
83783
83784 /* Flush the current leaf node to %_segments, and adding the resulting
83785 ** blockid and the starting term to the interior node which will
83786 ** contain it.
83787 */
83788 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
83789                                    int iData, int nData){
83790   sqlite_int64 iBlockid = 0;
83791   const char *pStartingTerm;
83792   int nStartingTerm, rc, n;
83793
83794   /* Must have the leading varint(0) flag, plus at least some
83795   ** valid-looking data.
83796   */
83797   assert( nData>2 );
83798   assert( iData>=0 );
83799   assert( iData+nData<=pWriter->data.nData );
83800   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
83801
83802   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
83803   if( rc!=SQLITE_OK ) return rc;
83804   assert( iBlockid!=0 );
83805
83806   /* Reconstruct the first term in the leaf for purposes of building
83807   ** the interior node.
83808   */
83809   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
83810   pStartingTerm = pWriter->data.pData+iData+1+n;
83811   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
83812   assert( pWriter->nTermDistinct>0 );
83813   assert( pWriter->nTermDistinct<=nStartingTerm );
83814   nStartingTerm = pWriter->nTermDistinct;
83815
83816   if( pWriter->has_parent ){
83817     interiorWriterAppend(&pWriter->parentWriter,
83818                          pStartingTerm, nStartingTerm, iBlockid);
83819   }else{
83820     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
83821                        &pWriter->parentWriter);
83822     pWriter->has_parent = 1;
83823   }
83824
83825   /* Track the span of this segment's leaf nodes. */
83826   if( pWriter->iEndBlockid==0 ){
83827     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
83828   }else{
83829     pWriter->iEndBlockid++;
83830     assert( iBlockid==pWriter->iEndBlockid );
83831   }
83832
83833   return SQLITE_OK;
83834 }
83835 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
83836   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
83837   if( rc!=SQLITE_OK ) return rc;
83838
83839   /* Re-initialize the output buffer. */
83840   dataBufferReset(&pWriter->data);
83841
83842   return SQLITE_OK;
83843 }
83844
83845 /* Fetch the root info for the segment.  If the entire leaf fits
83846 ** within ROOT_MAX, then it will be returned directly, otherwise it
83847 ** will be flushed and the root info will be returned from the
83848 ** interior node.  *piEndBlockid is set to the blockid of the last
83849 ** interior or leaf node written to disk (0 if none are written at
83850 ** all).
83851 */
83852 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
83853                               char **ppRootInfo, int *pnRootInfo,
83854                               sqlite_int64 *piEndBlockid){
83855   /* we can fit the segment entirely inline */
83856   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
83857     *ppRootInfo = pWriter->data.pData;
83858     *pnRootInfo = pWriter->data.nData;
83859     *piEndBlockid = 0;
83860     return SQLITE_OK;
83861   }
83862
83863   /* Flush remaining leaf data. */
83864   if( pWriter->data.nData>0 ){
83865     int rc = leafWriterFlush(v, pWriter);
83866     if( rc!=SQLITE_OK ) return rc;
83867   }
83868
83869   /* We must have flushed a leaf at some point. */
83870   assert( pWriter->has_parent );
83871
83872   /* Tenatively set the end leaf blockid as the end blockid.  If the
83873   ** interior node can be returned inline, this will be the final
83874   ** blockid, otherwise it will be overwritten by
83875   ** interiorWriterRootInfo().
83876   */
83877   *piEndBlockid = pWriter->iEndBlockid;
83878
83879   return interiorWriterRootInfo(v, &pWriter->parentWriter,
83880                                 ppRootInfo, pnRootInfo, piEndBlockid);
83881 }
83882
83883 /* Collect the rootInfo data and store it into the segment directory.
83884 ** This has the effect of flushing the segment's leaf data to
83885 ** %_segments, and also flushing any interior nodes to %_segments.
83886 */
83887 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
83888   sqlite_int64 iEndBlockid;
83889   char *pRootInfo;
83890   int rc, nRootInfo;
83891
83892   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
83893   if( rc!=SQLITE_OK ) return rc;
83894
83895   /* Don't bother storing an entirely empty segment. */
83896   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
83897
83898   return segdir_set(v, pWriter->iLevel, pWriter->idx,
83899                     pWriter->iStartBlockid, pWriter->iEndBlockid,
83900                     iEndBlockid, pRootInfo, nRootInfo);
83901 }
83902
83903 static void leafWriterDestroy(LeafWriter *pWriter){
83904   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
83905   dataBufferDestroy(&pWriter->term);
83906   dataBufferDestroy(&pWriter->data);
83907 }
83908
83909 /* Encode a term into the leafWriter, delta-encoding as appropriate.
83910 ** Returns the length of the new term which distinguishes it from the
83911 ** previous term, which can be used to set nTermDistinct when a node
83912 ** boundary is crossed.
83913 */
83914 static int leafWriterEncodeTerm(LeafWriter *pWriter,
83915                                 const char *pTerm, int nTerm){
83916   char c[VARINT_MAX+VARINT_MAX];
83917   int n, nPrefix = 0;
83918
83919   assert( nTerm>0 );
83920   while( nPrefix<pWriter->term.nData &&
83921          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
83922     nPrefix++;
83923     /* Failing this implies that the terms weren't in order. */
83924     assert( nPrefix<nTerm );
83925   }
83926
83927   if( pWriter->data.nData==0 ){
83928     /* Encode the node header and leading term as:
83929     **  varint(0)
83930     **  varint(nTerm)
83931     **  char pTerm[nTerm]
83932     */
83933     n = fts3PutVarint(c, '\0');
83934     n += fts3PutVarint(c+n, nTerm);
83935     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
83936   }else{
83937     /* Delta-encode the term as:
83938     **  varint(nPrefix)
83939     **  varint(nSuffix)
83940     **  char pTermSuffix[nSuffix]
83941     */
83942     n = fts3PutVarint(c, nPrefix);
83943     n += fts3PutVarint(c+n, nTerm-nPrefix);
83944     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
83945   }
83946   dataBufferReplace(&pWriter->term, pTerm, nTerm);
83947
83948   return nPrefix+1;
83949 }
83950
83951 /* Used to avoid a memmove when a large amount of doclist data is in
83952 ** the buffer.  This constructs a node and term header before
83953 ** iDoclistData and flushes the resulting complete node using
83954 ** leafWriterInternalFlush().
83955 */
83956 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
83957                                  const char *pTerm, int nTerm,
83958                                  int iDoclistData){
83959   char c[VARINT_MAX+VARINT_MAX];
83960   int iData, n = fts3PutVarint(c, 0);
83961   n += fts3PutVarint(c+n, nTerm);
83962
83963   /* There should always be room for the header.  Even if pTerm shared
83964   ** a substantial prefix with the previous term, the entire prefix
83965   ** could be constructed from earlier data in the doclist, so there
83966   ** should be room.
83967   */
83968   assert( iDoclistData>=n+nTerm );
83969
83970   iData = iDoclistData-(n+nTerm);
83971   memcpy(pWriter->data.pData+iData, c, n);
83972   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
83973
83974   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
83975 }
83976
83977 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
83978 ** %_segments.
83979 */
83980 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
83981                                const char *pTerm, int nTerm,
83982                                DLReader *pReaders, int nReaders){
83983   char c[VARINT_MAX+VARINT_MAX];
83984   int iTermData = pWriter->data.nData, iDoclistData;
83985   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
83986
83987   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
83988   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
83989
83990   /* Remember nTermDistinct if opening a new node. */
83991   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
83992
83993   iDoclistData = pWriter->data.nData;
83994
83995   /* Estimate the length of the merged doclist so we can leave space
83996   ** to encode it.
83997   */
83998   for(i=0, nData=0; i<nReaders; i++){
83999     nData += dlrAllDataBytes(&pReaders[i]);
84000   }
84001   n = fts3PutVarint(c, nData);
84002   dataBufferAppend(&pWriter->data, c, n);
84003
84004   docListMerge(&pWriter->data, pReaders, nReaders);
84005   ASSERT_VALID_DOCLIST(DL_DEFAULT,
84006                        pWriter->data.pData+iDoclistData+n,
84007                        pWriter->data.nData-iDoclistData-n, NULL);
84008
84009   /* The actual amount of doclist data at this point could be smaller
84010   ** than the length we encoded.  Additionally, the space required to
84011   ** encode this length could be smaller.  For small doclists, this is
84012   ** not a big deal, we can just use memmove() to adjust things.
84013   */
84014   nActualData = pWriter->data.nData-(iDoclistData+n);
84015   nActual = fts3PutVarint(c, nActualData);
84016   assert( nActualData<=nData );
84017   assert( nActual<=n );
84018
84019   /* If the new doclist is big enough for force a standalone leaf
84020   ** node, we can immediately flush it inline without doing the
84021   ** memmove().
84022   */
84023   /* TODO(shess) This test matches leafWriterStep(), which does this
84024   ** test before it knows the cost to varint-encode the term and
84025   ** doclist lengths.  At some point, change to
84026   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
84027   */
84028   if( nTerm+nActualData>STANDALONE_MIN ){
84029     /* Push leaf node from before this term. */
84030     if( iTermData>0 ){
84031       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
84032       if( rc!=SQLITE_OK ) return rc;
84033
84034       pWriter->nTermDistinct = nTermDistinct;
84035     }
84036
84037     /* Fix the encoded doclist length. */
84038     iDoclistData += n - nActual;
84039     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
84040
84041     /* Push the standalone leaf node. */
84042     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
84043     if( rc!=SQLITE_OK ) return rc;
84044
84045     /* Leave the node empty. */
84046     dataBufferReset(&pWriter->data);
84047
84048     return rc;
84049   }
84050
84051   /* At this point, we know that the doclist was small, so do the
84052   ** memmove if indicated.
84053   */
84054   if( nActual<n ){
84055     memmove(pWriter->data.pData+iDoclistData+nActual,
84056             pWriter->data.pData+iDoclistData+n,
84057             pWriter->data.nData-(iDoclistData+n));
84058     pWriter->data.nData -= n-nActual;
84059   }
84060
84061   /* Replace written length with actual length. */
84062   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
84063
84064   /* If the node is too large, break things up. */
84065   /* TODO(shess) This test matches leafWriterStep(), which does this
84066   ** test before it knows the cost to varint-encode the term and
84067   ** doclist lengths.  At some point, change to
84068   ** pWriter->data.nData>LEAF_MAX.
84069   */
84070   if( iTermData+nTerm+nActualData>LEAF_MAX ){
84071     /* Flush out the leading data as a node */
84072     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
84073     if( rc!=SQLITE_OK ) return rc;
84074
84075     pWriter->nTermDistinct = nTermDistinct;
84076
84077     /* Rebuild header using the current term */
84078     n = fts3PutVarint(pWriter->data.pData, 0);
84079     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
84080     memcpy(pWriter->data.pData+n, pTerm, nTerm);
84081     n += nTerm;
84082
84083     /* There should always be room, because the previous encoding
84084     ** included all data necessary to construct the term.
84085     */
84086     assert( n<iDoclistData );
84087     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
84088     ** following memcpy() is safe (as opposed to needing a memmove).
84089     */
84090     assert( 2*STANDALONE_MIN<=LEAF_MAX );
84091     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
84092     memcpy(pWriter->data.pData+n,
84093            pWriter->data.pData+iDoclistData,
84094            pWriter->data.nData-iDoclistData);
84095     pWriter->data.nData -= iDoclistData-n;
84096   }
84097   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
84098
84099   return SQLITE_OK;
84100 }
84101
84102 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
84103 ** %_segments.
84104 */
84105 /* TODO(shess) Revise writeZeroSegment() so that doclists are
84106 ** constructed directly in pWriter->data.
84107 */
84108 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
84109                           const char *pTerm, int nTerm,
84110                           const char *pData, int nData){
84111   int rc;
84112   DLReader reader;
84113
84114   dlrInit(&reader, DL_DEFAULT, pData, nData);
84115   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
84116   dlrDestroy(&reader);
84117
84118   return rc;
84119 }
84120
84121
84122 /****************************************************************/
84123 /* LeafReader is used to iterate over an individual leaf node. */
84124 typedef struct LeafReader {
84125   DataBuffer term;          /* copy of current term. */
84126
84127   const char *pData;        /* data for current term. */
84128   int nData;
84129 } LeafReader;
84130
84131 static void leafReaderDestroy(LeafReader *pReader){
84132   dataBufferDestroy(&pReader->term);
84133   SCRAMBLE(pReader);
84134 }
84135
84136 static int leafReaderAtEnd(LeafReader *pReader){
84137   return pReader->nData<=0;
84138 }
84139
84140 /* Access the current term. */
84141 static int leafReaderTermBytes(LeafReader *pReader){
84142   return pReader->term.nData;
84143 }
84144 static const char *leafReaderTerm(LeafReader *pReader){
84145   assert( pReader->term.nData>0 );
84146   return pReader->term.pData;
84147 }
84148
84149 /* Access the doclist data for the current term. */
84150 static int leafReaderDataBytes(LeafReader *pReader){
84151   int nData;
84152   assert( pReader->term.nData>0 );
84153   fts3GetVarint32(pReader->pData, &nData);
84154   return nData;
84155 }
84156 static const char *leafReaderData(LeafReader *pReader){
84157   int n, nData;
84158   assert( pReader->term.nData>0 );
84159   n = fts3GetVarint32(pReader->pData, &nData);
84160   return pReader->pData+n;
84161 }
84162
84163 static void leafReaderInit(const char *pData, int nData,
84164                            LeafReader *pReader){
84165   int nTerm, n;
84166
84167   assert( nData>0 );
84168   assert( pData[0]=='\0' );
84169
84170   CLEAR(pReader);
84171
84172   /* Read the first term, skipping the header byte. */
84173   n = fts3GetVarint32(pData+1, &nTerm);
84174   dataBufferInit(&pReader->term, nTerm);
84175   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
84176
84177   /* Position after the first term. */
84178   assert( 1+n+nTerm<nData );
84179   pReader->pData = pData+1+n+nTerm;
84180   pReader->nData = nData-1-n-nTerm;
84181 }
84182
84183 /* Step the reader forward to the next term. */
84184 static void leafReaderStep(LeafReader *pReader){
84185   int n, nData, nPrefix, nSuffix;
84186   assert( !leafReaderAtEnd(pReader) );
84187
84188   /* Skip previous entry's data block. */
84189   n = fts3GetVarint32(pReader->pData, &nData);
84190   assert( n+nData<=pReader->nData );
84191   pReader->pData += n+nData;
84192   pReader->nData -= n+nData;
84193
84194   if( !leafReaderAtEnd(pReader) ){
84195     /* Construct the new term using a prefix from the old term plus a
84196     ** suffix from the leaf data.
84197     */
84198     n = fts3GetVarint32(pReader->pData, &nPrefix);
84199     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
84200     assert( n+nSuffix<pReader->nData );
84201     pReader->term.nData = nPrefix;
84202     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
84203
84204     pReader->pData += n+nSuffix;
84205     pReader->nData -= n+nSuffix;
84206   }
84207 }
84208
84209 /* strcmp-style comparison of pReader's current term against pTerm.
84210 ** If isPrefix, equality means equal through nTerm bytes.
84211 */
84212 static int leafReaderTermCmp(LeafReader *pReader,
84213                              const char *pTerm, int nTerm, int isPrefix){
84214   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
84215   if( n==0 ){
84216     if( pReader->term.nData>0 ) return -1;
84217     if(nTerm>0 ) return 1;
84218     return 0;
84219   }
84220
84221   c = memcmp(pReader->term.pData, pTerm, n);
84222   if( c!=0 ) return c;
84223   if( isPrefix && n==nTerm ) return 0;
84224   return pReader->term.nData - nTerm;
84225 }
84226
84227
84228 /****************************************************************/
84229 /* LeavesReader wraps LeafReader to allow iterating over the entire
84230 ** leaf layer of the tree.
84231 */
84232 typedef struct LeavesReader {
84233   int idx;                  /* Index within the segment. */
84234
84235   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
84236   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
84237
84238   LeafReader leafReader;    /* reader for the current leaf. */
84239   DataBuffer rootData;      /* root data for inline. */
84240 } LeavesReader;
84241
84242 /* Access the current term. */
84243 static int leavesReaderTermBytes(LeavesReader *pReader){
84244   assert( !pReader->eof );
84245   return leafReaderTermBytes(&pReader->leafReader);
84246 }
84247 static const char *leavesReaderTerm(LeavesReader *pReader){
84248   assert( !pReader->eof );
84249   return leafReaderTerm(&pReader->leafReader);
84250 }
84251
84252 /* Access the doclist data for the current term. */
84253 static int leavesReaderDataBytes(LeavesReader *pReader){
84254   assert( !pReader->eof );
84255   return leafReaderDataBytes(&pReader->leafReader);
84256 }
84257 static const char *leavesReaderData(LeavesReader *pReader){
84258   assert( !pReader->eof );
84259   return leafReaderData(&pReader->leafReader);
84260 }
84261
84262 static int leavesReaderAtEnd(LeavesReader *pReader){
84263   return pReader->eof;
84264 }
84265
84266 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
84267 ** leaving the statement handle open, which locks the table.
84268 */
84269 /* TODO(shess) This "solution" is not satisfactory.  Really, there
84270 ** should be check-in function for all statement handles which
84271 ** arranges to call sqlite3_reset().  This most likely will require
84272 ** modification to control flow all over the place, though, so for now
84273 ** just punt.
84274 **
84275 ** Note the the current system assumes that segment merges will run to
84276 ** completion, which is why this particular probably hasn't arisen in
84277 ** this case.  Probably a brittle assumption.
84278 */
84279 static int leavesReaderReset(LeavesReader *pReader){
84280   return sqlite3_reset(pReader->pStmt);
84281 }
84282
84283 static void leavesReaderDestroy(LeavesReader *pReader){
84284   leafReaderDestroy(&pReader->leafReader);
84285   dataBufferDestroy(&pReader->rootData);
84286   SCRAMBLE(pReader);
84287 }
84288
84289 /* Initialize pReader with the given root data (if iStartBlockid==0
84290 ** the leaf data was entirely contained in the root), or from the
84291 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
84292 */
84293 static int leavesReaderInit(fulltext_vtab *v,
84294                             int idx,
84295                             sqlite_int64 iStartBlockid,
84296                             sqlite_int64 iEndBlockid,
84297                             const char *pRootData, int nRootData,
84298                             LeavesReader *pReader){
84299   CLEAR(pReader);
84300   pReader->idx = idx;
84301
84302   dataBufferInit(&pReader->rootData, 0);
84303   if( iStartBlockid==0 ){
84304     /* Entire leaf level fit in root data. */
84305     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
84306     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
84307                    &pReader->leafReader);
84308   }else{
84309     sqlite3_stmt *s;
84310     int rc = sql_get_leaf_statement(v, idx, &s);
84311     if( rc!=SQLITE_OK ) return rc;
84312
84313     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
84314     if( rc!=SQLITE_OK ) return rc;
84315
84316     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
84317     if( rc!=SQLITE_OK ) return rc;
84318
84319     rc = sqlite3_step(s);
84320     if( rc==SQLITE_DONE ){
84321       pReader->eof = 1;
84322       return SQLITE_OK;
84323     }
84324     if( rc!=SQLITE_ROW ) return rc;
84325
84326     pReader->pStmt = s;
84327     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
84328                    sqlite3_column_bytes(pReader->pStmt, 0),
84329                    &pReader->leafReader);
84330   }
84331   return SQLITE_OK;
84332 }
84333
84334 /* Step the current leaf forward to the next term.  If we reach the
84335 ** end of the current leaf, step forward to the next leaf block.
84336 */
84337 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
84338   assert( !leavesReaderAtEnd(pReader) );
84339   leafReaderStep(&pReader->leafReader);
84340
84341   if( leafReaderAtEnd(&pReader->leafReader) ){
84342     int rc;
84343     if( pReader->rootData.pData ){
84344       pReader->eof = 1;
84345       return SQLITE_OK;
84346     }
84347     rc = sqlite3_step(pReader->pStmt);
84348     if( rc!=SQLITE_ROW ){
84349       pReader->eof = 1;
84350       return rc==SQLITE_DONE ? SQLITE_OK : rc;
84351     }
84352     leafReaderDestroy(&pReader->leafReader);
84353     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
84354                    sqlite3_column_bytes(pReader->pStmt, 0),
84355                    &pReader->leafReader);
84356   }
84357   return SQLITE_OK;
84358 }
84359
84360 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
84361 ** always sort to the end.
84362 */
84363 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
84364   if( leavesReaderAtEnd(lr1) ){
84365     if( leavesReaderAtEnd(lr2) ) return 0;
84366     return 1;
84367   }
84368   if( leavesReaderAtEnd(lr2) ) return -1;
84369
84370   return leafReaderTermCmp(&lr1->leafReader,
84371                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
84372                            0);
84373 }
84374
84375 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
84376 ** so that older segments sort before newer segments.
84377 */
84378 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
84379   int c = leavesReaderTermCmp(lr1, lr2);
84380   if( c!=0 ) return c;
84381   return lr1->idx-lr2->idx;
84382 }
84383
84384 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
84385 ** sorted position.
84386 */
84387 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
84388   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
84389     LeavesReader tmp = pLr[0];
84390     pLr[0] = pLr[1];
84391     pLr[1] = tmp;
84392     nLr--;
84393     pLr++;
84394   }
84395 }
84396
84397 /* Initializes pReaders with the segments from level iLevel, returning
84398 ** the number of segments in *piReaders.  Leaves pReaders in sorted
84399 ** order.
84400 */
84401 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
84402                              LeavesReader *pReaders, int *piReaders){
84403   sqlite3_stmt *s;
84404   int i, rc = sql_get_statement(v, SEGDIR_SELECT_STMT, &s);
84405   if( rc!=SQLITE_OK ) return rc;
84406
84407   rc = sqlite3_bind_int(s, 1, iLevel);
84408   if( rc!=SQLITE_OK ) return rc;
84409
84410   i = 0;
84411   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
84412     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
84413     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
84414     const char *pRootData = sqlite3_column_blob(s, 2);
84415     int nRootData = sqlite3_column_bytes(s, 2);
84416
84417     assert( i<MERGE_COUNT );
84418     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
84419                           &pReaders[i]);
84420     if( rc!=SQLITE_OK ) break;
84421
84422     i++;
84423   }
84424   if( rc!=SQLITE_DONE ){
84425     while( i-->0 ){
84426       leavesReaderDestroy(&pReaders[i]);
84427     }
84428     return rc;
84429   }
84430
84431   *piReaders = i;
84432
84433   /* Leave our results sorted by term, then age. */
84434   while( i-- ){
84435     leavesReaderReorder(pReaders+i, *piReaders-i);
84436   }
84437   return SQLITE_OK;
84438 }
84439
84440 /* Merge doclists from pReaders[nReaders] into a single doclist, which
84441 ** is written to pWriter.  Assumes pReaders is ordered oldest to
84442 ** newest.
84443 */
84444 /* TODO(shess) Consider putting this inline in segmentMerge(). */
84445 static int leavesReadersMerge(fulltext_vtab *v,
84446                               LeavesReader *pReaders, int nReaders,
84447                               LeafWriter *pWriter){
84448   DLReader dlReaders[MERGE_COUNT];
84449   const char *pTerm = leavesReaderTerm(pReaders);
84450   int i, nTerm = leavesReaderTermBytes(pReaders);
84451
84452   assert( nReaders<=MERGE_COUNT );
84453
84454   for(i=0; i<nReaders; i++){
84455     dlrInit(&dlReaders[i], DL_DEFAULT,
84456             leavesReaderData(pReaders+i),
84457             leavesReaderDataBytes(pReaders+i));
84458   }
84459
84460   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
84461 }
84462
84463 /* Forward ref due to mutual recursion with segdirNextIndex(). */
84464 static int segmentMerge(fulltext_vtab *v, int iLevel);
84465
84466 /* Put the next available index at iLevel into *pidx.  If iLevel
84467 ** already has MERGE_COUNT segments, they are merged to a higher
84468 ** level to make room.
84469 */
84470 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
84471   int rc = segdir_max_index(v, iLevel, pidx);
84472   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
84473     *pidx = 0;
84474   }else if( rc==SQLITE_ROW ){
84475     if( *pidx==(MERGE_COUNT-1) ){
84476       rc = segmentMerge(v, iLevel);
84477       if( rc!=SQLITE_OK ) return rc;
84478       *pidx = 0;
84479     }else{
84480       (*pidx)++;
84481     }
84482   }else{
84483     return rc;
84484   }
84485   return SQLITE_OK;
84486 }
84487
84488 /* Merge MERGE_COUNT segments at iLevel into a new segment at
84489 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
84490 ** merged to make room.
84491 */
84492 static int segmentMerge(fulltext_vtab *v, int iLevel){
84493   LeafWriter writer;
84494   LeavesReader lrs[MERGE_COUNT];
84495   int i, rc, idx = 0;
84496
84497   /* Determine the next available segment index at the next level,
84498   ** merging as necessary.
84499   */
84500   rc = segdirNextIndex(v, iLevel+1, &idx);
84501   if( rc!=SQLITE_OK ) return rc;
84502
84503   /* TODO(shess) This assumes that we'll always see exactly
84504   ** MERGE_COUNT segments to merge at a given level.  That will be
84505   ** broken if we allow the developer to request preemptive or
84506   ** deferred merging.
84507   */
84508   memset(&lrs, '\0', sizeof(lrs));
84509   rc = leavesReadersInit(v, iLevel, lrs, &i);
84510   if( rc!=SQLITE_OK ) return rc;
84511   assert( i==MERGE_COUNT );
84512
84513   leafWriterInit(iLevel+1, idx, &writer);
84514
84515   /* Since leavesReaderReorder() pushes readers at eof to the end,
84516   ** when the first reader is empty, all will be empty.
84517   */
84518   while( !leavesReaderAtEnd(lrs) ){
84519     /* Figure out how many readers share their next term. */
84520     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
84521       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
84522     }
84523
84524     rc = leavesReadersMerge(v, lrs, i, &writer);
84525     if( rc!=SQLITE_OK ) goto err;
84526
84527     /* Step forward those that were merged. */
84528     while( i-->0 ){
84529       rc = leavesReaderStep(v, lrs+i);
84530       if( rc!=SQLITE_OK ) goto err;
84531
84532       /* Reorder by term, then by age. */
84533       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
84534     }
84535   }
84536
84537   for(i=0; i<MERGE_COUNT; i++){
84538     leavesReaderDestroy(&lrs[i]);
84539   }
84540
84541   rc = leafWriterFinalize(v, &writer);
84542   leafWriterDestroy(&writer);
84543   if( rc!=SQLITE_OK ) return rc;
84544
84545   /* Delete the merged segment data. */
84546   return segdir_delete(v, iLevel);
84547
84548  err:
84549   for(i=0; i<MERGE_COUNT; i++){
84550     leavesReaderDestroy(&lrs[i]);
84551   }
84552   leafWriterDestroy(&writer);
84553   return rc;
84554 }
84555
84556 /* Accumulate the union of *acc and *pData into *acc. */
84557 static void docListAccumulateUnion(DataBuffer *acc,
84558                                    const char *pData, int nData) {
84559   DataBuffer tmp = *acc;
84560   dataBufferInit(acc, tmp.nData+nData);
84561   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
84562   dataBufferDestroy(&tmp);
84563 }
84564
84565 /* TODO(shess) It might be interesting to explore different merge
84566 ** strategies, here.  For instance, since this is a sorted merge, we
84567 ** could easily merge many doclists in parallel.  With some
84568 ** comprehension of the storage format, we could merge all of the
84569 ** doclists within a leaf node directly from the leaf node's storage.
84570 ** It may be worthwhile to merge smaller doclists before larger
84571 ** doclists, since they can be traversed more quickly - but the
84572 ** results may have less overlap, making them more expensive in a
84573 ** different way.
84574 */
84575
84576 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
84577 ** *out (any doclists with duplicate docids overwrite those in *out).
84578 ** Internal function for loadSegmentLeaf().
84579 */
84580 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
84581                                 const char *pTerm, int nTerm, int isPrefix,
84582                                 DataBuffer *out){
84583   /* doclist data is accumulated into pBuffers similar to how one does
84584   ** increment in binary arithmetic.  If index 0 is empty, the data is
84585   ** stored there.  If there is data there, it is merged and the
84586   ** results carried into position 1, with further merge-and-carry
84587   ** until an empty position is found.
84588   */
84589   DataBuffer *pBuffers = NULL;
84590   int nBuffers = 0, nMaxBuffers = 0, rc;
84591
84592   assert( nTerm>0 );
84593
84594   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
84595       rc=leavesReaderStep(v, pReader)){
84596     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
84597     ** already taken to compare the terms of two LeavesReaders.  Think
84598     ** on a better name.  [Meanwhile, break encapsulation rather than
84599     ** use a confusing name.]
84600     */
84601     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
84602     if( c>0 ) break;      /* Past any possible matches. */
84603     if( c==0 ){
84604       const char *pData = leavesReaderData(pReader);
84605       int iBuffer, nData = leavesReaderDataBytes(pReader);
84606
84607       /* Find the first empty buffer. */
84608       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
84609         if( 0==pBuffers[iBuffer].nData ) break;
84610       }
84611
84612       /* Out of buffers, add an empty one. */
84613       if( iBuffer==nBuffers ){
84614         if( nBuffers==nMaxBuffers ){
84615           DataBuffer *p;
84616           nMaxBuffers += 20;
84617
84618           /* Manual realloc so we can handle NULL appropriately. */
84619           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
84620           if( p==NULL ){
84621             rc = SQLITE_NOMEM;
84622             break;
84623           }
84624
84625           if( nBuffers>0 ){
84626             assert(pBuffers!=NULL);
84627             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
84628             sqlite3_free(pBuffers);
84629           }
84630           pBuffers = p;
84631         }
84632         dataBufferInit(&(pBuffers[nBuffers]), 0);
84633         nBuffers++;
84634       }
84635
84636       /* At this point, must have an empty at iBuffer. */
84637       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
84638
84639       /* If empty was first buffer, no need for merge logic. */
84640       if( iBuffer==0 ){
84641         dataBufferReplace(&(pBuffers[0]), pData, nData);
84642       }else{
84643         /* pAcc is the empty buffer the merged data will end up in. */
84644         DataBuffer *pAcc = &(pBuffers[iBuffer]);
84645         DataBuffer *p = &(pBuffers[0]);
84646
84647         /* Handle position 0 specially to avoid need to prime pAcc
84648         ** with pData/nData.
84649         */
84650         dataBufferSwap(p, pAcc);
84651         docListAccumulateUnion(pAcc, pData, nData);
84652
84653         /* Accumulate remaining doclists into pAcc. */
84654         for(++p; p<pAcc; ++p){
84655           docListAccumulateUnion(pAcc, p->pData, p->nData);
84656
84657           /* dataBufferReset() could allow a large doclist to blow up
84658           ** our memory requirements.
84659           */
84660           if( p->nCapacity<1024 ){
84661             dataBufferReset(p);
84662           }else{
84663             dataBufferDestroy(p);
84664             dataBufferInit(p, 0);
84665           }
84666         }
84667       }
84668     }
84669   }
84670
84671   /* Union all the doclists together into *out. */
84672   /* TODO(shess) What if *out is big?  Sigh. */
84673   if( rc==SQLITE_OK && nBuffers>0 ){
84674     int iBuffer;
84675     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
84676       if( pBuffers[iBuffer].nData>0 ){
84677         if( out->nData==0 ){
84678           dataBufferSwap(out, &(pBuffers[iBuffer]));
84679         }else{
84680           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
84681                                  pBuffers[iBuffer].nData);
84682         }
84683       }
84684     }
84685   }
84686
84687   while( nBuffers-- ){
84688     dataBufferDestroy(&(pBuffers[nBuffers]));
84689   }
84690   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
84691
84692   return rc;
84693 }
84694
84695 /* Call loadSegmentLeavesInt() with pData/nData as input. */
84696 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
84697                            const char *pTerm, int nTerm, int isPrefix,
84698                            DataBuffer *out){
84699   LeavesReader reader;
84700   int rc;
84701
84702   assert( nData>1 );
84703   assert( *pData=='\0' );
84704   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
84705   if( rc!=SQLITE_OK ) return rc;
84706
84707   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
84708   leavesReaderReset(&reader);
84709   leavesReaderDestroy(&reader);
84710   return rc;
84711 }
84712
84713 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
84714 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
84715 ** out.
84716 */
84717 static int loadSegmentLeaves(fulltext_vtab *v,
84718                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
84719                              const char *pTerm, int nTerm, int isPrefix,
84720                              DataBuffer *out){
84721   int rc;
84722   LeavesReader reader;
84723
84724   assert( iStartLeaf<=iEndLeaf );
84725   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
84726   if( rc!=SQLITE_OK ) return rc;
84727
84728   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
84729   leavesReaderReset(&reader);
84730   leavesReaderDestroy(&reader);
84731   return rc;
84732 }
84733
84734 /* Taking pData/nData as an interior node, find the sequence of child
84735 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
84736 ** interior node terms logically come between the blocks, so there is
84737 ** one more blockid than there are terms (that block contains terms >=
84738 ** the last interior-node term).
84739 */
84740 /* TODO(shess) The calling code may already know that the end child is
84741 ** not worth calculating, because the end may be in a later sibling
84742 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
84743 ** it is not worthwhile.
84744 */
84745 static void getChildrenContaining(const char *pData, int nData,
84746                                   const char *pTerm, int nTerm, int isPrefix,
84747                                   sqlite_int64 *piStartChild,
84748                                   sqlite_int64 *piEndChild){
84749   InteriorReader reader;
84750
84751   assert( nData>1 );
84752   assert( *pData!='\0' );
84753   interiorReaderInit(pData, nData, &reader);
84754
84755   /* Scan for the first child which could contain pTerm/nTerm. */
84756   while( !interiorReaderAtEnd(&reader) ){
84757     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
84758     interiorReaderStep(&reader);
84759   }
84760   *piStartChild = interiorReaderCurrentBlockid(&reader);
84761
84762   /* Keep scanning to find a term greater than our term, using prefix
84763   ** comparison if indicated.  If isPrefix is false, this will be the
84764   ** same blockid as the starting block.
84765   */
84766   while( !interiorReaderAtEnd(&reader) ){
84767     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
84768     interiorReaderStep(&reader);
84769   }
84770   *piEndChild = interiorReaderCurrentBlockid(&reader);
84771
84772   interiorReaderDestroy(&reader);
84773
84774   /* Children must ascend, and if !prefix, both must be the same. */
84775   assert( *piEndChild>=*piStartChild );
84776   assert( isPrefix || *piStartChild==*piEndChild );
84777 }
84778
84779 /* Read block at iBlockid and pass it with other params to
84780 ** getChildrenContaining().
84781 */
84782 static int loadAndGetChildrenContaining(
84783   fulltext_vtab *v,
84784   sqlite_int64 iBlockid,
84785   const char *pTerm, int nTerm, int isPrefix,
84786   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
84787 ){
84788   sqlite3_stmt *s = NULL;
84789   int rc;
84790
84791   assert( iBlockid!=0 );
84792   assert( pTerm!=NULL );
84793   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
84794   assert( piStartChild!=NULL );
84795   assert( piEndChild!=NULL );
84796
84797   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
84798   if( rc!=SQLITE_OK ) return rc;
84799
84800   rc = sqlite3_bind_int64(s, 1, iBlockid);
84801   if( rc!=SQLITE_OK ) return rc;
84802
84803   rc = sqlite3_step(s);
84804   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
84805   if( rc!=SQLITE_ROW ) return rc;
84806
84807   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
84808                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
84809
84810   /* We expect only one row.  We must execute another sqlite3_step()
84811    * to complete the iteration; otherwise the table will remain
84812    * locked. */
84813   rc = sqlite3_step(s);
84814   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
84815   if( rc!=SQLITE_DONE ) return rc;
84816
84817   return SQLITE_OK;
84818 }
84819
84820 /* Traverse the tree represented by pData[nData] looking for
84821 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
84822 ** loadSegment() to make error-handling cleaner.
84823 */
84824 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
84825                           sqlite_int64 iLeavesEnd,
84826                           const char *pTerm, int nTerm, int isPrefix,
84827                           DataBuffer *out){
84828   /* Special case where root is a leaf. */
84829   if( *pData=='\0' ){
84830     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
84831   }else{
84832     int rc;
84833     sqlite_int64 iStartChild, iEndChild;
84834
84835     /* Process pData as an interior node, then loop down the tree
84836     ** until we find the set of leaf nodes to scan for the term.
84837     */
84838     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
84839                           &iStartChild, &iEndChild);
84840     while( iStartChild>iLeavesEnd ){
84841       sqlite_int64 iNextStart, iNextEnd;
84842       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
84843                                         &iNextStart, &iNextEnd);
84844       if( rc!=SQLITE_OK ) return rc;
84845
84846       /* If we've branched, follow the end branch, too. */
84847       if( iStartChild!=iEndChild ){
84848         sqlite_int64 iDummy;
84849         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
84850                                           &iDummy, &iNextEnd);
84851         if( rc!=SQLITE_OK ) return rc;
84852       }
84853
84854       assert( iNextStart<=iNextEnd );
84855       iStartChild = iNextStart;
84856       iEndChild = iNextEnd;
84857     }
84858     assert( iStartChild<=iLeavesEnd );
84859     assert( iEndChild<=iLeavesEnd );
84860
84861     /* Scan through the leaf segments for doclists. */
84862     return loadSegmentLeaves(v, iStartChild, iEndChild,
84863                              pTerm, nTerm, isPrefix, out);
84864   }
84865 }
84866
84867 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
84868 ** merge its doclist over *out (any duplicate doclists read from the
84869 ** segment rooted at pData will overwrite those in *out).
84870 */
84871 /* TODO(shess) Consider changing this to determine the depth of the
84872 ** leaves using either the first characters of interior nodes (when
84873 ** ==1, we're one level above the leaves), or the first character of
84874 ** the root (which will describe the height of the tree directly).
84875 ** Either feels somewhat tricky to me.
84876 */
84877 /* TODO(shess) The current merge is likely to be slow for large
84878 ** doclists (though it should process from newest/smallest to
84879 ** oldest/largest, so it may not be that bad).  It might be useful to
84880 ** modify things to allow for N-way merging.  This could either be
84881 ** within a segment, with pairwise merges across segments, or across
84882 ** all segments at once.
84883 */
84884 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
84885                        sqlite_int64 iLeavesEnd,
84886                        const char *pTerm, int nTerm, int isPrefix,
84887                        DataBuffer *out){
84888   DataBuffer result;
84889   int rc;
84890
84891   assert( nData>1 );
84892
84893   /* This code should never be called with buffered updates. */
84894   assert( v->nPendingData<0 );
84895
84896   dataBufferInit(&result, 0);
84897   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
84898                       pTerm, nTerm, isPrefix, &result);
84899   if( rc==SQLITE_OK && result.nData>0 ){
84900     if( out->nData==0 ){
84901       DataBuffer tmp = *out;
84902       *out = result;
84903       result = tmp;
84904     }else{
84905       DataBuffer merged;
84906       DLReader readers[2];
84907
84908       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
84909       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
84910       dataBufferInit(&merged, out->nData+result.nData);
84911       docListMerge(&merged, readers, 2);
84912       dataBufferDestroy(out);
84913       *out = merged;
84914       dlrDestroy(&readers[0]);
84915       dlrDestroy(&readers[1]);
84916     }
84917   }
84918   dataBufferDestroy(&result);
84919   return rc;
84920 }
84921
84922 /* Scan the database and merge together the posting lists for the term
84923 ** into *out.
84924 */
84925 static int termSelect(fulltext_vtab *v, int iColumn,
84926                       const char *pTerm, int nTerm, int isPrefix,
84927                       DocListType iType, DataBuffer *out){
84928   DataBuffer doclist;
84929   sqlite3_stmt *s;
84930   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
84931   if( rc!=SQLITE_OK ) return rc;
84932
84933   /* This code should never be called with buffered updates. */
84934   assert( v->nPendingData<0 );
84935
84936   dataBufferInit(&doclist, 0);
84937
84938   /* Traverse the segments from oldest to newest so that newer doclist
84939   ** elements for given docids overwrite older elements.
84940   */
84941   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
84942     const char *pData = sqlite3_column_blob(s, 0);
84943     const int nData = sqlite3_column_bytes(s, 0);
84944     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
84945     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
84946                      &doclist);
84947     if( rc!=SQLITE_OK ) goto err;
84948   }
84949   if( rc==SQLITE_DONE ){
84950     if( doclist.nData!=0 ){
84951       /* TODO(shess) The old term_select_all() code applied the column
84952       ** restrict as we merged segments, leading to smaller buffers.
84953       ** This is probably worthwhile to bring back, once the new storage
84954       ** system is checked in.
84955       */
84956       if( iColumn==v->nColumn) iColumn = -1;
84957       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
84958                   iColumn, iType, out);
84959     }
84960     rc = SQLITE_OK;
84961   }
84962
84963  err:
84964   dataBufferDestroy(&doclist);
84965   return rc;
84966 }
84967
84968 /****************************************************************/
84969 /* Used to hold hashtable data for sorting. */
84970 typedef struct TermData {
84971   const char *pTerm;
84972   int nTerm;
84973   DLCollector *pCollector;
84974 } TermData;
84975
84976 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
84977 ** for equal, >0 for greater-than).
84978 */
84979 static int termDataCmp(const void *av, const void *bv){
84980   const TermData *a = (const TermData *)av;
84981   const TermData *b = (const TermData *)bv;
84982   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
84983   int c = memcmp(a->pTerm, b->pTerm, n);
84984   if( c!=0 ) return c;
84985   return a->nTerm-b->nTerm;
84986 }
84987
84988 /* Order pTerms data by term, then write a new level 0 segment using
84989 ** LeafWriter.
84990 */
84991 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
84992   fts3HashElem *e;
84993   int idx, rc, i, n;
84994   TermData *pData;
84995   LeafWriter writer;
84996   DataBuffer dl;
84997
84998   /* Determine the next index at level 0, merging as necessary. */
84999   rc = segdirNextIndex(v, 0, &idx);
85000   if( rc!=SQLITE_OK ) return rc;
85001
85002   n = fts3HashCount(pTerms);
85003   pData = sqlite3_malloc(n*sizeof(TermData));
85004
85005   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
85006     assert( i<n );
85007     pData[i].pTerm = fts3HashKey(e);
85008     pData[i].nTerm = fts3HashKeysize(e);
85009     pData[i].pCollector = fts3HashData(e);
85010   }
85011   assert( i==n );
85012
85013   /* TODO(shess) Should we allow user-defined collation sequences,
85014   ** here?  I think we only need that once we support prefix searches.
85015   */
85016   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
85017
85018   /* TODO(shess) Refactor so that we can write directly to the segment
85019   ** DataBuffer, as happens for segment merges.
85020   */
85021   leafWriterInit(0, idx, &writer);
85022   dataBufferInit(&dl, 0);
85023   for(i=0; i<n; i++){
85024     dataBufferReset(&dl);
85025     dlcAddDoclist(pData[i].pCollector, &dl);
85026     rc = leafWriterStep(v, &writer,
85027                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
85028     if( rc!=SQLITE_OK ) goto err;
85029   }
85030   rc = leafWriterFinalize(v, &writer);
85031
85032  err:
85033   dataBufferDestroy(&dl);
85034   sqlite3_free(pData);
85035   leafWriterDestroy(&writer);
85036   return rc;
85037 }
85038
85039 /* If pendingTerms has data, free it. */
85040 static int clearPendingTerms(fulltext_vtab *v){
85041   if( v->nPendingData>=0 ){
85042     fts3HashElem *e;
85043     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
85044       dlcDelete(fts3HashData(e));
85045     }
85046     fts3HashClear(&v->pendingTerms);
85047     v->nPendingData = -1;
85048   }
85049   return SQLITE_OK;
85050 }
85051
85052 /* If pendingTerms has data, flush it to a level-zero segment, and
85053 ** free it.
85054 */
85055 static int flushPendingTerms(fulltext_vtab *v){
85056   if( v->nPendingData>=0 ){
85057     int rc = writeZeroSegment(v, &v->pendingTerms);
85058     if( rc==SQLITE_OK ) clearPendingTerms(v);
85059     return rc;
85060   }
85061   return SQLITE_OK;
85062 }
85063
85064 /* If pendingTerms is "too big", or docid is out of order, flush it.
85065 ** Regardless, be certain that pendingTerms is initialized for use.
85066 */
85067 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
85068   /* TODO(shess) Explore whether partially flushing the buffer on
85069   ** forced-flush would provide better performance.  I suspect that if
85070   ** we ordered the doclists by size and flushed the largest until the
85071   ** buffer was half empty, that would let the less frequent terms
85072   ** generate longer doclists.
85073   */
85074   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
85075     int rc = flushPendingTerms(v);
85076     if( rc!=SQLITE_OK ) return rc;
85077   }
85078   if( v->nPendingData<0 ){
85079     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
85080     v->nPendingData = 0;
85081   }
85082   v->iPrevDocid = iDocid;
85083   return SQLITE_OK;
85084 }
85085
85086 /* This function implements the xUpdate callback; it is the top-level entry
85087  * point for inserting, deleting or updating a row in a full-text table. */
85088 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
85089                           sqlite_int64 *pRowid){
85090   fulltext_vtab *v = (fulltext_vtab *) pVtab;
85091   int rc;
85092
85093   FTSTRACE(("FTS3 Update %p\n", pVtab));
85094
85095   if( nArg<2 ){
85096     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
85097   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
85098     /* An update:
85099      * ppArg[0] = old rowid
85100      * ppArg[1] = new rowid
85101      * ppArg[2..2+v->nColumn-1] = values
85102      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
85103      * ppArg[2+v->nColumn+1] = value for docid
85104      */
85105     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
85106     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
85107         sqlite3_value_int64(ppArg[1]) != rowid ){
85108       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
85109     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
85110               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
85111       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
85112     }else{
85113       assert( nArg==2+v->nColumn+2);
85114       rc = index_update(v, rowid, &ppArg[2]);
85115     }
85116   } else {
85117     /* An insert:
85118      * ppArg[1] = requested rowid
85119      * ppArg[2..2+v->nColumn-1] = values
85120      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
85121      * ppArg[2+v->nColumn+1] = value for docid
85122      */
85123     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
85124     assert( nArg==2+v->nColumn+2);
85125     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
85126         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
85127       /* TODO(shess) Consider allowing this to work if the values are
85128       ** identical.  I'm inclined to discourage that usage, though,
85129       ** given that both rowid and docid are special columns.  Better
85130       ** would be to define one or the other as the default winner,
85131       ** but should it be fts3-centric (docid) or SQLite-centric
85132       ** (rowid)?
85133       */
85134       rc = SQLITE_ERROR;
85135     }else{
85136       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
85137         pRequestDocid = ppArg[1];
85138       }
85139       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
85140     }
85141   }
85142
85143   return rc;
85144 }
85145
85146 static int fulltextSync(sqlite3_vtab *pVtab){
85147   FTSTRACE(("FTS3 xSync()\n"));
85148   return flushPendingTerms((fulltext_vtab *)pVtab);
85149 }
85150
85151 static int fulltextBegin(sqlite3_vtab *pVtab){
85152   fulltext_vtab *v = (fulltext_vtab *) pVtab;
85153   FTSTRACE(("FTS3 xBegin()\n"));
85154
85155   /* Any buffered updates should have been cleared by the previous
85156   ** transaction.
85157   */
85158   assert( v->nPendingData<0 );
85159   return clearPendingTerms(v);
85160 }
85161
85162 static int fulltextCommit(sqlite3_vtab *pVtab){
85163   fulltext_vtab *v = (fulltext_vtab *) pVtab;
85164   FTSTRACE(("FTS3 xCommit()\n"));
85165
85166   /* Buffered updates should have been cleared by fulltextSync(). */
85167   assert( v->nPendingData<0 );
85168   return clearPendingTerms(v);
85169 }
85170
85171 static int fulltextRollback(sqlite3_vtab *pVtab){
85172   FTSTRACE(("FTS3 xRollback()\n"));
85173   return clearPendingTerms((fulltext_vtab *)pVtab);
85174 }
85175
85176 /*
85177 ** Implementation of the snippet() function for FTS3
85178 */
85179 static void snippetFunc(
85180   sqlite3_context *pContext,
85181   int argc,
85182   sqlite3_value **argv
85183 ){
85184   fulltext_cursor *pCursor;
85185   if( argc<1 ) return;
85186   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
85187       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
85188     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
85189   }else{
85190     const char *zStart = "<b>";
85191     const char *zEnd = "</b>";
85192     const char *zEllipsis = "<b>...</b>";
85193     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
85194     if( argc>=2 ){
85195       zStart = (const char*)sqlite3_value_text(argv[1]);
85196       if( argc>=3 ){
85197         zEnd = (const char*)sqlite3_value_text(argv[2]);
85198         if( argc>=4 ){
85199           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
85200         }
85201       }
85202     }
85203     snippetAllOffsets(pCursor);
85204     snippetText(pCursor, zStart, zEnd, zEllipsis);
85205     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
85206                         pCursor->snippet.nSnippet, SQLITE_STATIC);
85207   }
85208 }
85209
85210 /*
85211 ** Implementation of the offsets() function for FTS3
85212 */
85213 static void snippetOffsetsFunc(
85214   sqlite3_context *pContext,
85215   int argc,
85216   sqlite3_value **argv
85217 ){
85218   fulltext_cursor *pCursor;
85219   if( argc<1 ) return;
85220   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
85221       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
85222     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
85223   }else{
85224     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
85225     snippetAllOffsets(pCursor);
85226     snippetOffsetText(&pCursor->snippet);
85227     sqlite3_result_text(pContext,
85228                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
85229                         SQLITE_STATIC);
85230   }
85231 }
85232
85233 /*
85234 ** This routine implements the xFindFunction method for the FTS3
85235 ** virtual table.
85236 */
85237 static int fulltextFindFunction(
85238   sqlite3_vtab *pVtab,
85239   int nArg,
85240   const char *zName,
85241   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
85242   void **ppArg
85243 ){
85244   if( strcmp(zName,"snippet")==0 ){
85245     *pxFunc = snippetFunc;
85246     return 1;
85247   }else if( strcmp(zName,"offsets")==0 ){
85248     *pxFunc = snippetOffsetsFunc;
85249     return 1;
85250   }
85251   return 0;
85252 }
85253
85254 /*
85255 ** Rename an fts3 table.
85256 */
85257 static int fulltextRename(
85258   sqlite3_vtab *pVtab,
85259   const char *zName
85260 ){
85261   fulltext_vtab *p = (fulltext_vtab *)pVtab;
85262   int rc = SQLITE_NOMEM;
85263   char *zSql = sqlite3_mprintf(
85264     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
85265     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
85266     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
85267     , p->zDb, p->zName, zName 
85268     , p->zDb, p->zName, zName 
85269     , p->zDb, p->zName, zName
85270   );
85271   if( zSql ){
85272     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
85273     sqlite3_free(zSql);
85274   }
85275   return rc;
85276 }
85277
85278 static const sqlite3_module fts3Module = {
85279   /* iVersion      */ 0,
85280   /* xCreate       */ fulltextCreate,
85281   /* xConnect      */ fulltextConnect,
85282   /* xBestIndex    */ fulltextBestIndex,
85283   /* xDisconnect   */ fulltextDisconnect,
85284   /* xDestroy      */ fulltextDestroy,
85285   /* xOpen         */ fulltextOpen,
85286   /* xClose        */ fulltextClose,
85287   /* xFilter       */ fulltextFilter,
85288   /* xNext         */ fulltextNext,
85289   /* xEof          */ fulltextEof,
85290   /* xColumn       */ fulltextColumn,
85291   /* xRowid        */ fulltextRowid,
85292   /* xUpdate       */ fulltextUpdate,
85293   /* xBegin        */ fulltextBegin,
85294   /* xSync         */ fulltextSync,
85295   /* xCommit       */ fulltextCommit,
85296   /* xRollback     */ fulltextRollback,
85297   /* xFindFunction */ fulltextFindFunction,
85298   /* xRename */       fulltextRename,
85299 };
85300
85301 static void hashDestroy(void *p){
85302   fts3Hash *pHash = (fts3Hash *)p;
85303   sqlite3Fts3HashClear(pHash);
85304   sqlite3_free(pHash);
85305 }
85306
85307 /*
85308 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
85309 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
85310 ** two forward declarations are for functions declared in these files
85311 ** used to retrieve the respective implementations.
85312 **
85313 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
85314 ** to by the argument to point a the "simple" tokenizer implementation.
85315 ** Function ...PorterTokenizerModule() sets *pModule to point to the
85316 ** porter tokenizer/stemmer implementation.
85317 */
85318 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
85319 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
85320 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
85321
85322 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
85323
85324 /*
85325 ** Initialise the fts3 extension. If this extension is built as part
85326 ** of the sqlite library, then this function is called directly by
85327 ** SQLite. If fts3 is built as a dynamically loadable extension, this
85328 ** function is called by the sqlite3_extension_init() entry point.
85329 */
85330 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
85331   int rc = SQLITE_OK;
85332   fts3Hash *pHash = 0;
85333   const sqlite3_tokenizer_module *pSimple = 0;
85334   const sqlite3_tokenizer_module *pPorter = 0;
85335   const sqlite3_tokenizer_module *pIcu = 0;
85336
85337   sqlite3Fts3SimpleTokenizerModule(&pSimple);
85338   sqlite3Fts3PorterTokenizerModule(&pPorter);
85339 #ifdef SQLITE_ENABLE_ICU
85340   sqlite3Fts3IcuTokenizerModule(&pIcu);
85341 #endif
85342
85343   /* Allocate and initialise the hash-table used to store tokenizers. */
85344   pHash = sqlite3_malloc(sizeof(fts3Hash));
85345   if( !pHash ){
85346     rc = SQLITE_NOMEM;
85347   }else{
85348     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
85349   }
85350
85351   /* Load the built-in tokenizers into the hash table */
85352   if( rc==SQLITE_OK ){
85353     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
85354      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
85355      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
85356     ){
85357       rc = SQLITE_NOMEM;
85358     }
85359   }
85360
85361   /* Create the virtual table wrapper around the hash-table and overload 
85362   ** the two scalar functions. If this is successful, register the
85363   ** module with sqlite.
85364   */
85365   if( SQLITE_OK==rc 
85366    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
85367    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
85368    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
85369   ){
85370     return sqlite3_create_module_v2(
85371         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
85372     );
85373   }
85374
85375   /* An error has occured. Delete the hash table and return the error code. */
85376   assert( rc!=SQLITE_OK );
85377   if( pHash ){
85378     sqlite3Fts3HashClear(pHash);
85379     sqlite3_free(pHash);
85380   }
85381   return rc;
85382 }
85383
85384 #if !SQLITE_CORE
85385 SQLITE_API int sqlite3_extension_init(
85386   sqlite3 *db, 
85387   char **pzErrMsg,
85388   const sqlite3_api_routines *pApi
85389 ){
85390   SQLITE_EXTENSION_INIT2(pApi)
85391   return sqlite3Fts3Init(db);
85392 }
85393 #endif
85394
85395 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
85396
85397 /************** End of fts3.c ************************************************/
85398 /************** Begin file fts3_hash.c ***************************************/
85399 /*
85400 ** 2001 September 22
85401 **
85402 ** The author disclaims copyright to this source code.  In place of
85403 ** a legal notice, here is a blessing:
85404 **
85405 **    May you do good and not evil.
85406 **    May you find forgiveness for yourself and forgive others.
85407 **    May you share freely, never taking more than you give.
85408 **
85409 *************************************************************************
85410 ** This is the implementation of generic hash-tables used in SQLite.
85411 ** We've modified it slightly to serve as a standalone hash table
85412 ** implementation for the full-text indexing module.
85413 */
85414
85415 /*
85416 ** The code in this file is only compiled if:
85417 **
85418 **     * The FTS3 module is being built as an extension
85419 **       (in which case SQLITE_CORE is not defined), or
85420 **
85421 **     * The FTS3 module is being built into the core of
85422 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
85423 */
85424 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
85425
85426
85427
85428 /*
85429 ** Malloc and Free functions
85430 */
85431 static void *fts3HashMalloc(int n){
85432   void *p = sqlite3_malloc(n);
85433   if( p ){
85434     memset(p, 0, n);
85435   }
85436   return p;
85437 }
85438 static void fts3HashFree(void *p){
85439   sqlite3_free(p);
85440 }
85441
85442 /* Turn bulk memory into a hash table object by initializing the
85443 ** fields of the Hash structure.
85444 **
85445 ** "pNew" is a pointer to the hash table that is to be initialized.
85446 ** keyClass is one of the constants 
85447 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
85448 ** determines what kind of key the hash table will use.  "copyKey" is
85449 ** true if the hash table should make its own private copy of keys and
85450 ** false if it should just use the supplied pointer.
85451 */
85452 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
85453   assert( pNew!=0 );
85454   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
85455   pNew->keyClass = keyClass;
85456   pNew->copyKey = copyKey;
85457   pNew->first = 0;
85458   pNew->count = 0;
85459   pNew->htsize = 0;
85460   pNew->ht = 0;
85461 }
85462
85463 /* Remove all entries from a hash table.  Reclaim all memory.
85464 ** Call this routine to delete a hash table or to reset a hash table
85465 ** to the empty state.
85466 */
85467 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
85468   fts3HashElem *elem;         /* For looping over all elements of the table */
85469
85470   assert( pH!=0 );
85471   elem = pH->first;
85472   pH->first = 0;
85473   fts3HashFree(pH->ht);
85474   pH->ht = 0;
85475   pH->htsize = 0;
85476   while( elem ){
85477     fts3HashElem *next_elem = elem->next;
85478     if( pH->copyKey && elem->pKey ){
85479       fts3HashFree(elem->pKey);
85480     }
85481     fts3HashFree(elem);
85482     elem = next_elem;
85483   }
85484   pH->count = 0;
85485 }
85486
85487 /*
85488 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
85489 */
85490 static int fts3StrHash(const void *pKey, int nKey){
85491   const char *z = (const char *)pKey;
85492   int h = 0;
85493   if( nKey<=0 ) nKey = (int) strlen(z);
85494   while( nKey > 0  ){
85495     h = (h<<3) ^ h ^ *z++;
85496     nKey--;
85497   }
85498   return h & 0x7fffffff;
85499 }
85500 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
85501   if( n1!=n2 ) return 1;
85502   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
85503 }
85504
85505 /*
85506 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
85507 */
85508 static int fts3BinHash(const void *pKey, int nKey){
85509   int h = 0;
85510   const char *z = (const char *)pKey;
85511   while( nKey-- > 0 ){
85512     h = (h<<3) ^ h ^ *(z++);
85513   }
85514   return h & 0x7fffffff;
85515 }
85516 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
85517   if( n1!=n2 ) return 1;
85518   return memcmp(pKey1,pKey2,n1);
85519 }
85520
85521 /*
85522 ** Return a pointer to the appropriate hash function given the key class.
85523 **
85524 ** The C syntax in this function definition may be unfamilar to some 
85525 ** programmers, so we provide the following additional explanation:
85526 **
85527 ** The name of the function is "ftsHashFunction".  The function takes a
85528 ** single parameter "keyClass".  The return value of ftsHashFunction()
85529 ** is a pointer to another function.  Specifically, the return value
85530 ** of ftsHashFunction() is a pointer to a function that takes two parameters
85531 ** with types "const void*" and "int" and returns an "int".
85532 */
85533 static int (*ftsHashFunction(int keyClass))(const void*,int){
85534   if( keyClass==FTS3_HASH_STRING ){
85535     return &fts3StrHash;
85536   }else{
85537     assert( keyClass==FTS3_HASH_BINARY );
85538     return &fts3BinHash;
85539   }
85540 }
85541
85542 /*
85543 ** Return a pointer to the appropriate hash function given the key class.
85544 **
85545 ** For help in interpreted the obscure C code in the function definition,
85546 ** see the header comment on the previous function.
85547 */
85548 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
85549   if( keyClass==FTS3_HASH_STRING ){
85550     return &fts3StrCompare;
85551   }else{
85552     assert( keyClass==FTS3_HASH_BINARY );
85553     return &fts3BinCompare;
85554   }
85555 }
85556
85557 /* Link an element into the hash table
85558 */
85559 static void fts3HashInsertElement(
85560   fts3Hash *pH,            /* The complete hash table */
85561   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
85562   fts3HashElem *pNew       /* The element to be inserted */
85563 ){
85564   fts3HashElem *pHead;     /* First element already in pEntry */
85565   pHead = pEntry->chain;
85566   if( pHead ){
85567     pNew->next = pHead;
85568     pNew->prev = pHead->prev;
85569     if( pHead->prev ){ pHead->prev->next = pNew; }
85570     else             { pH->first = pNew; }
85571     pHead->prev = pNew;
85572   }else{
85573     pNew->next = pH->first;
85574     if( pH->first ){ pH->first->prev = pNew; }
85575     pNew->prev = 0;
85576     pH->first = pNew;
85577   }
85578   pEntry->count++;
85579   pEntry->chain = pNew;
85580 }
85581
85582
85583 /* Resize the hash table so that it cantains "new_size" buckets.
85584 ** "new_size" must be a power of 2.  The hash table might fail 
85585 ** to resize if sqliteMalloc() fails.
85586 */
85587 static void fts3Rehash(fts3Hash *pH, int new_size){
85588   struct _fts3ht *new_ht;          /* The new hash table */
85589   fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
85590   int (*xHash)(const void*,int);   /* The hash function */
85591
85592   assert( (new_size & (new_size-1))==0 );
85593   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
85594   if( new_ht==0 ) return;
85595   fts3HashFree(pH->ht);
85596   pH->ht = new_ht;
85597   pH->htsize = new_size;
85598   xHash = ftsHashFunction(pH->keyClass);
85599   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
85600     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
85601     next_elem = elem->next;
85602     fts3HashInsertElement(pH, &new_ht[h], elem);
85603   }
85604 }
85605
85606 /* This function (for internal use only) locates an element in an
85607 ** hash table that matches the given key.  The hash for this key has
85608 ** already been computed and is passed as the 4th parameter.
85609 */
85610 static fts3HashElem *fts3FindElementByHash(
85611   const fts3Hash *pH, /* The pH to be searched */
85612   const void *pKey,   /* The key we are searching for */
85613   int nKey,
85614   int h               /* The hash for this key. */
85615 ){
85616   fts3HashElem *elem;            /* Used to loop thru the element list */
85617   int count;                     /* Number of elements left to test */
85618   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
85619
85620   if( pH->ht ){
85621     struct _fts3ht *pEntry = &pH->ht[h];
85622     elem = pEntry->chain;
85623     count = pEntry->count;
85624     xCompare = ftsCompareFunction(pH->keyClass);
85625     while( count-- && elem ){
85626       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
85627         return elem;
85628       }
85629       elem = elem->next;
85630     }
85631   }
85632   return 0;
85633 }
85634
85635 /* Remove a single entry from the hash table given a pointer to that
85636 ** element and a hash on the element's key.
85637 */
85638 static void fts3RemoveElementByHash(
85639   fts3Hash *pH,         /* The pH containing "elem" */
85640   fts3HashElem* elem,   /* The element to be removed from the pH */
85641   int h                 /* Hash value for the element */
85642 ){
85643   struct _fts3ht *pEntry;
85644   if( elem->prev ){
85645     elem->prev->next = elem->next; 
85646   }else{
85647     pH->first = elem->next;
85648   }
85649   if( elem->next ){
85650     elem->next->prev = elem->prev;
85651   }
85652   pEntry = &pH->ht[h];
85653   if( pEntry->chain==elem ){
85654     pEntry->chain = elem->next;
85655   }
85656   pEntry->count--;
85657   if( pEntry->count<=0 ){
85658     pEntry->chain = 0;
85659   }
85660   if( pH->copyKey && elem->pKey ){
85661     fts3HashFree(elem->pKey);
85662   }
85663   fts3HashFree( elem );
85664   pH->count--;
85665   if( pH->count<=0 ){
85666     assert( pH->first==0 );
85667     assert( pH->count==0 );
85668     fts3HashClear(pH);
85669   }
85670 }
85671
85672 /* Attempt to locate an element of the hash table pH with a key
85673 ** that matches pKey,nKey.  Return the data for this element if it is
85674 ** found, or NULL if there is no match.
85675 */
85676 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
85677   int h;                 /* A hash on key */
85678   fts3HashElem *elem;    /* The element that matches key */
85679   int (*xHash)(const void*,int);  /* The hash function */
85680
85681   if( pH==0 || pH->ht==0 ) return 0;
85682   xHash = ftsHashFunction(pH->keyClass);
85683   assert( xHash!=0 );
85684   h = (*xHash)(pKey,nKey);
85685   assert( (pH->htsize & (pH->htsize-1))==0 );
85686   elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
85687   return elem ? elem->data : 0;
85688 }
85689
85690 /* Insert an element into the hash table pH.  The key is pKey,nKey
85691 ** and the data is "data".
85692 **
85693 ** If no element exists with a matching key, then a new
85694 ** element is created.  A copy of the key is made if the copyKey
85695 ** flag is set.  NULL is returned.
85696 **
85697 ** If another element already exists with the same key, then the
85698 ** new data replaces the old data and the old data is returned.
85699 ** The key is not copied in this instance.  If a malloc fails, then
85700 ** the new data is returned and the hash table is unchanged.
85701 **
85702 ** If the "data" parameter to this function is NULL, then the
85703 ** element corresponding to "key" is removed from the hash table.
85704 */
85705 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
85706   fts3Hash *pH,        /* The hash table to insert into */
85707   const void *pKey,    /* The key */
85708   int nKey,            /* Number of bytes in the key */
85709   void *data           /* The data */
85710 ){
85711   int hraw;                 /* Raw hash value of the key */
85712   int h;                    /* the hash of the key modulo hash table size */
85713   fts3HashElem *elem;       /* Used to loop thru the element list */
85714   fts3HashElem *new_elem;   /* New element added to the pH */
85715   int (*xHash)(const void*,int);  /* The hash function */
85716
85717   assert( pH!=0 );
85718   xHash = ftsHashFunction(pH->keyClass);
85719   assert( xHash!=0 );
85720   hraw = (*xHash)(pKey, nKey);
85721   assert( (pH->htsize & (pH->htsize-1))==0 );
85722   h = hraw & (pH->htsize-1);
85723   elem = fts3FindElementByHash(pH,pKey,nKey,h);
85724   if( elem ){
85725     void *old_data = elem->data;
85726     if( data==0 ){
85727       fts3RemoveElementByHash(pH,elem,h);
85728     }else{
85729       elem->data = data;
85730     }
85731     return old_data;
85732   }
85733   if( data==0 ) return 0;
85734   new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
85735   if( new_elem==0 ) return data;
85736   if( pH->copyKey && pKey!=0 ){
85737     new_elem->pKey = fts3HashMalloc( nKey );
85738     if( new_elem->pKey==0 ){
85739       fts3HashFree(new_elem);
85740       return data;
85741     }
85742     memcpy((void*)new_elem->pKey, pKey, nKey);
85743   }else{
85744     new_elem->pKey = (void*)pKey;
85745   }
85746   new_elem->nKey = nKey;
85747   pH->count++;
85748   if( pH->htsize==0 ){
85749     fts3Rehash(pH,8);
85750     if( pH->htsize==0 ){
85751       pH->count = 0;
85752       fts3HashFree(new_elem);
85753       return data;
85754     }
85755   }
85756   if( pH->count > pH->htsize ){
85757     fts3Rehash(pH,pH->htsize*2);
85758   }
85759   assert( pH->htsize>0 );
85760   assert( (pH->htsize & (pH->htsize-1))==0 );
85761   h = hraw & (pH->htsize-1);
85762   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
85763   new_elem->data = data;
85764   return 0;
85765 }
85766
85767 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
85768
85769 /************** End of fts3_hash.c *******************************************/
85770 /************** Begin file fts3_porter.c *************************************/
85771 /*
85772 ** 2006 September 30
85773 **
85774 ** The author disclaims copyright to this source code.  In place of
85775 ** a legal notice, here is a blessing:
85776 **
85777 **    May you do good and not evil.
85778 **    May you find forgiveness for yourself and forgive others.
85779 **    May you share freely, never taking more than you give.
85780 **
85781 *************************************************************************
85782 ** Implementation of the full-text-search tokenizer that implements
85783 ** a Porter stemmer.
85784 */
85785
85786 /*
85787 ** The code in this file is only compiled if:
85788 **
85789 **     * The FTS3 module is being built as an extension
85790 **       (in which case SQLITE_CORE is not defined), or
85791 **
85792 **     * The FTS3 module is being built into the core of
85793 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
85794 */
85795 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
85796
85797
85798
85799
85800 /*
85801 ** Class derived from sqlite3_tokenizer
85802 */
85803 typedef struct porter_tokenizer {
85804   sqlite3_tokenizer base;      /* Base class */
85805 } porter_tokenizer;
85806
85807 /*
85808 ** Class derived from sqlit3_tokenizer_cursor
85809 */
85810 typedef struct porter_tokenizer_cursor {
85811   sqlite3_tokenizer_cursor base;
85812   const char *zInput;          /* input we are tokenizing */
85813   int nInput;                  /* size of the input */
85814   int iOffset;                 /* current position in zInput */
85815   int iToken;                  /* index of next token to be returned */
85816   char *zToken;                /* storage for current token */
85817   int nAllocated;              /* space allocated to zToken buffer */
85818 } porter_tokenizer_cursor;
85819
85820
85821 /* Forward declaration */
85822 static const sqlite3_tokenizer_module porterTokenizerModule;
85823
85824
85825 /*
85826 ** Create a new tokenizer instance.
85827 */
85828 static int porterCreate(
85829   int argc, const char * const *argv,
85830   sqlite3_tokenizer **ppTokenizer
85831 ){
85832   porter_tokenizer *t;
85833   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
85834   if( t==NULL ) return SQLITE_NOMEM;
85835   memset(t, 0, sizeof(*t));
85836   *ppTokenizer = &t->base;
85837   return SQLITE_OK;
85838 }
85839
85840 /*
85841 ** Destroy a tokenizer
85842 */
85843 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
85844   sqlite3_free(pTokenizer);
85845   return SQLITE_OK;
85846 }
85847
85848 /*
85849 ** Prepare to begin tokenizing a particular string.  The input
85850 ** string to be tokenized is zInput[0..nInput-1].  A cursor
85851 ** used to incrementally tokenize this string is returned in 
85852 ** *ppCursor.
85853 */
85854 static int porterOpen(
85855   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
85856   const char *zInput, int nInput,        /* String to be tokenized */
85857   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
85858 ){
85859   porter_tokenizer_cursor *c;
85860
85861   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
85862   if( c==NULL ) return SQLITE_NOMEM;
85863
85864   c->zInput = zInput;
85865   if( zInput==0 ){
85866     c->nInput = 0;
85867   }else if( nInput<0 ){
85868     c->nInput = (int)strlen(zInput);
85869   }else{
85870     c->nInput = nInput;
85871   }
85872   c->iOffset = 0;                 /* start tokenizing at the beginning */
85873   c->iToken = 0;
85874   c->zToken = NULL;               /* no space allocated, yet. */
85875   c->nAllocated = 0;
85876
85877   *ppCursor = &c->base;
85878   return SQLITE_OK;
85879 }
85880
85881 /*
85882 ** Close a tokenization cursor previously opened by a call to
85883 ** porterOpen() above.
85884 */
85885 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
85886   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
85887   sqlite3_free(c->zToken);
85888   sqlite3_free(c);
85889   return SQLITE_OK;
85890 }
85891 /*
85892 ** Vowel or consonant
85893 */
85894 static const char cType[] = {
85895    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
85896    1, 1, 1, 2, 1
85897 };
85898
85899 /*
85900 ** isConsonant() and isVowel() determine if their first character in
85901 ** the string they point to is a consonant or a vowel, according
85902 ** to Porter ruls.  
85903 **
85904 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
85905 ** 'Y' is a consonant unless it follows another consonant,
85906 ** in which case it is a vowel.
85907 **
85908 ** In these routine, the letters are in reverse order.  So the 'y' rule
85909 ** is that 'y' is a consonant unless it is followed by another
85910 ** consonent.
85911 */
85912 static int isVowel(const char*);
85913 static int isConsonant(const char *z){
85914   int j;
85915   char x = *z;
85916   if( x==0 ) return 0;
85917   assert( x>='a' && x<='z' );
85918   j = cType[x-'a'];
85919   if( j<2 ) return j;
85920   return z[1]==0 || isVowel(z + 1);
85921 }
85922 static int isVowel(const char *z){
85923   int j;
85924   char x = *z;
85925   if( x==0 ) return 0;
85926   assert( x>='a' && x<='z' );
85927   j = cType[x-'a'];
85928   if( j<2 ) return 1-j;
85929   return isConsonant(z + 1);
85930 }
85931
85932 /*
85933 ** Let any sequence of one or more vowels be represented by V and let
85934 ** C be sequence of one or more consonants.  Then every word can be
85935 ** represented as:
85936 **
85937 **           [C] (VC){m} [V]
85938 **
85939 ** In prose:  A word is an optional consonant followed by zero or
85940 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
85941 ** number of vowel consonant pairs.  This routine computes the value
85942 ** of m for the first i bytes of a word.
85943 **
85944 ** Return true if the m-value for z is 1 or more.  In other words,
85945 ** return true if z contains at least one vowel that is followed
85946 ** by a consonant.
85947 **
85948 ** In this routine z[] is in reverse order.  So we are really looking
85949 ** for an instance of of a consonant followed by a vowel.
85950 */
85951 static int m_gt_0(const char *z){
85952   while( isVowel(z) ){ z++; }
85953   if( *z==0 ) return 0;
85954   while( isConsonant(z) ){ z++; }
85955   return *z!=0;
85956 }
85957
85958 /* Like mgt0 above except we are looking for a value of m which is
85959 ** exactly 1
85960 */
85961 static int m_eq_1(const char *z){
85962   while( isVowel(z) ){ z++; }
85963   if( *z==0 ) return 0;
85964   while( isConsonant(z) ){ z++; }
85965   if( *z==0 ) return 0;
85966   while( isVowel(z) ){ z++; }
85967   if( *z==0 ) return 1;
85968   while( isConsonant(z) ){ z++; }
85969   return *z==0;
85970 }
85971
85972 /* Like mgt0 above except we are looking for a value of m>1 instead
85973 ** or m>0
85974 */
85975 static int m_gt_1(const char *z){
85976   while( isVowel(z) ){ z++; }
85977   if( *z==0 ) return 0;
85978   while( isConsonant(z) ){ z++; }
85979   if( *z==0 ) return 0;
85980   while( isVowel(z) ){ z++; }
85981   if( *z==0 ) return 0;
85982   while( isConsonant(z) ){ z++; }
85983   return *z!=0;
85984 }
85985
85986 /*
85987 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
85988 */
85989 static int hasVowel(const char *z){
85990   while( isConsonant(z) ){ z++; }
85991   return *z!=0;
85992 }
85993
85994 /*
85995 ** Return TRUE if the word ends in a double consonant.
85996 **
85997 ** The text is reversed here. So we are really looking at
85998 ** the first two characters of z[].
85999 */
86000 static int doubleConsonant(const char *z){
86001   return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
86002 }
86003
86004 /*
86005 ** Return TRUE if the word ends with three letters which
86006 ** are consonant-vowel-consonent and where the final consonant
86007 ** is not 'w', 'x', or 'y'.
86008 **
86009 ** The word is reversed here.  So we are really checking the
86010 ** first three letters and the first one cannot be in [wxy].
86011 */
86012 static int star_oh(const char *z){
86013   return
86014     z[0]!=0 && isConsonant(z) &&
86015     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
86016     z[1]!=0 && isVowel(z+1) &&
86017     z[2]!=0 && isConsonant(z+2);
86018 }
86019
86020 /*
86021 ** If the word ends with zFrom and xCond() is true for the stem
86022 ** of the word that preceeds the zFrom ending, then change the 
86023 ** ending to zTo.
86024 **
86025 ** The input word *pz and zFrom are both in reverse order.  zTo
86026 ** is in normal order. 
86027 **
86028 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
86029 ** match.  Not that TRUE is returned even if xCond() fails and
86030 ** no substitution occurs.
86031 */
86032 static int stem(
86033   char **pz,             /* The word being stemmed (Reversed) */
86034   const char *zFrom,     /* If the ending matches this... (Reversed) */
86035   const char *zTo,       /* ... change the ending to this (not reversed) */
86036   int (*xCond)(const char*)   /* Condition that must be true */
86037 ){
86038   char *z = *pz;
86039   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
86040   if( *zFrom!=0 ) return 0;
86041   if( xCond && !xCond(z) ) return 1;
86042   while( *zTo ){
86043     *(--z) = *(zTo++);
86044   }
86045   *pz = z;
86046   return 1;
86047 }
86048
86049 /*
86050 ** This is the fallback stemmer used when the porter stemmer is
86051 ** inappropriate.  The input word is copied into the output with
86052 ** US-ASCII case folding.  If the input word is too long (more
86053 ** than 20 bytes if it contains no digits or more than 6 bytes if
86054 ** it contains digits) then word is truncated to 20 or 6 bytes
86055 ** by taking 10 or 3 bytes from the beginning and end.
86056 */
86057 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
86058   int i, mx, j;
86059   int hasDigit = 0;
86060   for(i=0; i<nIn; i++){
86061     int c = zIn[i];
86062     if( c>='A' && c<='Z' ){
86063       zOut[i] = c - 'A' + 'a';
86064     }else{
86065       if( c>='0' && c<='9' ) hasDigit = 1;
86066       zOut[i] = c;
86067     }
86068   }
86069   mx = hasDigit ? 3 : 10;
86070   if( nIn>mx*2 ){
86071     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
86072       zOut[j] = zOut[i];
86073     }
86074     i = j;
86075   }
86076   zOut[i] = 0;
86077   *pnOut = i;
86078 }
86079
86080
86081 /*
86082 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
86083 ** zOut is at least big enough to hold nIn bytes.  Write the actual
86084 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
86085 **
86086 ** Any upper-case characters in the US-ASCII character set ([A-Z])
86087 ** are converted to lower case.  Upper-case UTF characters are
86088 ** unchanged.
86089 **
86090 ** Words that are longer than about 20 bytes are stemmed by retaining
86091 ** a few bytes from the beginning and the end of the word.  If the
86092 ** word contains digits, 3 bytes are taken from the beginning and
86093 ** 3 bytes from the end.  For long words without digits, 10 bytes
86094 ** are taken from each end.  US-ASCII case folding still applies.
86095 ** 
86096 ** If the input word contains not digits but does characters not 
86097 ** in [a-zA-Z] then no stemming is attempted and this routine just 
86098 ** copies the input into the input into the output with US-ASCII
86099 ** case folding.
86100 **
86101 ** Stemming never increases the length of the word.  So there is
86102 ** no chance of overflowing the zOut buffer.
86103 */
86104 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
86105   int i, j, c;
86106   char zReverse[28];
86107   char *z, *z2;
86108   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
86109     /* The word is too big or too small for the porter stemmer.
86110     ** Fallback to the copy stemmer */
86111     copy_stemmer(zIn, nIn, zOut, pnOut);
86112     return;
86113   }
86114   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
86115     c = zIn[i];
86116     if( c>='A' && c<='Z' ){
86117       zReverse[j] = c + 'a' - 'A';
86118     }else if( c>='a' && c<='z' ){
86119       zReverse[j] = c;
86120     }else{
86121       /* The use of a character not in [a-zA-Z] means that we fallback
86122       ** to the copy stemmer */
86123       copy_stemmer(zIn, nIn, zOut, pnOut);
86124       return;
86125     }
86126   }
86127   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
86128   z = &zReverse[j+1];
86129
86130
86131   /* Step 1a */
86132   if( z[0]=='s' ){
86133     if(
86134      !stem(&z, "sess", "ss", 0) &&
86135      !stem(&z, "sei", "i", 0)  &&
86136      !stem(&z, "ss", "ss", 0)
86137     ){
86138       z++;
86139     }
86140   }
86141
86142   /* Step 1b */  
86143   z2 = z;
86144   if( stem(&z, "dee", "ee", m_gt_0) ){
86145     /* Do nothing.  The work was all in the test */
86146   }else if( 
86147      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
86148       && z!=z2
86149   ){
86150      if( stem(&z, "ta", "ate", 0) ||
86151          stem(&z, "lb", "ble", 0) ||
86152          stem(&z, "zi", "ize", 0) ){
86153        /* Do nothing.  The work was all in the test */
86154      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
86155        z++;
86156      }else if( m_eq_1(z) && star_oh(z) ){
86157        *(--z) = 'e';
86158      }
86159   }
86160
86161   /* Step 1c */
86162   if( z[0]=='y' && hasVowel(z+1) ){
86163     z[0] = 'i';
86164   }
86165
86166   /* Step 2 */
86167   switch( z[1] ){
86168    case 'a':
86169      stem(&z, "lanoita", "ate", m_gt_0) ||
86170      stem(&z, "lanoit", "tion", m_gt_0);
86171      break;
86172    case 'c':
86173      stem(&z, "icne", "ence", m_gt_0) ||
86174      stem(&z, "icna", "ance", m_gt_0);
86175      break;
86176    case 'e':
86177      stem(&z, "rezi", "ize", m_gt_0);
86178      break;
86179    case 'g':
86180      stem(&z, "igol", "log", m_gt_0);
86181      break;
86182    case 'l':
86183      stem(&z, "ilb", "ble", m_gt_0) ||
86184      stem(&z, "illa", "al", m_gt_0) ||
86185      stem(&z, "iltne", "ent", m_gt_0) ||
86186      stem(&z, "ile", "e", m_gt_0) ||
86187      stem(&z, "ilsuo", "ous", m_gt_0);
86188      break;
86189    case 'o':
86190      stem(&z, "noitazi", "ize", m_gt_0) ||
86191      stem(&z, "noita", "ate", m_gt_0) ||
86192      stem(&z, "rota", "ate", m_gt_0);
86193      break;
86194    case 's':
86195      stem(&z, "msila", "al", m_gt_0) ||
86196      stem(&z, "ssenevi", "ive", m_gt_0) ||
86197      stem(&z, "ssenluf", "ful", m_gt_0) ||
86198      stem(&z, "ssensuo", "ous", m_gt_0);
86199      break;
86200    case 't':
86201      stem(&z, "itila", "al", m_gt_0) ||
86202      stem(&z, "itivi", "ive", m_gt_0) ||
86203      stem(&z, "itilib", "ble", m_gt_0);
86204      break;
86205   }
86206
86207   /* Step 3 */
86208   switch( z[0] ){
86209    case 'e':
86210      stem(&z, "etaci", "ic", m_gt_0) ||
86211      stem(&z, "evita", "", m_gt_0)   ||
86212      stem(&z, "ezila", "al", m_gt_0);
86213      break;
86214    case 'i':
86215      stem(&z, "itici", "ic", m_gt_0);
86216      break;
86217    case 'l':
86218      stem(&z, "laci", "ic", m_gt_0) ||
86219      stem(&z, "luf", "", m_gt_0);
86220      break;
86221    case 's':
86222      stem(&z, "ssen", "", m_gt_0);
86223      break;
86224   }
86225
86226   /* Step 4 */
86227   switch( z[1] ){
86228    case 'a':
86229      if( z[0]=='l' && m_gt_1(z+2) ){
86230        z += 2;
86231      }
86232      break;
86233    case 'c':
86234      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
86235        z += 4;
86236      }
86237      break;
86238    case 'e':
86239      if( z[0]=='r' && m_gt_1(z+2) ){
86240        z += 2;
86241      }
86242      break;
86243    case 'i':
86244      if( z[0]=='c' && m_gt_1(z+2) ){
86245        z += 2;
86246      }
86247      break;
86248    case 'l':
86249      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
86250        z += 4;
86251      }
86252      break;
86253    case 'n':
86254      if( z[0]=='t' ){
86255        if( z[2]=='a' ){
86256          if( m_gt_1(z+3) ){
86257            z += 3;
86258          }
86259        }else if( z[2]=='e' ){
86260          stem(&z, "tneme", "", m_gt_1) ||
86261          stem(&z, "tnem", "", m_gt_1) ||
86262          stem(&z, "tne", "", m_gt_1);
86263        }
86264      }
86265      break;
86266    case 'o':
86267      if( z[0]=='u' ){
86268        if( m_gt_1(z+2) ){
86269          z += 2;
86270        }
86271      }else if( z[3]=='s' || z[3]=='t' ){
86272        stem(&z, "noi", "", m_gt_1);
86273      }
86274      break;
86275    case 's':
86276      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
86277        z += 3;
86278      }
86279      break;
86280    case 't':
86281      stem(&z, "eta", "", m_gt_1) ||
86282      stem(&z, "iti", "", m_gt_1);
86283      break;
86284    case 'u':
86285      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
86286        z += 3;
86287      }
86288      break;
86289    case 'v':
86290    case 'z':
86291      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
86292        z += 3;
86293      }
86294      break;
86295   }
86296
86297   /* Step 5a */
86298   if( z[0]=='e' ){
86299     if( m_gt_1(z+1) ){
86300       z++;
86301     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
86302       z++;
86303     }
86304   }
86305
86306   /* Step 5b */
86307   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
86308     z++;
86309   }
86310
86311   /* z[] is now the stemmed word in reverse order.  Flip it back
86312   ** around into forward order and return.
86313   */
86314   *pnOut = i = strlen(z);
86315   zOut[i] = 0;
86316   while( *z ){
86317     zOut[--i] = *(z++);
86318   }
86319 }
86320
86321 /*
86322 ** Characters that can be part of a token.  We assume any character
86323 ** whose value is greater than 0x80 (any UTF character) can be
86324 ** part of a token.  In other words, delimiters all must have
86325 ** values of 0x7f or lower.
86326 */
86327 static const char porterIdChar[] = {
86328 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
86329     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
86330     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
86331     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
86332     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
86333     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
86334 };
86335 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
86336
86337 /*
86338 ** Extract the next token from a tokenization cursor.  The cursor must
86339 ** have been opened by a prior call to porterOpen().
86340 */
86341 static int porterNext(
86342   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
86343   const char **pzToken,               /* OUT: *pzToken is the token text */
86344   int *pnBytes,                       /* OUT: Number of bytes in token */
86345   int *piStartOffset,                 /* OUT: Starting offset of token */
86346   int *piEndOffset,                   /* OUT: Ending offset of token */
86347   int *piPosition                     /* OUT: Position integer of token */
86348 ){
86349   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
86350   const char *z = c->zInput;
86351
86352   while( c->iOffset<c->nInput ){
86353     int iStartOffset, ch;
86354
86355     /* Scan past delimiter characters */
86356     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
86357       c->iOffset++;
86358     }
86359
86360     /* Count non-delimiter characters. */
86361     iStartOffset = c->iOffset;
86362     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
86363       c->iOffset++;
86364     }
86365
86366     if( c->iOffset>iStartOffset ){
86367       int n = c->iOffset-iStartOffset;
86368       if( n>c->nAllocated ){
86369         c->nAllocated = n+20;
86370         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
86371         if( c->zToken==NULL ) return SQLITE_NOMEM;
86372       }
86373       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
86374       *pzToken = c->zToken;
86375       *piStartOffset = iStartOffset;
86376       *piEndOffset = c->iOffset;
86377       *piPosition = c->iToken++;
86378       return SQLITE_OK;
86379     }
86380   }
86381   return SQLITE_DONE;
86382 }
86383
86384 /*
86385 ** The set of routines that implement the porter-stemmer tokenizer
86386 */
86387 static const sqlite3_tokenizer_module porterTokenizerModule = {
86388   0,
86389   porterCreate,
86390   porterDestroy,
86391   porterOpen,
86392   porterClose,
86393   porterNext,
86394 };
86395
86396 /*
86397 ** Allocate a new porter tokenizer.  Return a pointer to the new
86398 ** tokenizer in *ppModule
86399 */
86400 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
86401   sqlite3_tokenizer_module const**ppModule
86402 ){
86403   *ppModule = &porterTokenizerModule;
86404 }
86405
86406 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
86407
86408 /************** End of fts3_porter.c *****************************************/
86409 /************** Begin file fts3_tokenizer.c **********************************/
86410 /*
86411 ** 2007 June 22
86412 **
86413 ** The author disclaims copyright to this source code.  In place of
86414 ** a legal notice, here is a blessing:
86415 **
86416 **    May you do good and not evil.
86417 **    May you find forgiveness for yourself and forgive others.
86418 **    May you share freely, never taking more than you give.
86419 **
86420 ******************************************************************************
86421 **
86422 ** This is part of an SQLite module implementing full-text search.
86423 ** This particular file implements the generic tokenizer interface.
86424 */
86425
86426 /*
86427 ** The code in this file is only compiled if:
86428 **
86429 **     * The FTS3 module is being built as an extension
86430 **       (in which case SQLITE_CORE is not defined), or
86431 **
86432 **     * The FTS3 module is being built into the core of
86433 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
86434 */
86435 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
86436
86437 #ifndef SQLITE_CORE
86438   SQLITE_EXTENSION_INIT1
86439 #endif
86440
86441
86442 /*
86443 ** Implementation of the SQL scalar function for accessing the underlying 
86444 ** hash table. This function may be called as follows:
86445 **
86446 **   SELECT <function-name>(<key-name>);
86447 **   SELECT <function-name>(<key-name>, <pointer>);
86448 **
86449 ** where <function-name> is the name passed as the second argument
86450 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
86451 **
86452 ** If the <pointer> argument is specified, it must be a blob value
86453 ** containing a pointer to be stored as the hash data corresponding
86454 ** to the string <key-name>. If <pointer> is not specified, then
86455 ** the string <key-name> must already exist in the has table. Otherwise,
86456 ** an error is returned.
86457 **
86458 ** Whether or not the <pointer> argument is specified, the value returned
86459 ** is a blob containing the pointer stored as the hash data corresponding
86460 ** to string <key-name> (after the hash-table is updated, if applicable).
86461 */
86462 static void scalarFunc(
86463   sqlite3_context *context,
86464   int argc,
86465   sqlite3_value **argv
86466 ){
86467   fts3Hash *pHash;
86468   void *pPtr = 0;
86469   const unsigned char *zName;
86470   int nName;
86471
86472   assert( argc==1 || argc==2 );
86473
86474   pHash = (fts3Hash *)sqlite3_user_data(context);
86475
86476   zName = sqlite3_value_text(argv[0]);
86477   nName = sqlite3_value_bytes(argv[0])+1;
86478
86479   if( argc==2 ){
86480     void *pOld;
86481     int n = sqlite3_value_bytes(argv[1]);
86482     if( n!=sizeof(pPtr) ){
86483       sqlite3_result_error(context, "argument type mismatch", -1);
86484       return;
86485     }
86486     pPtr = *(void **)sqlite3_value_blob(argv[1]);
86487     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
86488     if( pOld==pPtr ){
86489       sqlite3_result_error(context, "out of memory", -1);
86490       return;
86491     }
86492   }else{
86493     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
86494     if( !pPtr ){
86495       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
86496       sqlite3_result_error(context, zErr, -1);
86497       sqlite3_free(zErr);
86498       return;
86499     }
86500   }
86501
86502   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
86503 }
86504
86505 #ifdef SQLITE_TEST
86506
86507
86508 /*
86509 ** Implementation of a special SQL scalar function for testing tokenizers 
86510 ** designed to be used in concert with the Tcl testing framework. This
86511 ** function must be called with two arguments:
86512 **
86513 **   SELECT <function-name>(<key-name>, <input-string>);
86514 **   SELECT <function-name>(<key-name>, <pointer>);
86515 **
86516 ** where <function-name> is the name passed as the second argument
86517 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
86518 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
86519 **
86520 ** The return value is a string that may be interpreted as a Tcl
86521 ** list. For each token in the <input-string>, three elements are
86522 ** added to the returned list. The first is the token position, the 
86523 ** second is the token text (folded, stemmed, etc.) and the third is the
86524 ** substring of <input-string> associated with the token. For example, 
86525 ** using the built-in "simple" tokenizer:
86526 **
86527 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
86528 **
86529 ** will return the string:
86530 **
86531 **   "{0 i I 1 dont don't 2 see see 3 how how}"
86532 **   
86533 */
86534 static void testFunc(
86535   sqlite3_context *context,
86536   int argc,
86537   sqlite3_value **argv
86538 ){
86539   fts3Hash *pHash;
86540   sqlite3_tokenizer_module *p;
86541   sqlite3_tokenizer *pTokenizer = 0;
86542   sqlite3_tokenizer_cursor *pCsr = 0;
86543
86544   const char *zErr = 0;
86545
86546   const char *zName;
86547   int nName;
86548   const char *zInput;
86549   int nInput;
86550
86551   const char *zArg = 0;
86552
86553   const char *zToken;
86554   int nToken;
86555   int iStart;
86556   int iEnd;
86557   int iPos;
86558
86559   Tcl_Obj *pRet;
86560
86561   assert( argc==2 || argc==3 );
86562
86563   nName = sqlite3_value_bytes(argv[0]);
86564   zName = (const char *)sqlite3_value_text(argv[0]);
86565   nInput = sqlite3_value_bytes(argv[argc-1]);
86566   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
86567
86568   if( argc==3 ){
86569     zArg = (const char *)sqlite3_value_text(argv[1]);
86570   }
86571
86572   pHash = (fts3Hash *)sqlite3_user_data(context);
86573   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
86574
86575   if( !p ){
86576     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
86577     sqlite3_result_error(context, zErr, -1);
86578     sqlite3_free(zErr);
86579     return;
86580   }
86581
86582   pRet = Tcl_NewObj();
86583   Tcl_IncrRefCount(pRet);
86584
86585   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
86586     zErr = "error in xCreate()";
86587     goto finish;
86588   }
86589   pTokenizer->pModule = p;
86590   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
86591     zErr = "error in xOpen()";
86592     goto finish;
86593   }
86594   pCsr->pTokenizer = pTokenizer;
86595
86596   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
86597     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
86598     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
86599     zToken = &zInput[iStart];
86600     nToken = iEnd-iStart;
86601     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
86602   }
86603
86604   if( SQLITE_OK!=p->xClose(pCsr) ){
86605     zErr = "error in xClose()";
86606     goto finish;
86607   }
86608   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
86609     zErr = "error in xDestroy()";
86610     goto finish;
86611   }
86612
86613 finish:
86614   if( zErr ){
86615     sqlite3_result_error(context, zErr, -1);
86616   }else{
86617     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
86618   }
86619   Tcl_DecrRefCount(pRet);
86620 }
86621
86622 static
86623 int registerTokenizer(
86624   sqlite3 *db, 
86625   char *zName, 
86626   const sqlite3_tokenizer_module *p
86627 ){
86628   int rc;
86629   sqlite3_stmt *pStmt;
86630   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
86631
86632   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
86633   if( rc!=SQLITE_OK ){
86634     return rc;
86635   }
86636
86637   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
86638   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
86639   sqlite3_step(pStmt);
86640
86641   return sqlite3_finalize(pStmt);
86642 }
86643
86644 static
86645 int queryTokenizer(
86646   sqlite3 *db, 
86647   char *zName,  
86648   const sqlite3_tokenizer_module **pp
86649 ){
86650   int rc;
86651   sqlite3_stmt *pStmt;
86652   const char zSql[] = "SELECT fts3_tokenizer(?)";
86653
86654   *pp = 0;
86655   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
86656   if( rc!=SQLITE_OK ){
86657     return rc;
86658   }
86659
86660   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
86661   if( SQLITE_ROW==sqlite3_step(pStmt) ){
86662     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
86663       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
86664     }
86665   }
86666
86667   return sqlite3_finalize(pStmt);
86668 }
86669
86670 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
86671
86672 /*
86673 ** Implementation of the scalar function fts3_tokenizer_internal_test().
86674 ** This function is used for testing only, it is not included in the
86675 ** build unless SQLITE_TEST is defined.
86676 **
86677 ** The purpose of this is to test that the fts3_tokenizer() function
86678 ** can be used as designed by the C-code in the queryTokenizer and
86679 ** registerTokenizer() functions above. These two functions are repeated
86680 ** in the README.tokenizer file as an example, so it is important to
86681 ** test them.
86682 **
86683 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
86684 ** function with no arguments. An assert() will fail if a problem is
86685 ** detected. i.e.:
86686 **
86687 **     SELECT fts3_tokenizer_internal_test();
86688 **
86689 */
86690 static void intTestFunc(
86691   sqlite3_context *context,
86692   int argc,
86693   sqlite3_value **argv
86694 ){
86695   int rc;
86696   const sqlite3_tokenizer_module *p1;
86697   const sqlite3_tokenizer_module *p2;
86698   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
86699
86700   /* Test the query function */
86701   sqlite3Fts3SimpleTokenizerModule(&p1);
86702   rc = queryTokenizer(db, "simple", &p2);
86703   assert( rc==SQLITE_OK );
86704   assert( p1==p2 );
86705   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
86706   assert( rc==SQLITE_ERROR );
86707   assert( p2==0 );
86708   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
86709
86710   /* Test the storage function */
86711   rc = registerTokenizer(db, "nosuchtokenizer", p1);
86712   assert( rc==SQLITE_OK );
86713   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
86714   assert( rc==SQLITE_OK );
86715   assert( p2==p1 );
86716
86717   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
86718 }
86719
86720 #endif
86721
86722 /*
86723 ** Set up SQL objects in database db used to access the contents of
86724 ** the hash table pointed to by argument pHash. The hash table must
86725 ** been initialised to use string keys, and to take a private copy 
86726 ** of the key when a value is inserted. i.e. by a call similar to:
86727 **
86728 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
86729 **
86730 ** This function adds a scalar function (see header comment above
86731 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
86732 ** defined at compilation time, a temporary virtual table (see header 
86733 ** comment above struct HashTableVtab) to the database schema. Both 
86734 ** provide read/write access to the contents of *pHash.
86735 **
86736 ** The third argument to this function, zName, is used as the name
86737 ** of both the scalar and, if created, the virtual table.
86738 */
86739 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
86740   sqlite3 *db, 
86741   fts3Hash *pHash, 
86742   const char *zName
86743 ){
86744   int rc = SQLITE_OK;
86745   void *p = (void *)pHash;
86746   const int any = SQLITE_ANY;
86747   char *zTest = 0;
86748   char *zTest2 = 0;
86749
86750 #ifdef SQLITE_TEST
86751   void *pdb = (void *)db;
86752   zTest = sqlite3_mprintf("%s_test", zName);
86753   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
86754   if( !zTest || !zTest2 ){
86755     rc = SQLITE_NOMEM;
86756   }
86757 #endif
86758
86759   if( rc!=SQLITE_OK
86760    || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
86761    || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
86762 #ifdef SQLITE_TEST
86763    || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
86764    || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
86765    || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
86766 #endif
86767   );
86768
86769   sqlite3_free(zTest);
86770   sqlite3_free(zTest2);
86771   return rc;
86772 }
86773
86774 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
86775
86776 /************** End of fts3_tokenizer.c **************************************/
86777 /************** Begin file fts3_tokenizer1.c *********************************/
86778 /*
86779 ** 2006 Oct 10
86780 **
86781 ** The author disclaims copyright to this source code.  In place of
86782 ** a legal notice, here is a blessing:
86783 **
86784 **    May you do good and not evil.
86785 **    May you find forgiveness for yourself and forgive others.
86786 **    May you share freely, never taking more than you give.
86787 **
86788 ******************************************************************************
86789 **
86790 ** Implementation of the "simple" full-text-search tokenizer.
86791 */
86792
86793 /*
86794 ** The code in this file is only compiled if:
86795 **
86796 **     * The FTS3 module is being built as an extension
86797 **       (in which case SQLITE_CORE is not defined), or
86798 **
86799 **     * The FTS3 module is being built into the core of
86800 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
86801 */
86802 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
86803
86804
86805
86806
86807 typedef struct simple_tokenizer {
86808   sqlite3_tokenizer base;
86809   char delim[128];             /* flag ASCII delimiters */
86810 } simple_tokenizer;
86811
86812 typedef struct simple_tokenizer_cursor {
86813   sqlite3_tokenizer_cursor base;
86814   const char *pInput;          /* input we are tokenizing */
86815   int nBytes;                  /* size of the input */
86816   int iOffset;                 /* current position in pInput */
86817   int iToken;                  /* index of next token to be returned */
86818   char *pToken;                /* storage for current token */
86819   int nTokenAllocated;         /* space allocated to zToken buffer */
86820 } simple_tokenizer_cursor;
86821
86822
86823 /* Forward declaration */
86824 static const sqlite3_tokenizer_module simpleTokenizerModule;
86825
86826 static int simpleDelim(simple_tokenizer *t, unsigned char c){
86827   return c<0x80 && t->delim[c];
86828 }
86829
86830 /*
86831 ** Create a new tokenizer instance.
86832 */
86833 static int simpleCreate(
86834   int argc, const char * const *argv,
86835   sqlite3_tokenizer **ppTokenizer
86836 ){
86837   simple_tokenizer *t;
86838
86839   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
86840   if( t==NULL ) return SQLITE_NOMEM;
86841   memset(t, 0, sizeof(*t));
86842
86843   /* TODO(shess) Delimiters need to remain the same from run to run,
86844   ** else we need to reindex.  One solution would be a meta-table to
86845   ** track such information in the database, then we'd only want this
86846   ** information on the initial create.
86847   */
86848   if( argc>1 ){
86849     int i, n = strlen(argv[1]);
86850     for(i=0; i<n; i++){
86851       unsigned char ch = argv[1][i];
86852       /* We explicitly don't support UTF-8 delimiters for now. */
86853       if( ch>=0x80 ){
86854         sqlite3_free(t);
86855         return SQLITE_ERROR;
86856       }
86857       t->delim[ch] = 1;
86858     }
86859   } else {
86860     /* Mark non-alphanumeric ASCII characters as delimiters */
86861     int i;
86862     for(i=1; i<0x80; i++){
86863       t->delim[i] = !isalnum(i);
86864     }
86865   }
86866
86867   *ppTokenizer = &t->base;
86868   return SQLITE_OK;
86869 }
86870
86871 /*
86872 ** Destroy a tokenizer
86873 */
86874 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
86875   sqlite3_free(pTokenizer);
86876   return SQLITE_OK;
86877 }
86878
86879 /*
86880 ** Prepare to begin tokenizing a particular string.  The input
86881 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
86882 ** used to incrementally tokenize this string is returned in 
86883 ** *ppCursor.
86884 */
86885 static int simpleOpen(
86886   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
86887   const char *pInput, int nBytes,        /* String to be tokenized */
86888   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
86889 ){
86890   simple_tokenizer_cursor *c;
86891
86892   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
86893   if( c==NULL ) return SQLITE_NOMEM;
86894
86895   c->pInput = pInput;
86896   if( pInput==0 ){
86897     c->nBytes = 0;
86898   }else if( nBytes<0 ){
86899     c->nBytes = (int)strlen(pInput);
86900   }else{
86901     c->nBytes = nBytes;
86902   }
86903   c->iOffset = 0;                 /* start tokenizing at the beginning */
86904   c->iToken = 0;
86905   c->pToken = NULL;               /* no space allocated, yet. */
86906   c->nTokenAllocated = 0;
86907
86908   *ppCursor = &c->base;
86909   return SQLITE_OK;
86910 }
86911
86912 /*
86913 ** Close a tokenization cursor previously opened by a call to
86914 ** simpleOpen() above.
86915 */
86916 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
86917   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
86918   sqlite3_free(c->pToken);
86919   sqlite3_free(c);
86920   return SQLITE_OK;
86921 }
86922
86923 /*
86924 ** Extract the next token from a tokenization cursor.  The cursor must
86925 ** have been opened by a prior call to simpleOpen().
86926 */
86927 static int simpleNext(
86928   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
86929   const char **ppToken,               /* OUT: *ppToken is the token text */
86930   int *pnBytes,                       /* OUT: Number of bytes in token */
86931   int *piStartOffset,                 /* OUT: Starting offset of token */
86932   int *piEndOffset,                   /* OUT: Ending offset of token */
86933   int *piPosition                     /* OUT: Position integer of token */
86934 ){
86935   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
86936   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
86937   unsigned char *p = (unsigned char *)c->pInput;
86938
86939   while( c->iOffset<c->nBytes ){
86940     int iStartOffset;
86941
86942     /* Scan past delimiter characters */
86943     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
86944       c->iOffset++;
86945     }
86946
86947     /* Count non-delimiter characters. */
86948     iStartOffset = c->iOffset;
86949     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
86950       c->iOffset++;
86951     }
86952
86953     if( c->iOffset>iStartOffset ){
86954       int i, n = c->iOffset-iStartOffset;
86955       if( n>c->nTokenAllocated ){
86956         c->nTokenAllocated = n+20;
86957         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
86958         if( c->pToken==NULL ) return SQLITE_NOMEM;
86959       }
86960       for(i=0; i<n; i++){
86961         /* TODO(shess) This needs expansion to handle UTF-8
86962         ** case-insensitivity.
86963         */
86964         unsigned char ch = p[iStartOffset+i];
86965         c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
86966       }
86967       *ppToken = c->pToken;
86968       *pnBytes = n;
86969       *piStartOffset = iStartOffset;
86970       *piEndOffset = c->iOffset;
86971       *piPosition = c->iToken++;
86972
86973       return SQLITE_OK;
86974     }
86975   }
86976   return SQLITE_DONE;
86977 }
86978
86979 /*
86980 ** The set of routines that implement the simple tokenizer
86981 */
86982 static const sqlite3_tokenizer_module simpleTokenizerModule = {
86983   0,
86984   simpleCreate,
86985   simpleDestroy,
86986   simpleOpen,
86987   simpleClose,
86988   simpleNext,
86989 };
86990
86991 /*
86992 ** Allocate a new simple tokenizer.  Return a pointer to the new
86993 ** tokenizer in *ppModule
86994 */
86995 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
86996   sqlite3_tokenizer_module const**ppModule
86997 ){
86998   *ppModule = &simpleTokenizerModule;
86999 }
87000
87001 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
87002
87003 /************** End of fts3_tokenizer1.c *************************************/